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 collection initializers are also supported with this new shortened syntax.

Code ​

csharp
private Dictionary<string, Customer> customers = new(5);
// ...
using var writer = XmlWriter.Create(stream, new() { Indent = true });
csharp
private Dictionary<string, Customer> customers = new Dictionary<string, Customer>(5);
// ...
using var writer = XmlWriter.Create(stream, new XmlWriterSettings() { Indent = true });

Notes ​

  • new() needs a target type, so it cannot be used with var, and an argument becomes ambiguous when several overloads accept different types in that position

More information ​

Powered by Intracia