Refactoring to replace var with an explicit type

Applies to: yesVisual Studio noVisual Studio for Mac noVisual Studio Code

Use this refactoring to replace var in a local variable declaration with an explicit type.

This refactoring applies to:

  • C#

Why to use an explicit type

Following are some reasons to declare a variable with an explicit type:

  • To improve the code's readability.

  • When you don't want to initialize the variable in the declaration.

However, var must be used when a variable is initialized with an anonymous type and the properties of the object are accessed at a later point. For more information, see Implicitly typed local variables (C#).

How to use it

  1. Place the caret on the var keyword.

  2. Press Ctrl+. or click the screwdriver screwdriver icon icon in the margin of the code file.

    Use explicit type quick actions menu

  3. Select Use explicit type. Or, select Preview changes to open the Preview Changes dialog, and then select Apply.

See also