Reputation: 64730
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 MyClass
{
public double[] MinMax
{
set
{
if (value.Length != 2) throw new ArgumentException();
_yMin = value[0];
_yMax = value[1];
}
}
};
Upvotes: 3
Views: 88
Reputation: 74949
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;
}
Upvotes: 1
Reputation: 40838
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 }
).
Upvotes: 0
Reputation: 34834
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};
Upvotes: 3