C#
Updated: September 10, 2025Categories: Languages, Backend, Frontend, Web
Printed from:
C# Cheatsheet
Language Overview
C# is a modern, object-oriented programming language developed by Microsoft, part of the .NET ecosystem. It is statically-typed, type-safe, and designed for building robust and scalable enterprise applications across web, mobile, desktop, cloud, and gaming platforms.
Key Characteristics
- Developed by Microsoft
- Part of the .NET framework
- Strongly-typed language
- Supports object-oriented, functional, and component-oriented programming paradigms
- Runs on the Common Language Runtime (CLR)
Basic Syntax
Hello World Example
C#
12345678910using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
Naming Conventions
- Classes: PascalCase (
MyClass) - Methods: PascalCase (
DoSomething()) - Variables: camelCase (
myVariable) - Constants: PascalCase (
MaxValue) - Interfaces: Start with 'I' (
IDisposable)
Data Types
Primitive Types
C#
1234567891011121314151617181920// Integral Types
byte b = 255; // 8-bit unsigned integer
sbyte sb = -128; // 8-bit signed integer
short s = 32767; // 16-bit signed integer
ushort us = 65535; // 16-bit unsigned integer
int i = 2147483647; // 32-bit signed integer
uint ui = 4294967295; // 32-bit unsigned integer
long l = 9223372036854775807; // 64-bit signed integer
ulong ul = 18446744073709551615;// 64-bit unsigned integer
// Floating-Point Types
float f = 3.14f; // 32-bit floating-point
double d = 3.14159; // 64-bit floating-point
decimal m = 3.14159m; // 128-bit high-precision decimal
// Other Types
char c = 'A'; // Single 16-bit Unicode character
bool boolean = true; // Logical true/false
string str = "Hello"; // String of Unicode characters
Nullable Types
C#
123456int? nullableInt = null; // Nullable integer
Nullable<bool> nullableBool = null;
// Null-coalescing operator
int definiteValue = nullableInt ?? 0;
Value vs Reference Types
C#
12345678910111213// Value Types (stored on stack)
struct Point
{
public int X;
public int Y;
}
// Reference Types (stored on heap)
class Person
{
public string Name;
}
Variables and Constants
Variable Declarations
C#
123456789// Explicit typing
int age = 30;
// Implicit typing
var name = "John"; // Compiler infers type
// Constants
const double PI = 3.14159;
Operators
Arithmetic Operators
C#
1234567int a = 10, b = 5;
int sum = a + b; // Addition
int diff = a - b; // Subtraction
int prod = a * b; // Multiplication
int div = a / b; // Division
int mod = a % b; // Modulus
Comparison Operators
C#
1234567bool result = (a == b); // Equal to
bool notEqual = (a != b);// Not equal to
bool greater = (a > b); // Greater than
bool less = (a < b); // Less than
bool greaterEqual = (a >= b); // Greater or equal
bool lessEqual = (a <= b); // Less or equal
Logical Operators
C#
12345bool x = true, y = false;
bool andResult = x && y; // Logical AND
bool orResult = x || y; // Logical OR
bool notResult = !x; // Logical NOT
Control Structures
Conditional Statements
C#
12345678910111213141516171819202122232425262728293031// If-Else
if (condition)
{
// Code block
}
else if (anotherCondition)
{
// Alternative block
}
else
{
// Default block
}
// Ternary Operator
string result = (age >= 18) ? "Adult" : "Minor";
// Switch Statement
switch (variable)
{
case value1:
// Code
break;
case value2:
// Code
break;
default:
// Default code
break;
}
Loops
C#
12345678910111213141516171819202122232425// For Loop
for (int i = 0; i < 10; i++)
{
// Repeated code
}
// While Loop
while (condition)
{
// Repeated code
}
// Do-While Loop
do
{
// Code executed at least once
} while (condition);
// Foreach Loop
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
Console.WriteLine(num);
}
Loop Control
C#
12345678910111213// Break: Exit loop
for (int i = 0; i < 10; i++)
{
if (i == 5) break;
}
// Continue: Skip current iteration
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0) continue;
// Process odd numbers
}
Functions
Basic Function
C#
123456789101112131415161718// Method with return type
public int Add(int a, int b)
{
return a + b;
}
// Void method (no return)
public void PrintMessage(string message)
{
Console.WriteLine(message);
}
// Optional and Named Parameters
public void Greet(string name, string greeting = "Hello")
{
Console.WriteLine($"{greeting}, {name}!");
}
Lambda Expressions
C#
12345678// Lambda for simple operations
Func<int, int, int> add = (x, y) => x + y;
int result = add(3, 4); // result = 7
// With LINQ
var numbers = new[] { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
Object-Oriented Programming
Classes and Objects
C#
1234567891011121314151617181920212223class Person
{
// Properties with auto-implementation
public string Name { get; set; }
public int Age { get; set; }
// Constructor
public Person(string name, int age)
{
Name = name;
Age = age;
}
// Method
public void Introduce()
{
Console.WriteLine($"Hi, I'm {Name}");
}
}
// Object creation
Person person = new Person("Alice", 30);
Inheritance
C#
12345678910111213141516171819// Base Class
class Animal
{
public string Name { get; set; }
public virtual void MakeSound()
{
Console.WriteLine("Some sound");
}
}
// Derived Class
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Woof!");
}
}
Access Modifiers
C#
12345678class Example
{
public int PublicField; // Accessible everywhere
private int PrivateField; // Accessible only within class
protected int ProtectedField; // Accessible in class and derived classes
internal int InternalField; // Accessible within same assembly
}
Error Handling
Exception Handling
C#
123456789101112131415161718192021try
{
// Code that might throw an exception
int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
// Code always executed, with or without exception
}
// Throwing custom exceptions
throw new ArgumentException("Invalid argument");
File I/O
Reading and Writing Files
C#
1234567891011121314using System.IO;
// Writing to a file
File.WriteAllText("example.txt", "Hello, World!");
// Reading from a file
string content = File.ReadAllText("example.txt");
// Using StreamReader/StreamWriter
using (StreamWriter writer = new StreamWriter("file.txt"))
{
writer.WriteLine("Some content");
}
LINQ (Language Integrated Query)
Query Syntax
C#
12345678910int[] numbers = { 1, 2, 3, 4, 5 };
// Query syntax
var evenNumbers = from num in numbers
where num % 2 == 0
select num;
// Method syntax
var evenNumbersMethod = numbers.Where(n => n % 2 == 0);
Asynchronous Programming
Async/Await
C#
123456789public async Task<string> FetchDataAsync()
{
using (HttpClient client = new HttpClient())
{
string result = await client.GetStringAsync("https://api.example.com/data");
return result;
}
}
Collections
.NET Collections
C#
1234567891011121314// List
List<string> names = new List<string> { "Alice", "Bob" };
names.Add("Charlie");
// Dictionary
Dictionary<string, int> ages = new Dictionary<string, int>
{
{ "Alice", 30 },
{ "Bob", 25 }
};
// HashSet
HashSet<int> uniqueNumbers = new HashSet<int> { 1, 2, 3 };
Generics
Generic Methods and Classes
C#
12345678910111213141516public class GenericClass<T>
{
private T _value;
public void SetValue(T value)
{
_value = value;
}
}
// Generic method with constraint
public T FindMax<T>(List<T> list) where T : IComparable<T>
{
return list.Max();
}
Package Management
NuGet Package Management
- Use
dotnet add package [PackageName]to add packages - Common packages:
- Newtonsoft.Json (JSON serialization)
- AutoMapper (Object-Object mapping)
- Entity Framework Core (ORM)
Testing
Unit Testing Frameworks
- MSTest
- NUnit
- xUnit
Example NUnit Test
C#
123456789101112[TestClass]
public class CalculatorTests
{
[TestMethod]
public void Add_PositiveNumbers_ReturnsCorrectSum()
{
Calculator calc = new Calculator();
int result = calc.Add(2, 3);
Assert.AreEqual(5, result);
}
}
Best Practices
Code Style
- Use meaningful variable and method names
- Keep methods small and focused
- Follow SOLID principles
- Use null-conditional and null-coalescing operators
- Prefer immutability when possible
Performance Tips
- Use
StringBuilderfor string concatenation - Prefer
foroverforeachfor large collections - Use
async/awaitfor I/O-bound operations - Use value types when appropriate
- Minimize boxing and unboxing
Resources for Further Learning
- Microsoft C# Documentation
- "C# in Depth" by Jon Skeet
- Pluralsight C# Courses
- .NET Core GitHub Repository
- Stack Overflow C# Community
Conclusion
C# is a powerful, versatile language with strong typing, extensive standard library, and robust ecosystem. Continuous learning and practice are key to mastering its capabilities.
Continue Learning
Discover more cheatsheets to boost your productivity