Language: EN

cheatsheet-csharp

.NET and C# Cheatsheet

C# is a programming language developed by Microsoft. It is a high-level, object-oriented, and general-purpose language.

It is used in the development of desktop, web, and mobile applications, primarily in the Microsoft ecosystem.

Basic Structure

Hello World in C#

The classic example to print “Hello World” in the console.

using System;

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Hello World");
    }
}

Structure of a Program

Programs in C# have a modular structure. All the code must be within a class. The entry point of execution is the Main method.

Comments

C# supports single-line and multi-line comments.

// This is a single-line comment
/* This is a
   multi-line comment */

Variables and Data Types

Variable Declaration

int number = 10;
string text = "Hello";
double decimal = 4.5;
bool isTrue = true;

Common Data Types

TypeSizeDescription
int32 bitsIntegers
double64 bitsDouble precision decimals
float32 bitsSingle precision decimals
char16 bitsUnicode character
string-Text string
bool1 bitBoolean value

Constant Variables

Variables whose value does not change are defined with const.

const double PI = 3.1416;

Control Structures

Conditionals

if-else Conditional

int a = 5;
if (a > 10) {
    Console.WriteLine("Greater than 10");
} else if (a == 10) {
    Console.WriteLine("Equal to 10");
} else {
    Console.WriteLine("Less than 10");
}

switch Conditional

int day = 3;
switch (day) {
    case 1:
        Console.WriteLine("Monday");
        break;
    case 2:
        Console.WriteLine("Tuesday");
        break;
    default:
        Console.WriteLine("Other day");
        break;
}

Loops

for Loop

for (int i = 0; i < 5; i++) {
    Console.WriteLine(i);
}

while Loop

int i = 0;
while (i < 5) {
    Console.WriteLine(i);
    i++;
}

do-while Loop

int i = 0;
do {
    Console.WriteLine(i);
    i++;
} while (i < 5);

Functions and Methods

Function Declaration

int Add(int a, int b) {
    return a + b;
}

Calling a Function

int result = Add(5, 3);
Console.WriteLine(result);  // Prints 8

Functions with Overloading

int Multiply(int a, int b) {
    return a * b;
}

double Multiply(double a, double b) {
    return a * b;
}

Optional Parameters

void Greet(string name, string greeting = "Hello")
{
    Console.WriteLine($"{greeting}, {name}!");
}

Greet("John"); // Hello, John!
Greet("Maria", "Bonjour"); // Bonjour, Maria!

Object-Oriented Programming (OOP)

Defining a Class

class Person {
    public string Name;
    public int Age;

    public void Greet() {
        Console.WriteLine($"Hello, I am {Name}");
    }
}

Creating an Object

Person person1 = new Person();
person1.Name = "John";
person1.Greet();  // Prints "Hello, I am John"

Properties

class Product
{
    private string _name;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
}

Defining a Constructor

class Person {
    public string Name;
    public int Age;

    public Person(string name, int age) {
        Name = name;
        Age = age;
    }
}

Creating an Object with Constructor

Person person2 = new Person("Ana", 25);
Console.WriteLine(person2.Name);  // Prints "Ana"

Defining an Interface

interface IVehicle {
    void Start();
}

class Car : IVehicle {
    public void Start() {
        Console.WriteLine("The car starts");
    }
}

Defining a Generic Class

class Box<T> {
    public T Content { get; set; }
}

Box<int> boxInt = new Box<int> { Content = 5 };
Console.WriteLine(boxInt.Content);  // Prints 5

Inheritance

Inheritance between Classes

class Animal {
    public void Eat() {
        Console.WriteLine("I am eating");
    }
}

class Dog : Animal {
    public void Bark() {
        Console.WriteLine("Woof Woof");
    }
}

Creating an Instance of a Derived Class

Dog dog = new Dog();
dog.Eat();  // Prints "I am eating"
dog.Bark(); // Prints "Woof Woof"

Polymorphism

Virtual Methods and Override

class Animal {
    public virtual void MakeSound() {
        Console.WriteLine("Generic sound");
    }
}

class Dog : Animal {
    public override void MakeSound() {
        Console.WriteLine("Woof");
    }
}

Collections and Arrays

Declaring an Array

int[] numbers = {1, 2, 3, 4, 5};

Accessing Array Elements

Console.WriteLine(numbers[0]);  // Prints 1

Generic Lists

List<int> list = new List<int>();
list.Add(10);
list.Add(20);
Console.WriteLine(list.Count);  // Prints 2

Iterating through a List

foreach (int number in list) {
    Console.WriteLine(number);
}

Exception Handling

Try-Catch for Error Handling

try {
    int result = 10 / 0;
} catch (DivideByZeroException ex) {
    Console.WriteLine("Error: Division by zero");
} finally {
    Console.WriteLine("Finally block executed");
}

Delegates and Events

Declaring a Delegate

delegate void Operation(int x, int y);

class Program {
    static void Add(int a, int b) {
        Console.WriteLine(a + b);
    }

    static void Main(string[] args) {
        Operation operation = Add;
        operation(5, 3);  // Prints 8
    }
}

Defining and Using an Event

class EventExample {
    public delegate void EventDelegate();
    public event EventDelegate Event;

    public void TriggerEvent() {
        if (Event != null) {
            Event();
        }
    }
}

class Program {
    static void Main(string[] args) {
        EventExample example = new EventExample();
        example.Event += () => Console.WriteLine("Event Triggered");
        example.TriggerEvent();  // Prints "Event Triggered"
    }
}

LINQ (Language Integrated Queries)

Basic Query with LINQ

int[] numbers = {1, 2, 3, 4, 5};
var result = numbers.Where(n => n > 2).ToList();

foreach (var n in result) {
    Console.WriteLine(n);  // Prints 3, 4, 5
}

Files and Input/Output

Writing to a File

using System.IO;
File.WriteAllText("file.txt", "File content");

Reading from a File

string content = File.ReadAllText("file.txt");
Console.WriteLine(content);

Asynchrony and Tasks

Declaring an async Method and Using await

async Task<int> CallApiAsync() {
    await Task.Delay(1000);  // Simulates an asynchronous operation
    return 42;
}

Using await

async Task Main() {
    int result = await CallApiAsync();
    Console.WriteLine(result);  // Prints 42
}

Namespaces

Using using to Include Namespaces

using System;  // Includes the System namespace

Console.WriteLine("Hello World");

Extension Methods

Defining an Extension Method

public static class Extensions {
    public static int Double(this int number) {
        return number * 2;
    }
}

int number = 10;
Console.WriteLine(number.Double());  // Prints 20