Reputation: 71
In the following code, which option (A or B), are the best way to declare a variable which will be assigned in the following if statement.
Alternatively, is there a better way than A or B.
(A) List<Dollars> amount;
(B) var amount = new List<Dollars>();
if (vortex is null)
{
amount = this.seven.Map<List<Dollars>>(twelve);
}
else
{
amount = rendered;
}
Upvotes: 3
Views: 349
Reputation: 10927
The answer lies in the post of Microsoft docs Implicitly Typed Local Variables:
The var keyword can also be useful when the specific type of the variable is tedious to type on the keyboard, or is obvious, or does not add to the readability of the code.
Look at the line -
One example where var is helpful in this manner is with nested generic types such as those used with group operations. In the following query, the type of the query variable is IEnumerable>. As long as you and others who must maintain your code understand this, there is no problem with using implicit typing for convenience and brevity.
The disadvantage here is, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required.
Your answer is, no. There is no
best way to declare a variable
There is: what type of way suits your needs the most.
Upvotes: 4