Code Syntax Style: Implicit/Explicit Typing ('var' Keyword)
Using implicitly typed local variables (also known as var
keyword) introduced in C# 3.0 has become quite popular as it improves readability in many scenarios. By default, JetBrains Rider also encourages using of var
keyword, but preferences of its usage are flexibly configurable — for example, you can opt for using explicit types in specific cases or everywhere and JetBrains Rider will help you enforce your preferences.
Starting from C# 7.0, you can declare local variables when deconstructing tuples. If you prefer var
in such declarations, you can additionally configure a style to use joined or separated notation, that is, for example: var (x, y) = GetTuple();
or (var x, var y) = GetTuple();
.
Another C# 7.0 feature is discards, which also allows using var
to make sure that there are no conflicts with variables in the scope that may be named _
. JetBrains Rider allows you to configure a style to always use var
with discards where appropriate.
Enforce preferences of using 'var' keyword
JetBrains Rider checks all local variables for compliance with your preferences and if they do not comply, JetBrains Rider highlights such declarations and suggests the corresponding quick-fix or fix in scope.
By default, JetBrains Rider's preferences say that 'var' keyword is preferred: If you change your preference, JetBrains Rider will help you to use explicit types:
Another option to enforce preferences of 'var' keyword usage in a bulk mode is code cleanup. You can either run code cleanup with one of the built-in profiles Full Cleanup or Reformat & Apply Syntax Style, or create and run a custom profile solely targeted at your specific task as described below.
Apply preferences of using 'var' keyword with custom Code Cleanup profile
Press Ctrl+Alt+S or choose
(Windows and Linux) or (macOS) from the menu.Go to the cleanup profiles settings page:
.Create a new profile as described in the Create a new custom cleanup profile section. In the Selected profile settings section for the new profile, tick the Enforce 'var' keyword usage settings checkbox. Optionally, you can enable other code cleanup tasks in this profile.
Click Save in the Settings dialog to apply the modifications and let JetBrains Rider choose where to save them, or save the modifications to a specific settings layer using the Save To list. For more information, see Layer-Based Settings.
Select the scope where you want to enforce your preferences:
Set the caret anywhere in the file to enforce your preferences to the file.
Select one or more items in the Solution Explorer to enforce your preferences in the files under these nodes and their child items.
Choose Code | Code Cleanup in the main menu.
In the Code Cleanup dialog that opens, select the newly created profile.
Click OK. JetBrains Rider will enforce your preferences in the selected scope.
If you want to enforce 'var' keyword usage setting without opening the Code Cleanup dialog to choose a profile, you can bind the created profile to the silent cleanup and run it by pressing Ctrl+E, F. You can also create a custom cleanup profile that would combine applying the preferences with other code style tasks.
Configure preferences of using 'var' keyword
Your 'var' keyword usage preferences are saved using the mechanism of layer-based settings. Among other things, this mechanism allows you to maintain different preferences for different solutions as well as to keep these preferences under a VCS and automatically share them with your team members.
Configure preferences of using 'var' keyword in the Settings/Preferences dialog
Go to the Syntax Style tab.
page of JetBrains Rider settings Ctrl+Alt+S, and then select theModify settings in the 'var' usage in declarations category according to your coding practices/standards.
You can set different preferences of using 'var' or explicit type for different types:
For built-in types — applies to C# built-in types.
For simple types — applies to types without generic parameters.
Elsewhere — applies to generic types and deconstruction declarations.
For each of these preferences you can opt for using 'var', explicit type, or 'var' when evident.
If you have chosen Use 'var' when evident in the previous step, you can opt to apply Visual Studio logic to decide which cases should be considered evident.
To learn the differences between JetBrains Rider and Visual Studio logic, see Use 'var' when evident: what is considered evident?.
By default, JetBrains Rider will suggest joined notation for multiple
var
's in deconstruction declarations, for examplevar (x, y) = GetTuple();
. You can select Prefer separate declarations for deconstructed variables to opt for separate notation, for example(var x, var y) = GetTuple();
.By default, JetBrains Rider suggests using standalone
_
for discards, for example(_, _) = (0, 1);
. You can select Use 'var' keyword for discards to always usevar
with discards where appropriate thus making sure that there are no conflicts with variables in the scope that may be named_
.The selectors in the right column allow you to set severity levels of code inspections detecting code that differs from your preferences.
Click Save in the Settings dialog to apply the modifications and let JetBrains Rider choose where to save them, or save the modifications to a specific settings layer using the Save To list. For more information, see Layer-Based Settings.
You can also change your preference of using 'var' keyword right in the editor, where a corresponding issue is highlighted:
Change preferences of using 'var' keyword from the editor
Set the caret to a code issue highlighted by a JetBrains Rider's inspection.
Press Alt+Enter or click the action indicator to the left of the caret to open the action list.
In the action list, go to Inspection "Use preferred 'var' style" | Configure code style and then select a desired preference:
Your change will be saved using the smart save logic.
If you need to save the modified style preference in a shared settings layer, click the Configure code style menu item or press Enter when it is selected. JetBrains Rider will open the page of JetBrains Rider settings Ctrl+Alt+S where you can modify your preference as needed, click Save To and then choose the desired settings layer.
Use 'var' when evident: what is considered evident?
When configuring preferences of using 'var' keyword vs. explicit type, you can opt for Use 'var' when evident. This option seems self-explanatory but in some cases it might be unclear what is considered 'evident' and what is not.
Apart from that, there are some differences between what is considered evident (apparent) by JetBrains Rider and by Visual Studio when both products suggest using 'var' keyword or explicit type.
The table below shows in which cases initializers that could be declared 'var' are considered evident depending on the state of the Prefer Roslyn (Visual Studio) logic for type evidence checkbox on the page of JetBrains Rider settings Ctrl+Alt+S.
Initializer expression | Examples | Off | On |
---|---|---|---|
Object creation expressions | new MyClass() | Evident | Evident |
Cast expressions | (MyClass) obj | Evident | Evident |
as expressions | obj as MyClass | Evident | Evident |
Literal expressions | "some string literal" 123 true | Evident | Evident |
Default expressions | default(MyClass) | Evident | Evident |
Tuple expressions | (1, 2, 3) | Evident when all component expressions are evident | |
Explicit array creation expressions | new int[] { 1, 2, 3 } new MyClass[5] | Evident | Evident |
Implicit array creation expressions | new [] { 1, 2, 3} new [,] { {1, 2, 3}, {1, 2, 3}, {1, 2, 3} } | Evident when all element initializers (up to 42) are evident | Not evident |
Non-generic factory (creation) methods (static methods declared in some type and returning a value of the same type) | MyClass.Build(someArgs) // returns MyClass | Evident when the method name contains a parent type name or one of the following substrings: "Create", "Build", "Construct", "Make", "Generate", "Produce", "New", "Instance" | Evident |
Generic factory (creation) methods (static methods returning a generic type and declared in a class with the same name as the return type) | Tuple.Create(1, 2, 3) | Evident when all method call arguments are evident and the method name contains one of the following substrings or a class name: "Create", "Build", "Construct", "Make", "Generate", "Produce", "New", "Instance" | Evident |
Conversion methods (methods with a name consisting of "To" plus the name of the return type) | obj.ToString() enumeration.ToList() | Evident when the return type is not generic | Evident |
Generic methods with an explicit type argument returning the value of that type argument | obj.GetValue<MyClass>() // returns MyClass | Evident | Not evident |
Enum members | KnownColor.Azure | Evident | Not evident |
Singleton fields (static/constant fields returning the value of the type where they are declared) | int.MaxValue string.Empty | Evident when the field name contains the type name or one of the following substrings: "Empty", "Instance", "Default", "Value" | Not evident |