C# Basics
Learn the syntax and fundamental features of the C# programming language
C# Basics
C# (pronounced “C sharp”) is a modern programming language developed by Microsoft. It’s strongly-typed, object-oriented, and continuously evolving with new features in every release.
Data Types
C# has a wide variety of data types:
Value Types
// Integer types
byte age = 25; // 0 to 255
short smallNumber = 100; // -32,768 to 32,767
int number = 1000; // most commonly used
long bigNumber = 1000000L;
// Floating point
float temperature = 36.5f; // 7 digits of precision
double price = 99.99; // 15-16 digits of precision
decimal money = 1000.50m; // for currency, 28-29 digits
// Boolean
bool active = true;
// Character
char letter = 'A';
Reference Types
// String
string name = "Anjar Priantoro";
string empty = "";
string? nullable = null; // nullable string (C# 8+)
// Array
int[] numbers = { 1, 2, 3, 4, 5 };
string[] names = new string[3];
// Object
object obj = "can be anything";
Operators
Arithmetic Operators
int a = 10, b = 3;
int sum = a + b; // 13
int diff = a - b; // 7
int product = a * b; // 30
int quotient = a / b; // 3 (integer division)
int remainder = a % b; // 1 (modulus)
// Increment/Decrement
a++; // a = 11
b--; // b = 2
Comparison Operators
int x = 5, y = 10;
bool equal = x == y; // false
bool notEqual = x != y; // true
bool greaterThan = x > y; // false
bool lessThan = x < y; // true
bool greaterOrEqual = x >= 5; // true
Logical Operators
bool a = true, b = false;
bool and = a && b; // false (AND)
bool or = a || b; // true (OR)
bool not = !a; // false (NOT)
Control Flow
If-Else
int score = 85;
if (score >= 90)
{
Console.WriteLine("A - Excellent!");
}
else if (score >= 80)
{
Console.WriteLine("B - Good");
}
else if (score >= 70)
{
Console.WriteLine("C - Average");
}
else
{
Console.WriteLine("Needs improvement");
}
Ternary Operator
int age = 20;
string status = age >= 18 ? "Adult" : "Minor";
Switch Statement
string day = "Monday";
switch (day)
{
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
Console.WriteLine("Weekday");
break;
case "Saturday":
case "Sunday":
Console.WriteLine("Weekend");
break;
default:
Console.WriteLine("Invalid day");
break;
}
Switch Expression (C# 8+)
string day = "Saturday";
string type = day switch
{
"Monday" or "Tuesday" or "Wednesday" or "Thursday" or "Friday" => "Weekday",
"Saturday" or "Sunday" => "Weekend",
_ => "Invalid"
};
Methods (Functions)
Basic Method
// Method with no return value
void SayHello(string name)
{
Console.WriteLine($"Hello, {name}!");
}
// Method with a return value
int Add(int a, int b)
{
return a + b;
}
// Using methods
SayHello("Anjar");
int result = Add(5, 3);
Optional Parameters
void Greet(string name, string greeting = "Hello")
{
Console.WriteLine($"{greeting}, {name}!");
}
Greet("Anjar"); // "Hello, Anjar!"
Greet("Anjar", "Hi"); // "Hi, Anjar!"
Named Arguments
void CreateUser(string name, int age, string city)
{
Console.WriteLine($"{name}, {age} years old, from {city}");
}
// Using named arguments
CreateUser(name: "Anjar", city: "Jakarta", age: 25);
Expression-bodied Members
// For simple methods
int Square(int n) => n * n;
string GetFullName(string first, string last) => $"{first} {last}";
Classes and Objects
Basic Class
public class Student
{
// Properties
public string Name { get; set; }
public int Age { get; set; }
public string Major { get; set; }
// Constructor
public Student(string name, int age, string major)
{
Name = name;
Age = age;
Major = major;
}
// Method
public void Introduce()
{
Console.WriteLine($"Hi, I'm {Name}, a {Major} student");
}
}
// Creating an object
var student = new Student("Anjar", 22, "Computer Science");
student.Introduce();
Properties with Validation
public class Product
{
private decimal _price;
public string Name { get; set; }
public decimal Price
{
get => _price;
set
{
if (value < 0)
throw new ArgumentException("Price cannot be negative");
_price = value;
}
}
// Read-only property
public decimal DiscountedPrice => _price * 0.9m;
}
Records (C# 9+)
// Simple immutable data class
public record Person(string Name, int Age);
// Usage
var person1 = new Person("Anjar", 25);
var person2 = person1 with { Age = 26 }; // copy with modification
Console.WriteLine(person1 == person2); // false (value comparison)
Null Handling
Nullable Types
int? nullableInt = null; // nullable int
string? nullableName = null; // nullable string (C# 8+)
// Check for null
if (nullableInt.HasValue)
{
Console.WriteLine(nullableInt.Value);
}
// Null-coalescing operator
int value = nullableInt ?? 0; // use 0 if null
// Null-conditional operator
string? name = null;
int? length = name?.Length; // null, not an error
Pattern Matching with Null
object? data = GetData();
if (data is string s)
{
Console.WriteLine($"String: {s}");
}
else if (data is int n)
{
Console.WriteLine($"Integer: {n}");
}
else if (data is null)
{
Console.WriteLine("Data is empty");
}
Exception Handling
try
{
int result = 10 / 0; // will throw
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Division error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"General error: {ex.Message}");
}
finally
{
Console.WriteLine("This always runs");
}
LINQ (Language Integrated Query)
LINQ is one of C#‘s most powerful features:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Filter even numbers
var evens = numbers.Where(n => n % 2 == 0);
// Transform
var squares = numbers.Select(n => n * n);
// Chaining
var result = numbers
.Where(n => n > 5)
.Select(n => n * 2)
.OrderByDescending(n => n)
.ToList();
// Aggregates
int total = numbers.Sum();
double average = numbers.Average();
int max = numbers.Max();
Next Steps
Now that you understand C# basics, continue with:
- ASP.NET Core — Building web APIs and applications
- Entity Framework Core — Database access with an ORM
- Async/Await — Asynchronous programming
Tip: Practice is key! Try building a small project to sharpen your C# skills.