Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does c# have a VB.NET-equivalent for shorthand array declaration like {"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 appears you have to do this:

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

Does c# have equivalent shorthand syntax that uses type inference to determine the type of array without it having to be explicitly declared?

like image 725
oscilatingcretin Avatar asked Dec 20 '12 13:12

oscilatingcretin


2 Answers

Implicitly typed arrays do not have to include their type, provided it can be inferred:

bool b = new [] { "string1", "string2" }.Contains("string1");
like image 199
burning_LEGION Avatar answered Sep 19 '22 03:09

burning_LEGION


It called Implicitly Typed Arrays

You can create an implicitly-typed array in which the type of the array instance is inferred from the elements specified in the array initializer. 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 jagged array.

like image 29
Soner Gönül Avatar answered Sep 21 '22 03:09

Soner Gönül