Please explain to me the use of static constructor. Why and when would we create a static constructor and is it possible to overload one?
No you can't overload it; a static constructor is useful for initializing any static fields associated with a type (or any other per-type operations) - useful in particular for reading required configuration data into readonly fields, etc.
It is run automatically by the runtime the first time it is needed (the exact rules there are complicated (see "beforefieldinit"), and changed subtly between CLR2 and CLR4). Unless you abuse reflection, it is guaranteed to run at most once (even if two threads arrive at the same time).
From Static Constructors (C# Programming Guide):
A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
Static constructors have the following properties:
A static constructor does not take access modifiers or have parameters.
A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
A static constructor cannot be called directly.
The user has no control on when the static constructor is executed in the program.
A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the
LoadLibrary
method.
Static constructors are also very useful when you have static fields that rely upon each other such that the order of initialization is important. If you run your code through a formatter/beautifier that changes the order of the fields then you may find yourself with null values where you didn't expect them.
Example: Suppose we had this class:
class ScopeMonitor
{
static string urlFragment = "foo/bar";
static string firstPart= "http://www.example.com/";
static string fullUrl= firstPart + urlFragment;
}
When you access fullUr
, it will be "http://www.example.com/foo/bar".
Months later you're cleaning up your code and alphabetize the fields (let's say they're part of a much larger list, so you don't notice the problem). You have:
class ScopeMonitor
{
static string firstPart= "http://www.example.com/";
static string fullUrl= firstPart + urlFragment;
static string urlFragment = "foo/bar";
}
Your fullUrl
value is now just "http://www.example.com/" since urlFragment
hadn't been initialized at the time fullUrl
was being set. Not good. So, you add a static constructor to take care of the initialization:
class ScopeMonitor
{
static string firstPart= "http://www.example.com/";
static string fullUrl;
static string urlFragment = "foo/bar";
static ScopeMonitor()
{
fullUrl= firstPart + urlFragment;
}
}
Now, no matter what order you have the fields, the initialization will always be correct.
1.It can only access the static member(s) of the class.
Reason : Non static member is specific to the object instance. If static constructor are allowed to work on non static members it will reflect the changes in all the object instance, which is impractical.
2.There should be no parameter(s) in static constructor.
Reason: Since, It is going to be called by CLR, nobody can pass the parameter to it. 3.Only one static constructor is allowed.
Reason: Overloading needs the two methods to be different in terms of method/constructor definition which is not possible in static constructor.
4.There should be no access modifier to it.
Reason: Again the reason is same call to static constructor is made by CLR and not by the object, no need to have access modifier to it
you can use static constructor to initializes static fields. It runs at an indeterminate time before those fields are used. Microsoft's documentation and many developers warn that static constructors on a type impose a substantial overhead.
It is best to avoid static constructors for maximum performance.
update: you can't use more than one static constructor in the same class, however you can use other instance constructors with (maximum) one static constructor.
Why and when would we create a static constructor ...?
One specific reason to use a static constructor is to create a 'super enum' class. Here's a (simple, contrived) example:
public class Animals
{
private readonly string _description;
private readonly string _speciesBinomialName;
public string Description { get { return _description; } }
public string SpeciesBinomialName { get { return _speciesBinomialName; } }
private Animals(string description, string speciesBinomialName)
{
_description = description;
_speciesBinomialName = speciesBinomialName;
}
private static readonly Animals _dog;
private static readonly Animals _cat;
private static readonly Animals _boaConstrictor;
public static Animals Dog { get { return _dog; } }
public static Animals Cat { get { return _cat; } }
public static Animals BoaConstrictor { get { return _boaConstrictor; } }
static Animals()
{
_dog = new Animals("Man's best friend", "Canis familiaris");
_cat = new Animals("Small, typically furry, killer", "Felis catus");
_boaConstrictor = new Animals("Large, heavy-bodied snake", "Boa constrictor");
}
}
You'd use it very similarly (in syntactical appearance) to any other enum:
Animals.Dog
The advantage of this over a regular enum
is that you can encapsulate related info easily. One disadvantage is that you can't use these values in a switch
statement (because it requires constant values).
Static Constructor
A constructor declared using static modifier is a static constructor. A static constructor is use to initialize static data or to perform a particular action that need to be performed only once in life cycle of class. Static constructor is first block of code to execute in class. Static constructor executes one and only one time in life cycle of class. It is called automatically. Static constructor does not take any parameters. It has no access specifiers. It is not called directly.
Static constructor is used to initialize static data members as soon as the class is referenced first time, whereas an instance constructor is used to create an instance of that class with keyword.
Source: http://www.c-sharpcorner.com/article/static-constructor-in-C-Sharp-and-their-usages/
using System;
namespace Constructor
{
class Test
{
//Declaration and initialization of static data member
private static int id = 5;
public static int Id
{
get
{
return id;
}
}
public static void print()
{
Console.WriteLine("Test.id = " + id);
}
static void Main(string[] args)
{
//Print the value of id
Test.print();
}
}
}
In the above example, static data member <id> is declared and initialized in same line. So if you compile and run this program your output would look similar to this :
Test.id = 5
Lets create one more class similar to class Test but this time the value of its static data member would depend on the value of static data member <id> of class Test.id.
//File Name : Test1.cs
using System;
namespace Constructor
{
class Test1
{
private static int id ;
//Static constructor, value of data member id is set conditionally here.
//This type of initialization is not possible at the time of declaration.
static Test1()
{
if( Test.Id < 10 )
{
id = 20;
}
else
{
id = 100;
}
Console.WriteLine("Static<Class> Constructor for Class Test1 Called..");
}
public static void print()
{
Console.WriteLine("Test1.id = " + id);
}
static void Main(string[] args)
{
//Print the value of id
Test1.print();
}
}
}
As you can see in the above static constructor, static data member <id> is initialized conditionally. This type of initialization is not possible at the time of declaration. This is where static constructor comes in picture
来源:https://stackoverflow.com/questions/4506990/what-is-the-use-of-static-constructors