sharpenrocks / Sharpen

Visual Studio extension that intelligently introduces new C# features into your existing codebase
https://sharpen.rocks
MIT License
418 stars 32 forks source link

[C# 3.0: Implicitly Typed Local Variables] Use var keyword in variable declaration with object creation #18

Closed ironcev closed 5 years ago

ironcev commented 5 years ago

C# Suggestion definition

C# Suggestion definition  
C# Language Versions 3.0
C# Feature Implicitly Typed Local Variables
C# Suggestion Use var keyword in variable declaration with object creation

Description

The suggestion suggests to use var keyword only if the variable is initialized with object creation (new keyword). In other words, suggestion suggests to use var keyword only if the type is directly obvious from the declaration itself.

Usage Examples

Non-usage Examples

When the explicit type and the type in the object creation is not exactly the same the suggestion should not appear.

Corner Cases

A type named var in the scope

If there is a type named var in the scope, the suggestion should not appear. Because "If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration." For more info see: http://thehumbleprogrammer.com/the-variform-var/ This corner case can be ignored in the first implementation since it is very unlikely to happen.

Multiple implicitly-typed variables cannot be initialized in the same statement

E. g. this is valid:

int a = 1, b = 2, c = 3;

but this is not:

var a = 1, b = 2, c = 3;

This corner case must be supported in the first implementation. This means the suggestion must not appear in a case like this:

References

Acceptance Criteria

ironcev commented 5 years ago

This suggestion is implemented and merged into master (thanks for the pull request @shankyjain7243!). It will be available in the v0.9.0.