Reputation: 45
namespace project1
{
public class testclass
{
int i = 0;
public int foobar()
{
int i = 1;
return i;
}
}
}
Result:
1
I am declaring two times of i
variable. Why does c# compiler allowing me this ?
If I will try to declare in same scope then compiler will give me exception so why allowing in nested scope?
Upvotes: 0
Views: 2190
Reputation: 2120
This is not a bug
Your field int i
in the class declaration can be accessed at any time with this.i
so there is no overlap. In fact, this is actually the convention to write (private) field names, parameters and local variables within methods in camelCase. Properties, method names, class names etc. on the other hand are written in PascalCase.
So in your class if you want to access the field i
of your class, you can do so by writing this.i
. Otherwise you will access the scope designated variable i
as long as you are within the if
-block.
namespace Project1 // PascalCase here for namespace name
{
public class TestClass // Again PascalCase for class name.
{
int i = 0; // camelCase correct here for field name.
public void Foobar() // PascalCase for method name.
{
if (0 == 0)
{
int i = 0; // camelCase correct here for local variable name.
// Cannot be re-declared until your if-block is finished.
// accessing both elements named 'i'
this.i = i;
}
return;
}
}
}
See Microsoft docs for further reference.
Upvotes: 3
Reputation: 8255
All variables declared in a particular scope have to be unique.
You can reuse some variables depending on their data types, but whether or not you should reuse a variable depends on what you're doing.
Your code can work, but you're declaring i
a second time which is incorrect as it already exists with a value of 0.
You need to change its value instead of trying to recreate the variable:
namespace project1
{
public class testclass
{
int i = 0;
public void foobar()
{
if (0 == 0)
{
i = 0;
}
return;
}
}
}
You could also create a new variable:
namespace project1
{
public class testclass
{
int i = 0;
public void foobar()
{
if (0 == 0)
{
int j = 0;
}
return;
}
}
}
Upvotes: 0