C# Cheat Sheet

Here’s a cheat sheet for C# programming language covering some key concepts and syntax:

Hello World

using System;

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

Variables and Data Types

int age = 25;
double salary = 50000.50;
string name = "John";
bool isStudent = true;

Control Flow

// If-else statement
if (condition)
{
    // Code to execute if condition is true
}
else
{
    // Code to execute if condition is false
}

// Switch statement
switch (variable)
{
    case value1:
        // Code for value1
        break;
    case value2:
        // Code for value2
        break;
    default:
        // Code if no match is found
        break;
}

Loops

// For loop
for (int i = 0; i < 5; i++)
{
    // Code to repeat
}

// While loop
while (condition)
{
    // Code to repeat while condition is true
}

// Do-while loop
do
{
    // Code to repeat at least once
} while (condition);

Arrays

int[] numbers = { 1, 2, 3, 4, 5 };
string[] names = new string[3] { "Alice", "Bob", "Charlie" };

Methods

// Method with parameters and return value
int Add(int a, int b)
{
    return a + b;
}

// Method with optional parameter
void DisplayMessage(string message, bool showAlert = true)
{
    if (showAlert)
    {
        Console.WriteLine($"Alert: {message}");
    }
    else
    {
        Console.WriteLine(message);
    }
}

Classes and Objects

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public void SayHello()
    {
        Console.WriteLine($"Hello, my name is {Name} and I'm {Age} years old.");
    }
}

// Creating an object
Person person = new Person();
person.Name = "John";
person.Age = 30;
person.SayHello();

Exception Handling

try
{
    // Code that may throw an exception
}
catch (Exception ex)
{
    // Handle the exception
    Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
    // Code that will always execute
}

LINQ (Language Integrated Query)

var result = from num in numbers
             where num % 2 == 0
             select num;

Delegates and Events

// Declare a delegate
delegate void MyDelegate(string message);

// Declare an event
event MyDelegate MyEvent;

// Subscribe to the event
MyEvent += HandleEvent;

// Define the event handler method
void HandleEvent(string message)
{
    Console.WriteLine($"Event handled: {message}");
}

This cheat sheet covers some fundamental aspects of C# programming. Explore the official documentation for more in-depth information and advanced features of the language.