C# Introduction
C# is a modern, object-oriented programming language that runs on the .NET platform.
What is C#?
- C# was created by Microsoft and first released in 2002
- It was designed by Anders Hejlsberg
- It runs on .NET, which is free, open source and works on Windows, macOS and Linux
- Its syntax looks like C, C++ and Java, so it is easy to move between them
What Can You Build?
| Type of app | Tool |
|---|---|
| Websites and web APIs | ASP.NET Core |
| Games | Unity |
| Desktop apps | WPF, Windows Forms, WinUI |
| Mobile apps | .NET MAUI |
| Cloud services | Azure Functions |
Setting Up
- Download and install the free .NET SDK (choose the latest LTS version) from Microsoft's .NET website.
- Install an editor: Visual Studio Community (Windows) or Visual Studio Code with the C# Dev Kit extension.
- Open a terminal and create a new console project:
Example
dotnet new console -o HelloApp
cd HelloApp
dotnet runHello, World!
The project contains a file named Program.cs. Open it and replace its code with your own.
Your First Program
Example
Console.WriteLine("Assalam o Alaikum!");
Console.WriteLine("Welcome to C# at Workownix.");Assalam o Alaikum! Welcome to C# at Workownix.
Console.WriteLine prints text and moves to a new line. Console.Write prints without moving to a new line. Each statement ends with a semicolon ;.
The Classic Program Structure
The short form above is called top-level statements (C# 9 and later). Behind the scenes, C# wraps it in a class with a Main method. In older code and many books you will see the full form:
Example
using System;
namespace HelloApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello from Main");
}
}
}Hello from Main
| Part | Meaning |
|---|---|
using System; | Lets you use classes like Console without writing System.Console |
namespace | A named group that keeps your classes organised |
class Program | A class that holds the code |
static void Main | The method where the program starts |
Comments
Example
// A single-line comment
/* A comment
over several lines */
Console.WriteLine("Comments are ignored"); // also hereC# is case sensitive. Console.WriteLine works, but console.writeline is an error.
Exercise
Exercise
Which command runs a C# console project from the terminal?
