C# 7.0 and 7.1 support in ReSharper – Default literal

ReSharper support for C# 7 and C# 7.1As part of our blog series about ReSharper support for C# 7.0 and C# 7.1, let’s talk about the default literal (spec) which was added to C# 7.1. It lets us initialize variables in our code regardless of these variables being value types or reference types. ReSharper adds inspections, quick-fixes and context actions around this new language feature.

In this series:

Default literal

We have been able to use default(T) when we did not know whether T would be a value type or reference type. Using default(T) would return null for reference types, or a zero-initialized value for value types.

Visual Studio 2017 15.3 introduced another nice C# 7.1 feature: the default literal. It can be used instead of the default(T) expression, inferring the target type based on usage context. It is shorter (T could be a long class name), and as a bonus we can use it in most places where we would normally use null – it is essentially the “null” that works with both value and reference types.

ReSharper recognizes the default literal syntax and comes with a code inspection that tells us when default(T) is used and can be replaced by just default. Of course, a quick-fix can remove the redundant type specification — either for one occurrence or for all occurrences in the current file, project or solution. And if you do prefer using default(T), the quick-fix allows us to add the type specification again.
Default literalcode analysis and quick-fix in ReSharper

Download ReSharper Ultimate or check out Rider that takes advantage of ReSharper’s language support updates. We’d love to hear your thoughts.

About Maarten Balliauw

Maarten Balliauw is a Developer Advocate at JetBrains, working on .NET tools. He focuses on .NET, Azure, web technologies and application performance. Maarten is a frequent speaker at various national and international events. In his free time, he brews his own beer. Follow him on Twitter or check his personal blog.
This entry was posted in How-To's and tagged , , , , . Bookmark the permalink.

Leave a Reply

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