Home > other >  Object Creation in .NET 6
Object Creation in .NET 6

Time:06-30

Is there a difference between creating an object like this

var list = new List<string>();

or

List<string> list = new();

in .NET 6? Both create a list but are there any benefits of using one over the other?

CodePudding user response:

There is no difference in the object creation. More info over using 'var' can you find here

CodePudding user response:

Name of this feature is Type Inference, F# and FP languages have way more strong implementation of this

It helps you to use static typed languages as dynamic typed, write only code, logic without thinking about types and Compiler will do their job, and infer all types at compile time

For your concrete sample, here is some example

  1. When you write chain of fluent api and don't exact final type

    var result = data.Select()

  2. When you pass params

    Method(new())

CodePudding user response:

There is no difference between those two. The second one is called target-typed new expressions and was introduced with C# 9 (so it was introduced before .NET 6 - with .NET 5). And both are compiled into the same - check out the desugared version using sharplab.io.

As for benefits - both var and target-typed new expressions have the same goal - to reduce size of code, for local variables it is matter of preference which to use, but there are scenarios when only one can be used, for example for properties/fields you can't use var but can use new:

class MyClass
{
    private Dictionary<int, int> Dictionary = new();
}

While for results of method invocation you can use only var:

var s = GetString();
  • Related