How to create instances of a class with new keyword in C#

Overview

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.

Syntax

ClassName objectName = new ClassName()
Syntax for creating a new instance of a Class in C#

Parameters

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 .

Return value

A new instance of the class ClassName is created.

Example

using System;
// create a Greeting class
class GreetUser
{
public void Greet(){
Console.WriteLine("Hi! Nice to meet you!");
}
}
// create main class
class MainClass
{
static void Main()
{
// create an instance of GreetUser class
GreetUser greet1 = new GreetUser();
// call inherited method
greet1.Greet();
}
}

Explanation

  • Line 4: We create a class GreetUser from which a new instance will be created.
  • Line 6: We create a method Greet() inside the class which greets a user. This method will be inherited by any instance of this class.
  • Line 12: We create the main class.
  • Line 17: We make use of the new keyword to create an instance of the class GreetUser. We name this instance greet1.
  • Line 20: We invoke the method Greet() using the newly created instance.