C# static class

The C# static class is like the normal class but it cannot be instantiated. It can have only static members. The advantage of static class is that it provides you guarantee that instance of static class cannot be created.

Points to remember

  • C# static class contains only static members.
  • C# static class cannot be instantiated.
  • C# static class is sealed.
  • C# static class cannot contain instance constructors.
Example

Let's see the example of static class that contains static field and static method.

snippet
using System;
   public static class MyMath
    {
        public static float PI=3.14f; 
        public static int cube(int n){return n*n*n;}
    }
   class TestMyMath{
       public static void Main(string[] args)
        {
            Console.WriteLine("Value of PI is: "+MyMath.PI);
            Console.WriteLine("Cube of 3 is: " + MyMath.cube(3));
        }
    }
Output
Value of PI is: 3.14 Cube of 3 is: 27
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +