Back Back

C# Programming Language

C# (pronounced "C-sharp") is a modern, object-oriented programming language developed by Microsoft in 2000. Designed for the .NET framework, C# is versatile, supporting web (ASP.NET), desktop (Windows Forms, WPF), mobile (Xamarin), cloud (Azure), and game development (Unity). It emphasizes type safety, simplicity, and productivity.

Origin

Introduced in 2000 by Microsoft, led by Anders Hejlsberg, as part of .NET.

Features

OOP, type safety, garbage collection, LINQ, async/await, cross-platform (.NET).

Applications

Web apps, desktop apps, Unity games, cloud services, mobile apps.

Why Learn C#?

Did You Know?

C# powers Unity-based games like Hollow Knight, Among Us, and enterprise apps like Stack Overflow.

How C# Was Developed

C# was created by Microsoft to address limitations in C++ and Java for the .NET framework. Led by Anders Hejlsberg (creator of Turbo Pascal and Delphi), the team aimed for a language that combined C++'s power with Java's simplicity and safety.

  • 2000: C# 1.0 released with .NET Framework, focusing on OOP and Windows development.
  • 2005: C# 2.0 introduced generics, enhancing type safety and performance.
  • 2008: C# 3.0 added LINQ and lambda expressions for data querying.
  • 2010: C# 4.0 brought dynamic typing and improved COM interoperability.
  • 2015: C# 6.0 and .NET Core enabled cross-platform development.
  • 2020+: C# 9.0+ introduced records, init-only properties, and enhanced performance.

C# evolved to support modern paradigms, with .NET (formerly .NET Core) making it cross-platform. Its open-source nature via GitHub fosters community contributions.

Advantages and Disadvantages of C#

Advantages

  • Simplified Syntax: Easy to learn with garbage collection.
  • Cross-Platform: .NET supports Windows, macOS, Linux, Android, iOS.
  • Unity Integration: Industry standard for game development.
  • Robust Ecosystem: Extensive .NET libraries, ASP.NET, Xamarin, EF Core.
  • Type Safety: Prevents common errors, enhancing reliability.
  • Community Support: Large community, open-source .NET, Microsoft backing.

Disadvantages

  • Performance: Slower than C++ for low-level tasks due to garbage collection.
  • Platform Dependency: Historically Windows-focused; .NET mitigates but adds complexity.
  • Learning Curve: Advanced features (LINQ, async/await) complex for beginners.
  • Licensing Costs: Some tools (e.g., Visual Studio Enterprise) are costly, though free options exist.
  • Less Control: Limited low-level access compared to C++.

Data Types and Variables

Value Types

Store data directly (e.g., integers, floats, structs).

Type Size (bytes) Description
int 4 Integer
float 4 Single-precision float
double 8 Double-precision float
char 2 Unicode character
bool 1 True/false
using System;

class Program {
    static void Main() {
        int age = 25;
        float height = 5.9f;
        char grade = 'A';
        bool isStudent = true;
        Console.WriteLine($"Age: {age}, Height: {height}, Grade: {grade}, Student: {isStudent}");
    }
}

Tip: Use var for implicit typing, e.g., var x = 10;.

Reference Types

Store references to data (e.g., strings, arrays, objects).

using System;

class Program {
    static void Main() {
        string name = "Alice";
        int[] scores = {90, 85, 88};
        Console.WriteLine($"Name: {name}, First Score: {scores[0]}");
    }
}

Tip: Use nullable types (e.g., int?) for optional values.

Operators

Arithmetic

Perform mathematical operations.

using System;

class Program {
    static void Main() {
        int a = 10, b = 3;
        Console.WriteLine($"Sum: {a + b}, Mod: {a % b}");
    }
}

Relational & Logical

Compare values or combine conditions.

using System;

class Program {
    static void Main() {
        int x = 5, y = 10;
        if (x < y && x > 0) {
            Console.WriteLine("Condition met");
        }
    }
}

Null-Coalescing

Handle null values efficiently.

using System;

class Program {
    static void Main() {
        string name = null;
        string result = name ?? "Unknown";
        Console.WriteLine(result);
    }
}

Control Flow

if-else

Conditional execution.

using System;

class Program {
    static void Main() {
        int num = 10;
        if (num > 0) {
            Console.WriteLine("Positive");
        } else if (num < 0) {
            Console.WriteLine("Negative");
        } else {
            Console.WriteLine("Zero");
        }
    }
}

switch

Multi-way branching.

