Show 25 50 100
PDF
11 result(s) in C# Clear

Index

Showing 11 topics
  1. C# and .NET Basics
  2. Value Types vs Reference Types
  3. Classes, Properties and Constructors
  4. Inheritance, Interface and Abstract Class in C#
  5. Collections and Generics
  6. LINQ
  7. Exception Handling in C#
  8. Delegates, Events and Lambdas
  9. async and await
  10. Garbage Collection in .NET
  11. C# Keywords Quick Reference
1 Index

C# is a modern, object-oriented, type-safe language by Microsoft that runs on .NET. Used for web (ASP.NET Core), desktop, games (Unity), cloud and mobile (MAUI).

Source → IL → JIT → native code

Source → IL → JIT → native code

Structure of a C# program C# 14 lines
using System;

namespace HelloApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter your name: ");
            string name = Console.ReadLine();
            Console.WriteLine($"Hello, {name}!");   // string interpolation
        }
    }
}

Q & A

  1. What is the CLR?
    Common Language Runtime: the .NET virtual machine that JIT-compiles IL to machine code and manages memory with the garbage collector.
  2. What is managed code?
    Code that runs under the CLR, so memory, security and exceptions are managed by the runtime.
2 Index
Value typeReference type
Stores the data itselfStores a reference (address) to the data
int, double, bool, char, struct, enumclass, string, array, interface, delegate
Usually on the stackObject lives on the heap
Assignment copies the valueAssignment copies the reference (both point to the same object)

Copying a value type vs copying a reference

Copying a value type vs copying a reference

C# 9 lines
int a = 10;
int b = a;
b = 20;
Console.WriteLine(a);   // 10

var p1 = new Person { Name = "Rahim" };
var p2 = p1;
p2.Name = "Karim";
Console.WriteLine(p1.Name);   // Karim

Boxing = value type → object (heap). Unboxing = object → value type. string is a reference type but immutable.

3 Index
C# 24 lines
public class Student
{
    public string Name { get; set; }            // auto-property
    private int _age;
    public int Age                              // property with validation
    {
        get => _age;
        set => _age = value >= 0 ? value : 0;
    }
    public static int Count { get; private set; }

    public Student(string name, int age)        // constructor
    {
        Name = name;
        Age = age;
        Count++;
    }

    public override string ToString() => $"{Name} ({Age})";
}

var s = new Student("Rahim", 21);
Console.WriteLine(s);                 // Rahim (21)
Console.WriteLine(Student.Count);     // 1
  • Access modifiers: public, private (default for members), protected, internal (same assembly), protected internal.
  • readonly fields can be set only in the constructor; const is a compile-time constant.
  • struct is a value type; record gives value-based equality for data classes.
4 Index

C# supports single class inheritance but a class can implement many interfaces. Use virtual + override for polymorphism, abstract for methods without a body, sealed to stop further inheritance.

C# 25 lines
public interface IShape { double Area(); }

public abstract class Shape : IShape
{
    public abstract double Area();
    public virtual string Describe() => $"Area = {Area():F2}";
}

public class Circle : Shape
{
    public double R { get; }
    public Circle(double r) => R = r;
    public override double Area() => Math.PI * R * R;
}

public sealed class Square : Shape
{
    public double A { get; }
    public Square(double a) => A = a;
    public override double Area() => A * A;
    public override string Describe() => "Square, " + base.Describe();
}

List<Shape> shapes = new() { new Circle(2), new Square(3) };
foreach (var s in shapes) Console.WriteLine(s.Describe());
5 Index
CollectionUse
List<T>Dynamic array
Dictionary<K,V>Key → value (hash table)
HashSet<T>Unique items
Queue<T> / Stack<T>FIFO / LIFO
Array (T[])Fixed size
C# 11 lines
var nums = new List<int> { 5, 2, 8 };
nums.Add(1);
nums.Sort();                       // 1 2 5 8

var ages = new Dictionary<string, int>();
ages["Rahim"] = 25;
if (ages.TryGetValue("Rahim", out int age))
    Console.WriteLine(age);

// generic method
static T Max<T>(T a, T b) where T : IComparable<T> => a.CompareTo(b) > 0 ? a : b;
6 Index

LINQ (Language Integrated Query) lets you filter, sort and transform collections (and databases through Entity Framework) with SQL-like methods.

C# 16 lines
var students = new List<Student> {
    new("Rahim", 21), new("Karim", 19), new("Sumi", 23)
};

var adults = students
    .Where(s => s.Age >= 20)
    .OrderBy(s => s.Name)
    .Select(s => s.Name)
    .ToList();                         // Rahim, Sumi

double avg = students.Average(s => s.Age);
var first = students.FirstOrDefault(s => s.Name.StartsWith("K"));
var groups = students.GroupBy(s => s.Age >= 20);

// query syntax
var q = from s in students where s.Age > 20 select s.Name;

LINQ uses deferred execution: the query runs only when you enumerate it (foreach, ToList, Count ...).

7 Index
C# 19 lines
try
{
    int x = int.Parse("abc");
}
catch (FormatException ex)
{
    Console.WriteLine("Invalid number: " + ex.Message);
}
catch (Exception ex)
{
    Console.WriteLine("Other error: " + ex.Message);
}
finally
{
    Console.WriteLine("Always runs");   // cleanup
}

// using disposes the object automatically (calls Dispose)
using var reader = new StreamReader("data.txt");

Catch specific exceptions first. Use throw; (not throw ex;) to re-throw and keep the stack trace.

8 Index

A delegate is a type-safe function pointer. Func<> returns a value, Action<> returns void, Predicate<T> returns bool. An event is a delegate that others can subscribe to.

C# 13 lines
Func<int, int, int> add = (a, b) => a + b;
Action<string> log = msg => Console.WriteLine(msg);
log(add(2, 3).ToString());     // 5

public class Button
{
    public event Action? Clicked;
    public void Click() => Clicked?.Invoke();
}

var btn = new Button();
btn.Clicked += () => Console.WriteLine("Button clicked");
btn.Click();
9 Index

async/await runs slow I/O work (web calls, files, database) without blocking the thread. An async method returns Task or Task<T>.

C# 11 lines
public async Task<string> DownloadAsync(string url)
{
    using var client = new HttpClient();
    string html = await client.GetStringAsync(url);   // thread is free while waiting
    return html;
}

// run several tasks at the same time
var t1 = DownloadAsync("https://a.com");
var t2 = DownloadAsync("https://b.com");
string[] pages = await Task.WhenAll(t1, t2);

Avoid .Result / .Wait() on tasks: they block and can deadlock.

10 Index

The GC frees heap objects that are no longer referenced. It is generational: Gen 0 (new, collected often), Gen 1, Gen 2 (long-lived). Large objects (> 85 KB) go to the Large Object Heap.

Unmanaged resources (files, sockets, DB connections) are not handled by the GC: implement IDisposable and use using.

11 Index
KeywordMeaning
varType inferred at compile time (still strongly typed)
dynamicType checked at run time
ref / out / inPass by reference; out must be assigned inside; in is read-only
staticBelongs to the class, not an object
sealedClass cannot be inherited
partialClass split across files
?? / ?.Null-coalescing / null-conditional operators
is / asType check / safe cast (null if it fails)
C# 5 lines
string? name = null;
Console.WriteLine(name?.Length ?? 0);   // 0

void Divide(int a, int b, out int q, out int r) { q = a / b; r = a % b; }
Divide(17, 5, out int q, out int r);    // q = 3, r = 2