Skip to content

Objects

In C#, creating an object involves two primary steps: declaring a variable of a specific type and then instantiating that variable using the new keyword. The new keyword is used to allocate memory for the object and call its constructor, initializing its state. Here's a general overview of how to instantiate objects in C#:

Object Instantiation

C#
// Declaration of a variable of a specific type
ClassName variableName;

// Instantiation using the new keyword
variableName = new ClassName();

Here's a concrete example:

C#
// Declaration of a variable of type Person
Person person;

// Instantiation using the new keyword
person = new Person();

Or, you can combine declaration and instantiation in a single line:

C#
// Combined declaration and instantiation
Person person = new Person();

If the class has one or more constructors, you can call a specific constructor based on your requirements:

C#
// Calling a parameterized constructor
Person person = new Person("Alice", "Smith", 25);

Invoking Object Methods

Invoking object methods in C# involves calling the methods defined within a class on instances of that class. This is accopmlished by using an object reference variable, followed by a dot (.), then the method you wish to call.

C#
class Program
{
    static void Main()
    {
        // Creating an instance of the Person class
        Person person = new Person("John", "Doe", 25);

        // Invoking methods on the Person object
        person.DisplayInfo();
        person.CelebrateBirthday();

        // Displaying updated information after the birthday
        person.DisplayInfo();
    }
}

In this example:

  • The Person class has attributes (firstName, lastName, age), a constructor, and two methods (DisplayInfo and CelebrateBirthday).
  • In the Main method, an instance of the Person class is created and referenced by the person variable.
  • Methods are invoked on the person object using the dot notation (object.Method()).

When you run this program, it will output:

Text Only
Name: John Doe, Age: 25
Happy Birthday!
Name: John Doe, Age: 26

This demonstrates invoking methods on a Person object. The DisplayInfo method displays information about the person, and the CelebrateBirthday method updates the person's age and prints a birthday message.

Remember that methods can perform various operations on object data, and invoking them allows you to interact with and manipulate the state of objects in your program.