Does C # have the equivalent of VB.NET to declare a shorthand array, for example {"string1", "string2"}?

In VB.NET, you can instantiate and immediately use an array like this:

Dim b as Boolean = {"string1", "string2"}.Contains("string1")

In C #, however, it looks like you should do this:

bool b = new string[] { "string1", "string2" }.Contains("string1");

Does C # have an equivalent shorthand syntax that uses type inference to determine the type of an array without explicitly declaring it?

+6
source share
2 answers

Implicitly typed arrays should not include their type if this could be the output :

 bool b = new [] { "string1", "string2" }.Contains("string1"); 
+19
source

It's called Implicitly Typed Arrays

You can create an implicitly typed array in which the Instance instance type is inferred from the elements specified in the initializer array. The rules for any implicitly typed variable also apply to implicitly typed arrays.

 static void Main() { var a = new[] { 1, 10, 100, 1000 }; // int[] var b = new[] { "hello", null, "world" }; // string[] } 

You can use it also for a jagged array.

+3
source

All Articles