C# Basics
Quick reference guide for C# fundamentals.
Variables and Data Types
C# is statically typed (types must be declared):
// ========== Numbers ==========
int age = 25; // Integer (whole numbers)
long bigNumber = 9223372036854775807L; // Larger integers
float price = 19.99f; // Single precision decimal
double distance = 1000000.0; // Double precision (default)
decimal money = 19.99m; // High precision for money
// ========== Strings ==========
string name = "Yudi"; // Text (immutable)
string message = "Hello!";
string multiline = @"
This is a
multi-line string
";
string interpolated = ___CODE_BLOCK_PLACEHOLDER___0___CODE_BLOCK_PLACEHOLDER___quot;My name is {name}"; // String interpolation
// ========== Characters ==========
char initial = 'Y'; // Single character (single quotes)
// ========== Booleans ==========
bool isActive = true; // true or false
bool hasPermission = false;
// ========== Type Inference (var) ==========
var count = 10; // Compiler infers int
var greeting = "Hello"; // Compiler infers string
// ========== Arrays (fixed size) ==========
int[] numbers = { 1, 2, 3, 4, 5 };
string[] fruits = new string[3]; // Initialize with size
fruits[0] = "apple";
// ========== Lists (dynamic size) ==========
using System.Collections.Generic;
List<string> cities = new List<string> { "Jakarta", "Bandung", "Surabaya" };
cities.Add("Yogyakarta");
// ========== Dictionaries (key-value pairs) ==========
Dictionary<string, int> ages = new Dictionary<string, int>
{
{ "Yudi", 25 },
{ "Budi", 30 }
};
// Access: ages["Yudi"] → 25
// ========== Nullable Types ==========
int? nullableAge = null; // Can be null
string? nullableString = null; // Reference types nullable in C# 8+
Control Flow
If Statements
int age = 18;
if (age >= 18)
{
Console.WriteLine("Adult");
}
else if (age >= 13)
{
Console.WriteLine("Teenager");
}
else
{
Console.WriteLine("Child");
}
// Ternary operator
string status = age >= 18 ? "Adult" : "Minor";
Switch Statements
// Traditional switch
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
default:
Console.WriteLine("Other day");
break;
}
// Switch expression (C# 8+)
string dayName = day switch
{
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
_ => "Other day"
};
Loops
// For loop
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
// While loop
int count = 0;
while (count < 5)
{
Console.WriteLine(count);
count++;
}
// Do-while loop (executes at least once)
int number = 0;
do
{
Console.WriteLine(number);
number++;
} while (number < 5);
// Foreach loop (iterate collections)
string[] fruits = { "apple", "banana", "orange" };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
// List iteration
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
Console.WriteLine(num);
}
Methods
Define reusable code blocks with specific return types:
// ========== Basic Method ==========
public string Greet(string name)
{
return ___CODE_BLOCK_PLACEHOLDER___4___CODE_BLOCK_PLACEHOLDER___quot;Hello, {name}!";
}
// ========== Multiple Parameters ==========
public int Add(int a, int b)
{
return a + b;
}
// ========== Void Method (no return) ==========
public void PrintMessage(string message)
{
Console.WriteLine(message);
}
// ========== Default Parameters ==========
public int Power(int baseNum, int exponent = 2)
{
return (int)Math.Pow(baseNum, exponent);
}
// ========== Out Parameters (multiple returns) ==========
public void GetUser(out string name, out int age)
{
name = "Yudi";
age = 25;
}
// ========== Tuple Return (C# 7+) ==========
public (string Name, int Age, string City) GetUserInfo()
{
return ("Yudi", 25, "Jakarta");
}
// ========== Variable Arguments ==========
public int SumAll(params int[] numbers)
{
return numbers.Sum();
}
// ========== Calling Methods ==========
string message = Greet("Yudi"); // "Hello, Yudi!"
int result = Add(5, 3); // 8
int squared = Power(5); // 25 (uses default)
int cubed = Power(5, 3); // 125
GetUser(out string userName, out int userAge); // Out parameters
var (name, age, city) = GetUserInfo(); // Tuple deconstruction
int total = SumAll(1, 2, 3, 4, 5); // 15
LINQ (Language Integrated Query)
Query and transform collections efficiently (similar to SQL):
using System.Linq;
// Sample data
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// ========== Filter (Where) ==========
var evens = numbers.Where(n => n % 2 == 0);
// Result: [2, 4, 6, 8, 10]
// ========== Transform (Select) ==========
var squares = numbers.Select(n => n * n);
// Result: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
// ========== Combine Filter and Transform ==========
var evenSquares = numbers
.Where(n => n % 2 == 0)
.Select(n => n * n);
// Result: [4, 16, 36, 64, 100]
// ========== Ordering ==========
var descending = numbers.OrderByDescending(n => n);
// Result: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
// ========== Aggregation ==========
int sum = numbers.Sum(); // 55
int max = numbers.Max(); // 10
double average = numbers.Average(); // 5.5
int count = numbers.Count(); // 10
// ========== Query Syntax (SQL-like) ==========
var query = from n in numbers
where n % 2 == 0
select n * n;
// Result: [4, 16, 36, 64, 100]
// ========== Complex Objects ==========
var people = new List<Person>
{
new Person { Name = "Alice", Age = 30 },
new Person { Name = "Bob", Age = 25 },
new Person { Name = "Charlie", Age = 35 }
};
var adults = people
.Where(p => p.Age >= 30)
.Select(p => p.Name);
// Result: ["Alice", "Charlie"]
Classes and Objects
C# is object-oriented (everything is a class):
// ========== Basic Class ==========
public class Person
{
// Properties
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(___CODE_BLOCK_PLACEHOLDER___6___CODE_BLOCK_PLACEHOLDER___quot;Hi, I'm {Name}, {Age} years old");
}
}
// Usage
Person person = new Person("Yudi", 25);
person.Introduce(); // "Hi, I'm Yudi, 25 years old"
// ========== Property Types ==========
public class Account
{
// Auto-property
public string Username { get; set; }
// Read-only property
public string Id { get; }
// Property with backing field
private decimal _balance;
public decimal Balance
{
get { return _balance; }
set
{
if (value >= 0)
_balance = value;
}
}
// Computed property
public string DisplayName => ___CODE_BLOCK_PLACEHOLDER___6___CODE_BLOCK_PLACEHOLDER___quot;@{Username}";
}
// ========== Inheritance ==========
public class Employee : Person
{
public string Department { get; set; }
public Employee(string name, int age, string department)
: base(name, age) // Call parent constructor
{
Department = department;
}
}
// ========== Interface ==========
public interface IVehicle
{
void Start();
void Stop();
}
public class Car : IVehicle
{
public void Start()
{
Console.WriteLine("Car started");
}
public void Stop()
{
Console.WriteLine("Car stopped");
}
}
Exception Handling
Handle errors gracefully to prevent crashes:
// ========== Try-Catch ==========
try
{
int result = 10 / 0; // Division by zero
}
catch (DivideByZeroException ex)
{
Console.WriteLine(___CODE_BLOCK_PLACEHOLDER___7___CODE_BLOCK_PLACEHOLDER___quot;Error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine(___CODE_BLOCK_PLACEHOLDER___7___CODE_BLOCK_PLACEHOLDER___quot;Unexpected error: {ex.Message}");
}
finally
{
// Always executes (cleanup code)
Console.WriteLine("Cleanup done");
}
// ========== Throw Exception ==========
public void ValidateAge(int age)
{
if (age < 0)
{
throw new ArgumentException("Age cannot be negative");
}
}
// ========== Custom Exception ==========
public class InvalidUserException : Exception
{
public InvalidUserException(string message) : base(message)
{
}
}
Common String Methods
string text = "Hello, World!";
text.ToLower(); // "hello, world!"
text.ToUpper(); // "HELLO, WORLD!"
text.Replace("Hello", "Hi"); // "Hi, World!"
text.Split(','); // ["Hello", " World!"]
text.Substring(0, 5); // "Hello"
text.Contains("World"); // true
text.StartsWith("Hello"); // true
text.EndsWith("!"); // true
text.Trim(); // Removes whitespace
// String interpolation
string name = "Yudi";
string greeting = ___CODE_BLOCK_PLACEHOLDER___8___CODE_BLOCK_PLACEHOLDER___quot;Hello, {name}!"; // "Hello, Yudi!"
Common List Methods
List<int> numbers = new List<int> { 1, 2, 3 };
numbers.Add(4); // [1, 2, 3, 4]
numbers.AddRange(new[] { 5, 6 }); // [1, 2, 3, 4, 5, 6]
numbers.Remove(3); // Removes first occurrence of 3
numbers.RemoveAt(0); // Removes at index 0
numbers.Contains(2); // true
numbers.Count; // Get size
numbers.Clear(); // Remove all items
numbers.Sort(); // Sort in place
numbers.Reverse(); // Reverse in place
Async/Await (Asynchronous Programming)
Handle long-running operations without blocking:
using System.Threading.Tasks;
// ========== Async Method ==========
public async Task<string> FetchDataAsync()
{
await Task.Delay(1000); // Simulate delay
return "Data loaded";
}
// ========== Calling Async Method ==========
public async Task ProcessAsync()
{
string result = await FetchDataAsync();
Console.WriteLine(result);
}
// ========== Multiple Async Operations ==========
public async Task FetchAllAsync()
{
Task<string> task1 = FetchDataAsync();
Task<string> task2 = FetchDataAsync();
// Wait for all tasks
await Task.WhenAll(task1, task2);
Console.WriteLine(task1.Result);
Console.WriteLine(task2.Result);
}
Tips
var when type is obvious from context