0

I was wondering if

var list = new List<t>();

exactly the same as

List<t> list = new List<t>()

Is this exactly the same or are there any differences?

  • 2
    Exactly to you; no, once compiled, yes. – Adrian Jan 05 '21 at 16:43
  • Well, the second example is missing a `;`. But in all seriousness, did you check out the documentation for [var](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var)? – crashmstr Jan 05 '21 at 16:44
  • Tips, every time you're wondering about these kinds of things, check it on SharpLab https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA0AXEBLANmgExAGoAfAAQCYBGAWAChyAGAAnOpQG4HyBmNyiwDCLAN4MWktv3IoWAWQAUASjESpGgG4BDKC1zYAzhhYBeFgDsYAdxYAZIxgA82CxgB8K7vQ0aHxlzd3fUdBcytbf2dXDy91SQBfBgSgA – Martheen Jan 05 '21 at 16:47

1 Answers1

0

Yes, this is totally the same. The compiler will internally replace the var with the actual type, inferred from right side of the expression.

In the C# 9 you can also use another type of record: List<t> list = new() and compiler will infer the type for the right part from the left one.

Serg
  • 3,454
  • 2
  • 13
  • 17