C# Objects
Creating and working with object instances
🎁 What are Objects?
An object is an instance of a class. While a class is a blueprint, an object is the actual thing created from that blueprint with real values and behaviors.
// Creating an object
Car myCar = new Car();
myCar.Brand = "Tesla";
myCar.Model = "Model 3";
Object Fundamentals
Creating Objects
Use 'new' keyword to instantiate
Person person = new Person();
Setting Values
Assign values to object fields
person.Name = "Alice";
person.Age = 25;
Calling Methods
Execute object behaviors
person.Walk();
person.Talk();
Multiple Instances
Create many objects from one class
Person p1 = new Person();
Person p2 = new Person();
🔹 Creating Your First Object
Objects are instances of a class, created using the new keyword, which allocates memory and calls the constructor. Instantiation brings the class blueprint to life: new Book() creates a Book object with its own set of property values like Title and Author. This fundamental process encapsulates data and behavior into a single entity, forming the basis of object-oriented programming.
// Define a class
class Book
{
public string Title;
public string Author;
public int Pages;
public void DisplayInfo()
{
Console.WriteLine("Title: " + Title);
Console.WriteLine("Author: " + Author);
Console.WriteLine("Pages: " + Pages);
}
}
// Create an object
Book myBook = new Book();
myBook.Title = "C# Programming";
myBook.Author = "John Smith";
myBook.Pages = 350;
myBook.DisplayInfo();
Output:
Title: C# Programming
Author: John Smith
Pages: 350
🔹 Multiple Objects Example
Multiple independent objects can be instantiated from the same class, each with its own state. Three Student objects—Emma, Liam, Olivia—each hold distinct values for Name and Grade. They share the same methods, like Study, but operate on separate data. This demonstrates how classes serve as templates, enabling the creation of numerous entities that model real-world diversity.
class Student
{
public string Name;
public int Grade;
public void Study()
{
Console.WriteLine(Name + " is studying.");
}
public void ShowGrade()
{
Console.WriteLine(Name + "'s grade: " + Grade);
}
}
// Create multiple student objects
Student student1 = new Student();
student1.Name = "Emma";
student1.Grade = 95;
Student student2 = new Student();
student2.Name = "Liam";
student2.Grade = 88;
Student student3 = new Student();
student3.Name = "Olivia";
student3.Grade = 92;
// Use the objects
student1.Study();
student1.ShowGrade();
student2.Study();
student2.ShowGrade();
student3.ShowGrade();
Output:
Emma is studying.
Emma's grade: 95
Liam is studying.
Liam's grade: 88
Olivia's grade: 92
🔹 Object Initialization
Object initializers provide concise syntax to set properties immediately after construction: new Product { Name = "iPhone", Price = 999 }. This enhances readability and reduces code compared to separate assignment statements. Initializers can be combined with constructors and are ideal for configuration, data transfer objects, and test data setup, making object creation more declarative.
class Phone
{
public string Brand;
public string Model;
public decimal Price;
public void DisplayPhone()
{
Console.WriteLine(Brand + " " + Model + " - $" + Price);
}
}
// Traditional way
Phone phone1 = new Phone();
phone1.Brand = "Apple";
phone1.Model = "iPhone 14";
phone1.Price = 999;
// Object initializer syntax (cleaner)
Phone phone2 = new Phone
{
Brand = "Samsung",
Model = "Galaxy S23",
Price = 899
};
phone1.DisplayPhone();
phone2.DisplayPhone();
Output:
Apple iPhone 14 - $999
Samsung Galaxy S23 - $899
🔹 Passing Objects to Methods
Objects can be passed as method parameters, allowing methods to operate on or modify the object's state. A CalculateArea method might accept a Rectangle object, read its Width and Height, and update its Area property. This enables behavior that is centered on objects, promoting modular and reusable code. Since objects are reference types, the method works on the original instance.
class Rectangle
{
public double Width;
public double Height;
}
class Calculator
{
public double CalculateArea(Rectangle rect)
{
return rect.Width * rect.Height;
}
public double CalculatePerimeter(Rectangle rect)
{
return 2 * (rect.Width + rect.Height);
}
}
// Create objects
Rectangle myRect = new Rectangle();
myRect.Width = 5;
myRect.Height = 10;
Calculator calc = new Calculator();
// Pass object to methods
double area = calc.CalculateArea(myRect);
double perimeter = calc.CalculatePerimeter(myRect);
Console.WriteLine("Area: " + area);
Console.WriteLine("Perimeter: " + perimeter);
Output:
Area: 50
Perimeter: 30
🔹 Comparing Objects
In C#, comparing objects using the equality operator (==) checks for reference equality by default. This means it determines whether two variables point to the same memory location, not whether they contain identical values. For value types or when you need to compare object state, you must implement the Equals() method or use IEquatable<T>. This is essential for ensuring logical comparisons in collections, dictionaries, and when testing object equivalence in your applications.
class Point
{
public int X;
public int Y;
}
Point point1 = new Point();
point1.X = 5;
point1.Y = 10;
Point point2 = new Point();
point2.X = 5;
point2.Y = 10;
Point point3 = point1;
// Compare references
Console.WriteLine("point1 == point2: " + (point1 == point2));
Console.WriteLine("point1 == point3: " + (point1 == point3));
// Compare values
Console.WriteLine("Same values? " +
(point1.X == point2.X && point1.Y == point2.Y));
Output:
point1 == point2: False
point1 == point3: True
Same values? True
🔹 Object Arrays
Arrays of objects allow you to store and manage collections of instances efficiently. This is ideal for grouping related entities like products, employees, or students. You can iterate through the array using loops, apply LINQ queries, and perform batch operations. Utilizing object arrays enhances code organization and scalability, making data handling more systematic and accessible for operations such as sorting, filtering, and serialization in C# applications.
class Product
{
public string Name;
public decimal Price;
public void Display()
{
Console.WriteLine(Name + ": $" + Price);
}
}
// Create an array of objects
Product[] products = new Product[3];
products[0] = new Product { Name = "Laptop", Price = 1200 };
products[1] = new Product { Name = "Mouse", Price = 25 };
products[2] = new Product { Name = "Keyboard", Price = 75 };
// Loop through array
Console.WriteLine("Product List:");
for (int i = 0; i < products.Length; i++)
{
products[i].Display();
}
Output:
Product List:
Laptop: $1200
Mouse: $25
Keyboard: $75
🔹 Key Points About Objects
- Instance: An object is an instance of a class
- Memory: Each object has its own memory space
- Independence: Objects are independent of each other
- Reference Type: Objects are reference types in C#
- Null: Object variables can be null if not initialized
- Garbage Collection: Unused objects are automatically cleaned up