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

keyword 'Is' and operator '=='

I wonder the difference between == operator and 'is' keyword. in the if clause I need to find if VocabularyWord is the same object type with 'object'. In this case can I use '==' operator? When we compare an object, not value, should we all use 'is' ? if(!(VocabularyWord == object)) vs if(!(VocabularyWord is object))

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(!(VocabularyWord is object))
{
return false;
}

VocabularyWord that = obj as VocabularyWord;

return this.Word==that.Word;

}



    }
}

1 Answer

Steven Parker
Steven Parker
217,443 Points

The "==" operator tests equality (or identity) and returns true for objects if both terms reference the same object. But the "is" operator tests type compatibility and returns true if the expression on the left can be converted to the type on the right. It does not compare references or values.

I would expect "VocabularyWord is object" to generate an error since "object" is not a type.