Share via


Implicitly Typed Arrays (C# Programming Guide)

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. For more information, see Implicitly Typed Local Variables (C# Programming Guide).

Implicitly-typed arrays are usually used in query expressions together with anonymous types and object and collection initializers.

The following examples show how to create an implicitly-typed array:

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

        // single-dimension jagged array 
        var c = new[]   
{  
    new[]{1,2,3,4},
    new[]{5,6,7,8}
};

        // jagged array of strings 
        var d = new[]   
{
    new[]{"Luca", "Mads", "Luke", "Dinesh"},
    new[]{"Karen", "Suma", "Frances"}
};
    }
}

In the previous example, notice that with implicitly-typed arrays, no square brackets are used on the left side of the initialization statement. Note also that jagged arrays are initialized by using new [] just like single-dimension arrays.

Implicitly-typed Arrays in Object Initializers

When you create an anonymous type that contains an array, the array must be implicitly typed in the type's object initializer. In the following example, contacts is an implicitly-typed array of anonymous types, each of which contains an array named PhoneNumbers. Note that the var keyword is not used inside the object initializers.

var contacts = new[] 
{
    new {
            Name = " Eugene Zabokritski",
            PhoneNumbers = new[] { "206-555-0108", "425-555-0001" }
        },
    new {
            Name = " Hanying Feng",
            PhoneNumbers = new[] { "650-555-0199" }
        }
};

See Also

Reference

Implicitly Typed Local Variables (C# Programming Guide)

Arrays (C# Programming Guide)

Anonymous Types (C# Programming Guide)

Object and Collection Initializers (C# Programming Guide)

var (C# Reference)

Concepts

C# Programming Guide

LINQ Query Expressions (C# Programming Guide)