Search code examples
c#arraysinitializer

Using Initializer Syntax on a C# Property


In C#, this is valid syntax:

int[] numbers = {1, 2, 3, 4, 5};

I'm trying to use similar syntax with a property on my object:

MyClass myinst = new MyClass();              // See Class Definition below
myinst.MinMax = {-3.141, 3.141};             // Invalid Expression
myinst.MinMax = new double[]{-3.141, 3.141}; // Works, but more verbose

Can I do anything like my desired syntax?


Class Definition

class MyClass
{
    public double[] MinMax
    {
        set
        {
            if (value.Length != 2) throw new ArgumentException();
            _yMin = value[0];
            _yMax = value[1];
        }
    }
};

Solution

  • The double syntax is redundant, as the type of the array can be inferred by the property's type, so the best you can do is this:

    myinst.MinMax = new[] {-3.141, 3.141};