C# compiler ignores duplicated parameter name in constructor
I'm not sure why this is happening - hoping someone can explain it!
I have a base class called BaseRequest with this in it:
protected int cartNumber;
I have a derived class, which inherits BaseRequest. It has a public field and constructor as follows:
public int currentCartNumber;
public ExtendedBaseRequest(int cartNumber)
{
c开发者_C百科urrentCartNumber = cartNumber;
}
Yes, I know it's a bit silly to have a parameter with the same name as the protected field in the base class, but I didn't notice it until now!
This compiles and runs, but the public currentCartNumber value in the derived class is not set as it uses the value from the base class, which is always zero as initialised.
Shouldn't the compiler moan about this because the declaration of cartNumber in the constructor's signature has the same name as the one in the base?
Looking forward to hearing from you.
This compiles and runs, but the public currentCartNumber value in the derived class is not set as it uses the value from the base class, which is always zero as initialised.
That description does not match the code fragment you've provided. Please provide a complete short program that we can compile and run ourselves to repro the alleged behaviour.
Shouldn't the compiler moan about this because the declaration of cartNumber in the constructor's signature has the same name as the one in the base?
No, that's perfectly legal. It is illegal to have the same name declared twice in the same declaration space, but a base class and a formal parameter list have different declaration spaces.
We want it to be legal to do this:
class C
{
int blah;
public C(int blah)
{
this.blah = blah;
}
}
Your analysis of what's happening is incorrect. There's something else going on here.
Are you sure that you're not passing 0
into the constructor?
The unqualified cartNumber
will always refer to the parameter. The inherited field would need to be qualified with this
or base
.
In the code shown in the question, the statement currentCartNumber = cartNumber
will assign the value of the cartNumber
parameter to the currentCartNumber
field.
I would say you have no way to solve this, you can use this to force usage of local member but you have no way to specify you want to use the parameter.
either you rename the local protected member using smth like m_ or my prefixes or you change the parameter name.
see here:
How do you name constructor argument and member variables?
精彩评论