I have a class and I would like to include an "Empty" constant member similar to Point.Empty in System.Drawing. Is that possible?
Here's a simplified version of what is giving an error:
public class TrivialClass
{
public const TrivialClass Empty = new TrivialClass(0);
public int MyValue;
public TrivialClass(int InitialValue)
{
MyValue = InitialValue;
}
}
The error given is: TrivialClass.Empty is of type TrivialClass. A const field of a reference type other than string can only be initialized with null.
If it matters, I'd like to use it like this:
void SomeFunction()
{
TrivialClass myTrivial = TrivialClass.Empty;
// Do stuff ...
}
You can use static readonly for these types. Constants can only be initialised with literal values (e.g. numbers, strings).
public class TrivialClass
{
public static readonly TrivialClass Empty = new TrivialClass(0);
public int MyValue;
public TrivialClass(int InitialValue)
{
MyValue = InitialValue;
}
}
After looking up the definition. Point.Empty is also static readonly. Reference here.
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