C# Basic Syntax Cheatsheet

15 min read

Table of Contents
- Basic Program Structure
- Data Types
- Variables & Constants
- Operators
- Control Structures
- Methods
- Arrays & Collections
- Classes & Objects
- Properties & Indexers
- Inheritance & Polymorphism
- Interfaces
- Exception Handling
- LINQ Basics
- Generics
Basic Program Structure
using System; // Import namespace
using System.Collections.Generic;
using System.Linq;
namespace MyApplication // Namespace declaration
{
class Program // Class declaration
{
static void Main(string[] args) // Main method - entry point
{
Console.WriteLine("Hello, World!");
Console.ReadKey(); // Wait for key press
}
}
}
// Alternative: Top-level programs (C# 9.0+)
using System;
Console.WriteLine("Hello, World!");
Comments
// Single line comment
/*
Multi-line comment
Can span multiple lines
*/
/// <summary>
/// XML documentation comment
/// Used for generating documentation
/// </summary>
/// <param name="parameter">Parameter description</param>
/// <returns>Return value description</returns>
Data Types
Value Types
// Integer types
byte b = 255; // 8-bit unsigned: 0 to 255
sbyte sb = -128; // 8-bit signed: -128 to 127
short s = 32767; // 16-bit signed: -32,768 to 32,767
ushort us = 65535; // 16-bit unsigned: 0 to 65,535
int i = 2147483647; // 32-bit signed: -2^31 to 2^31-1
uint ui = 4294967295U; // 32-bit unsigned: 0 to 2^32-1
long l = 9223372036854775807L; // 64-bit signed
ulong ul = 18446744073709551615UL; // 64-bit unsigned
// Floating point types
float f = 3.14f; // 32-bit float
double d = 3.141592653589793; // 64-bit double
decimal dec = 3.14159m; // 128-bit decimal (for financial calculations)
// Character and boolean
char c = 'A'; // Unicode character
bool flag = true; // true or false
// Other value types
DateTime now = DateTime.Now;
TimeSpan duration = TimeSpan.FromMinutes(30);
Reference Types
// String (reference type but immutable)
string text = "Hello, World!";
string multiline = @"This is a
multi-line string";
string interpolated = $"Value: {i}"; // String interpolation
// Object (base class for all types)
object obj = 42;
object obj2 = "Hello";
// Arrays
int[] numbers = {1, 2, 3, 4, 5};
string[] names = new string[3];
// Nullable types (C# 2.0+)
int? nullableInt = null; // Nullable value type
string? nullableString = null; // Nullable reference type (C# 8.0+)
Type Inference
var number = 42; // Compiler infers int
var text = "Hello"; // Compiler infers string
var array = new[] {1, 2, 3}; // Compiler infers int[]
var list = new List<string>(); // Compiler infers List<string>
Variables & Constants
Variable Declaration
int x; // Declaration
int y = 10; // Declaration with initialization
int a = 5, b = 10; // Multiple variables
// Implicit typing
var name = "John"; // string
var age = 25; // int
var price = 9.99; // double
Constants and Read-only
const int MAX_SIZE = 100; // Compile-time constant
const string APP_NAME = "MyApp";
static readonly DateTime StartTime = DateTime.Now; // Runtime constant
readonly int instanceId; // Instance read-only field
// Static readonly vs const
public class Constants
{
public const double PI = 3.14159; // Compile-time
public static readonly DateTime AppStart = DateTime.Now; // Runtime
}
Access Modifiers
public int publicField; // Accessible from anywhere
private int privateField; // Only within same class
protected int protectedField; // Within class and derived classes
internal int internalField; // Within same assembly
protected internal int protectedInternalField; // Protected OR internal
private protected int privateProtectedField; // Protected AND internal (C# 7.2+)
Operators
Arithmetic Operators
int a = 10, b = 3;
int sum = a + b; // Addition: 13
int diff = a - b; // Subtraction: 7
int product = a * b; // Multiplication: 30
int quotient = a / b; // Division: 3 (integer division)
int remainder = a % b; // Modulus: 1
double division = (double)a / b; // Floating-point division: 3.333...
// Compound assignment
a += 5; // a = a + 5
a -= 3; // a = a - 3
a *= 2; // a = a * 2
a /= 4; // a = a / 4
a %= 3; // a = a % 3
Increment/Decrement
int x = 5;
++x; // Pre-increment: x becomes 6, returns 6
x++; // Post-increment: returns 6, then x becomes 7
--x; // Pre-decrement: x becomes 6, returns 6
x--; // Post-decrement: returns 6, then x becomes 5
Comparison Operators
int a = 5, b = 10;
bool equal = (a == b); // Equal to: false
bool notEqual = (a != b); // Not equal to: true
bool less = (a < b); // Less than: true
bool lessEqual = (a <= b); // Less than or equal: true
bool greater = (a > b); // Greater than: false
bool greaterEqual = (a >= b); // Greater than or equal: false
Logical Operators
bool p = true, q = false;
bool and = p && q; // Logical AND: false
bool or = p || q; // Logical OR: true
bool not = !p; // Logical NOT: false
bool xor = p ^ q; // Logical XOR: true
Null-Coalescing Operators
string? name = null;
string displayName = name ?? "Unknown"; // If name is null, use "Unknown"
name ??= "Default"; // Assign if null (C# 8.0+)
// Null-conditional operators
int? length = name?.Length; // null if name is null
char? firstChar = name?[0]; // null if name is null
Pattern Matching (C# 7.0+)
object obj = "Hello";
// is operator with pattern
if (obj is string str)
{
Console.WriteLine($"String: {str}");
}
// switch expression (C# 8.0+)
string GetTypeDescription(object obj) => obj switch
{
string s => $"String with {s.Length} characters",
int i when i > 0 => "Positive integer",
int i => "Non-positive integer",
null => "Null value",
_ => "Unknown type"
};
Control Structures
If-Else Statements
int score = 85;
if (score >= 90)
{
Console.WriteLine("Grade A");
}
else if (score >= 80)
{
Console.WriteLine("Grade B");
}
else if (score >= 70)
{
Console.WriteLine("Grade C");
}
else
{
Console.WriteLine("Grade F");
}
// Ternary operator
string result = score >= 60 ? "Pass" : "Fail";
// Null-conditional operator
string? name = GetName();
int length = name?.Length ?? 0;
Switch Statement
int dayOfWeek = 3;
switch (dayOfWeek)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
case 4:
Console.WriteLine("Midweek");
break;
default:
Console.WriteLine("Other day");
break;
}
// Switch expression (C# 8.0+)
string dayName = dayOfWeek switch
{
1 => "Monday",
2 => "Tuesday",
3 or 4 => "Midweek",
>= 5 and <= 7 => "Weekend area",
_ => "Invalid day"
};
Loops
For Loop
// Traditional for loop
for (int i = 0; i < 10; i++)
{
Console.Write($"{i} ");
}
// Multiple variables
for (int i = 0, j = 10; i < j; i++, j--)
{
Console.WriteLine($"i={i}, j={j}");
}
Foreach Loop
int[] numbers = {1, 2, 3, 4, 5};
foreach (int number in numbers)
{
Console.Write($"{number} ");
}
// With var
foreach (var item in numbers)
{
Console.Write($"{item} ");
}
// With index (C# 8.0+)
foreach (var (item, index) in numbers.Select((value, i) => (value, i)))
{
Console.WriteLine($"Index {index}: {item}");
}
While and Do-While
int count = 0;
while (count < 5)
{
Console.Write($"{count} ");
count++;
}
int num;
do
{
Console.Write("Enter a positive number: ");
int.TryParse(Console.ReadLine(), out num);
} while (num <= 0);
Loop Control
for (int i = 0; i < 10; i++)
{
if (i == 3)
continue; // Skip rest of this iteration
if (i == 7)
break; // Exit the loop
Console.Write($"{i} ");
}
Methods
Method Declaration and Definition
public class Calculator
{
// Basic method
public int Add(int a, int b)
{
return a + b;
}
// Method with no return value
public void PrintMessage(string message)
{
Console.WriteLine(message);
}
// Method with default parameters
public void Greet(string name = "World", int times = 1)
{
for (int i = 0; i < times; i++)
{
Console.WriteLine($"Hello, {name}!");
}
}
// Method with params array
public int Sum(params int[] numbers)
{
return numbers.Sum();
}
// Method with out parameter
public bool TryDivide(int a, int b, out double result)
{
if (b != 0)
{
result = (double)a / b;
return true;
}
result = 0;
return false;
}
// Method with ref parameter
public void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
// Method with in parameter (C# 7.2+)
public void ProcessLargeStruct(in LargeStruct data)
{
// data is passed by readonly reference
}
}
Method Overloading
public class MathHelper
{
public int Add(int a, int b)
{
return a + b;
}
public double Add(double a, double b)
{
return a + b;
}
public int Add(int a, int b, int c)
{
return a + b + c;
}
}
Expression-Bodied Members (C# 6.0+)
public class Person
{
private string firstName;
private string lastName;
// Expression-bodied method
public string GetFullName() => $"{firstName} {lastName}";
// Expression-bodied property
public string FullName => $"{firstName} {lastName}";
// Expression-bodied constructor (C# 7.0+)
public Person(string first, string last) => (firstName, lastName) = (first, last);
}
Local Functions (C# 7.0+)
public int Calculate(int[] numbers)
{
// Local function
int Sum(int[] nums)
{
int total = 0;
foreach (int num in nums)
total += num;
return total;
}
return Sum(numbers) * 2;
}
Arrays & Collections
Arrays
// One-dimensional arrays
int[] numbers = new int[5]; // Array with 5 elements
int[] values = {1, 2, 3, 4, 5}; // Array with initialization
int[] scores = new int[] {90, 85, 92, 78}; // Explicit initialization
var grades = new[] {95, 87, 92}; // Implicitly typed
// Multi-dimensional arrays
int[,] matrix = new int[3, 4]; // 2D array: 3 rows, 4 columns
int[,] grid = {{1, 2}, {3, 4}, {5, 6}}; // 2D array with initialization
// Jagged arrays
int[][] jaggedArray = new int[3][]; // Array of arrays
jaggedArray[0] = new int[] {1, 2, 3};
jaggedArray[1] = new int[] {4, 5};
jaggedArray[2] = new int[] {6, 7, 8, 9};
// Array properties and methods
int length = numbers.Length; // Array length
Array.Sort(values); // Sort array
int index = Array.IndexOf(values, 3); // Find index of element
Generic Collections
using System.Collections.Generic;
// List<T> - dynamic array
List<string> names = new List<string>();
names.Add("Alice");
names.Add("Bob");
names.AddRange(new[] {"Charlie", "David"});
names.Insert(1, "Eve"); // Insert at index
names.Remove("Bob"); // Remove by value
names.RemoveAt(0); // Remove by index
// Dictionary<TKey, TValue> - key-value pairs
Dictionary<string, int> ages = new Dictionary<string, int>
{
{"Alice", 25},
{"Bob", 30},
["Charlie"] = 35 // Index initializer syntax
};
ages.Add("David", 28);
ages["Eve"] = 22; // Add or update
if (ages.TryGetValue("Alice", out int aliceAge))
{
Console.WriteLine($"Alice is {aliceAge} years old");
}
// HashSet<T> - unique elements
HashSet<int> uniqueNumbers = new HashSet<int> {1, 2, 3, 3, 4};
uniqueNumbers.Add(5);
bool contains = uniqueNumbers.Contains(3); // true
// Queue<T> - FIFO
Queue<string> queue = new Queue<string>();
queue.Enqueue("First");
queue.Enqueue("Second");
string first = queue.Dequeue(); // "First"
// Stack<T> - LIFO
Stack<int> stack = new Stack<int>();
stack.Push(10);
stack.Push(20);
int top = stack.Pop(); // 20
Collection Initializers
// Collection initializer syntax
List<int> numbers = new List<int> {1, 2, 3, 4, 5};
Dictionary<string, string> countries = new Dictionary<string, string>
{
{"US", "United States"},
{"UK", "United Kingdom"},
{"DE", "Germany"}
};
// Object and collection initializers combined
var people = new List<Person>
{
new Person { Name = "Alice", Age = 25 },
new Person { Name = "Bob", Age = 30 }
};
Classes & Objects
Class Definition
public class Person
{
// Fields
private string name;
private int age;
// Constructors
public Person()
{
name = "Unknown";
age = 0;
}
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
// Methods
public void Introduce()
{
Console.WriteLine($"Hi, I'm {name} and I'm {age} years old.");
}
// Getters and Setters
public string GetName()
{
return name;
}
public void SetName(string value)
{
if (!string.IsNullOrWhiteSpace(value))
name = value;
}
}
// Using the class
Person person1 = new Person();
Person person2 = new Person("Alice", 25);
person1.SetName("Bob");
person1.Introduce();
Auto-Implemented Properties (C# 3.0+)
public class Student
{
// Auto-implemented properties
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; private set; } // Read-only outside class
// Property with backing field
private double gpa;
public double GPA
{
get { return gpa; }
set
{
if (value >= 0.0 && value <= 4.0)
gpa = value;
else
throw new ArgumentOutOfRangeException(nameof(value));
}
}
// Property with default value (C# 6.0+)
public bool IsActive { get; set; } = true;
// Expression-bodied property (C# 6.0+)
public string DisplayName => $"{Name} (Age: {Age})";
// Init-only property (C# 9.0+)
public string StudentId { get; init; }
}
// Object initializer syntax
Student student = new Student
{
Name = "John Doe",
Age = 20,
StudentId = "S12345"
};
Static Members
public class MathHelper
{
// Static field
public static readonly double PI = 3.14159;
// Static property
public static int InstanceCount { get; private set; }
// Static constructor
static MathHelper()
{
Console.WriteLine("MathHelper static constructor called");
}
// Static method
public static double CalculateCircleArea(double radius)
{
return PI * radius * radius;
}
}
// Usage
double area = MathHelper.CalculateCircleArea(5.0);
Console.WriteLine($"PI = {MathHelper.PI}");
Object Lifecycle
public class Resource : IDisposable
{
private bool disposed = false;
// Finalizer (destructor)
~Resource()
{
Dispose(false);
}
// IDisposable implementation
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// Dispose managed resources
}
// Dispose unmanaged resources
disposed = true;
}
}
}
// Using statement ensures Dispose is called
using (Resource resource = new Resource())
{
// Use resource
} // Dispose automatically called here
// Using declaration (C# 8.0+)
using var resource2 = new Resource();
// Dispose called at end of scope
Properties & Indexers
Advanced Properties
public class Temperature
{
private double celsius;
// Property with full implementation
public double Celsius
{
get => celsius;
set
{
if (value < -273.15)
throw new ArgumentOutOfRangeException(nameof(value), "Temperature cannot be below absolute zero");
celsius = value;
}
}
// Computed property
public double Fahrenheit
{
get => celsius * 9.0 / 5.0 + 32;
set => celsius = (value - 32) * 5.0 / 9.0;
}
// Read-only property
public double Kelvin => celsius + 273.15;
}
Indexers
public class StringCollection
{
private List<string> items = new List<string>();
// Basic indexer
public string this[int index]
{
get => items[index];
set => items[index] = value;
}
// Multiple parameter indexer
public string this[string key, int version]
{
get => $"{key}_v{version}";
set => Console.WriteLine($"Setting {key}_v{version} = {value}");
}
public void Add(string item) => items.Add(item);
}
// Usage
StringCollection collection = new StringCollection();
collection.Add("First");
collection.Add("Second");
string first = collection[0]; // Using indexer
collection[1] = "Modified"; // Setting via indexer
Inheritance & Polymorphism
Basic Inheritance
// Base class
public class Animal
{
protected string name;
public Animal(string name)
{
this.name = name;
}
public virtual void MakeSound()
{
Console.WriteLine($"{name} makes a sound");
}
public virtual string GetInfo()
{
return $"Animal: {name}";
}
}
// Derived class
public class Dog : Animal
{
private string breed;
public Dog(string name, string breed) : base(name)
{
this.breed = breed;
}
// Override virtual method
public override void MakeSound()
{
Console.WriteLine($"{name} barks");
}
// Override with base call
public override string GetInfo()
{
return base.GetInfo() + $", Breed: {breed}";
}
// New method (not overriding)
public void Fetch()
{
Console.WriteLine($"{name} fetches the ball");
}
}
Abstract Classes and Methods
public abstract class Shape
{
protected string color;
public Shape(string color)
{
this.color = color;
}
// Abstract method - must be implemented in derived classes
public abstract double CalculateArea();
// Virtual method - can be overridden
public virtual void Draw()
{
Console.WriteLine($"Drawing a {color} shape");
}
// Concrete method
public string GetColor()
{
return color;
}
}
public class Circle : Shape
{
private double radius;
public Circle(string color, double radius) : base(color)
{
this.radius = radius;
}
public override double CalculateArea()
{
return Math.PI * radius * radius;
}
public override void Draw()
{
Console.WriteLine($"Drawing a {color} circle with radius {radius}");
}
}
Sealed Classes and Methods
public sealed class FinalClass
{
// This class cannot be inherited
}
public class BaseClass
{
public virtual void Method1() { }
public virtual void Method2() { }
}
public class DerivedClass : BaseClass
{
public sealed override void Method1()
{
// This override cannot be overridden further
}
public override void Method2() { }
}
Interfaces
Interface Definition and Implementation
public interface IShape
{
double Area { get; }
double Perimeter { get; }
void Draw();
}
public interface IMovable
{
void Move(int x, int y);
int X { get; set; }
int Y { get; set; }
}
// Implementing interfaces
public class Rectangle : IShape, IMovable
{
public double Width { get; set; }
public double Height { get; set; }
public int X { get; set; }
public int Y { get; set; }
public double Area => Width * Height;
public double Perimeter => 2 * (Width + Height);
public void Draw()
{
Console.WriteLine($"Drawing rectangle at ({X}, {Y})");
}
public void Move(int x, int y)
{
X = x;
Y = y;
}
}
Default Interface Methods (C# 8.0+)
public interface ILogger
{
void Log(string message);
// Default implementation
void LogError(string message)
{
Log($"ERROR: {message}");
}
void LogWarning(string message)
{
Log($"WARNING: {message}");
}
}
public class ConsoleLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine($"[{DateTime.Now}] {message}");
}
// LogError and LogWarning are inherited from interface
}
Explicit Interface Implementation
public interface IEnglishSpeaker
{
void Speak();
}
public interface ISpanishSpeaker
{
void Speak();
}
public class BilingualPerson : IEnglishSpeaker, ISpanishSpeaker
{
// Explicit implementation
void IEnglishSpeaker.Speak()
{
Console.WriteLine("Hello!");
}
void ISpanishSpeaker.Speak()
{
Console.WriteLine("Hola!");
}
// Public method
public void SpeakBoth()
{
((IEnglishSpeaker)this).Speak();
((ISpanishSpeaker)this).Speak();
}
}
Exception Handling
Try-Catch-Finally
try
{
int result = 10 / 0; // This will throw an exception
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Division by zero: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"General error: {ex.Message}");
}
finally
{
Console.WriteLine("This always executes");
}
Exception Filters (C# 6.0+)
try
{
// Some operation
}
catch (Exception ex) when (ex.Message.Contains("network"))
{
// Handle network-related exceptions
}
catch (Exception ex) when (ex.InnerException != null)
{
// Handle exceptions with inner exceptions
}
Custom Exceptions
public class CustomException : Exception
{
public string ErrorCode { get; }
public CustomException(string message, string errorCode) : base(message)
{
ErrorCode = errorCode;
}
public CustomException(string message, string errorCode, Exception innerException)
: base(message, innerException)
{
ErrorCode = errorCode;
}
}
// Usage
throw new CustomException("Something went wrong", "ERR001");
Using Statement for Resource Management
// Traditional using statement
using (var file = new FileStream("test.txt", FileMode.Open))
{
// Use file
} // Dispose automatically called
// Using declaration (C# 8.0+)
using var reader = new StreamReader("test.txt");
// Dispose called at end of scope
// Multiple using statements
using var file1 = new FileStream("file1.txt", FileMode.Open);
using var file2 = new FileStream("file2.txt", FileMode.Create);
LINQ Basics
LINQ Query Syntax
using System.Linq;
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Query syntax
var evenNumbers = from n in numbers
where n % 2 == 0
select n;
var squaredNumbers = from n in numbers
where n > 5
select n * n;
// Method syntax
var evenNumbersMethod = numbers.Where(n => n % 2 == 0);
var squaredNumbersMethod = numbers.Where(n => n > 5).Select(n => n * n);
0
Subscribe to my newsletter
Read articles from Anni Huang directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Anni Huang
Anni Huang
I am Anni HUANG, a software engineer with 3 years of experience in IDE development and Chatbot.