Skip to content

Commit 683102b

Browse files
authored
Rephrased the use of var (#250)
1 parent 80d0260 commit 683102b

1 file changed

Lines changed: 29 additions & 11 deletions

File tree

_rules/1520.md

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,40 @@
11
---
22
rule_id: 1520
33
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
55
severity: 1
66
---
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.
88

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;
1111

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.
1522

1623
Instead, use `var` like this:
1724

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);
2139

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

Comments
 (0)