Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. C#

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 →
C# LINQ and PropertiesBasic Class and ObjectStudent Management SystemConstructor DemonstrationProperty ExampleMethod OverloadingArray OperationsMultidimensional ArrayJagged ArrayString ManipulationString PalindromeIndexer ExampleSingle InheritanceBase Keyword ExampleMethod HidingMethod OverridingPolymorphism ExampleAbstract Class ExampleInterface ExampleMultiple Interface ImplementationStruct ExampleEnum ExampleDelegate ExampleEvent ExamplePartial Class ExampleGeneric ClassGeneric MethodList CollectionDictionary CollectionStack Collection+48 more examples

Learn CSHARP with Real Code Examples

Updated Nov 17, 2025

Explain

C# compiles to IL (Intermediate Language) and runs on the .NET CLR.

Supports OOP, functional programming, asynchronous programming, and modern language abstractions.

Used for enterprise apps, web APIs, Unity game development, cloud-native apps, and Windows desktop systems.

Core Features

CLR runtime and IL execution

Classes, structs, interfaces, records

Generics and type inference

LINQ for data querying

Async/await for concurrency

Basic Concepts Overview

Variables, data types

Classes, structs, interfaces

OOP principles

Delegates, events, lambdas

LINQ and collections

Async/await concurrency

Project Structure

Program.cs / Startup.cs

Controllers/Services folders (for APIs)

appsettings.json

csproj project file

bin/obj build directories

Building Workflow

Write .cs files

Build with dotnet build

Run via dotnet run

Manage dependencies via NuGet

Publish as DLL/EXE or container

Difficulty Use Cases

Beginner: Console apps

Intermediate: ASP.NET APIs

Advanced: Enterprise services

Expert: Game development or high-scale distributed systems

Comparisons

More structured than JavaScript

More enterprise-ready than PHP

Faster development cycle than Java

Higher-level than Go or Rust

Versioning Timeline

C# 3.0 - LINQ

C# 5.0 - async/await

C# 7-9 - pattern matching, records

C# 10/11 - global usings, file-scoped namespaces

C# 12 - primary constructors

Glossary

CLR: Common Language Runtime

IL: Intermediate Language

NuGet: .NET package manager

EF Core: ORM framework

Installation Setup

Install .NET SDK (8+ recommended)

Install Visual Studio or VS Code

Install NuGet packages

Configure CLI tools (dotnet CLI)

Environment Setup

Install .NET SDK

Install Visual Studio or VS Code

Install NuGet dependencies

Setup environment variables

Config Files

appsettings.json

csproj project file

launchSettings.json

NuGet.config

Cli Commands

dotnet new

dotnet build

dotnet run

dotnet publish

Internationalization

resx resource files

CultureInfo APIs

Localization middleware

Unicode-friendly runtime

Accessibility

XAML accessibility APIs

Blazor ARIA support

Localization metadata

Assistive technology integration

Ui Styling

WPF/WinUI XAML styling

MAUI cross-platform styling

Blazor component styling

Unity UI toolkit for games

State Management

ASP.NET services DI container

Singleton and scoped services

EF Core database tracking

In-memory caching

Data Management

Entity Framework Core ORM

Dapper for micro-ORM

ADO.NET for raw SQL

NoSQL via Cosmos DB

Architecture

C# -> IL via Roslyn compiler

IL executed by CLR

JIT optimizations

Cross-platform with .NET Core

Rendering Model

C# compiles to IL

Executed by CLR

Optimized via RyuJIT

Uses AOT in modern .NET

Architectural Patterns

Clean Architecture

Onion Architecture

DDD for enterprise apps

Event-driven with SignalR/Kafka

Real World Architectures

Enterprise ERP systems

ASP.NET microservice ecosystems

Unity game architectures

Cloud-native Azure apps

Design Principles

Productivity first

Type safety

Cross-platform runtime

Performance through JIT optimizations

Scalability Guide

Use async I/O everywhere

Use caching (Redis/IActionCache)

Use CQRS patterns

Scale via Kubernetes & Azure

Migration Guide

Move .NET Framework to .NET Core

Replace old async patterns

Use minimal APIs

Refactor to records and pattern matching

Performance Notes

Use Span<T> for memory efficiency

Pool objects using ArrayPool

Use async/await for scalable I/O

Enable RyuJIT optimizations

Security Notes

Use ASP.NET Core Identity

Validate all user input

Implement JWT/OAuth

Use HTTPS and strong API validation

Monitoring Analytics

Application Insights

Prometheus/Grafana

Serilog logging

OpenTelemetry tracing

Code Quality

Use Roslyn analyzers

Clean Architecture guidelines

Use SonarQube

Write xUnit tests

Practical Examples

Build REST APIs with ASP.NET Core

Create cross-platform mobile apps with MAUI

Develop games with Unity

Build cloud services using Azure functions

Troubleshooting

Resolve NuGet package conflicts

Fix null reference exceptions

Handle async deadlocks

Resolve configuration or DI errors

Testing Guide

Unit tests with xUnit or NUnit

Mocking with Moq

Integration tests in ASP.NET

Load testing with k6/JMeter

Deployment Options

Self-contained EXE

Docker container

Azure App Service

Kubernetes deployment

Tools Ecosystem