using System;

class Program {
    static void Main() {
        int day = 3;
        switch (day) {
            case 1:
                Console.WriteLine("Monday");
                break;
            case 3:
                Console.WriteLine("Wednesday");
                break;
            default:
                Console.WriteLine("Other day");
                break;
        }
    }
}

for Loop

Iterate with a counter.

using System;

class Program {
    static void Main() {
        for (int i = 1; i <= 5; i++) {
            Console.WriteLine(i);
        }
    }
}

while Loop

Repeat while condition is true.

using System;

class Program {
    static void Main() {
        int i = 1;
        while (i <= 5) {
            Console.WriteLine(i);
            i++;
        }
    }
}

foreach Loop

Iterate over collections.

using System;

class Program {
    static void Main() {
        int[] numbers = {1, 2, 3, 4, 5};
        foreach (int num in numbers) {
            Console.WriteLine(num);
        }
    }
}

Methods

Method Basics

Encapsulate reusable logic.

using System;

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

    static void Main() {
        Console.WriteLine($"Sum: {Add(5, 3)}");
    }
}

Tip: Use out or ref for modifying arguments.

Method Overloading

Same name, different signatures.

using System;

class Program {
    static int Add(int a, int b) => a + b;
    static double Add(double a, double b) => a + b;

    static void Main() {
        Console.WriteLine($"Int: {Add(5, 3)}, Double: {Add(5.5, 3.3)}");
    }
}

Arrays and Collections

Arrays

Fixed-size collections.

using System;

class Program {
    static void Main() {
        int[] arr = {1, 2, 3, 4, 5};
        foreach (int num in arr) {
            Console.WriteLine(num);
        }
    }
}

List

Dynamic collections.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        List numbers = new List {1, 2, 3};
        numbers.Add(4);
        foreach (int num in numbers) {
            Console.WriteLine(num);
        }
    }
}

Object-Oriented Programming

Classes and Objects

Blueprints for objects.

using System;

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

    public void Introduce() {
        Console.WriteLine($"Hi, I'm {Name}, {Age} years old.");
    }
}

class Program {
    static void Main() {
        Person p = new Person { Name = "Alice", Age = 25 };
        p.Introduce();
    }
}

Tip: Use properties for encapsulation.

Inheritance

Extend base classes.

using System;

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

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

class Program {
    static void Main() {
        Dog d = new Dog();
        d.Speak();
    }
}

Exception Handling

Try-Catch

Handle errors gracefully.

using System;

