How to instantiate a class in C#?


Use the new operator to instantiate a class in C#.

Let’s say our class is Line. Instantiation will create a new object as shown below −

Line line = new Line();

Using the object, you can now call the method −

line.setLength(6.0);

Let us see the example −

Example

 Live Demo

using System;

namespace LineApplication {
   class Line {
      private double length; // Length of a line

      public Line() {
         Console.WriteLine("Object is being created");
      }
      public void setLength( double len ) {
         length = len;
      }
      public double getLength() {
         return length;
      }

      static void Main(string[] args) {
         Line line = new Line();

         // set line length
         line.setLength(6.0);
         Console.WriteLine("Length of line : {0}", line.getLength());
      }
   }
}

Output

Object is being created
Length of line : 6

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 22-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements