logo
eng-flag

C# Cheatsheet

Table of Contents

  1. Basic Syntax
  2. Data Types
  3. Variables
  4. Operators
  5. Control Flow
  6. Methods
  7. Arrays and Collections
  8. Object-Oriented Programming
  9. Exception Handling
  10. LINQ
  11. Async Programming
  12. File Handling
  13. Generics
  14. Delegates and Events

Basic Syntax

Comments

// This is a single-line comment

/*
This is a
multi-line comment
*/

/// <summary>
/// This is an XML documentation comment
/// </summary>

Main Method

Every C# program starts from the Main method:

using System;

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

Data Types

Value Types

byte b = 255;
short s = 32000;
int i = 2147483647;
long l = 9223372036854775807L;
float f = 3.14f;
double d = 3.14159265359;
decimal m = 3.14m;
bool boolean = true;
char c = 'A';

Reference Types

string str = "Hello, World!";
object obj = new object();
dynamic dyn = 42;

Variables

// Variable declaration
int number;

// Variable initialization
number = 10;

// Declaration and initialization
string name = "John";

// Constants
const double PI = 3.14159;

// Implicitly typed local variables
var message = "Hello";

Operators

Arithmetic Operators

int a = 10, b = 3;

Console.WriteLine(a + b);  // Addition: 13
Console.WriteLine(a - b);  // Subtraction: 7
Console.WriteLine(a * b);  // Multiplication: 30
Console.WriteLine(a / b);  // Division: 3
Console.WriteLine(a % b);  // Modulus: 1

Comparison Operators

int x = 5, y = 10;

Console.WriteLine(x == y);  // Equal to: false
Console.WriteLine(x != y);  // Not equal to: true
Console.WriteLine(x > y);   // Greater than: false
Console.WriteLine(x < y);   // Less than: true
Console.WriteLine(x >= y);  // Greater than or equal to: false
Console.WriteLine(x <= y);  // Less than or equal to: true

Logical Operators

bool a = true, b = false;

Console.WriteLine(a && b);  // Logical AND: false
Console.WriteLine(a || b);  // Logical OR: true
Console.WriteLine(!a);      // Logical NOT: false

Control Flow

If-Else Statement

int x = 10;

if (x > 0)
{
    Console.WriteLine("Positive");
}
else if (x < 0)
{
    Console.WriteLine("Negative");
}
else
{
    Console.WriteLine("Zero");
}

Switch Statement

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("Other day");
        break;
}

For Loop

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

// Foreach loop
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
    Console.WriteLine(num);
}

While Loop

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

Do-While Loop

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

Methods

// Method definition
static int Add(int a, int b)
{
    return a + b;
}

// Method overloading
static double Add(double a, double b)
{
    return a + b;
}

// Method call
int sum = Add(5, 3);
double sumDouble = Add(5.5, 3.3);

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

// Named arguments
Greet(greeting: "Hi", name: "Alice");

Arrays and Collections

Arrays

// Array declaration and initialization
int[] numbers = { 1, 2, 3, 4, 5 };

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

// Multi-dimensional array
int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

// Jagged array
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9 };

Lists

using System.Collections.Generic;

List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };
fruits.Add("Date");
fruits.Remove("Banana");
Console.WriteLine(fruits[0]);  // Prints "Apple"
Console.WriteLine(fruits.Count);  // Prints 3

Dictionaries

Dictionary<string, int> ages = new Dictionary<string, int>
{
    { "Alice", 30 },
    { "Bob", 25 },
    { "Charlie", 35 }
};

Console.WriteLine(ages["Bob"]);  // Prints 25
ages["David"] = 40;
ages.Remove("Alice");

Object-Oriented Programming

Class Definition

public class Car
{
    // Fields
    private string brand;
    private string model;
    
    // Properties
    public int Year { get; set; }
    
    // Constructor
    public Car(string brand, string model)
    {
        this.brand = brand;
        this.model = model;
    }
    
    // Methods
    public void Start()
    {
        Console.WriteLine("The car is starting...");
    }
    
    // Getters and Setters
    public string GetBrand()
    {
        return brand;
    }
    
    public void SetBrand(string brand)
    {
        this.brand = brand;
    }
}

Object Creation and Usage

Car myCar = new Car("Toyota", "Corolla");
myCar.Year = 2022;
myCar.Start();
Console.WriteLine(myCar.GetBrand());

Inheritance

public class ElectricCar : Car
{
    public int BatteryCapacity { get; set; }
    
    public ElectricCar(string brand, string model, int batteryCapacity) 
        : base(brand, model)
    {
        BatteryCapacity = batteryCapacity;
    }
    
    public override void Start()
    {
        Console.WriteLine("The electric car is starting silently...");
    }
}

Interface

public interface IDrivable
{
    void Drive();
    void Stop();
}

public class Car : IDrivable
{
    public void Drive()
    {
        Console.WriteLine("The car is driving");
    }
    
    public void Stop()
    {
        Console.WriteLine("The car has stopped");
    }
}

Exception Handling

try
{
    int result = 10 / 0;
}
catch (DivideByZeroException e)
{
    Console.WriteLine("Cannot divide by zero!");
}
finally
{
    Console.WriteLine("This always executes");
}

// Throwing an exception
public void CheckAge(int age)
{
    if (age < 0)
    {
        throw new ArgumentException("Age cannot be negative");
    }
}

LINQ

using System.Linq;

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// Query syntax
var evenNumbers = from num in numbers
                  where num % 2 == 0
                  select num;

// Method syntax
var oddNumbers = numbers.Where(x => x % 2 != 0);

var sum = numbers.Sum();
var average = numbers.Average();
var max = numbers.Max();

Async Programming

using System.Threading.Tasks;

public async Task<string> FetchDataAsync()
{
    await Task.Delay(1000);  // Simulating an async operation
    return "Data fetched successfully";
}

// Usage
public async Task ProcessDataAsync()
{
    string result = await FetchDataAsync();
    Console.WriteLine(result);
}

File Handling

using System.IO;

// Reading from a file
string content = File.ReadAllText("file.txt");

// Writing to a file
File.WriteAllText("output.txt", "Hello, World!");

// Reading lines from a file
string[] lines = File.ReadAllLines("file.txt");

// Appending to a file
File.AppendAllText("log.txt", "New log entry
");

Generics

public class Box<T>
{
    private T item;

    public void SetItem(T item)
    {
        this.item = item;
    }

    public T GetItem()
    {
        return item;
    }
}

// Usage
Box<int> intBox = new Box<int>();
intBox.SetItem(10);
int value = intBox.GetItem();

Delegates and Events

// Delegate declaration
public delegate void MessageHandler(string message);

// Event declaration
public event MessageHandler MessageReceived;

// Method that matches the delegate signature
public void DisplayMessage(string message)
{
    Console.WriteLine(message);
}

// Usage
MessageHandler handler = DisplayMessage;
handler("Hello, Delegate!");

// Event usage
MessageReceived += DisplayMessage;
MessageReceived?.Invoke("Hello, Event!");

2024 © All rights reserved - buraxta.com