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# 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
229,644 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.