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 Loops and Final Touches Foreach Loops

Pedro Gonzalez
Pedro Gonzalez
2,097 Points

I am stuck in the Foreach loop task. Any help is greatly appreciated

My code can't run because i get a compiling error stating "Cannot convert type Treehouse.CodeChallenges.Frog' todouble' ". So my question is How can I fix my code so I don't get this compiling error and what does it mean? Thank you in advance to whoever replies.

FrogStats.cs
namespace Treehouse.CodeChallenges
{
    class FrogStats
    {
        public static double GetAverageTongueLength(Frog[] frogs)
        {
            double total = 0;
            foreach(double i in frogs)
            {
                total = total + frogs[i].TongueLength;                
            }
            return total/frogs.Length;
        }
    }
}
Frog.cs
namespace Treehouse.CodeChallenges
{
    public class Frog
    {
        public int TongueLength { get; }

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

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! Oh wow, you're really close here! Inside your foreach loop you're saying for every double i in the frogs array. But the frogs array doesn't contain a set of doubles. It contains a set of frogs of type Frog! :frog:

So your code is trying to explicitly cast a Frog to a double, which cannot be done and results in the compiler error. If I modify your code just slightly, it passes.

namespace Treehouse.CodeChallenges
{
    class FrogStats
    {
        public static double GetAverageTongueLength(Frog[] frogs)
        {
            double total = 0;
            foreach(Frog i in frogs)
            {
                total = total + i.TongueLength;                
            }
            return total/frogs.Length;
        }
    }
}

Now our i variable is of type Frog instead of a double. Hope this helps! :sparkles:

Pedro Gonzalez
Pedro Gonzalez
2,097 Points

Thank you so much for helping me.Hope you have a great day.