Great choice!
**C# (C-Sharp)** is a modern, versatile programming language that is
widely used for web development, game development, and desktop applications. It was
developed by Microsoft and is a key language in the **.NET framework**. C# is
commonly used for building Windows applications, enterprise software, and
especially in game development with **Unity**.
Let’s walk through the basics of C# to help you get started.
---
### 1. **Setting Up C#**
To start programming in C#, you’ll need the **.NET SDK** (Software Development
Kit). The easiest way to get started is by installing **Visual Studio**
(Windows/macOS) or **Visual Studio Code** (cross-platform) with the C# extension.
1. **Download and Install**:
- Install **Visual Studio**: [Download Visual
Studio](https://visualstudio.microsoft.com/)
- Install **Visual Studio Code**: [Download VS
Code](https://code.visualstudio.com/), then add the C# extension from the
marketplace.
2. **Verify C# Installation**:
After installing, you can verify if C# is working by running this in your
terminal/command prompt:
```bash
dotnet --version
```
This will show the installed version of the .NET SDK.
---
### 2. **Your First C# Program**
Let's start with a simple "Hello, World!" program.
**Code:**
```csharp
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
```
#### Explanation:
- **`using System;`**: This line imports the `System` namespace, which contains the
`Console` class.
- **`class Program`**: Defines a class named `Program`. In C#, everything is
contained within classes or structs.
- **`static void Main(string[] args)`**: This is the entry point of a C#
application. `Main()` is where execution starts. `void` means this function doesn't
return anything.
- **`Console.WriteLine("Hello, World!");`**: This writes text to the console.
To run the program:
1. Save the code in a file named `Program.cs`.
2. Open the terminal/command prompt, navigate to the directory where the file is
saved, and run:
```bash
dotnet new console -n HelloWorldApp
cd HelloWorldApp
dotnet run
```
This should print `Hello, World!` to the console.
---
### 3. **Variables and Data Types**
C# is statically typed, meaning you need to declare the type of each variable.
**Common Data Types:**
- **int** – Integer (whole numbers)
- **double** – Double precision floating point numbers
- **string** – A sequence of characters (text)
- **bool** – Boolean (true/false)
- **char** – Single character
**Example:**
```csharp
using System;
class Program
{
static void Main(string[] args)
{
int age = 25;
double height = 5.9;
string name = "Alice";
bool isStudent = true;
Console.WriteLine($"Name: {name}, Age: {age}, Height: {height}, Is Student:
{isStudent}");
}
}
```
- **`int`** for whole numbers (e.g., age, count).
- **`double`** for floating-point numbers (e.g., height, weight).
- **`string`** for text (e.g., names, messages).
- **`bool`** for boolean values (e.g., `true`/`false`).
You can also use the `var` keyword when you want the compiler to infer the type
automatically.
```csharp
var name = "Alice"; // The type is inferred as string
var age = 25; // The type is inferred as int
```
---
### 4. **Control Flow (if/else, loops)**
C# uses standard control flow statements, like `if/else` and loops.
#### Conditional Statements:
```csharp
int age = 18;
if (age >= 18)
{
Console.WriteLine("You are an adult.");
}
else
{
Console.WriteLine("You are a minor.");
}
```
#### Loops:
- **For Loop**:
```csharp
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
```
- **While Loop**:
```csharp
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
```
#### Switch Statement:
A `switch` statement is often used when you have multiple conditions to check.
```csharp
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
default:
Console.WriteLine("Invalid day");
break;
}
```
---
### 5. **Functions/Methods**
Functions in C# are called methods and are used to encapsulate reusable logic.
**Defining a Method:**
```csharp
using System;
class Program
{
static void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
static void Main(string[] args)
{
Greet("Alice");
}
}
```
- **`static`**: Indicates that the method belongs to the class, not an instance of
the class.
- **`void`**: Specifies that the method doesn’t return a value.
- **`string name`**: A parameter that the method accepts.
You can return a value from a method using a return type other than `void`.
```csharp
static int Add(int a, int b)
{
return a + b;
}
```
---
### 6. **Arrays and Collections**
#### Arrays:
Arrays are used to store multiple values of the same type.
```csharp
int[] numbers = { 1, 2, 3, 4, 5 };
Console.WriteLine(numbers[0]); // Output: 1
```
#### Lists (from `System.Collections.Generic`):
A more flexible alternative to arrays. You can add, remove, and resize elements.
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<string> fruits = new List<string>();
fruits.Add("Apple");
fruits.Add("Banana");
Console.WriteLine(fruits[0]); // Output: Apple
}
}
```
---
### 7. **Object-Oriented Programming (OOP)**
C# is an object-oriented language, which means it uses classes and objects to
organize code.
#### Defining a Class:
```csharp
using System;
class Person
{
public string Name;
public int Age;
public void Greet()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}
class Program
{
static void Main(string[] args)
{
Person person = new Person(); // Create an instance of the class
person.Name = "Alice";
person.Age = 25;
person.Greet(); // Output: Hello, my name is Alice and I am 25 years old.
}
}
```
- **`class`**: Defines a class (blueprint for creating objects).
- **`public`**: The keyword that makes members accessible from outside the class.
- **`new`**: Used to create a new instance (object) of a class.
---
### 8. **Error Handling (Exceptions)**
In C#, you handle errors using `try`, `catch`, and `finally` blocks.
```csharp
try
{
int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
Console.WriteLine("This will always run.");
}
```
- **`try`**: Code that might throw an exception.
- **`catch`**: Catches and handles the exception.
- **`finally`**: Executes code regardless of whether an exception occurred or not.
---
### 9. **LINQ (Language Integrated Query)**
C# has a powerful feature called **LINQ** for querying collections of data.
Example of using LINQ to filter a list:
```csharp
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var evenNumbers = from n in numbers
where n % 2 == 0
select n;
foreach (var num in evenNumbers)
{
Console.WriteLine(num); // Output: 2, 4
}
}
}
```
---
### Next Steps:
Now that you have the basics, here are some topics you can explore next:
1. **Advanced OOP Concepts**: Inheritance, polymorphism, abstraction, etc.
2. **Asynchronous Programming**: Learn about `async`/`await`, `Task` class, and
working with asynchronous code.
3. **Building Web Applications with ASP.NET Core**: Create APIs and web
applications using C# and the .NET framework.
4. **Game Development with Unity**: Learn C# for