Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force child class to override function of ancestor via parent

Tags:

c#

inheritance

I am writing an algorithm which requires the user to create his own class which inherits from a class defined by me. However, the algorithm requires the user to override the Equals and GetHashCode functions from the C# standard libraries.

Can I force the class inherited from my class to implement the GetHashCode and Equals functions?

public abstract int GetHashCode();

Writing this in my base class is not an option, as my base class inherits GetHashCode from it's parent, where it is implemented already.

like image 404
Aart Stuurman Avatar asked Nov 05 '13 14:11

Aart Stuurman


2 Answers

This is what you're looking for. Since your class is abstract you can pretty much do this without any problem.

public abstract override int GetHashCode();

This despite of it derived from some other class, this makes your sub class must override this method.

like image 70
Sriram Sakthivel Avatar answered Oct 15 '22 06:10

Sriram Sakthivel


You can create 2 new methods that will be abstract and will be called from GetHashCode and Equals your class.

Example:

public abstract ParentClass {
    public abstract int MyGetHashCode();

    public override int GetHashCode(){
        return MyGetHashCode();
    }

    // same thing for Equals
}
like image 42
Euphoric Avatar answered Oct 15 '22 06:10

Euphoric