Page Content

Tutorials

Objects In C#: Creating And Using Instances Of Classes

Objects in C#

A key idea in Object-Oriented Programming (OOP) is an object, which is a tangible representation of a class. A class serves as a template or blueprint that specifies the traits and actions, but an object is the real thing that is made from that template and is stored in computer memory.

Essential Features of Items:

Relationship to Classes

  • Each object is a class instance. For instance, “Lassie” might be an instance of the Dog class. Likewise, “Tony” and “Pepy” belong to the Cat class.
  • A type of object’s broad properties and behaviour are described by its class, whereas the object itself contains the data and executes operations.
  • Almost everything is an object in the genuinely object-oriented language of C#. Basic value types, which are implicitly confined to objects when handled as such, and arrays, which are classes in and of themselves, are examples of this.

Components (State and Behavior)

  • The term “state” describes an object’s attributes and data, which are frequently embodied in class properties and fields (member variables). A Cat object, for example, may have a name and colour that correspond to its condition.
  • Behaviour is what determines the activities or functions that an object can execute. These are put into practice in the class as methods. SayMiau(), for instance, might be a method on a Cat object.

Object Creation (Instantiation)

  • The newly added keyword is used to create objects. We call this process instantiation.
  • An object’s data members are initialized by a unique procedure known as a constructor, and memory is set aside for it when it is constructed using new. Although they lack return values, constructors share the same name as classes.
  • Instead of directly holding the data of a freshly created object, a variable given to it has a reference (memory address) to that object. The heap (dynamic memory) is where the values of classes, which are reference types in C#, are kept.

Accessing Object Members

  • When an object is formed and assigned to a variable, the dot operator (.) on the variable is used to access its members, which include fields, properties, and methods.
  • MyObject.myProperty, for instance, accesses a property, and myObject.myMethod() invokes a method.

Benefits of Object-Oriented Design

  • Data is more intimately linked to the functions that work on it because to OOP’s classes and objects, which also shield data from unintentional changes made by external operations.
  • It makes it possible to break down issues into smaller, more manageable things (objects), which serve as the foundation for data and functions.
  • Through functions, objects can speak to one another.
  • OOP encourages software reuse and modularisation since classes are enclosed components that may be applied to other systems.

Code Examples of Objects

These code samples, show how to declare a class and create and use its objects, or instances:

Cat Class and Objects

using System;
// 1. Defining a Class: Cat
// A class is a blueprint for objects.
public class Cat 
{
    // Fields: Private instance variables to hold the object's state (data).
    private string name;
    private string color;
    // Properties: Public accessors that provide a controlled way to read and write private fields.
    // Properties are "somewhere between a field and a method" and are normal in C#.
    public string Name 
    {
        get { return this.name; } // Getter: retrieves the value of the 'name' field.
        set { this.name = value; } // Setter: assigns a value to the 'name' field.
    }
    public string Color 
    {
        get { return this.color; }
        set { this.color = value; }
    }
    // Constructors: Special methods called when an object is created.
    // They initialize the object's members.
    // Default Constructor (parameterless constructor):
    public Cat() 
    {
        this.name = "Unnamed";
        this.color = "gray";
        Console.WriteLine("A new cat is born!"); // Demonstrates constructor execution
    }
    // Parameterized Constructor:
    public Cat(string name, string color) 
    {
        this.name = name;
        this.color = color;
        Console.WriteLine("A new cat named {0} ({1}) is born!", name, color);
    }
    // Methods: Defines the object's behavior (actions).
    public void SayMiau() 
    {
        Console.WriteLine("Cat {0} said: Miauuuuuu!", name); // Accessing the 'name' field
    }
}
// Class to demonstrate how to create and use objects of the Cat class
public class ObjectUsageExample
{
    public static void Main()
    {
        // 2. Creating Objects (Instantiation) using the 'new' operator.
        // This calls the default constructor.
        Cat firstCat = new Cat(); 
        // 3. Accessing Object Members: Using the dot operator '.'.
        firstCat.Name = "Tony";    // Setting the Name property
        firstCat.Color = "black";  // Setting the Color property
        firstCat.SayMiau();        // Calling the SayMiau() method
        // Creating another object using the parameterized constructor
        Cat secondCat = new Cat("Pepy", "red");
        secondCat.SayMiau();
        Console.WriteLine("Cat {0} is {1}.", secondCat.Name, secondCat.Color); // Getting Name and Color properties
        // Example demonstrating that an object variable holds a reference.
        // If we assign one object reference to another, both will point to the same object in memory.
        Cat thirdCat = firstCat; // thirdCat now refers to the same object as firstCat
        thirdCat.Name = "Garfield"; // Changing name via thirdCat changes the original object
        Console.WriteLine("After change via thirdCat:");
        firstCat.SayMiau(); // Output will show "Garfield"
        Console.WriteLine("The color of {0} is {1}.", thirdCat.Name, thirdCat.Color);
        // Example of creating an object reference without an actual object (not recommended for direct use).
        Cat uninitializedCat; 
        // Attempting to access uninitializedCat.Name here would cause a compile-time error.
       
    }
}

Output

A new cat is born!
Cat Tony said: Miauuuuuu!
A new cat named Pepy (red) is born!
Cat Pepy said: Miauuuuuu!
Cat Pepy is red.
After change via thirdCat:
Cat Garfield said: Miauuuuuu!
The color of Garfield is black.

Simple User Class with Object Initializer:

using System;
public class User
{
    // Properties can be set directly during object creation using initializers.
    public string Name { get; set; }
    public int Id { get; set; }
    // Override ToString() to provide a custom textual representation of the object.
    public override string ToString()
    {
        return string.Format("Id: {0}, Name: {1}", Id, Name);
    }
}
public class UserExample
{
    public static void Main()
    {
        // Creating a User object and initializing its properties using an object initializer.
        User user1 = new User { Name = "Alice", Id = 101 };
        Console.WriteLine(user1.ToString());
        // Creating another User object
        User user2 = new User();
        user2.Name = "Bob";
        user2.Id = 102;
        Console.WriteLine($"User 2: {user2.Name}, ID: {user2.Id}"); // Using string interpolation (similar to Console.WriteLine)
    }
}

Output

Id: 101, Name: Alice
User 2: Bob, ID: 102

To put it briefly, objects are the live, breathing things that are made from class blueprints. They have information and characteristics and work together to carry out the logic of the program.

You can also read What Is C# Recursion, How It Works And It’s Advantages

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index