ASP.NET Core

Entity Framework Core

Visual Studio

NuGet package manager

xUnit/NUnit testing frameworks

Integrations

SQL Server / PostgreSQL

Azure services (Functions, Cosmos DB)

RabbitMQ/Kafka

Redis caching

Docker/Kubernetes

Productivity Tips

Use Visual Studio shortcuts

Use records & init setters

Use global usings

Use LINQ effectively

Challenges

Build a Todo API with ASP.NET Core

Create a Unity 2D game

Build a real-time chat app with SignalR

Create a microservice with Azure Functions

Learning Path

Learn C# basics & OOP

Master LINQ and collections

Learn async/await

Learn ASP.NET Core or Unity

Build real projects

Skill Improvement Plan

Week 1: OOP + delegates + LINQ

Week 2: Async programming

Week 3: ASP.NET Core

Week 4: EF Core + Cloud deployment

Interview Questions

Explain the CLR

What are records in C#?

Explain async/await

What is dependency injection in ASP.NET?

What is LINQ?

Cheat Sheet

Basic C# syntax

LINQ operators

Async patterns

ASP.NET routing & attributes

Books

C# in Depth

Pro ASP.NET Core

CLR via C#

Tutorials

Microsoft Learn C#

ASP.NET Core Tutorials

Unity Learn

Official Docs

Microsoft C# Documentation

.NET Runtime Documentation

ASP.NET Core Docs

Community Links

StackOverflow C# tag

Reddit r/csharp

.NET Foundation GitHub

Community Support

Microsoft developer community

Large .NET OSS ecosystem

Unity game dev community

Global enterprise adoption

Monetization

Enterprise .NET developer jobs

Unity game development

Azure cloud engineering

Freelancing ASP.NET projects

Future Roadmap

Native AOT improvements

More pattern matching evolution

Higher performance features

Unified MAUI improvements

When Not To Use

Ultra-low level systems (use Rust/C++)

High-performance bare-metal apps

Small throwaway scripts (Python fits better)

Legacy systems expecting JVM or C

Final Summary

C# is a powerful, productive, enterprise-friendly language.

Ideal for web APIs, games, cloud services, and desktop apps.

Modern .NET delivers high performance and cross-platform runtime.

Long-term career value with massive corporate demand.

Faq

Is C# still relevant?

Yes - it powers enterprise apps, Unity games, and modern cloud systems.

Is C# beginner friendly?

Very - its syntax is clean and expressive.

Is C# good for high performance?

Yes - modern .NET rivals Java and Go in performance.

Why choose C#?

Strong tooling, cross-platform support, performance, and large ecosystem.

Code Sample Descriptions

1

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.

Let’s Try →
2

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.

Let’s Try →
3

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.

Let’s Try →
4

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.

Let’s Try →
5

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.

Let’s Try →
6

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.

Let’s Try →
7

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.

Let’s Try →
8

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.

Let’s Try →
9

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.

Let’s Try →
10

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.

Let’s Try →
11

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.

Let’s Try →
12

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.

Let’s Try →
13

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.

Let’s Try →
14

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.

Let’s Try →
15

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.

Let’s Try →
16

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.

Let’s Try →
17

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.

Let’s Try →
18

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.

Let’s Try →
19

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.

Let’s Try →
20

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#.

Let’s Try →
21

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.

Let’s Try →
22

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.

Let’s Try →
23

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.

Let’s Try →
24

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).

Let’s Try →
25

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.

Let’s Try →
26

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.

Let’s Try →
27

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>.

Let’s Try →
28

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.

Let’s Try →
29

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.

Let’s Try →
30

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.

Let’s Try →
31

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.

Let’s Try →
32

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.

Let’s Try →
33

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#.

Let’s Try →
34

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.

Let’s Try →
35

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.

Let’s Try →
36

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.

Let’s Try →
37

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.

Let’s Try →
38

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.

Let’s Try →
39

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.

Let’s Try →
40

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.

Let’s Try →
41

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.

Let’s Try →
42

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().

Let’s Try →
43

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.

Let’s Try →
44

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.

Let’s Try →
45

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.

Let’s Try →
46

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.

Let’s Try →
47

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.

Let’s Try →
48

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.

Let’s Try →
49

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.

Let’s Try →
50

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.

Let’s Try →
51

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.

Let’s Try →
52

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.

Let’s Try →
53

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.

Let’s Try →
54

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.

Let’s Try →
55

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.

Let’s Try →
56

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.

Let’s Try →
57

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.

Let’s Try →
58

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.

Let’s Try →
59

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.

Let’s Try →
60

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.

Let’s Try →
61

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.

Let’s Try →
62

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.

Let’s Try →
63

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.

Let’s Try →
64

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.

Let’s Try →
65

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.

Let’s Try →
66

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.

Let’s Try →
67

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.

Let’s Try →
68

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.

Let’s Try →
69

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.

Let’s Try →
70

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.

Let’s Try →
71

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.

Let’s Try →
72

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.

Let’s Try →
73

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.

Let’s Try →
74

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.

Let’s Try →
75

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.

Let’s Try →
76

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.

Let’s Try →
77

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.

Let’s Try →
78

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#.

Let’s Try →

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.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaRubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpJuliaView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.