Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
        }
    }
};
like image 729
abelenky Avatar asked Apr 19 '26 20:04

abelenky


1 Answers

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};
like image 127
Karl Anderson Avatar answered Apr 21 '26 12:04

Karl Anderson



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!