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

Error, operator += not valid

Whenever i try to use the operator "+=", it tells me it isnt valid to use in int or double units. Last time i tried to get the average of something I used "+=", and i have no idea how to do it otherwise.

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

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

1 Answer

Tim Danner
Tim Danner
3,281 Points

The problem here is that you're trying to assign frog objects to an int variable, which causes type error.

Keep in mind that when you're looping through an array of a certain type, all the elements will also be of that type. To access the properties or methods, use the dot notation:

namespace Treehouse.CodeChallenges
{
    class FrogStats
    {
        public static double GetAverageTongueLength(Frog[] frogs)
        {
            int sum = 0;
            foreach (Frog frog in frogs)
            {
                // access the TongueLength property through dot notation
                sum += frog.TongueLength;
            }
            return sum / frogs.Length;
        }
    }
}