So here is what I'm thinking...
public class MyClass
{
public const string MyConstant = "MyConstantValue";
private static MyClass DefaultInstance;
static MyClass()
{
DefaultInstance = new MyClass();
}
}
...
NotificationService.RegisterForNotification(MyClass.MyConstant, Callback);
Will this work or do I need to use something like a static readonly
property field to trigger the static constructor?
A static constructor is called automatically. It initializes the class before the first instance is created or any static members declared in that class (not its base classes) are referenced. A static constructor runs before an instance constructor.
yes we can have static constructor inside a non-static class. Yes, it can. But user will not have any control on its invoke.
You can define a static field using the static keyword. If you declare a static variable in a class, if you haven't initialized it, just like with instance variables compiler initializes these with default values in the default constructor. Yes, you can also initialize these values using the constructor.
Because you can't call a static constructor directly, you can't include an access modifier (e.g. public, private) when defining a static constructor. Static constructors are defined without access modifiers.
Use of a constant doesn't necessarily result in a member access which would cause the static constructor to be called. The compiler is allowed to (encouraged, even) substitute the value of the constant at compile time.
Your suggested workaround of static readonly
should be ok, although readonly
suggests a field, not a property. Properties are read-only when they have no setter, the readonly
keyword isn't involved.
A simple example:
class HasSConstructor
{
internal const int Answer = 42;
static HasSConstructor()
{
System.Console.WriteLine("static constructor running");
}
}
public class Program
{
public static void Main()
{
System.Console.WriteLine("The answer is " + HasSConstructor.Answer.ToString());
}
}
Output under .NET 4.0:
The answer is 42
The static constructor never runs!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With