Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple inheritance problem in C#

Tags:

c#

This question came to my mind while I am reading the post Why doesn't C# support multiple inheritance? from MSDN Blog.

At first look at the following code:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class A
    {
        int num;
        public A()
        {
            num = 0;
        }
        public A(int x)
        {
            num = x;
        }
        public override int GetHashCode()
        {
            return num + base.GetHashCode();
        }
    }
    class B : A
    {
        int num;
        public B()
        {
            num = 0;
        }
        public B(int x)
        {
            num = x;
        }
        public override int GetHashCode()
        {
            return num + base.GetHashCode();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            B b = new B();
            Console.Write(a.GetHashCode() + " " + b.GetHashCode());
            Console.Read();
        }
    }
}

Object class is the ultimate base class of all classes. So it is the base class of A and B both in my program and also make A as a base class of B. So B has now two base class, one is A and another is Object. I override one method GetHashCode() of Object Class in class A and B both. But in class B, base.GetHashCode() method returns the return value of GetHashCode() method of class A. But I want this value from Object class. How can I get that?

like image 638
chanchal1987 Avatar asked Aug 06 '10 16:08

chanchal1987


2 Answers

B has only one base class, and that is A. A has one base class, and that is object. There is no multiple inheritance; object is only inherited by classes that don’t already inherit from something else.

If you still think you need to call object.GetHashCode(), there is a very hacky workaround to do this in the question How to invoke (non virtually) the original implementation of a virtual method?.

like image 86
Timwi Avatar answered Oct 16 '22 14:10

Timwi


You could write a protected instance method in class A that exposes GetHashCode() from Object. Then call that protected method in class B.

like image 23
Curt Avatar answered Oct 16 '22 14:10

Curt