class Program {
    static void Main() {
        try {
            int x = 10, y = 0;
            Console.WriteLine(x / y);
        } catch (DivideByZeroException ex) {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

Custom Exceptions

Application-specific exceptions.

using System;

class CustomException : Exception {
    public CustomException(string message) : base(message) {}
}

class Program {
    static void Main() {
        try {
            throw new CustomException("Something went wrong");
        } catch (CustomException ex) {
            Console.WriteLine(ex.Message);
        }
    }
}

LINQ

Querying Collections

SQL-like querying for data.

using System;
using System.Linq;
using System.Collections.Generic;

class Program {
    static void Main() {
        List numbers = new List {1, 2, 3, 4, 5};
        var even = from num in numbers
                   where num % 2 == 0
                   select num;
        foreach (int num in even) {
            Console.WriteLine(num);
        }
    }
}

Tip: Use method syntax (e.g., numbers.Where(n => n % 2 == 0)) for concise queries.

Async/Await

Asynchronous Programming

Responsive apps with async operations.

using System;
using System.Threading.Tasks;

class Program {
    static async Task Main() {
        await Task.Delay(1000);
        Console.WriteLine("Task completed after 1 second");
    }
}

Tip: Use async Task for I/O operations.

Delegates and Events

Delegates

Type-safe function pointers.

using System;

delegate void MyDelegate(string message);

class Program {
    static void PrintMessage(string message) {
        Console.WriteLine(message);
    }

    static void Main() {
        MyDelegate del = PrintMessage;
        del("Hello, Delegate!");
    }
}

Events

Publisher-subscriber model.

using System;

class Publisher {
    public event EventHandler OnMessage;

    public void SendMessage(string msg) {
        OnMessage?.Invoke(this, msg);
    }
}

class Program {
    static void Main() {
        Publisher pub = new Publisher();
        pub.OnMessage += (sender, msg) => Console.WriteLine($"Received: {msg}");
        pub.SendMessage("Hello, Event!");
    }
}

File Handling

Writing to Files

Write data to files.

using System;
using System.IO;

class Program {
    static void Main() {
        File.WriteAllText("example.txt", "Hello, C#!");
        Console.WriteLine("File written");
    }
}

Reading from Files

Read data from files.

using System;
using System.IO;

class Program {
    static void Main() {
        if (File.Exists("example.txt")) {
            string content = File.ReadAllText("example.txt");
            Console.WriteLine(content);
        }
    }
}

ASP.NET Framework

Building Web Applications

ASP.NET is a framework for building scalable web applications, APIs, and microservices using C# and .NET. It includes ASP.NET Core for cross-platform web development.

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class HelloController : ControllerBase {
    [HttpGet]
    public IActionResult Get() {
        return Ok("Hello, ASP.NET Core!");
    }
}

Tip: Use ASP.NET Core for modern, cross-platform web apps. Install via dotnet new webapi.

MVC Example

Create a simple MVC web app.

using Microsoft.AspNetCore.Mvc;

public class HomeController : Controller {
    public IActionResult Index() {
        ViewBag.Message = "Welcome to ASP.NET MVC!";
        return View();
    }
}

// Views/Home/Index.cshtml
@{
    ViewData["Title"] = "Home Page";
}

@ViewBag.Message

Tip: Use Razor Pages for simpler web apps or Blazor for interactive UI.

Windows Forms Applications

Building Desktop GUIs

Windows Forms is a framework for creating desktop applications with graphical user interfaces using C#.

using System;
using System.Windows.Forms;

class Program {
    static void Main() {
        Application.Run(new MyForm());
    }
}

class MyForm : Form {
    public MyForm() {
        Button btn = new Button {
            Text = "Click Me",
            Location = new System.Drawing.Point(100, 50)
        };
        btn.Click += (s, e) => MessageBox.Show("Hello, Windows Forms!");
        Controls.Add(btn);
    }
}

Tip: Use Visual Studio’s Form Designer for drag-and-drop UI creation.

Note: For modern desktop apps, consider WPF or .NET MAUI.

Try our recommended online C# compiler:

Open C# Compiler

Download Basic C# Notes

View PDF Notes Download PDF Notes

C# Programming Quiz

Test Your Knowledge

Answer these questions to reinforce your C# skills.

1. What is the output?

using System;

class Program {
    static void Main() {
        int x = 5;
        Console.WriteLine(x++ + " " + ++x);
    }
}

Answer: 5 7

Explanation: x++ outputs 5, increments to 6; ++x increments to 7, outputs 7.

2. What does this LINQ query do?

using System.Linq;

var result = from n in new[] {1, 2, 3, 4}
             where n > 2
             select n;

Answer: Selects numbers > 2

Explanation: Returns {3, 4}.

3. What is wrong with this code?

using System;

class Program {
    static void Main() {
        int[] arr = new int[3];
        Console.WriteLine(arr[3]);
    }
}

Answer: Index out-of-range exception

Explanation: Indices are 0–2.

4. What is the output?

using System;

class Animal {
    public virtual void Speak() => Console.WriteLine("Animal");
}

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

class Program {
    static void Main() {
        Animal a = new Dog();
        a.Speak();
    }
}

Answer: Woof

Explanation: Polymorphism calls overridden method.

5. What does this async code do?

using System;
using System.Threading.Tasks;

class Program {
    static async Task Main() {
        await Task.Delay(1000);
        Console.WriteLine("Done");
    }
}

Answer: Prints "Done" after 1 second

Explanation: await Task.Delay(1000) pauses for 1 second.

6. What is the purpose of this delegate?

using System;

delegate void MyDelegate(string message);

class Program {
    static void PrintMessage(string message) {
        Console.WriteLine(message);
    }

    static void Main() {
        MyDelegate del = PrintMessage;
        del("Hello, Delegate!");
    }
}

Answer: Calls a method via a function pointer

Explanation: Delegates allow methods to be passed as parameters.

7. What does this event code do?

using System;

class Publisher {
    public event EventHandler OnMessage;

    public void SendMessage(string msg) {
        OnMessage?.Invoke(this, msg);
    }
}

class Program {
    static void Main() {
        Publisher pub = new Publisher();
        pub.OnMessage += (sender, msg) => Console.WriteLine($"Received: {msg}");
        pub.SendMessage("Hello, Event!");
    }
}

Answer: Triggers a subscriber method

Explanation: Events enable a publisher-subscriber pattern for notifications.