Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Objects Object-Oriented Programming Initialization

dsteelz
dsteelz
1,203 Points

code won't work

I'm stuck on the final question of the C# objects course "initialization" challenge. my code won't compile. according to the challenge, "my constructor isn't initializing the TongueLength to the value passed in."

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

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

1 Answer

public readonly int TongueLength;

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

Try changing the constructor's variable to tongueLength along with the assignment. Having both variables in upper case is most likely confusing the treehouse test engine.

andren
andren
28,558 Points

While it's true that the Treehouse challenge checker is far from perfect in this case its not really a matter of it being confused, but a matter of the solution code actually being incorrect.

When you have a field variable and a parameter that is named the same thing and you want to reference the field variable you have to prepend it with "this", like so:

this.TongueLength

If you don't then the C# compiler will always assume that you are referencing the variable that is local to the method, in other words the parameter.

So by setting "TongueLength = TongueLength" you are telling C# to assign the value of the parameter variable to the parameter variable. While that's not technically invalid code it will not fulfill the criteria of the challenge, hence the challenge checker marks it as wrong.

This means that besides changing the name of the parameter the challenge could be complete like this:

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

        public Frog(int TongueLength)
        {
           this.TongueLength = TongueLength;
        }
    }
}
dsteelz
dsteelz
1,203 Points

thanks. yours and andren's solutions did the trick.