1

I have a class that contains a method of which parameter name matches a field name.

class Test 
{
    private int num;

    public void Setup(int num)
    {
        if (num == 10)
        {
            ...
        }
    }
}

Is there any case in which evaluation inside the method Setup, could instead of the parameter, use the field instead?

J. Doe
  • 905
  • 1
  • 10
  • 23

2 Answers2

3

No, there is no possibility that an evaluation would use the field instead of the parameter. Variables within a scope always shadow variables of outer scopes.

So, if your method has a num parameter, there is no way to access the instance member num from within that method without qualifying it with this.

But it is best to try and avoid these situations, if you can.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
2

Yes, refer to it as this.num rather than just num.

class Test 
{
    private int num;

    public void Setup(int num)
    {
        if (num == 10) //parameter
        {
            this.num = 42; //field
        }
    }
}
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
  • Your answer assumes that the OP is asking how to access a field when there is also a parameter with the same name, but that's not what the OP is asking. The OP is asking whether having them both could potentially cause problems. (So, look at the difference between your answer and my answer.) – Mike Nakis Jan 29 '17 at 09:39
  • @MikeNakis - I read the question the other way around that he wants to know how to access the field. The way you're suggesting didn't make sense to me that the OP would be asking that. – Enigmativity Jan 29 '17 at 09:44
  • Yes, I know, your reading of the question is not unreasonable, but I think that the "Can [...] cause issues?" part in the title gives it away. So, for me downvoting you was a way to give my answer a chance, (since yours had already been upvoted, but I considered it off-mark,) and apparently there is one more person who agrees with me. – Mike Nakis Jan 29 '17 at 09:49
  • @MikeNakis - Fair enough. I guess the OP will let us know. – Enigmativity Jan 29 '17 at 09:57
  • it seems like it was settled. C-:= – Mike Nakis Jan 29 '17 at 13:44