Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a second-level base class method like base.base.GetHashCode()

Tags:

c#

inheritance

class A {     public override int GetHashCode()     {         return 1;     } } class B : A {     public override int GetHashCode()     {         return ((object)this).GetHashCode();     } }  new B().GetHashCode() 

this overflows the stack. How can I call Object.GetHashCode() from B.GetHashCode()?

edit: B now inherits from A.

like image 672
usr Avatar asked Jun 17 '09 11:06

usr


People also ask

How do you call a base method in C#?

base (C# Reference)The base keyword is used to access members of the base class from within a derived class: Call a method on the base class that has been overridden by another method. Specify which base-class constructor should be called when creating instances of the derived class.

Which is base class in C#?

A base class, in the context of C#, is a class that is used to create, or derive, other classes. Classes derived from a base class are called child classes, subclasses or derived classes. A base class does not inherit from any other class and is considered parent of a derived class.


1 Answers

(edit - misread question)

If you want to get the original object.GetHashCode() version; you can't - at least, not unless A makes it available via something like:

protected int GetBaseHashCode() { return base.GetHashCode();} 

(and have B call GetBaseHashCode()).

The reason it overflows is that GetHashCode is (obviously) virtual - it doesn't matter if you cast it to object; it still starts at the most-derived implementation in the actual object, i.e. B.GetHashCode() (hence the explosion).

like image 113
Marc Gravell Avatar answered Sep 23 '22 19:09

Marc Gravell