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# Intermediate C# System.Object Object.Equals

Nathan Reinauer
Nathan Reinauer
2,097 Points

Compiler says "override" doesn't work with Equals method...

The compiler accepted an overridden Equals method in the video though, so I'm confused. When I take "override" out, it tells me "not all code paths return a value".

VocabularyWord.cs
using System;
namespace Treehouse.CodeChallenges
{
    public class VocabularyWord
    {
        public string Word { get; private set; }

        public VocabularyWord(string word)
        {
            Word = word;
        }

        public override string ToString()
        {
            return Word;
        }

        public override bool Equals(VocabularyWord x, VocabularyWord y)
        {
            if(x == y)
            {
                return true;
            }
        }
    }
}

1 Answer

Steven Parker
Steven Parker
217,443 Points

:point_right: The error is unrelated to the override.

Whether it reports it or not, the issue is the same with or without override. Examine your method and you'll notice that the only return statement is within an if conditional block. If the conditional turns out to be false, the method would end without executing any return and thus be unable to satisfy the requirement of returning an item of type bool.

You could fix this by putting another return (presumably with the argument "false") after the conditional block.

But in this case there's an even easier fix, just replace the entire method body with this:

           return x == y;

Then, without any conditionals, it will return either true or false based on the comparison.