Prove One Instance of an Object for Static Class



Here in the example a static Demo class is created and a static variable count is declared.

Here the count variable is treated as a global variable .so it keeps on increasing in the example ,because only one instance of the class is created

Example

static class Demo{
   public static int count;
   static Demo(){
      System.Console.WriteLine("Static Constuctor called");
   }
}
class Program{
   static void Main(){
      Demo.count++;
      Demo.count++;
      System.Console.WriteLine(Demo.count);
      Console.ReadKey();
   }
}

Output

Static Constuctor called
2
Updated on: 2020-08-04T07:01:58+05:30

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements