What are non-contentious scenarios when using new(…)?

From the release notes for Visual Studio 2019 version 16.9:

There is now a refactoring that suggests using new(…) in non-contentious scenarios.

What are non-contentious vs contentious scenarios?

Answer

Credit to Jeroen Mostert for finding the the original feature request

Add new feature to suggest using ‘new(…)’ in non-contentious scenarios

Only appears in scenarios where the type is obvious from syntax. i.e. field declarations. Will not appear in cases where the existing ‘var’ preference would prefer that be ‘var’ instead.

Basically the feature is saying, it will give you suggestions when var is not preferred in the context.

Contentious Example

List<string> bob = new List<String>();

In the above case it will prefer to suggest var

var bob = new List<String>(); 

Non-contentious Example

public class Bob
{
    List<string> _bob = new List<String>();
}

In the above case var cannot be used, so it would suggest new(). This is because the contextual keyword var may only appear within a local variable declaration.

public class Bob
{
    List<string> _bob = new();
}

Another non-contentious Example

var derp = new List<Bob>()
   {
      new Bob(),
      new Bob(),
      new Bob(),
   }

The above would be a valid place to suggest new()

var derp = new List<Bob>()
   {
      new(),
      new(),
      new(),
   }

Note to Jeroen Mostert, if you answer I’ll remove this post.

Leave a Reply

Your email address will not be published. Required fields are marked *