Search code examples
c#.netsyntaxvar

What does the `var` inside the curly braces mean in C#?


What does the var inside the curly braces mean in C#?

E.g. there is the question.

Below the question there is a piece of code in an answer:

BitArray bits = new BitArray(new byte[] { var });

I have never seen the var being used like that and I was not able to find anything about it by googling.

When I try to run the following:

using System;

public class Program
{
    public static void Main()
    {
        var bytes = new byte[] { var };
    }
}

I am getting the error:

Compilation error (line 7, col 34): The name 'var' does not exist in the current context

I am using the .NET 4.7.2. Probably a different version of the .NET is needed?


Solution

  • In the referenced question there is a variable declared with name var (this is possible because var is not one of the reserved keywords in C#).

    This syntax:

    var bytes = new byte[] { var };
    

    Is for collection initializer which creates an array of byte containing one item (var). So in your case you are getting an error because there is no variable/field/property with name var accessible in the scope.