Skip to content

Target-typed new C# 9.0code reductionreadability

Use new without a type if the compiler can infer it.

It is necessary prior to C# 9.0 to specify the type of object you want to be created even when the compiler should be able to determine it from the variable type declaration, parameter type declaration, or other type information.

C# 9.0 relaxes these rules and allows you to just specify new() instead of new MyClass() - constructor parameters, object initializers and list initializers are also supported with this new shortened syntax.

Code inferring from instance member type

C#
private Dictionary<string, Customer> customers = new(5);
// ...
JsonSerializer.Serialize(invoice, new() { IgnoreReadOnlyFields = true });
C#
private Dictionary<string, Customer> customers = new Dictionary<string, Customer>(5);
// ...
JsonSerializer.Serialize(invoice, new JsonSerializerOptions() { IgnoreReadOnlyFields = true });

More information