Wednesday, 12 May 2010

C# Array Literal?

C# allows you to declare an array in the following way:

string[] strArray = { "a","b" };

thus gives you the illusion that { "a","b" } is an array liberal, just like "good string" is a string literal, because you can declare a string like this:

string myString = "good string";

However, if you pass { "a","b" } directly to a method that take string array as a parameter, e.g. String.Split(), you will get a compile error. It has to be done like this:
{ "a","b" } is just a short cut for compiler when declaring an array, in the same way that var is used. It is not an array literal. Actually If you use var in combination with { "a","b" } as below, you will get a compile error, as compiler cannot infer the type you want to declare.

var mySring = {"a", "b"};

You have to specify the type explicitly in either side of the equation:

string[] myString = {"a", "b"};

or

var myString = new[] {"a", "b"};


The easiest way to remember this is that when declaring an array, a pair of square brackets ([]) is mandatory! So, if you want to pass an array as a parameter to a method without giving the array a variable name, use this form:

new[]{ , , ,.....}






No comments:

Post a Comment