Advertisement
Advanced C#, Fundamentals

How do target-typed 'new' expressions work, and what ambiguity do they resolve compared to always specifying the type twice?

Short answer

Target-typed 'new()' lets you OMIT the type name on the right-hand side of an assignment when the LEFT-HAND side's declared type (or a method's parameter/return type) already makes it unambiguous — reducing redundant repetition, especially useful for long generic type names…

Save C# mock interview
Advertisement
AModel answer
Target-typed 'new()' lets you OMIT the type name on the right-hand side of an assignment when the LEFT-HAND side's declared type (or a method's parameter/return type) already makes it unambiguous — reducing redundant repetition, especially useful for long generic type names, while the compiler still infers the FULL type exactly as if you'd written it explicitly.
List<Dictionary<string, int>> data = new(); // target-typed: type inferred from the left side
// equivalent to: List<Dictionary<string, int>> data = new List<Dictionary<string, int>>();

Point origin = new(0, 0); // works with constructors taking arguments too
Real-world example
Reducing repetitive, verbose type names when declaring and initializing a variable with a long generic type on the left side.
Likely follow-ups
  • In what situation would target-typed 'new()' actually be AMBIGUOUS or disallowed by the compiler?
Related topics