Classes and Objects
Why Classes Are Needed
C# is an object-oriented language where almost everything is an object. We previously wrote code using top-level statements, but real C# programs are built from classes. A class is a blueprint for objects — it defines data (fields) and behavior (methods), while an object is a concrete instance of a class.
Class Definition
Use the class keyword to define a class. Class names use PascalCase (capitalize the first letter of each word).
class Person
{
public string Name;
public int Age;
public void SayHello()
{
System.Console.WriteLine($"Hello, I'm {Name}, {Age} years old.");
}
}
publicmeans the member is accessible from outsideName,Ageare fields (store data)SayHellois a method (defines behavior)
Creating Objects
Use the new keyword to create an object from a class:
Person p = new Person();
p.Name = "Tom";
p.Age = 18;
p.SayHello();
Hello, I'm Tom, 18 years old.
Each new creates an independent object with its own copy of fields.
Fields and Field Initialization
Fields can be assigned initial values at declaration:
class Student
{
public string Name = "Unknown";
public int Score = 0;
}
If no initial value is assigned, numeric types default to 0, and reference types default to null.
Access modifiers control field visibility:
| Modifier | Meaning |
|---|---|
public |
Accessible from anywhere |
private |
Only accessible within the class (default) |
Typically, fields are set to private and access is controlled through methods or properties.
Example
using System;
class BankAccount
{
private decimal balance = 1000m;
public void Deposit(decimal amount)
{
balance += amount;
Console.WriteLine($"Deposited {amount}, balance is {balance}");
}
public void ShowBalance()
{
Console.WriteLine($"Current balance: {balance}");
}
}
class Program
{
static void Main()
{
BankAccount acc = new BankAccount();
acc.ShowBalance();
acc.Deposit(500m);
}
}
Current balance: 1000
Deposited 500, balance is 1500
Methods
Methods are functions defined within a class that describe an object's behavior. Methods can access fields within the same class:
class Calculator
{
private int result = 0;
public void Add(int value)
{
result += value;
}
public int GetResult()
{
return result;
}
}
The this Keyword
this refers to the current object instance. Its most common use is to distinguish fields from parameters with the same name:
class Person
{
public string Name;
public int Age;
public Person(string Name, int Age)
{
this.Name = Name;
this.Age = Age;
}
}
this.Namerefers to the field,Namerefers to the parameterthiscan be omitted when there is no ambiguity
Constructors
Constructors are called automatically when an object is created, used to initialize the object.
Parameterless Constructor
If no constructor is defined, the compiler automatically generates a parameterless constructor:
class Dog
{
public string Name;
public Dog()
{
Name = "Unnamed";
}
}
Parameterized Constructor
class Dog
{
public string Name;
public Dog(string name)
{
Name = name;
}
}
⚠️ Once you define any constructor, the compiler will no longer automatically generate a parameterless constructor.
Constructor Overloading
You can define multiple constructors with different parameters:
class Dog
{
public string Name;
public int Age;
public Dog()
{
Name = "Unnamed";
Age = 0;
}
public Dog(string name)
{
Name = name;
Age = 0;
}
public Dog(string name, int age)
{
Name = name;
Age = age;
}
}
Constructor Chaining
Use this(...) to have one constructor call another, avoiding code duplication:
class Dog
{
public string Name;
public int Age;
public Dog() : this("Unnamed", 0) { }
public Dog(string name) : this(name, 0) { }
public Dog(string name, int age)
{
Name = name;
Age = age;
}
}
Example
using System;
class Book
{
public string Title;
public string Author;
public decimal Price;
public Book() : this("Unknown", "Unknown", 0m) { }
public Book(string title, string author) : this(title, author, 29.9m) { }
public Book(string title, string author, decimal price)
{
Title = title;
Author = author;
Price = price;
}
public void PrintInfo()
{
Console.WriteLine($"\"{Title}\" Author: {Author} Price: {Price}");
}
}
class Program
{
static void Main()
{
Book b1 = new Book();
Book b2 = new Book("C# Basics", "Alice");
Book b3 = new Book("Advanced C#", "Bob", 59.9m);
b1.PrintInfo();
b2.PrintInfo();
b3.PrintInfo();
}
}
"Unknown" Author: Unknown Price: 0
"C# Basics" Author: Alice Price: 29.9
"Advanced C#" Author: Bob Price: 59.9
Destructors
A destructor is called before an object is garbage collected. The syntax is ~ClassName():
class Resource
{
~Resource()
{
Console.WriteLine("Object is being reclaimed");
}
}
📌 C# has automatic garbage collection (GC), so you rarely need to write a destructor manually. Destructors are only used to release unmanaged resources (such as file handles, database connections), which will be discussed in detail in later lessons.
Object Initializers
C# 3.0 introduced object initializer syntax, which allows you to directly assign values to public fields or properties when using new:
Person p = new Person { Name = "Lily", Age = 20 };
This is equivalent to:
Person p = new Person();
p.Name = "Lily";
p.Age = 20;
Object initializers can be combined with parameterized constructors:
Person p = new Person("Lily") { Age = 20 };
Example
using System;
class Rectangle
{
public double Width = 1;
public double Height = 1;
public double Area()
{
return Width * Height;
}
}
class Program
{
static void Main()
{
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle { Width = 5, Height = 3 };
Rectangle r3 = new Rectangle { Width = 10 };
Console.WriteLine($"r1 area: {r1.Area()}");
Console.WriteLine($"r2 area: {r2.Area()}");
Console.WriteLine($"r3 area: {r3.Area()}");
}
}
r1 area: 1
r2 area: 15
r3 area: 10
Difference Between new and null
| Concept | Meaning |
|---|---|
new ClassName() |
Creates an object on the heap, returns a reference to the object |
null |
Does not point to any object, is the default value for reference types |
Person p1 = new Person();
Person p2 = null;
Console.WriteLine(p1 == null);
Console.WriteLine(p2 == null);
False
True
⚠️ Accessing a member on a null reference throws a NullReferenceException, the most common runtime error in C#:
Person p = null;
p.SayHello();
💡 Check for null before accessing:
if (p != null)
{
p.SayHello();
}
❓ FAQ
📖 Summary
- A class is a blueprint for objects, defined with
class - Objects are created with
new, each object has its own copy of fields - Fields store data, methods define behavior,
public/privatecontrols access thisrefers to the current instance, commonly used to distinguish fields from same-named parameters- Constructors are called automatically when creating an object, can be overloaded, and can use
this(...)for chaining - Destructors are called by GC automatically, generally no need to write them manually
- Object initializers
new T { Field = value }simplify assignment newcreates an object,nullmeans no object reference, accessing null members causes an error
📝 Exercises
- Define a
Carclass withBrand(string) andSpeed(int) fields, anAccelerate(int amount)method that increases Speed, and a parameterless constructor that initializes Speed to 0 - Add a parameterized constructor
Car(string brand)to theCarclass, and usethis(...)to implement constructor chaining - Use an object initializer to create a
Carobject and set Brand and Speed, then call the Accelerate method and print the final Speed - Write code demonstrating: create a
Carreference assigned tonull, try to access its member, use try-catch to catch theNullReferenceExceptionand print a message



