C# Documentation
Microsoft's modern, type-safe language for .NET — desktop apps, web APIs, games with Unity and more.
C# (C-sharp) is a modern, type-safe, object-oriented language from Microsoft that runs on .NET. It is used for web APIs (ASP.NET Core), desktop apps, cloud services, and games with Unity. It combines Java-like OOP with powerful features such as LINQ, async/await, properties and records.
1. Introduction & Installation
Install the .NET SDK (8 LTS or newer) from dotnet.microsoft.com. Editors: Visual Studio, VS Code with the C# Dev Kit, or JetBrains Rider.
dotnet --version
dotnet new console -o HelloApp # create a project
cd HelloApp
dotnet run # build + run
Modern C# allows top-level statements — Program.cs can contain just:
Console.WriteLine("Hello, Codify!");
Output:
Hello, Codify!
The classic form with an explicit Main method still works:
using System;
namespace HelloApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello from Main!");
}
}
}
⚠️ Common error:
Couldn't find a project to run— rundotnet runinside the folder that contains the.csprojfile.
2. Basic Syntax
- Statements end with
;, blocks use{ }, names are case-sensitive. - Conventions:
PascalCasefor types, methods and properties;camelCasefor local variables. using System;imports a namespace (new projects include common ones implicitly).- String interpolation:
$"Hello {name}".
string name = "Asha";
int age = 20;
Console.WriteLine($"{name} will be {age + 1} next year");
Console.WriteLine("Total: " + (age * 2));
Console.WriteLine($"{3.14159:F2} |{42,5}|{"ab",-4}|"); // decimals and alignment
Output:
Asha will be 21 next year
Total: 40
3.14 | 42|ab |
💡 Tip: reading input:
string? line = Console.ReadLine(); int n = int.Parse(line!);. Number formats like{x:N0}follow your system's culture —1234567prints as12,34,567on an Indian locale and1,234,567on a US one.
3. Variables & Data Types
C# is statically typed. Value types (int, double, bool, char, struct) hold data directly; reference types (string, arrays, classes) hold a reference.
| Type | Example |
|---|---|
int, long |
int n = 42; long big = 9_000_000_000L; |
double, decimal |
double d = 3.14; decimal price = 99.99m; (use decimal for money) |
bool, char |
true, 'A' |
string |
"text" (immutable) |
var |
type inferred from the value |
| nullable | int? maybe = null; |
int count = 10;
long views = 5_000_000_000L;
double ratio = 2.0 / 3;
decimal price = 19.99m;
bool active = true;
char grade = 'A';
var city = "Mumbai"; // string
int? score = null; // nullable value type
const double Pi = 3.14159;
Console.WriteLine($"{count} {views} {ratio:F3} {price} {active} {grade} {city}");
Console.WriteLine($"{score ?? -1} {int.MaxValue} {(int)9.8} {int.Parse("25") + 5} {Pi}");
Console.WriteLine($"{7 / 2} {7 / 2.0} {7 % 3}");
Output:
10 5000000000 0.667 19.99 True A Mumbai
-1 2147483647 9 30 3.14159
3 3.5 1
⚠️ Common error:
Cannot implicitly convert type 'double' to 'int'— cast explicitly with(int)valueor useConvert.ToInt32.
4. Operators
Arithmetic + - * / %, comparison == != < > <= >=, logical && || !, bitwise & | ^ ~ << >>, assignment = += -= ??=, null operators ?. and ??, ternary ?:, type checks is and as.
int a = 17, b = 5;
Console.WriteLine($"{a / b} {a % b} {(double)a / b}");
Console.WriteLine($"{a > b && b > 0} {!(a == 17)} {6 & 3} {6 | 3} {1 << 10}");
string? nick = null;
Console.WriteLine(nick?.Length ?? 0);
nick ??= "guest";
Console.WriteLine(nick);
object o = "hello";
if (o is string s && s.Length > 3) Console.WriteLine($"string of length {s.Length}");
Output:
3 2 3.4
True False 2 7 1024
0
guest
string of length 5
⚠️ Common error:
NullReferenceException— accessing a member ofnull. Use?.and??, and enable nullable reference types (on by default in new projects).
5. Conditional Statements
int marks = 78;
if (marks >= 90) Console.WriteLine("A");
else if (marks >= 75) Console.WriteLine("B");
else Console.WriteLine("C");
string day = "Sat";
switch (day)
{
case "Sat":
case "Sun":
Console.WriteLine("Weekend");
break;
default:
Console.WriteLine("Weekday");
break;
}
// switch expression with patterns (C# 8+)
string Size(int n) => n switch
{
< 0 => "negative",
0 => "zero",
>= 1 and <= 9 => "small",
_ => "large",
};
Console.WriteLine($"{Size(-3)} {Size(5)} {Size(42)}");
Output:
B
Weekend
negative small large
⚠️ Common error: C# does not allow silent fall-through — every non-empty
casemust end withbreak,returnorgoto.
6. Loops
for (int i = 1; i <= 5; i++) Console.Write(i + " ");
Console.WriteLine();
string[] langs = { "C#", "Java", "Go" };
foreach (var lang in langs) Console.WriteLine(lang);
int n = 1;
while (n < 100) n *= 3;
Console.WriteLine($"n = {n}");
int tries = 0;
do { tries++; } while (tries < 3);
Console.WriteLine($"tries = {tries}");
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0) continue;
if (i > 7) break;
Console.Write(i + " ");
}
Console.WriteLine();
Output:
1 2 3 4 5
C#
Java
Go
n = 243
tries = 3
1 3 5 7
⚠️ Common error: modifying a
Listinside aforeachover it throwsInvalidOperationException: Collection was modified. Use aforloop orRemoveAll.
7. Functions
In C#, functions are methods. Top-level programs can declare local functions directly.
static int Add(int a, int b = 10) => a + b; // expression-bodied, default parameter
static double Add2(double a, double b) => a + b;
static int Sum(params int[] nums) { int s = 0; foreach (var x in nums) s += x; return s; }
static void Swap(ref int a, ref int b) { (a, b) = (b, a); } // pass by reference
static bool TryHalf(int n, out int half) // out parameter
{
half = n / 2;
return n % 2 == 0;
}
static (int Min, int Max) MinMax(int[] arr) // tuple return
{
int lo = arr[0], hi = arr[0];
foreach (var x in arr) { if (x < lo) lo = x; if (x > hi) hi = x; }
return (lo, hi);
}
int x = 1, y = 2;
Swap(ref x, ref y);
var (lo, hi) = MinMax(new[] { 4, -2, 9 });
Console.WriteLine($"{Add(5)} {Add2(1.5, 2.25)} {Sum(1, 2, 3, 4)} {x}{y} {lo} {hi}");
Console.WriteLine(TryHalf(10, out int h) ? $"half = {h}" : "odd");
Func<int, int> square = v => v * v; // lambda
Action<string> log = msg => Console.WriteLine($"[log] {msg}");
log($"square(12) = {square(12)}");
Output:
15 3.75 10 21 -2 9
half = 5
[log] square(12) = 144
⚠️ Common error:
Use of unassigned out parameter— a method must assign everyoutparameter before returning.
8. Arrays & Data Structures
using System.Linq;
int[] nums = { 5, 3, 9, 1 };
Array.Sort(nums);
Console.WriteLine($"{string.Join(",", nums)} len={nums.Length} idx={Array.IndexOf(nums, 9)}");
int[,] grid = new int[2, 3]; // 2-D array
grid[1, 2] = 7;
Console.WriteLine(grid[1, 2]);
var names = new List<string> { "Ravi", "Asha" };
names.Add("Neha");
names.Sort();
Console.WriteLine($"{string.Join(" ", names)} {names.Count} {names.Contains("Asha")}");
var marks = new Dictionary<string, int> { ["asha"] = 91, ["ravi"] = 78 };
marks["neha"] = 85;
if (marks.TryGetValue("john", out int m)) Console.WriteLine(m); else Console.WriteLine("john missing");
foreach (var (k, v) in marks.OrderBy(p => p.Key)) Console.Write($"{k}:{v} ");
Console.WriteLine();
var set = new HashSet<int> { 1, 2, 2, 3 };
var stack = new Stack<int>(); stack.Push(1); stack.Push(2);
var queue = new Queue<int>(); queue.Enqueue(1); queue.Enqueue(2);
var pq = new PriorityQueue<string, int>();
pq.Enqueue("low", 5); pq.Enqueue("high", 1);
Console.WriteLine($"{set.Count} {stack.Peek()} {queue.Peek()} {pq.Dequeue()}");
Output:
1,3,5,9 len=4 idx=3
7
Asha Neha Ravi 3 True
john missing
asha:91 neha:85 ravi:78
3 2 1 high
Use StringBuilder (in System.Text) to build strings in loops.
⚠️ Common error:
KeyNotFoundException— readingdict["missing"]. UseTryGetValueorContainsKey.
9. Object-Oriented Programming
var accounts = new List<Account> { new Savings("Asha", 12000m), new Current("Ravi", 5000m) };
foreach (var a in accounts) // polymorphism
Console.WriteLine($"{a} -> interest {a.MonthlyInterest():F2}");
var s = (Savings)accounts[0];
s.Deposit(3000m);
Console.WriteLine($"{s.Owner} balance {s.Balance}, points {s.Points}");
var p1 = new Point(1, 2);
var p2 = p1 with { Y = 5 }; // records: value equality + copy-with
Console.WriteLine($"{p1} {p2} {p1 == new Point(1, 2)}");
abstract class Account // abstraction + encapsulation
{
public string Owner { get; } // read-only auto-property
public decimal Balance { get; protected set; }
protected Account(string owner, decimal balance) { Owner = owner; Balance = balance; }
public void Deposit(decimal amount)
{
if (amount <= 0) throw new ArgumentException("Amount must be positive");
Balance += amount;
}
public abstract decimal MonthlyInterest();
public override string ToString() => $"{Owner}: {Balance}";
}
interface IRewardable { int Points { get; } }
class Savings : Account, IRewardable // inheritance + interface
{
public Savings(string owner, decimal balance) : base(owner, balance) { }
public override decimal MonthlyInterest() => Balance * 0.04m / 12;
public int Points => (int)(Balance / 100);
}
class Current : Account
{
public Current(string owner, decimal balance) : base(owner, balance) { }
public override decimal MonthlyInterest() => 0;
}
record Point(int X, int Y);
Output:
Asha: 12000 -> interest 40.00
Ravi: 5000 -> interest 0.00
Asha balance 15000, points 150
Point { X = 1, Y = 2 } Point { X = 1, Y = 5 } True
Key ideas: properties (get; set;), access modifiers (public, private, protected, internal), virtual/override, abstract, sealed, static classes, interfaces with default methods, struct (value type) vs class (reference type), and records for immutable data.
⚠️ Common error: forgetting
virtualon the base method — thennew/hiding happens instead of overriding, and polymorphism doesn't work.
10. Advanced Concepts
LINQ queries any collection:
using System.Linq;
var students = new[]
{
new { Name = "Asha", Dept = "CSE", Marks = 91 },
new { Name = "Ravi", Dept = "ECE", Marks = 78 },
new { Name = "Neha", Dept = "CSE", Marks = 85 },
new { Name = "Kabir", Dept = "ECE", Marks = 66 },
};
var toppers = students.Where(s => s.Marks > 80).OrderByDescending(s => s.Marks).Select(s => s.Name);
Console.WriteLine(string.Join(", ", toppers));
foreach (var g in students.GroupBy(s => s.Dept))
Console.WriteLine($"{g.Key}: avg {g.Average(s => s.Marks):F1}, best {g.Max(s => s.Marks)}");
var query = from s in students where s.Dept == "ECE" select s.Name.ToUpper(); // query syntax
Console.WriteLine(string.Join(" ", query));
Console.WriteLine($"{students.Any(s => s.Marks < 70)} {students.Sum(s => s.Marks)} {Enumerable.Range(1, 5).Aggregate((a, b) => a * b)}");
Asha, Neha
CSE: avg 88.0, best 91
ECE: avg 72.0, best 78
RAVI KABIR
True 320 120
Delegates and events:
var button = new Button();
button.Clicked += (sender, msg) => Console.WriteLine($"Handler 1: {msg}");
button.Clicked += (sender, msg) => Console.WriteLine($"Handler 2: {msg.ToUpper()}");
button.Click();
class Button
{
public event EventHandler<string>? Clicked; // event based on a delegate type
public void Click() => Clicked?.Invoke(this, "button pressed");
}
Handler 1: button pressed
Handler 2: BUTTON PRESSED
async / await — non-blocking I/O:
static async Task<int> DownloadAsync(string name, int ms)
{
await Task.Delay(ms); // e.g. an HTTP call
return name.Length;
}
var t1 = DownloadAsync("report", 100);
var t2 = DownloadAsync("photo", 50);
int[] sizes = await Task.WhenAll(t1, t2);
Console.WriteLine($"downloaded {sizes[0] + sizes[1]} units");
downloaded 11 units
Exceptions:
try
{
int[] arr = new int[2];
arr[5] = 1;
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine($"Caught: {ex.GetType().Name}");
}
finally
{
Console.WriteLine("cleanup");
}
Caught: IndexOutOfRangeException
cleanup
.NET fundamentals: code compiles to IL that the CLR runs with a JIT compiler and a garbage collector; NuGet is the package manager (dotnet add package Newtonsoft.Json); ASP.NET Core builds web APIs; Entity Framework Core is the ORM for databases.
11. Examples with Output
Example 1 — Word frequency with a dictionary
var text = "to be or not to be";
var freq = new Dictionary<string, int>();
foreach (var w in text.Split(' ')) freq[w] = freq.GetValueOrDefault(w) + 1;
foreach (var (word, count) in freq.OrderByDescending(p => p.Value).ThenBy(p => p.Key))
Console.WriteLine($"{word} {count}");
be 2
to 2
not 1
or 1
Example 2 — Generic method with a constraint
static T MaxOf<T>(IEnumerable<T> items) where T : IComparable<T>
{
T best = items.First();
foreach (var x in items) if (x.CompareTo(best) > 0) best = x;
return best;
}
Console.WriteLine($"{MaxOf(new[] { 3, 9, 4 })} {MaxOf(new[] { "kiwi", "apple", "mango" })}");
9 mango
Example 3 — Validate parentheses with Stack
static bool Valid(string s)
{
var st = new Stack<char>();
var pairs = new Dictionary<char, char> { [')'] = '(', [']'] = '[', ['}'] = '{' };
foreach (char c in s)
{
if ("([{".Contains(c)) st.Push(c);
else if (st.Count == 0 || st.Pop() != pairs[c]) return false;
}
return st.Count == 0;
}
Console.WriteLine($"{Valid("{[()]}")} {Valid("([)]")}");
True False
12. Practice Problems
- Read two numbers with
Console.ReadLine()and print their sum, difference and average. - Print the Fibonacci series up to n using a loop, then using recursion with memoization (
Dictionary<int, long>). - Build a
Studentclass with properties and compute the class topper using LINQ. - Use
Dictionary<string, List<string>>to group words by their first letter. - Implement an
IShapeinterface withCircle,RectangleandTriangle. - Write an async method that "downloads" three files concurrently with
Task.DelayandTask.WhenAll. - Create a minimal ASP.NET Core API:
dotnet new webapi, add aGET /api/todosendpoint. - Solve the logic of Two Sum and Binary Search in C# (submit in C++/Java/Python on Codify).
13. Interview Questions
1. Value type vs reference type?
Value types (int, struct) store data directly and are copied on assignment; reference types (class, string, arrays) store a reference to heap data.
2. class vs struct vs record?
class — reference type with identity; struct — value type for small data; record — concise type with value-based equality and with copies.
3. What is LINQ?
Language-Integrated Query: methods like Where, Select, OrderBy, GroupBy (and query syntax) to query collections, databases and XML uniformly.
4. abstract class vs interface?
Abstract classes can have state and constructors; a class inherits only one. Interfaces define contracts (with optional default methods) and a class can implement many.
5. What are delegates and events?
A delegate is a type-safe function reference (Func, Action). An event is a delegate-based notification that only the declaring class can raise.
6. How does async/await work?
await frees the thread while waiting for a Task to finish, then continues the method afterwards — non-blocking code that reads sequentially.
7. ref vs out?
Both pass by reference. ref requires the variable to be initialised before the call; out requires the method to assign it.
8. What is garbage collection in .NET?
The CLR frees unreachable objects automatically using a generational GC (gen 0, 1, 2). IDisposable + using release unmanaged resources deterministically.
9. string vs StringBuilder?
string is immutable — each change creates a new object; StringBuilder modifies a buffer, so it's much faster for many concatenations.
10. What are const and readonly?
const is a compile-time constant; readonly fields can be set once at declaration or in the constructor.
14. Cheat Sheet & References
CLI
# new project, run, add packages, publish
dotnet new console -o App
dotnet run
dotnet add package Newtonsoft.Json
dotnet build -c Release
dotnet publish -c Release
Basics
Console.WriteLine($"Hi {name}"); string? line = Console.ReadLine();
int n = int.Parse(s); bool ok = int.TryParse(s, out int v);
var x = 5; const int Max = 10; int? maybe = null;
x ??= 0; obj?.Prop; a ?? b;
Strings
s.Length; s.ToUpper(); s.Trim(); s.Split(','); string.Join("-", arr);
s.Contains("a"); s.Substring(1, 3); s.Replace("a", "b"); s.IndexOf('x');
var sb = new StringBuilder(); sb.Append("x"); sb.ToString();
Collections
var list = new List<int> { 1, 2 }; list.Add(3); list.Remove(1); list.Count;
var dict = new Dictionary<string, int>(); dict["a"] = 1; dict.TryGetValue("a", out var v);
var set = new HashSet<int>(); var st = new Stack<int>(); var q = new Queue<int>();
int[] arr = new int[5]; Array.Sort(arr); int[,] grid = new int[3, 3];
LINQ
items.Where(x => x > 0).Select(x => x * 2).ToList();
items.OrderBy(x => x.Name).ThenByDescending(x => x.Age);
items.GroupBy(x => x.Dept); items.First(); items.FirstOrDefault();
items.Any(x => x > 5); items.Count(); items.Sum(); items.Max();
OOP
class A { public int Id { get; set; } public A(int id) { Id = id; } }
class B : A, IFoo { public B() : base(1) { } public override string ToString() => "B"; }
abstract class Shape { public abstract double Area(); }
record Person(string Name, int Age);
Async and errors
async Task<int> GetAsync() { await Task.Delay(100); return 1; }
await Task.WhenAll(t1, t2);
try { } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { }
using var file = File.OpenRead("a.txt");
Official documentation