C# - 'new' Keyword Example

C# | "new" Keyword: In this tutorial, we will learn about the "new" keyword with the help of C# program. By Nidhi Last updated : April 15, 2023

C# new Keyword

The new keyword is used to create an instance of an object, and to invoke a constructor. It allocates the space for a class object during the execution of the program.

Consider the below example, showing how can you use new keyword to create the objects.

C# program to demonstrate the example 'new' keyword

The source code to demonstrate the new keyword is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

// Program to demonstrate the example 
// of New keyword in C#

using System;

// Creating class "Sample1"
class Sample1 {
  public void Method() {
    Console.WriteLine("Sample1.Method() called");
  }
}

// Creating class "Sample2"
class Sample2 {
  public void Method() {
    Console.WriteLine("Sample2.Method() called");
  }
}

// The main class
class NewDemo {
  // Main() code/function
  static void Main() {
    // Creating the obejcts with the help 
    // of new keyword
    Sample1 S1 = new Sample1();
    Sample2 S2 = new Sample2();
    
    // Calling the member function
    S1.Method();
    S2.Method();
  }
}

Output

Sample1.Method() called
Sample2.Method() called
Press any key to continue . . .

Explanation

In the above program, we created three classes Sample1, Sample2, and NewDemo. Sample1 and Sample2 class contains a method Method(). The NewDemo class contains the Main() method. In the Main() method we created the object S1 and S2 of Sample1 and Sample2 class. Then print the method Method() of both classes.

C# Basic Programs »


Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.