arrays - Got surprised knowing that C# compiler can infer less informative declaration -


consider following code snippet follow mind chronologically. commented statements cannot compiled.

    var data1 = new int[3] { 1, 2, 3 };     var data2 = new int[] { 1, 2, 3 };      var data3 = new[] { 1, 2, 3 };     var data4 = new[] { 1, 2, 3.0f }; 

the simplification done data3 , data4 understandable.

    int[] data5 = { 1, 2, 3 };     //var data6 = { 1, 2, 3 }; 

unable infer declaration data6 understandable.

    var data7 = new int[] { };     //var data8 = new [] { };      //int[] data9 = new [] { }; 

unable infer declaration data8 understandable.

what don't understand why data9 more informative cannot compiled while data10 less informative can compiled.

    int[] data10 = { };     //var data11 = { }; 

declaring data11 cannot compiled understandable.

the cases there new keyword present, usual expressions can used in context expression required. use them declarations assignment, can used in other contexts, example:

return new[] { 3 }; 

or:

call(new[] { 3 }); 

and on. in these new array expressions, type must clear expression itself. required when there variable declaration on left.

the case data9 therefore, int[] data9 = new [] { }; illegal because expression new[] { } illegal. like:

object related9 = someboolean ? "yes" : new exception(); 

which illegal because expression someboolean ? "yes" : new exception() illegal in itself, incompatible types. there declaration of type object, not make right-hand side legal.


the examples data5 , data10 show unrelated syntax array variable declaration.

int[] data5 = { 1, 2, 3 }; 

here right-hand side of = operator not expression in itself. syntax requires declaration explicit type on left of = sign (so data6 not ok). syntax related object initializers , collection initializers , introduced in c# language them, whereas new[] { ... } syntax bit older.


you should see this answer lippert, read official c# language specification.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -