C# C# Objects Loops and Final Touches Foreach Loops

Hermes Crespo
Hermes Crespo
980 Points

Why am I getting the error message: FrogStats.cs(12,45): error CS1061: Type `Treehouse.CodeChallenges.Frog[]' does....

...not contain a definition for TongueLength' and no extension methodTongueLength' of type `Treehouse.CodeChallenges.Frog[]' could be found. Are you missing an assembly reference" ....... If in the Frog.cs program file there is a Frog class created with a property called "TongueLength"???

FrogStats.cs
namespace Treehouse.CodeChallenges
{
    class FrogStats
    {
        public static double GetAverageTongueLength(Frog[] frogs)
        {
            double total = 0;
            double AverageTongueLength = 0;



            foreach(double element in frogs.TongueLength)
            {
                total = total + element;

            }

            return AverageTongueLength = total / frogs.TongueLength;
        }
    }
}
Frog.cs
namespace Treehouse.CodeChallenges
{
    public class Frog
    {
        public int TongueLength { get; }

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

1 Answer

andren
andren
28,391 Points

The TongueLength property exists on the Frog object, but frogs is not a Frog object. It is an array of Frog objects. In order to access the TongueLength property you have to pull out the individual objects from the array, you can't just call TongueLength directly on the array.

So the thing you should be looping over is frogs itself, and that will give you a Frog object, from which you can access the TongueLength property.

Like this:

foreach(Frog frog in frogs) // Pull out individual Frog objects from frogs array
{
  total = total + frog.TongueLength; // Access the TongueLength property on the object
}

Also you don't need AverageTongueLength if you intend to just return the calculation directly. You can just return it like this:

return total / frogs.Length;

Notice also that I replaced frogs.TongueLength with frogs.Length in the above code example. frogs.TongueLength is invalid as mentioned earlier, and the Length property is how you access the number of items in an array.

Hermes Crespo
Hermes Crespo
980 Points

Excellent!!! You have shown me the light!! THANKS!!