The instance of a class refers to an object of that class that inherits the properties and methods of that class. We can create an instance of any class in C# using the new
keyword.
ClassName objectName = new ClassName()
ClassName
: This is the class we want to create an instance from.
objectName
: This is the name we want to give to the new instance of the class ClassName
.
A new instance of the class ClassName
is created.
using System;// create a Greeting classclass GreetUser{public void Greet(){Console.WriteLine("Hi! Nice to meet you!");}}// create main classclass MainClass{static void Main(){// create an instance of GreetUser classGreetUser greet1 = new GreetUser();// call inherited methodgreet1.Greet();}}
GreetUser
from which a new instance will be created.Greet()
inside the class which greets a user. This method will be inherited by any instance of this class.new
keyword to create an instance of the class GreetUser
. We name this instance greet1
. Greet()
using the newly created instance.