How to include an "empty" constant in a class
I have a class and I would like to include an "Empty" constant member similar to Point.Empty in System.Drawing. Is it possible?
Here's a simplified version of what is giving the error:
public class TrivialClass
{
public const TrivialClass Empty = new TrivialClass(0);
public int MyValue;
public TrivialClass(int InitialValue)
{
MyValue = InitialValue;
}
}
The error indicated: TrivialClass.Empty is of type TrivialClass. A const field of a reference type other than a string can only be initialized to zero.
If it matters, I would like to use it like this:
void SomeFunction()
{
TrivialClass myTrivial = TrivialClass.Empty;
// Do stuff ...
}
+3
source to share
2 answers
You can use static readonly
for these types. Constants can only be initialized 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 for a definition. Point.Empty
also static readonly
. Link here .
+11
source to share