Classes and Properties
Classes and Properties in C#
Class declaration
Classes bundle data (fields/properties) and behaviour (methods). Create instances with new.
Auto-properties C# auto-properties generate a backing field automatically:
csharp
public string Name { get; set; }
public int Age { get; private set; }
public string Id { get; } = Guid.NewGuid().ToString();Constructors
Initialize object state. The this keyword refers to the current instance and can call overloaded constructors.
Static members
- Static fields and methods belong to the type, not instances.
- Use static members for utilities and shared state.
Object initializer syntax Set properties without custom constructors:
csharp
var p = new Person { Name = "Alice", Age = 30 };Key points:
- Prefer properties over public fields — they allow future validation logic.
recordtypes (C# 9+) auto-generate equality, ToString, and immutable properties.init-only setters (C# 9+) allow setting properties only during object initialization.
Code Examples
Class with auto-properties and constructorscsharp
using System;
class BankAccount {
public string Owner { get; }
public string AccountNumber { get; }
public decimal Balance { get; private set; }
public BankAccount(string owner, decimal initialBalance) {
Owner = owner;
AccountNumber = $"ACC-{new Random().Next(1000, 9999)}";
Balance = initialBalance;
}
public void Deposit(decimal amount) {
if (amount <= 0) throw new ArgumentException("Amount must be positive");
Balance += amount;
}
public override string ToString() => $"{Owner} | {AccountNumber} | ${Balance:F2}";
static void Main() {
var acc = new BankAccount("Alice", 1000m);
acc.Deposit(250m);
Console.WriteLine(acc);
}
}Auto-properties with private setters allow reading from outside but only writing from inside the class.
Static members and object initializerscsharp
using System;
class Counter {
private static int _total = 0;
public int Id { get; }
public string Label { get; set; }
public Counter(string label) {
_total++;
Id = _total;
Label = label;
}
public static int Total => _total;
}
class Program {
static void Main() {
var a = new Counter("Alpha") { Label = "First" };
var b = new Counter("Beta");
Console.WriteLine($"Total counters: {Counter.Total}");
Console.WriteLine($"{a.Id}: {a.Label}");
Console.WriteLine($"{b.Id}: {b.Label}");
}
}Static fields are shared across all instances. Object initializers set properties right after construction.
Quick Quiz
1. What does `public int Age { get; private set; }` mean?
2. What is an object initializer in C#?
Was this lesson helpful?