Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct or best way to declare variable in C# ASP.NET

Tags:

c#

asp.net

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;
}
like image 217
Nabil A Avatar asked Dec 06 '25 18:12

Nabil A


1 Answers

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 -

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

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.

like image 178
Barr J Avatar answered Dec 09 '25 15:12

Barr J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!