jjw
jjw

Reputation: 294

Is there a way to designate a default property of a class?

I wonder if there is a way to designate a default property of a class in C#.

For example, if I have the class below:

class NewType
{
    public object Value 
    {
        get => _value;
        set
        {
            IsInitialized = true;
            _value = value;
        }
    }
    public bool IsInitialized { get; private set; }

    // ... etc properties
}

I want to use the above class as follows:

void Test()
{
    NewType Value = new NewType();

    // The follow assignment expression means 'Value.Value = 10;'
    Value = 10;
}

I don't know if the above idea is good but I think it can improve readability in my case.

Is there a way to achieve this goal?

Upvotes: 1

Views: 2329

Answers (1)

Rufus L
Rufus L

Reputation: 37070

In answer to your question about a "default property", the answer is no. The best you can do is specify the property whose value you want to assign:

var newType = new NewType {Value = 10};

The next best thing is to create a constructor that sets the value:

class NewType
{
    private int _value;
    public int Value
    {
        get { return _value; }
        set
        {
            IsInitialized = true;
            _value = value;
        }
    }

    public bool IsInitialized { get; private set; }

    public NewType(int value) 
    {
        Value = value;
    }

    // ... etc properties
}

And now there's slightly less typing:

var newType = new NewType(10);

If you want to be able to initialize your class based on an integer without calling the constructor, you can implement an implicit operator for int, and create a new instance of your class from the assigned value:

class NewType
{
    private int _value;
    public int Value
    {
        get { return _value; }
        set
        {
            IsInitialized = true;
            _value = value;
        }
    }

    public bool IsInitialized { get; private set; }

    public static implicit operator NewType(int i) => new NewType {Value = i};

    // ... etc properties
}

And now you can do:

NewType newType = 10;

The problem here is that if you already have a class with some other properties set and then you use the implicit operator to try to set Value, you actually reassign the whole object and the other properties will be set back to their default values.

Upvotes: 3

Related Questions