So this code compiles:
var foo = new[]
{
new { prop1 = 1, prop2 = "whatever" },
default,
new { prop1 = 2, prop2 = "something" },
};
But the following doesn't:
var foo = new[]
{
new { value = new { prop1 = 1, prop2 = "whatever" } },
new { value = default },
new { value = new { prop1 = 2, prop2 = "something" } },
};
And so far the only way I can find to get it to do so is via:
T MakeDefaultOf<T>(T dummy) => default(T);
var foo = new[]
{
new { value = new { prop1 = 1, prop2 = "whatever" } },
new { value = MakeDefaultOf(new { prop1 = 0, prop2 = "" }) },
new { value = new { prop1 = 2, prop2 = "something" } }
};
But it would seem for both the first two examples the compiler has enough information to work out the implicit type of 'default' - so is there a reason it doesn't? Are there any ways of achieving what I want without an ancillary function or variable?
Depending on your use case, you may get away with this:
var foo = new[]
{
new { prop1 = 1, prop2 = "whatever" },
default,
new { prop1 = 2, prop2 = "something" },
}.Select(x => new { value = x } ).ToArray();
I'm not aware of any syntax sugar to initialize such default values.
The reason why second (new {value = default} ) initialization fails is due to
C# arrays
For a single-dimensional array, the array initializer must consist of a sequence of expressions that are assignment compatible with the element type of the array.
Compiler checks type of each individual element and then computes the best suitable base type. There is no second pass over objects to figure out if all can be made compatible with the likely resulting type (which had to be the first step to implement the behavior you expect).
As result the compiler tries to reason what new {value = default} is and there is not enough information to construct the type. Note that passing null instead default would not help as it will not define particular type - the helper method you have need to be used to provide the exact type for null at this point. And the resulting type must be exactly the same as all other elements of array because anonymous types must match exactly to be assignment compatible - C# anonymous types:
Anonymous types are class types that derive directly from object, and that cannot be cast to any type except object...
...If two or more anonymous object initializers in an assembly specify a sequence of properties that are in the same order and that have the same names and types, the compiler treats the objects as instances of the same type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With