Learn C# - 78 Code Examples & CST Typing Practice Test
C# (C-Sharp) is a modern, object-oriented, multi-paradigm programming language built by Microsoft for the .NET platform. It is designed for productivity, type safety, performance, and building scalable applications across desktop, web, mobile, gaming, and cloud systems.
View all 78 C# code examples →
Learn CSHARP with Real Code Examples
Updated Nov 17, 2025
Code Sample Descriptions
C# LINQ and Properties
using System;
using System.Collections.Generic;
using System.Linq;
public class Person {
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
}
class Program {
static void Main() {
var people = new List<Person> {
new Person { Name = "Alice", Age = 25, City = "New York" },
new Person { Name = "Bob", Age = 30, City = "London" },
new Person { Name = "Charlie", Age = 35, City = "New York" }
};
var adults = people
.Where(p => p.Age >= 30)
.OrderBy(p => p.Name)
.Select(p => new { p.Name, p.Age })
.ToList();
foreach (var person in adults) {
Console.WriteLine($"{person.Name} is {person.Age} years old");
}
}
}
Shows modern C# features including LINQ, auto-properties, and string interpolation.
Basic Class and Object
using System;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public void Introduce()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}
class Program
{
static void Main()
{
Person person = new Person();
person.Name = "Alice";
person.Age = 25;
person.Introduce();
}
}
Create a class, define properties and methods, create an object and access its members.
Student Management System
using System;
public class Student
{
private string studentId;
public string Name { get; set; }
public int Age { get; set; }
public Student(string studentId, string name, int age)
{
this.studentId = studentId;
Name = name;
Age = age;
}
public void DisplayInfo()
{
Console.WriteLine($"ID: {studentId}");
Console.WriteLine($"Name: {Name}");
Console.WriteLine($"Age: {Age}");
}
}
class Program
{
static void Main()
{
Student student = new Student("S101", "Alice", 20);
student.DisplayInfo();
}
}
Store and display student information using a class with fields, properties, methods, and a constructor.
Constructor Demonstration
using System;
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
public Employee()
{
Name = "Unknown";
Age = 0;
}
public Employee(string name, int age)
{
this.Name = name;
this.Age = age;
}
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, Age: {Age}");
}
}
class Program
{
static void Main()
{
Employee employee1 = new Employee();
Employee employee2 = new Employee("Alice", 28);
employee1.DisplayInfo();
employee2.DisplayInfo();
}
}
Demonstrates default constructors, parameterized constructors, constructor overloading, object creation, and the use of the this keyword.
Property Example
using System;
public class BankAccount
{
private decimal balance;
public decimal Balance
{
get { return balance; }
set
{
if (value >= 0)
{
balance = value;
}
}
}
}
class Program
{
static void Main()
{
BankAccount account = new BankAccount();
account.Balance = 1000;
Console.WriteLine($"Current Balance: {account.Balance}");
}
}
Demonstrates properties with getters and setters, using a private backing field to control access to data.
Method Overloading
using System;
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
public int Add(int a, int b, int c)
{
return a + b + c;
}
public double Add(double a, double b)
{
return a + b;
}
}
class Program
{
static void Main()
{
Calculator calculator = new Calculator();
Console.WriteLine(calculator.Add(5, 10));
Console.WriteLine(calculator.Add(5, 10, 15));
Console.WriteLine(calculator.Add(2.5, 3.7));
}
}
Demonstrates method overloading by creating multiple methods with the same name but different parameter lists and return types.
Array Operations
using System;
class Program
{
static void Main()
{
int[] numbers = { 10, 20, 30, 40, 50 };
Console.WriteLine("Using for loop:");
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine($"Index {i}: {numbers[i]}");
}
Console.WriteLine("\nUsing foreach loop:");
foreach (int num in numbers)
{
Console.WriteLine(num);
}
}
}
Stores multiple values in an array and performs basic operations using loops, indexing, and array properties.
Multidimensional Array
using System;
class Program
{
static void Main()
{
int[,] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j] + "\t");
}
Console.WriteLine();
}
}
}
Demonstrates working with a 2D array (matrix) using nested loops and array indexing.
Jagged Array
using System;
class Program
{
static void Main()
{
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2 };
jaggedArray[1] = new int[] { 3, 4, 5 };
jaggedArray[2] = new int[] { 6 };
for (int i = 0; i < jaggedArray.Length; i++)
{
for (int j = 0; j < jaggedArray[i].Length; j++)
{
Console.Write(jaggedArray[i][j] + "\t");
}
Console.WriteLine();
}
}
}
Demonstrates a jagged array (array of arrays) where each row can have different lengths, accessed using nested loops.
String Manipulation
using System;
class Program
{
static void Main()
{
string text = "Hello World from CSharp";
Console.WriteLine("Length: " + text.Length);
Console.WriteLine("Substring: " + text.Substring(6, 5));
string[] words = text.Split(' ');
Console.WriteLine("Split words:");
foreach (string word in words)
{
Console.WriteLine(word);
}
Console.WriteLine("Replace: " + text.Replace("World", "Universe"));
Console.WriteLine("Upper: " + text.ToUpper());
Console.WriteLine("Lower: " + text.ToLower());
}
}
Demonstrates common string operations such as length, substring, split, replace, and case conversion methods.
String Palindrome
using System;
class Program
{
static void Main()
{
string text = "madam";
bool isPalindrome = true;
for (int i = 0, j = text.Length - 1; i < j; i++, j--)
{
if (text[i] != text[j])
{
isPalindrome = false;
break;
}
}
if (isPalindrome)
{
Console.WriteLine("Palindrome");
}
else
{
Console.WriteLine("Not Palindrome");
}
}
}
Checks whether a given string is a palindrome by comparing characters from both ends using loop and conditional logic.
Indexer Example
using System;
public class SampleCollection
{
private string[] data = new string[5];
public string this[int index]
{
get
{
return data[index];
}
set
{
data[index] = value;
}
}
}
class Program
{
static void Main()
{
SampleCollection collection = new SampleCollection();
collection[0] = "Apple";
collection[1] = "Banana";
collection[2] = "Mango";
for (int i = 0; i < 3; i++)
{
Console.WriteLine(collection[i]);
}
}
}
Demonstrates the use of an indexer to provide array-like access to class elements using this[] syntax.
Single Inheritance
using System;
public class Animal
{
public string Name { get; set; }
public void Eat()
{
Console.WriteLine(Name + " is eating.");
}
}
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine(Name + " is barking.");
}
}
class Program
{
static void Main()
{
Dog dog = new Dog();
dog.Name = "Buddy";
dog.Eat();
dog.Bark();
}
}
Demonstrates single inheritance where a derived class inherits properties and methods from a base class.
Base Keyword Example
using System;
public class Person
{
public string Name;
public Person(string name)
{
Name = name;
}
public void Show()
{
Console.WriteLine("Name: " + Name);
}
}
public class Student : Person
{
public int RollNo;
public Student(string name, int rollNo) : base(name)
{
RollNo = rollNo;
}
public void Display()
{
base.Show();
Console.WriteLine("Roll No: " + RollNo);
}
}
class Program
{
static void Main()
{
Student student = new Student("Alice", 101);
student.Display();
}
}
Demonstrates the use of the base keyword to access parent class constructor and methods in an inheritance hierarchy.
Method Hiding
using System;
public class BaseClass
{
public void Show()
{
Console.WriteLine("Base class method");
}
}
public class DerivedClass : BaseClass
{
public new void Show()
{
Console.WriteLine("Derived class method");
}
}
class Program
{
static void Main()
{
BaseClass obj1 = new BaseClass();
obj1.Show();
DerivedClass obj2 = new DerivedClass();
obj2.Show();
BaseClass obj3 = new DerivedClass();
obj3.Show(); // Calls base class method due to method hiding
}
}
Demonstrates method hiding using the new keyword where a derived class hides a base class method with its own implementation.
Method Overriding
using System;
public class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal makes a sound");
}
}
public class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Dog barks");
}
}
class Program
{
static void Main()
{
Animal a1 = new Animal();
Animal a2 = new Dog();
a1.Speak();
a2.Speak();
}
}
Demonstrates method overriding using virtual and override keywords to achieve runtime polymorphism.
Polymorphism Example
using System;
public class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing Shape");
}
}
public class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing Circle");
}
}
public class Rectangle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing Rectangle");
}
}
class Program
{
static void Main()
{
Shape s1 = new Circle();
Shape s2 = new Rectangle();
s1.Draw();
s2.Draw();
}
}
Demonstrates runtime polymorphism where a base class reference is used to invoke overridden methods in different derived classes.
Abstract Class Example
using System;
public abstract class Animal
{
public abstract void MakeSound();
public void Sleep()
{
Console.WriteLine("Sleeping...");
}
}
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Dog barks");
}
}
class Program
{
static void Main()
{
Animal animal = new Dog();
animal.MakeSound();
animal.Sleep();
}
}
Demonstrates abstraction using an abstract class with abstract and concrete methods implemented by derived classes.
Interface Example
using System;
public interface IAnimal
{
void Speak();
}
public class Dog : IAnimal
{
public void Speak()
{
Console.WriteLine("Dog barks");
}
}
public class Cat : IAnimal
{
public void Speak()
{
Console.WriteLine("Cat meows");
}
}
class Program
{
static void Main()
{
IAnimal a1 = new Dog();
IAnimal a2 = new Cat();
a1.Speak();
a2.Speak();
}
}
Demonstrates the use of an interface to define a contract that multiple classes implement with their own behavior.
Multiple Interface Implementation
using System;
public interface IPrinter
{
void Print();
}
public interface IScanner
{
void Scan();
}
public class MultiFunctionDevice : IPrinter, IScanner
{
public void Print()
{
Console.WriteLine("Printing document");
}
public void Scan()
{
Console.WriteLine("Scanning document");
}
}
class Program
{
static void Main()
{
MultiFunctionDevice device = new MultiFunctionDevice();
device.Print();
device.Scan();
}
}
Demonstrates implementing multiple interfaces in a single class to achieve multiple inheritance-like behavior in C#.
Struct Example
using System;
public struct Point
{
public int X;
public int Y;
public void Display()
{
Console.WriteLine($"Point: ({X}, {Y})");
}
}
class Program
{
static void Main()
{
Point p;
p.X = 10;
p.Y = 20;
p.Display();
}
}
Demonstrates the use of a struct as a lightweight value type with fields and methods.
Enum Example
using System;
public enum Days
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
class Program
{
static void Main()
{
Days today = Days.Monday;
Console.WriteLine("Today: " + today);
Console.WriteLine("Numeric value: " + (int)today);
switch (today)
{
case Days.Monday:
Console.WriteLine("Start of work week");
break;
case Days.Friday:
Console.WriteLine("Weekend is near");
break;
default:
Console.WriteLine("Regular day");
break;
}
}
}
Demonstrates the use of enums to represent a fixed set of constants along with casting and switch statement usage.
Delegate Example
using System;
public delegate void Operation(int a, int b);
class Program
{
static void Add(int a, int b)
{
Console.WriteLine("Sum: " + (a + b));
}
static void Multiply(int a, int b)
{
Console.WriteLine("Product: " + (a * b));
}
static void Main()
{
Operation op;
op = Add;
op(5, 10);
op = Multiply;
op(5, 10);
}
}
Demonstrates the use of delegates to store and invoke method references for achieving loose coupling.
Event Example
using System;
public class Publisher
{
public event Action OnChange;
public void RaiseEvent()
{
Console.WriteLine("Event triggered");
OnChange?.Invoke();
}
}
class Program
{
static void Handler1()
{
Console.WriteLine("Handler 1 executed");
}
static void Handler2()
{
Console.WriteLine("Handler 2 executed");
}
static void Main()
{
Publisher pub = new Publisher();
pub.OnChange += Handler1;
pub.OnChange += Handler2;
pub.RaiseEvent();
}
}
Demonstrates the use of events and delegates to notify subscribers when an action occurs (observer pattern).
Partial Class Example
using System;
public partial class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public partial class Employee
{
public void DisplayFullName()
{
Console.WriteLine($"Full Name: {FirstName} {LastName}");
}
}
class Program
{
static void Main()
{
Employee emp = new Employee();
emp.FirstName = "John";
emp.LastName = "Doe";
emp.DisplayFullName();
}
}
Demonstrates partial classes where a single class definition is split into multiple parts for better organization.
Generic Class
using System;
public class Box<T>
{
private T value;
public void SetValue(T value)
{
this.value = value;
}
public T GetValue()
{
return value;
}
}
class Program
{
static void Main()
{
Box<int> intBox = new Box<int>();
intBox.SetValue(100);
Console.WriteLine("Integer: " + intBox.GetValue());
Box<string> strBox = new Box<string>();
strBox.SetValue("Hello Generics");
Console.WriteLine("String: " + strBox.GetValue());
}
}
Demonstrates a generic class using type parameter <T> to create reusable and type-safe code.
Generic Method
using System;
class Program
{
static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
static void Main()
{
int x = 10, y = 20;
Swap(ref x, ref y);
Console.WriteLine($"x = {x}, y = {y}");
string s1 = "Hello", s2 = "World";
Swap(ref s1, ref s2);
Console.WriteLine($"s1 = {s1}, s2 = {s2}");
}
}
Demonstrates a generic method that can work with different data types using type parameter <T>.
List Collection
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> fruits = new List<string>();
fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Mango");
Console.WriteLine("Count: " + fruits.Count);
fruits.Remove("Banana");
Console.WriteLine("After removal:");
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
}
}
Demonstrates the use of List<T> for storing dynamic data with add, remove, and count operations.
Dictionary Collection
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<int, string> students = new Dictionary<int, string>();
students.Add(1, "Alice");
students.Add(2, "Bob");
students.Add(3, "Charlie");
Console.WriteLine("Student with ID 2: " + students[2]);
Console.WriteLine("All Students:");
foreach (var item in students)
{
Console.WriteLine($"ID: {item.Key}, Name: {item.Value}");
}
}
}
Demonstrates the use of Dictionary<TKey, TValue> to store and retrieve key-value pairs with add and lookup operations.
Stack Collection
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Stack<int> stack = new Stack<int>();
stack.Push(10);
stack.Push(20);
stack.Push(30);
Console.WriteLine("Top Element (Peek): " + stack.Peek());
Console.WriteLine("Popped: " + stack.Pop());
Console.WriteLine("Popped: " + stack.Pop());
Console.WriteLine("Remaining Stack Count: " + stack.Count);
}
}
Demonstrates the use of Stack<T> for LIFO (Last In First Out) operations using push, pop, and peek methods.
Queue Collection
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Queue<string> queue = new Queue<string>();
queue.Enqueue("Alice");
queue.Enqueue("Bob");
queue.Enqueue("Charlie");
Console.WriteLine("Front Element (Peek): " + queue.Peek());
Console.WriteLine("Removed: " + queue.Dequeue());
Console.WriteLine("Removed: " + queue.Dequeue());
Console.WriteLine("Remaining Count: " + queue.Count);
}
}
Demonstrates the use of Queue<T> for FIFO (First In First Out) operations using enqueue and dequeue methods.
File Write Program
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "output.txt";
try
{
using (StreamWriter writer = new StreamWriter(path))
{
writer.WriteLine("Hello, File Handling in C#");
writer.WriteLine("Writing data to a file.");
}
Console.WriteLine("File written successfully.");
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
Demonstrates writing data to a file using StreamWriter with basic exception handling.
File Read Program
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "output.txt";
try
{
using (StreamReader reader = new StreamReader(path))
{
string content = reader.ReadToEnd();
Console.WriteLine("File Content:");
Console.WriteLine(content);
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
Demonstrates reading data from a file using StreamReader with basic file handling in C#.
Exception Handling
using System;
class Program
{
static void Main()
{
try
{
int a = 10;
int b = 0;
if (b == 0)
{
throw new DivideByZeroException("Cannot divide by zero");
}
int result = a / b;
Console.WriteLine("Result: " + result);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General Error: " + ex.Message);
}
finally
{
Console.WriteLine("Execution completed.");
}
}
}
Demonstrates exception handling in C# using try, catch, finally, and throw to manage runtime errors safely.
Custom Exception
using System;
public class InvalidAgeException : Exception
{
public InvalidAgeException(string message) : base(message)
{
}
}
class Program
{
static void ValidateAge(int age)
{
if (age < 18)
{
throw new InvalidAgeException("Age must be 18 or above.");
}
Console.WriteLine("Valid Age");
}
static void Main()
{
try
{
ValidateAge(15);
}
catch (InvalidAgeException ex)
{
Console.WriteLine("Custom Error: " + ex.Message);
}
}
}
Demonstrates creating and using a user-defined custom exception by inheriting from the Exception class.
LINQ Query Syntax
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var evenNumbers = from num in numbers
where num % 2 == 0
select num;
Console.WriteLine("Even Numbers:");
foreach (var n in evenNumbers)
{
Console.WriteLine(n);
}
}
}
Demonstrates LINQ query syntax using from, where, and select clauses to filter and project data from a collection.
LINQ Method Syntax
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 5, 2, 8, 1, 9, 3, 6, 4, 7 };
var filtered = numbers.Where(n => n > 3);
var sorted = numbers.OrderBy(n => n);
var squared = numbers.Select(n => n * n);
var grouped = numbers.GroupBy(n => n % 2 == 0);
Console.WriteLine("Filtered (>3):");
foreach (var n in filtered)
{
Console.WriteLine(n);
}
Console.WriteLine("\nSorted:");
foreach (var n in sorted)
{
Console.WriteLine(n);
}
Console.WriteLine("\nSquared:");
foreach (var n in squared)
{
Console.WriteLine(n);
}
Console.WriteLine("\nGrouped (Even/Odd):");
foreach (var group in grouped)
{
Console.WriteLine(group.Key ? "Even" : "Odd");
foreach (var n in group)
{
Console.WriteLine(" " + n);
}
}
}
}
Demonstrates LINQ method syntax using Where, Select, OrderBy, and GroupBy for querying and transforming collections.
Lambda Expression
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
delegate int Operation(int x, int y);
static void Main()
{
// Lambda with delegate
Operation add = (x, y) => x + y;
Console.WriteLine("Sum: " + add(5, 10));
// Lambda with LINQ
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
var evens = numbers.Where(n => n % 2 == 0);
Console.WriteLine("Even Numbers:");
foreach (var n in evens)
{
Console.WriteLine(n);
}
}
}
Demonstrates lambda expressions using => operator with delegates and LINQ for concise functional-style operations.
Custom Attribute
using System;
[AttributeUsage(AttributeTargets.Class)]
public class InfoAttribute : Attribute
{
public string Description { get; }
public InfoAttribute(string description)
{
Description = description;
}
}
[Info("This is a sample user class with custom metadata")]
public class User
{
public string Name { get; set; }
}
class Program
{
static void Main()
{
Type type = typeof(User);
object[] attributes = type.GetCustomAttributes(typeof(InfoAttribute), false);
foreach (InfoAttribute attr in attributes)
{
Console.WriteLine("Metadata: " + attr.Description);
}
}
}
Demonstrates creating and applying a custom attribute to a class and retrieving it using reflection.
Async Await Program
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
Console.WriteLine("Start");
await DoWorkAsync();
Console.WriteLine("End");
}
static async Task DoWorkAsync()
{
Console.WriteLine("Work started...");
await Task.Delay(2000);
Console.WriteLine("Work completed after delay");
}
}
Demonstrates asynchronous programming in C# using async, await, and Task to run operations without blocking the main thread.
ADO.NET CRUD
using System;
using System.Data.SqlClient;
class Program
{
static string connectionString = "your_connection_string_here";
static void Main()
{
CreateRecord();
ReadRecords();
UpdateRecord();
DeleteRecord();
}
static void CreateRecord()
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
string query = "INSERT INTO Students (Name, Age) VALUES ('Alice', 20)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
}
}
static void ReadRecords()
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
string query = "SELECT * FROM Students";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader["Name"] + " - " + reader["Age"]);
}
}
}
static void UpdateRecord()
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
string query = "UPDATE Students SET Age = 25 WHERE Name = 'Alice'";
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
}
}
static void DeleteRecord()
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
string query = "DELETE FROM Students WHERE Name = 'Alice'";
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
}
}
}
Demonstrates basic ADO.NET CRUD operations using SqlConnection, SqlCommand, and SqlDataReader.
Entity Framework CRUD
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public class AppDbContext : DbContext
{
public DbSet<Student> Students { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseInMemoryDatabase("StudentDB");
}
}
class Program
{
static void Main()
{
using (var context = new AppDbContext())
{
// CREATE
context.Students.Add(new Student { Name = "Alice", Age = 20 });
context.SaveChanges();
// READ
var students = context.Students.ToList();
foreach (var s in students)
{
Console.WriteLine($"{s.Id} - {s.Name} - {s.Age}");
}
// UPDATE
var student = context.Students.First();
student.Age = 25;
context.SaveChanges();
// DELETE
context.Students.Remove(student);
context.SaveChanges();
}
}
}
Demonstrates CRUD operations using Entity Framework with DbContext, DbSet, and SaveChanges().
MVC Controller Example
using Microsoft.AspNetCore.Mvc;
namespace DemoApp.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return Content("Welcome to Home Page");
}
public IActionResult About()
{
return Content("About Page");
}
public IActionResult Details(int id)
{
return Content("Requested ID: " + id);
}
}
}
Demonstrates an ASP.NET MVC controller handling HTTP requests using action methods and IActionResult.
Razor View Example
using Microsoft.AspNetCore.Mvc;
namespace DemoApp.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
ViewBag.Message = "Hello from Controller";
return View();
}
}
}
@{
ViewData["Title"] = "Home Page";
}
<h1>@ViewBag.Message</h1>
<p>Current Time: @DateTime.Now</p>
Demonstrates Razor view syntax in ASP.NET MVC for rendering dynamic HTML using model binding.
Model Validation
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
public class User
{
[Required]
public string Name { get; set; }
[Range(18, 60)]
public int Age { get; set; }
}
public class UserController : Controller
{
[HttpPost]
public IActionResult Create(User user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
return Ok("User is valid");
}
}
Demonstrates model validation in ASP.NET using data annotations and ModelState to validate user input.
Web API Example
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace DemoApi.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private static List<string> products = new List<string> { "Laptop", "Phone", "Tablet" };
[HttpGet]
public IEnumerable<string> GetAll()
{
return products;
}
[HttpGet("{id}")]
public string GetById(int id)
{
return products[id];
}
[HttpPost]
public IActionResult Add(string product)
{
products.Add(product);
return Ok("Product added");
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
products.RemoveAt(id);
return Ok("Product deleted");
}
}
}
Demonstrates a simple ASP.NET Web API controller with REST endpoints using HTTP methods and route attributes.
Dependency Injection
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
public interface IMessageService
{
string GetMessage();
}
public class MessageService : IMessageService
{
public string GetMessage()
{
return "Hello from Dependency Injection";
}
}
public class HomeController : Controller
{
private readonly IMessageService _messageService;
public HomeController(IMessageService messageService)
{
_messageService = messageService;
}
public IActionResult Index()
{
return Content(_messageService.GetMessage());
}
}
// In Program.cs (for reference)
// builder.Services.AddScoped<IMessageService, MessageService>();
Demonstrates dependency injection in ASP.NET Core using interface-based service registration and constructor injection.
Session Management
using Microsoft.AspNetCore.Mvc;
public class AccountController : Controller
{
public IActionResult Login()
{
HttpContext.Session.SetString("Username", "Alice");
return Content("User logged in and session set");
}
public IActionResult Profile()
{
string username = HttpContext.Session.GetString("Username");
if (username == null)
{
return Content("No session found");
}
return Content("Welcome " + username);
}
}
Demonstrates session management in ASP.NET Core using HttpContext.Session to store and retrieve user data on the server.
Cookie Management
using Microsoft.AspNetCore.Mvc;
public class HomeController : Controller
{
public IActionResult SetCookie()
{
HttpContext.Response.Cookies.Append("Username", "Alice");
return Content("Cookie has been set");
}
public IActionResult GetCookie()
{
string username = HttpContext.Request.Cookies["Username"];
if (username == null)
{
return Content("No cookie found");
}
return Content("Welcome " + username);
}
}
Demonstrates cookie management in ASP.NET Core by setting and reading cookies using HttpContext request and response objects.
Authentication System
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity;
using System.Threading.Tasks;
public class AccountController : Controller
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly UserManager<IdentityUser> _userManager;
public AccountController(SignInManager<IdentityUser> signInManager, UserManager<IdentityUser> userManager)
{
_signInManager = signInManager;
_userManager = userManager;
}
public async Task<IActionResult> Login(string email, string password)
{
var user = await _userManager.FindByEmailAsync(email);
if (user == null)
{
return Content("User not found");
}
var result = await _signInManager.PasswordSignInAsync(user, password, false, false);
if (result.Succeeded)
{
return Content("Login successful");
}
return Content("Invalid credentials");
}
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
return Content("Logged out successfully");
}
}
Demonstrates a basic authentication system in ASP.NET Core using SignInManager and UserManager for login and logout functionality.
Authorization Example
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
public class AdminController : Controller
{
[Authorize(Roles = "Admin")]
public IActionResult Dashboard()
{
return Content("Welcome Admin Dashboard");
}
[Authorize(Policy = "RequireHRAccess")]
public IActionResult HRPanel()
{
return Content("Welcome HR Panel");
}
[Authorize]
public IActionResult Profile()
{
return Content("User Profile - Authenticated Users Only");
}
}
Demonstrates authorization in ASP.NET Core using roles, claims, policies, and the Authorize attribute to restrict access to endpoints.
Basic Language Constructs
using System;
class Program
{
static void Main()
{
// Variables and Data Types
int age = 25;
double price = 99.99;
string name = "Alice";
bool isActive = true;
// Constant
const float pi = 3.14f;
// Operators
int sum = age + 5;
// Type Casting
double converted = (double)age;
// Input
Console.WriteLine("Enter your name:");
string inputName = Console.ReadLine();
// Output
Console.WriteLine("Hello " + inputName);
Console.WriteLine($"Age: {age}, Price: {price}, PI: {pi}");
}
}
Demonstrates fundamental C# syntax including variables, data types, constants, operators, type casting, input/output, and comments.
Conditional Statements
using System;
class Program
{
static void Main()
{
int age = 20;
// if
if (age >= 18)
{
Console.WriteLine("Adult");
}
// if-else
if (age % 2 == 0)
Console.WriteLine("Even Age");
else
Console.WriteLine("Odd Age");
// nested if
if (age >= 13)
{
if (age < 18)
Console.WriteLine("Teenager");
}
// switch
switch (age)
{
case 10:
Console.WriteLine("Ten");
break;
case 20:
Console.WriteLine("Twenty");
break;
default:
Console.WriteLine("Other Age");
break;
}
// ternary
string result = (age >= 18) ? "Eligible" : "Not Eligible";
Console.WriteLine(result);
}
}
Demonstrates decision-making in C# using if, if-else, nested if, switch, and ternary operator.
Looping Statements
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// for loop
for (int i = 1; i <= 5; i++)
{
if (i == 3)
continue;
Console.WriteLine("For: " + i);
}
// while loop
int j = 1;
while (j <= 5)
{
if (j == 4)
break;
Console.WriteLine("While: " + j);
j++;
}
// do-while loop
int k = 1;
do
{
Console.WriteLine("DoWhile: " + k);
k++;
} while (k <= 3);
// foreach loop
List<string> items = new List<string> { "A", "B", "C" };
foreach (string item in items)
{
Console.WriteLine("Foreach: " + item);
}
}
}
Demonstrates looping constructs in C# including for, while, do-while, foreach, break, and continue statements.
Method Parameters
using System;
class Program
{
static void ModifyValue(int x)
{
x = x + 10;
}
static void ModifyRef(ref int x)
{
x = x + 10;
}
static void GetValues(out int a, out int b)
{
a = 10;
b = 20;
}
static int Sum(params int[] numbers)
{
int total = 0;
foreach (int n in numbers)
total += n;
return total;
}
static void Display(string name = "Guest")
{
Console.WriteLine("Hello " + name);
}
static void Main()
{
int num = 5;
ModifyValue(num);
Console.WriteLine("Value Parameter: " + num);
ModifyRef(ref num);
Console.WriteLine("Ref Parameter: " + num);
int a, b;
GetValues(out a, out b);
Console.WriteLine($"Out Parameters: {a}, {b}");
Console.WriteLine("Params Sum: " + Sum(1, 2, 3, 4));
Display();
Display("Alice");
}
}
Demonstrates different method parameter types in C# including value, ref, out, params, and optional parameters.
StringBuilder
using System;
using System.Text;
class Program
{
static void Main()
{
StringBuilder sb = new StringBuilder("Hello");
sb.Append(" World");
Console.WriteLine("After Append: " + sb);
sb.Insert(5, " CSharp");
Console.WriteLine("After Insert: " + sb);
sb.Remove(5, 7);
Console.WriteLine("After Remove: " + sb);
sb.Replace("World", "Universe");
Console.WriteLine("After Replace: " + sb);
}
}
Demonstrates efficient string manipulation using StringBuilder with append, insert, remove, and replace operations.
Collection Iteration
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
// foreach iteration
Console.WriteLine("Foreach iteration:");
foreach (int n in numbers)
{
Console.WriteLine(n);
}
// IEnumerator iteration
Console.WriteLine("\nIEnumerator iteration:");
IEnumerator enumerator = numbers.GetEnumerator();
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}
// IEnumerable (LINQ iteration)
Console.WriteLine("\nLINQ iteration:");
IEnumerable<int> filtered = numbers.Where(n => n > 2);
foreach (var n in filtered)
{
Console.WriteLine(n);
}
}
}
Demonstrates collection iteration in C# using IEnumerable, IEnumerator, foreach loop, and LINQ-based iteration.
Dependency Injection Lifetimes
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
public interface IGuidService
{
string GetId();
}
public class GuidService : IGuidService
{
private readonly string _id;
public GuidService()
{
_id = Guid.NewGuid().ToString();
}
public string GetId() => _id;
}
public class HomeController : Controller
{
private readonly IGuidService _service;
public HomeController(IGuidService service)
{
_service = service;
}
public IActionResult Index()
{
return Content("Service ID: " + _service.GetId());
}
}
// Program.cs registration examples
// builder.Services.AddSingleton<IGuidService, GuidService>();
// builder.Services.AddScoped<IGuidService, GuidService>();
// builder.Services.AddTransient<IGuidService, GuidService>();
Demonstrates dependency injection service lifetimes in ASP.NET Core including Singleton, Scoped, and Transient services.
Routing in ASP.NET Core
using Microsoft.AspNetCore.Mvc;
// Attribute Routing Example
[Route("products")]
public class ProductsController : Controller
{
// GET: /products
[HttpGet]
public IActionResult Index()
{
return Content("All Products");
}
// GET: /products/details/5
[HttpGet("details/{id}")]
public IActionResult Details(int id)
{
return Content("Product ID: " + id);
}
}
// Conventional Routing (Program.cs)
// app.MapControllerRoute(
// name: "default",
// pattern: "{controller=Home}/{action=Index}/{id?}");
Demonstrates routing in ASP.NET Core including conventional routing, attribute routing, and route parameters.
Action Result Types
using Microsoft.AspNetCore.Mvc;
public class DemoController : Controller
{
public IActionResult ViewExample()
{
return View(); // ViewResult
}
public IActionResult JsonExample()
{
return Json(new { Name = "Alice", Age = 25 }); // JsonResult
}
public IActionResult ContentExample()
{
return Content("Hello World"); // ContentResult
}
public IActionResult RedirectExample()
{
return Redirect("https://example.com"); // RedirectResult
}
public IActionResult FileExample()
{
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes("Sample File Content");
return File(fileBytes, "text/plain", "sample.txt"); // FileResult
}
}
Demonstrates different ASP.NET Core ActionResult types including ViewResult, JsonResult, ContentResult, RedirectResult, and FileResult.
Tag Helpers
using Microsoft.AspNetCore.Mvc;
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Details(int id)
{
return Content("ID: " + id);
}
}
/* Razor View: Index.cshtml */
@*
<a asp-controller="Home" asp-action="Details" asp-route-id="5">Go to Details</a>
<form asp-controller="Home" asp-action="Details" method="get">
<input type="text" name="id" />
<button type="submit">Submit</button>
</form>
*@
Demonstrates ASP.NET Core Tag Helpers for generating dynamic HTML using asp-controller, asp-action, asp-route, and form tag helpers.
Model Binding
using Microsoft.AspNetCore.Mvc;
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}
public class HomeController : Controller
{
// Form Binding
[HttpPost]
public IActionResult Create(User user)
{
return Content($"Form Binding: {user.Name}, {user.Age}");
}
// Query String Binding: /home/search?name=Alice
public IActionResult Search(string name)
{
return Content("Query Binding: " + name);
}
// Route Binding: /home/details/5
[HttpGet("details/{id}")]
public IActionResult Details(int id)
{
return Content("Route Binding ID: " + id);
}
}
Demonstrates ASP.NET Core model binding from form data, query strings, and route parameters into action method parameters and models.
JSON Serialization
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}
public class HomeController : Controller
{
public IActionResult SerializeExample()
{
User user = new User { Name = "Alice", Age = 25 };
string json = JsonSerializer.Serialize(user);
return Content(json, "application/json");
}
public IActionResult DeserializeExample()
{
string json = "{\"Name\":\"Bob\",\"Age\":30}";
User user = JsonSerializer.Deserialize<User>(json);
return Content($"Name: {user.Name}, Age: {user.Age}");
}
}
Demonstrates JSON serialization and deserialization in ASP.NET Core using System.Text.Json for API responses.
AJAX with jQuery
using Microsoft.AspNetCore.Mvc;
public class ApiController : Controller
{
[HttpGet]
public IActionResult GetMessage()
{
return Json(new { message = "Hello from server" });
}
[HttpPost]
public IActionResult PostData(string name)
{
return Json(new { message = "Received " + name });
}
}
/* Razor View (Index.cshtml) */
@*
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// GET AJAX
$.get("/api/getmessage", function (data) {
console.log(data.message);
});
// POST AJAX
$.post("/api/postdata", { name: "Alice" }, function (data) {
console.log(data.message);
});
</script>
*@
Demonstrates AJAX communication using jQuery to send GET and POST requests and receive JSON responses without page refresh.
Cache Management
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System;
public class CacheController : Controller
{
private readonly IMemoryCache _cache;
public CacheController(IMemoryCache cache)
{
_cache = cache;
}
public IActionResult SetCache()
{
_cache.Set("key1", "Cached Data", TimeSpan.FromMinutes(5));
return Content("Data Cached");
}
public IActionResult GetCache()
{
if (_cache.TryGetValue("key1", out string value))
{
return Content("Cache Hit: " + value);
}
return Content("Cache Miss");
}
}
Demonstrates caching in ASP.NET Core using IMemoryCache with data storage, retrieval, and expiration policies.
HttpContext
using Microsoft.AspNetCore.Mvc;
public class DemoController : Controller
{
public IActionResult Info()
{
string method = HttpContext.Request.Method;
string path = HttpContext.Request.Path;
string user = HttpContext.User?.Identity?.Name ?? "Anonymous";
HttpContext.Response.Headers.Add("Custom-Header", "HelloWorld");
HttpContext.Session.SetString("Key", "SessionValue");
string sessionValue = HttpContext.Session.GetString("Key");
return Content($"Method: {method}\nPath: {path}\nUser: {user}\nSession: {sessionValue}");
}
}
Demonstrates how to use HttpContext in ASP.NET Core to access request, response, user identity, and session data.
CRUD MVC Application
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Range(1, 10000)]
public decimal Price { get; set; }
}
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<Product> Products { get; set; }
}
public class ProductController : Controller
{
private readonly AppDbContext _context;
public ProductController(AppDbContext context)
{
_context = context;
}
public IActionResult Index()
{
List<Product> products = _context.Products.ToList();
return View(products);
}
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(Product product)
{
if (!ModelState.IsValid)
{
return View(product);
}
_context.Products.Add(product);
_context.SaveChanges();
return RedirectToAction("Index");
}
}
Demonstrates a complete ASP.NET Core MVC CRUD application using Entity Framework Core with model, view, controller, validation, routing, and dependency injection.
Authentication and Authorization Combined Project
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
public class AccountController : Controller
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly UserManager<IdentityUser> _userManager;
public AccountController(SignInManager<IdentityUser> signInManager, UserManager<IdentityUser> userManager)
{
_signInManager = signInManager;
_userManager = userManager;
}
public async Task<IActionResult> Login(string email, string password)
{
var user = await _userManager.FindByEmailAsync(email);
if (user == null)
{
return Content("User not found");
}
var result = await _signInManager.PasswordSignInAsync(user, password, false, false);
if (result.Succeeded)
{
return Content("Login successful");
}
return Content("Invalid login");
}
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
return Content("Logged out");
}
}
public class AdminController : Controller
{
[Authorize(Roles = "Admin")]
public IActionResult Dashboard()
{
return Content("Admin Dashboard");
}
[Authorize(Policy = "RequireHR")]
public IActionResult HRPanel()
{
return Content("HR Panel Access");
}
[Authorize]
public IActionResult Profile()
{
return Content("Authenticated User Profile");
}
}
// Program.cs (configuration example)
// builder.Services.AddIdentity<IdentityUser, IdentityRole>()
// .AddEntityFrameworkStores<AppDbContext>();
//
// builder.Services.AddAuthorization(options =>
// {
// options.AddPolicy("RequireHR", policy => policy.RequireClaim("Department", "HR"));
// });
Demonstrates a combined ASP.NET Core Identity system with authentication, authorization, roles, claims, and policy-based access control.
RESTful API CRUD
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<Product> Products { get; set; }
}
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly AppDbContext _context;
public ProductsController(AppDbContext context)
{
_context = context;
}
[HttpGet]
public IEnumerable<Product> GetAll()
{
return _context.Products.ToList();
}
[HttpGet("{id}")]
public ActionResult<Product> GetById(int id)
{
var product = _context.Products.Find(id);
if (product == null)
return NotFound();
return product;
}
[HttpPost]
public IActionResult Create(Product product)
{
_context.Products.Add(product);
_context.SaveChanges();
return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
}
[HttpPut("{id}")]
public IActionResult Update(int id, Product product)
{
var existing = _context.Products.Find(id);
if (existing == null)
return NotFound();
existing.Name = product.Name;
existing.Price = product.Price;
_context.SaveChanges();
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
var product = _context.Products.Find(id);
if (product == null)
return NotFound();
_context.Products.Remove(product);
_context.SaveChanges();
return NoContent();
}
}
Demonstrates a RESTful Web API CRUD application using ASP.NET Core Web API with Entity Framework Core and JSON responses.
C# Basic Class and Object
using System;
public class Car {
public string Model { get; set; }
public int Year { get; set; }
public void ShowInfo() {
Console.WriteLine($"Car: {Model}, Year: {Year}");
}
}
class Program {
static void Main() {
Car car = new Car { Model = "Tesla", Year = 2023 };
car.ShowInfo();
}
}
Defines a class with properties and methods, then creates and uses objects.
C# List and ForEach
using System;
using System.Collections.Generic;
class Program {
static void Main() {
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };
fruits.ForEach(f => Console.WriteLine(f));
}
}
Demonstrates iterating over a list using ForEach and lambda expressions.
C# Dictionary Example
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Dictionary<string, int> ages = new Dictionary<string, int> {
{"Alice", 25},
{"Bob", 30}
};
foreach (var kvp in ages) {
Console.WriteLine($"{kvp.Key} is {kvp.Value} years old");
}
}
}
Shows using Dictionary to store key-value pairs and iterate over them.
C# LINQ Filter and Select
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var evenSquares = numbers.Where(n => n % 2 == 0).Select(n => n * n).ToList();
evenSquares.ForEach(n => Console.WriteLine(n));
}
}
Filters and projects data from a list using LINQ methods.
C# Nullable Types and Null-Coalescing
using System;
class Program {
static void Main() {
int? nullableNumber = null;
int value = nullableNumber ?? 10;
Console.WriteLine(value);
}
}
Demonstrates nullable types and using the ?? operator.
C# Async Await Example
using System;
using System.Threading.Tasks;
class Program {
static async Task Main() {
await PrintMessageAsync();
}
static async Task PrintMessageAsync() {
await Task.Delay(1000);
Console.WriteLine("Hello after 1 second!");
}
}
Demonstrates async and await for asynchronous operations.
C# String Interpolation
using System;
class Program {
static void Main() {
string name = "Alice";
int age = 25;
Console.WriteLine($"{name} is {age} years old");
}
}
Demonstrates using string interpolation to embed expressions inside strings.
C# Custom Class with Constructor
using System;
public class Book {
public string Title { get; set; }
public string Author { get; set; }
public Book(string title, string author) {
Title = title;
Author = author;
}
}
class Program {
static void Main() {
Book book = new Book("1984", "George Orwell");
Console.WriteLine($"{book.Title} by {book.Author}");
}
}
Defines a class with a constructor and uses it to initialize properties.
C# Events and Delegates Example
using System;
class Publisher {
public event Action OnChange;
public void RaiseEvent() {
OnChange?.Invoke();
}
}
class Program {
static void Main() {
Publisher p = new Publisher();
p.OnChange += () => Console.WriteLine("Event triggered!");
p.RaiseEvent();
}
}
Demonstrates a simple event and delegate usage in C#.
Frequently Asked Questions about C#
What is C#?
C# (C-Sharp) is a modern, object-oriented, multi-paradigm programming language built by Microsoft for the .NET platform. It is designed for productivity, type safety, performance, and building scalable applications across desktop, web, mobile, gaming, and cloud systems.
What are the primary use cases for C#?
Enterprise backend systems. Web APIs (ASP.NET Core). Unity game development. Desktop software (WPF/WinUI). Cloud-native microservices on Azure. Cross-platform mobile apps (MAUI/Xamarin)
What are the strengths of C#?
Excellent tooling and developer productivity. High performance with modern .NET. Strong type safety. Great for enterprise systems. Massive ecosystem (ASP.NET, Unity, MAUI)
What are the limitations of C#?
Heavily tied to Microsoft ecosystem historically. Slightly more complex runtime model. Not ideal for low-level systems. Unity uses older C# versions at times
How can I practice C# typing speed?
CodeSpeedTest offers 78+ real C# code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.