Skip to main content

Static classes in C#

- Static class is basically same is a normal class, the difference is only single instance created for the lifetime of the application.

- During the lifetime of the application, when the first-time static class member called that time it call its constructor and create the instance and further use the same instance.

- It contains only static members means you can't create a non-static member in the static class.

- Cannot be instantiated means you can't manually using new keyword create an instance of the static class.

- It is sealed and therefore cannot be inherited.


- Static class constructors have the following properties:

- Access modifier is not allowed for the static constructor.

- Static constructor must be parameterless.

- You can't call the static constructor directly means manual or using the new keyword.

- If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.



Below is the Interview Questions related to static class
  1. Can I create more than one instance of static class?
  2. How can I create more than one instance of static class?
  3. When static class constructor execute?
  4. Can I add non-static member in static class?
  5. Can I use 'new' keyword to create an static class instance?
  6. Can I inherit static class?
  7. Can I create private constructor in static class?
  8. Can I create more than one constructor in static class?


Console application codes snippets:
using System;

namespace StaticClassExample
{
    public static class StaticClass
    {
        public static string City = string.Empty;

        static StaticClass()
        {
            City = "Mumbai";
        }
    }

    public class Program
    {
        public static void Main()
        {
            string city = StaticClass.City;

            city = StaticClass.City;

            Console.WriteLine(city);
            Console.ReadLine();
        }
    }
}


References:
https://msdn.microsoft.com/en-IN/library/79b3xss3.aspx
https://msdn.microsoft.com/en-in/library/k9x6w0hc.aspx