ReSharper
 
Get ReSharper
Get your hands on the new features ahead of the release by joining the Early Access Program for ReSharper 2025.1! Learn more

Code Syntax Style: Object Creation ('new()' vs 'new T()')

Last modified: 11 February 2024

Starting with C# 9.0, you can create objects with the target-typed new operator without explicit type specification when the type can be inferred, that is List<string> _myList = new(); instead of List<string> _myList = new List<string>();.

Depending on the context, the optional type specification can either clutter your code with redundant information or, on the contrary, improve the readability.

Therefore, ReSharper provides two code style preferences for object creation expressions:

  • when the created type is evident from usage, like in the following cases:

    • Initializers of fields/constants/properties/events private Test field = new()

    • Initializers of local variables when an explicit type is preferred Test local = new()

    • Return values of expression-bodied members public List <Test> M() => new()

    • Values within array initializer new Test[] { new(), new() }

    • Values within collection initializer new List <Test> { new(), new() }

    • Default parameter values void M(TestStruct arg = new()) { }

  • when the created type is not evident (for example, in return statements).

ReSharper helps you enforce style preferences for object creation expressions in the existing code and takes your preferences into account when it produces new code with code completion and code generation features, applies code templates and performs refactorings.