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.GetHashCode

Mark Phillips
Mark Phillips
1,749 Points

How come the Int32.GetHashCode() would return its value for integers? I would expect them to return the memory address?

In the video Jeremy says that the has code is just the memory address, but then appears to contradict this by explaining that

class Program
    {
        static void Main(string[] args)
        {
            var i = 3;
            Console.WriteLine(  i.GetHashCode());
        }
    }

1 Answer

andren
andren
28,521 Points

He says that by default the hashcode is just the memory address, in other words the GetHashCode method defined in the Object class just returns the object's memory address. However just like you can override the default equals method with another method you can also override the GetHashCode method with a new method as well.

The Int32 class overrides the GetHashCode method to just return itself. That's why you don't get its memory address when you call that method.