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

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
231,269 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.