Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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 Peak
Balazs Peak
46,097 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
        }