Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include "Empty" constant in class

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 ...
}
like image 814
AppFzx Avatar asked Jul 10 '26 08:07

AppFzx


1 Answers

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.

like image 164
Paul Fleming Avatar answered Jul 12 '26 00:07

Paul Fleming



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!