I like variables named correctly but in some cases it is very hard to do.
So if my object implements IDisposable
then I can use:
using (var whatever = new Whatever()) { //... }
But it is rare case, so I found another way to handle it - anonymous block (not sure how it called correctly):
//...
{
var whatever = new Whatever();
//...
}
//...
if (condition)
{
var whatever = new Whatever();
}
Is it a good approach? Are there any pitfalls or widespread belief that it reduces code readability?
Said in simple terms, if multiple variables in a program have the same name, then there are fixed guidelines that the compiler follows as to which variable to pick for the execution.
February 14, 2021. A name can represent only one entity in each scope. That is why, in the same scope, there cannot be two variables with the same name as this may generate compiler errors. We can declare two variables or member functions that have the same name within the same scope using namespace .
Yes it's fine, mainly because, syntactically , they're used differently.
"Of course you cannot have int x and long x fields in the same class, just as you cannot have two methods with the same name and parameter list.". A better analogy is that you cannot have a method with the same name and a different type in the same class.
Basically, if the compiler doesn't complain and your code is readable and easy to understand, there's nothing wrong with that.
For example:
foreach (var foo in foos)
{
var task = new FooTask(foo);
task.Run();
}
foreach (var bar in bars)
{
var task = new BarTask(bar);
task.Run();
}
This is actually (in my opinion) slightly easier to read than
foreach (var foo in foos)
{
var task1 = new FooTask(foo);
task1.Run();
}
foreach (var bar in bars)
{
var task2 = new BarTask(bar);
task2.Run();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With