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

Nir Klein
Nir Klein
7,353 Points

Regarding 'Equals' override

Hi there, I've been working on the following challenge: https://teamtreehouse.com/library/intermediate-c/systemobject/objectequals

The challenge is about overriding 'Equals' in 'VocabularyWord' class.

Get someone share a hint about what I might missing here? (attached my code)

Thanks!

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(object obj)
        {
            if(obj != null)
            {
                string checkThat = obj as string;

                if(Word.Length != checkThat.Length)
                {
                    return false;   
                }

                for(int i = 0; i < Word.Length; i++)
                {
                    if(Word[i] != checkThat[i])
                    {
                        return false;   
                    }
                }
                return true;
            }
            else
            {
                return false;   
            }
        }
    }
}

2 Answers

Steven Parker
Steven Parker
218,692 Points

You're close! But the objects being compared are both VocabularyWord objects, so it doesn't make sense to cast one as a string. Instead, you can cast it to a VocabularyWord and then access the Word inside it:

                string checkThat = (obj as VocabularyWord).Word;

Once you've done that, the rest of the code will work, but you really only need to compare the strings directly:

                return Word == checkThat;
Nir Klein
Nir Klein
7,353 Points

It works! thanks!