C# C# Objects Object-Oriented Programming Initialization

I don't understand

It says to initialize the constructor with ToungeLength which I did and its not working.

Frog.cs
namespace Treehouse.CodeChallenges
{
    class Frog
    {
        public readonly int TongueLength;

        public Frog(int TongueLength)
        {
            TongueLength = TongueLength;
        }
    }
}

1 Answer

Balazs Pukli
Balazs Pukli
46,037 Points

You are referencing two different things with the same variable name, which causes ambiguity.

C# has a built in feature to handle these situations. If the class variable and the local variable passed in as a parameter would have a different name, you wouldn't need to specify which one are you trying to influence. But in this case, you named both the same. In this case:

  • with "TongueLength", you can refer to the local variable of the constructor function, passed in as a parameter.
  • with "this.TongueLength" , you can refer to the class variable. "This" keyword is a reference to the current object instance, which is just being created by the constructor.
        public Frog(int TongueLength)
        {
            this.TongueLength = TongueLength;
        }

Another solution would be using another name for the parameter to avoid ambiguity.

(Please note that this is not considered best practice among C# developers. Using the "this" keyword is more common solution. )

        public Frog(int tongueLengthParameter)
        {
            TongueLength = tongueLengthParameter;
        }

It is also worth mentioning, that you can use the this keyword in the latter case as well, but in that case, it is not necessary to avoid ambiguity.

        public Frog(int tongueLengthParameter)
        {
            this.TongueLength = tongueLengthParameter; // you can use "this" keyword, even when it is not necessary to avoid ambiguity
        }