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 readonlyfor these types. Constants can only be initialised with literal values (e.g. numbers, strings).After looking up the definition.
Point.Emptyis alsostatic readonly. Reference here.