var array type

You can create an implicitly-typed array.

We can use var to declare array and let C# figure out the array type.

The type of the array instance is inferred from the elements in the array initializer.

With implicitly-typed arrays, no square brackets are used on the left side of the initialization statement.


using System;

class Program
{
    static void Main(string[] args)
    {
        var anArray = new int[] { 1, 2, 3 };

        var rectMatrix = new int[,]  // rectMatrix is implicitly of type int[,]
            {
              {0,1,2},
              {3,4,5},
              {6,7,8}
            };

        var jagged = new int[][]  // jagged is implicitly of type int[][]
                {
                   new int[] {0,1,2}, 
                   new int[] {3,4,5}, 
                   new int[] {6,7,8}
                };

    }
}

For single dimensional array C# can infer the type by converting all array elements to one type.


using System;

class Program
{
    static void Main(string[] args)
    {
        var anArray = new[] { 1, 2, 3 };

    }
}

Implicitly-typed Arrays in Object Initializers

In the following example, contacts is an implicitly-typed array of anonymous types.

The var keyword is not used inside the object initializers.


public class MainClass
{
    public static void Main()
    {
        var a = new[] 
        {
            new {
                    Name = "C#",
                    ISBNs = new[] { "1-111555-08", "2-222222-01" }
                },
            new {
                    Name = "Java",
                    ISBNs= new[] { "3-333650-55" }
                }
        };
    }
}
java2s.com  |  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.