C# — Classes and Objects
Basic class
using System;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public void Greet()
{
Console.WriteLine($"Hi, I'm {Name}!");
}
}
class Program
{
static void Main()
{
var alice = new Person { Name = "Alice", Age = 30 };
alice.Greet();
}
}
Access modifiers
public class BankAccount
{
public string Owner { get; set; } // Accessible everywhere
protected double Balance { get; set; } // Accessible in derived classes
private double interestRate; // Accessible only in this class
public BankAccount(string owner, double initial)
{
Owner = owner;
Balance = initial;
interestRate = 0.05;
}
public void Deposit(double amount)
{
if (amount > 0) Balance += amount;
}
public double GetBalance() => Balance;
}
Properties
using System;
public class Person
{
// Auto-property
public string Name { get; set; }
// Property with validation
private int age;
public int Age
{
get => age;
set
{
if (value < 0)
throw new ArgumentException("Age cannot be negative");
age = value;
}
}
// Read-only property
public string Description => $"{Name} is {Age} years old";
// Init-only property (C# 9)
public string Id { get; init; }
}
class Program
{
static void Main()
{
var p = new Person { Name = "Alice", Age = 30, Id = "P001" };
Console.WriteLine(p.Description);
// p.Id = "P002"; // Error: init-only
}
}
Constructors
using System;
public class Rectangle
{
public double Width { get; }
public double Height { get; }
// Primary constructor (C# 12)
public Rectangle(double width, double height)
{
Width = width;
Height = height;
}
// Constructor chaining
public Rectangle(double side) : this(side, side) { }
// Static factory method
public static Rectangle CreateSquare(double side) => new(side, side);
public double Area() => Width * Height;
}
class Program
{
static void Main()
{
var r1 = new Rectangle(5, 3);
var r2 = new Rectangle(4); // Square
var r3 = Rectangle.CreateSquare(6);
Console.WriteLine($"Area 1: {r1.Area()}"); // 15
Console.WriteLine($"Area 2: {r2.Area()}"); // 16
Console.WriteLine($"Area 3: {r3.Area()}"); // 36
}
}
Destructor / IDisposable
using System;
public class Resource : IDisposable
{
private bool disposed = false;
public Resource()
{
Console.WriteLine("Resource acquired");
}
public void Dispose()
{
if (!disposed)
{
Console.WriteLine("Resource released");
disposed = true;
}
GC.SuppressFinalize(this);
}
~Resource()
{
Dispose();
}
}
class Program
{
static void Main()
{
// Using statement ensures Dispose is called
using (var res = new Resource())
{
Console.WriteLine("Using resource...");
}
// Resource released here
// C# 8 using declaration
using var res2 = new Resource();
Console.WriteLine("Using resource 2...");
}
}
Static members
using System;
public class User
{
private static int count = 0;
public string Name { get; }
public User(string name)
{
Name = name;
count++;
}
public static int GetCount() => count;
// Static constructor
static User()
{
Console.WriteLine("User class initialized");
}
}
class Program
{
static void Main()
{
new User("Alice");
new User("Bob");
Console.WriteLine($"Total users: {User.GetCount()}"); // 2
}
}
Records (C# 9+)
using System;
// Immutable data class
public record Point(double X, double Y);
// Record with custom methods
public record Person(string Name, int Age)
{
public string Greeting => $"Hello, I'm {Name}!";
}
class Program
{
static void Main()
{
var p1 = new Point(3, 4);
var p2 = new Point(3, 4);
Console.WriteLine(p1 == p2); // True (value equality)
Console.WriteLine(p1); // Point { X = 3, Y = 4 }
// Non-destructive mutation
var p3 = p1 with { X = 10 };
Console.WriteLine(p3); // Point { X = 10, Y = 4 }
}
}
Mini Practice
Write C# code that:
- Creates a
Carclass with properties and methods - Implements
IDisposablefor cleanup - Uses a primary constructor
- Demonstrates record equality
Up Next
In the next lesson, you'll learn about Constructors — initialization patterns in C#.
Related Topics
Frequently Asked Questions about Classes and Objects
What is Classes and Objects in C#?
Classes and Objects is a fundamental concept in C#. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Classes and Objects?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Classes and Objects.
Why is Classes and Objects important in C#?
Classes and Objects is essential for C# development. Understanding this concept will help you write better code and solve real-world problems more effectively.