Here lets discuss what is the Difference between Static Constructor & Non-static Constructors with example
Constructor is usually used to initialize data. However Static Constructor is used to initialize only static members.
Non-static constructors can also be called as Instance Constructors as they need instance to get executed.
Static Constructor
1. Static constructor is used to initialize static data members.
2. Static constructor can't access anything but static members.
3. Static constructor can't have parameters
4. Static constructor can't have access modifiers like Public, Private or Protected.
Lets see the difference between Static Class and Non-static Class
1. Static Class cannot be instantiated unlike the non-static class. You should directly access its Method via the StaticClassName.MethodName
2. Your Program can't tell when it is going to load static class but its definitely loaded before the call.
3. One more point, A Static class will always have the static constructor and its called only once since after that its in the memory for its lifetime.
4. A Static class can contain only static members. So all the members and functions have to be static.
5. A Static class is always sealed since it cannot be inherited further. Further they cannot inherit form any other class (except Object)
• How to declare the static constructor?
Static constructors are declared using a static modifier explicitly while all other remaining constructors are non-static constructors. Non-static constructors can also be called as Instance Constructors as they need instance to get executed.
• How it gets called?
• How it gets called?
Static constructors are always called implicitly but the non-static constructors are called explicitly i.e by creating the instance of the class.
• How it gets Executed?
• How it gets Executed?
Static constructor executes as soon as the execution of a class starts and it is the first block of code which runs under a class. But the non-static constructors executes only after the creation of the instance of the class. Each and every time the instance of the class is created, it will call the non-static constructor.
Lets summarize this again -
Lets summarize this again -
A static constructor will always execute once in the entire life cycle of a class. But a non-static constructor can execute when an instance of that class is created.
Sample code as below for your reference that shows the declaration, execution of the static and non-static constuctor.
Sample code as below for your reference that shows the declaration, execution of the static and non-static constuctor.
class TestClass
{
static TestClass()
{
Console.WriteLine("this is static constructor...");
}
public TestClass()
{
Console.WriteLine("this is public constructor..");
}
}
class Program
{
static void Main(string[] args)
{
TestClass obj = new TestClass();
TestClass obj1 = new TestClass();
Console.ReadLine();
}
}
0 comments:
Post a Comment