Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tool to refactor C# var to explicit type

Tags:

c#

refactoring

Our coding standards ask that we minimise the use of C# var (suggests limiting it's use to being in conjunction with Linq). However there are times when using generics where it's reasonably convenient e.g.

Dictionary<DateTime, Dictionary<string, float>> allValues = ...
// ...
foreach (var dateEntry in allValue)

is easier to type

foreach (KeyValue<DateTime, Dictionary<string, float>> dateEntry in allValue) 

(and easier than remembering what the explicit type is in some cases).

Do any of the refactoring tools have the ability to convert the former to the latter. I've had a look at Resharper but it doesn't seem to do (indeed it's default suggestion is to go in the opposite direction).

like image 575
Ian G Avatar asked Nov 14 '08 10:11

Ian G


2 Answers

I've got ReSharper 4.1, and it does offer this option (in either direction).

Actually, I'd recommend challenging the standard... the former is far more readable than the latter (especially if you call the variable pair or something similar). I would't use "var" for var i = 0, but it is ideally suited to the above.

For bulk changing, go to:

  • Cleanup Code... (pick a profile => "Edit Profiles" => Tools => Code Cleanup)
    • C#
      • Use 'var' in declaration
        • Replace direction = Can 'var' to type usage
        • 'foreach' iterator declaration style = Always use explicit type
        • Local variable declaration style = Always use explicit type

and run...

like image 98
Marc Gravell Avatar answered Nov 09 '22 00:11

Marc Gravell


This is possible in Visual Studio 2017.

Tools > Options > Text Editor > C# > Code Style > General –

Find 'var' preferences > When variable type is apparent. For Preference select "Prefer explicit type," and for Severity select "Suggestion."

enter image description here

You'll now get the light bulb actions when you use var, and you can quickly change to the explicit type by using the Ctrl. shortcut key.

enter image description here

enter image description here

like image 44
HaveSpacesuit Avatar answered Nov 09 '22 00:11

HaveSpacesuit