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
// Declaration of a variable of a specific type
ClassName variableName;
// Instantiation using the new keyword
variableName = new ClassName();
Here's a concrete example:
// 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:
If the class has one or more constructors, you can call a specific constructor based on your requirements:
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.
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
andCelebrateBirthday
). - In the
Main
method, an instance of thePerson
class is created and referenced by theperson
variable. - Methods are invoked on the
person
object using the dot notation (object.Method()
).
When you run this program, it will output:
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.