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 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();}}
Explanation
- Line 4: We create a class
GreetUserfrom 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
newkeyword to create an instance of the classGreetUser. We name this instancegreet1. - Line 20: We invoke the method
Greet()using the newly created instance.