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.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,558 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.