Reputation: 1465
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 ...
}
Upvotes: 3
Views: 249
Reputation: 24526
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.
Upvotes: 11
Reputation: 11
Just a quick shoot, but I would suggest that Point.Empty is a static member, not a constant:
public class TrivialClass
{
public static readonly TrivialClass Empty = new TrivialClass(0);
...
}
Upvotes: 1