How to instantiate a class in C#?

CsharpProgrammingServer Side Programming

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
raja
Published on 31-Aug-2018 08:08:58
Advertisements