3

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];
        }
    }
};

3 Answers 3

3

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};
Sign up to request clarification or add additional context in comments.

1 Comment

Its a shame my preferred syntax won't work, since I don't think the new[] says anything that cannot be fully inferred by the compiler.
1

You can drop double but other than that, it's all required.

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

If you're really intent on shortening it, you can create a helper function like this, but it's an extra function call (not a big deal, just something to know).

private static void Main()
{
    int[] a = A(1, 2, 3);

    double[] b = A(1.2, 3.4, 1);
}

private static T[] A<T>(params T[] array)
{
    return array;
}

Comments

0

The shortest valid form is:

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

The shorter form you have mentioned is called an array initializer, but you cannot use it in a property setter. The reason being that array initializers are not actually expressions and calling a property setter requires an expression on the right hand side. Array initializers are only valid in the context of a field declaration, local variable declaration, or array creation expression (i.e. new[] { -3.141, 3.141 }).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.