|
1 | 1 | --- |
2 | 2 | rule_id: 1520 |
3 | 3 | rule_category: maintainability |
4 | | -title: Only use `var` when the type is very obvious |
| 4 | +title: Only use `var` when the type is obvious or unimportant |
5 | 5 | severity: 1 |
6 | 6 | --- |
7 | | -Only use `var` as the result of a LINQ query, or if the type is very obvious from the same statement and using it would improve readability. So don't |
| 7 | +Only use `var` as the result of a LINQ query, if the type is very obvious from the same statement, or when it's really not important. |
8 | 8 |
|
9 | | - // what type? int? uint? float? |
10 | | - var item = 3; |
| 9 | + // Debatable: Did the author intend to use a long here? |
| 10 | + var indexInSpan = 0; |
11 | 11 |
|
12 | | - // Not obvious what base-class or interface to expect. |
13 | | - // Also difficult to refactor if you can't search for the class. |
14 | | - var myfoo = MyFactoryMethod.Create("arg"); |
| 12 | + // Bad: What does this return? An IEnumerable<T>? IEqueryable<T>? What about deferred execution? |
| 13 | + var results = RunSearchQuery(searchColumnsSql); |
| 14 | + |
| 15 | + // Bad: If the type is so important you have to put it in the name of the variable, use an explicit type. |
| 16 | + var valueString = GetDisplayValueOf(context); |
| 17 | + |
| 18 | + // Debatable: DbType? SqlDbType? OracleDbType? Might be good to know. |
| 19 | + var dataType = row.GetColumnType(columnIndex); |
| 20 | + |
| 21 | +Even for the debatable cases, making the type explicit will avoid another round of code review comments. |
15 | 22 |
|
16 | 23 | Instead, use `var` like this: |
17 | 24 |
|
18 | | - var query = from order in orders where order.Items > 10 and order.TotalValue > 1000; |
19 | | - var repository = new RepositoryFactory.Get(); |
20 | | - var list = new ReadOnlyCollection(); |
| 25 | + // Good |
| 26 | + var query = |
| 27 | + from order in orders |
| 28 | + where order.Items > 10 and |
| 29 | + order.TotalValue > 1000; |
| 30 | + |
| 31 | + // Good: In most cases, it's clear that we're returning a User. Although it may be useful to know if it's a domain entity or an abstraction. |
| 32 | + var user = new UserFactory.Get(); |
| 33 | + |
| 34 | + // Good: Nothing to clarify here |
| 35 | + var list = new ReadOnlyCollection(); |
| 36 | + |
| 37 | + // Good enough: We can safely assume it's a string |
| 38 | + var displayValue = GetDisplayValueOf(context); |
21 | 39 |
|
22 | | -In all of three above examples it is clear what type to expect. For a more detailed rationale about the advantages and disadvantages of using `var`, read Eric Lippert's [Uses and misuses of implicit typing](https://docs.microsoft.com/en-us/archive/blogs/ericlippert/uses-and-misuses-of-implicit-typing). |
| 40 | +The consequence of this guideline is that you can't use tooling to determine whether `var` is warranted. It all depends on the context. |
0 commit comments