VSO VSO - 3 months ago 8
C# Question

New Array Without Explicitly Specifying Data Type

I just saw this syntax while checking the docs for EF:

DropIndex("dbo.MyTable", new[]{"MyColumName"});


I was confused for a second before figuring out that it was just shorthand for
new string[]{"MyColumName"}
. I couldn't really find examples of that being valid syntax, so I tried:

string[] fooArray = new[] {"SomeString"};


The compiler doesn't have a problem with it, I guess since it can absolutely determine the type from the fact that the array is being populated by a string.

I don't see anything about it in the docs and it doesn't seem to work with int values (I guess because it doesn't know automatically if I am passing
int
or
long
automatically). So, I guess this is just a curiosity, rather than a useful feature.

Anyway, the actual question. Is there any advantage to this syntax, situations where it should be used, and where it should be avoided? Can it be used with numbers somehow?

P.S. I do feel a bit silly asking this, seems like semantics.

Answer

It should work for all types provided all items are of the same type or it can know what is the left hand side is or the parameter type is.

Notice it does work for ints: https://dotnetfiddle.net/S2DLzV

Comments