Multiple Inheritance in C# using Dynamic Features

Multiple Inheritance is a feature that a class that can inherit more than one class. Although CLR does not really care about it, it is not possible in the mainstream .NET languages to have multiple inheritance.

It is arguable that why we would ever need multiple inheritance. I think it is the same paradox as having dynamic types in a statically typed language. I am not going into that debate as it is already decided for almost a decade. This is an attempt on how to achieve the same effect using dynamic types easily.

In C++, multiple inheritance can simply be expressed like this :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Auto {
public:
  virtual void Go(int a) {}
  virtual ~Auto() {}
};
class Animal {
public:
  virtual void Go() {}
  virtual ~Animal() {}
};
class SampleClass : public Auto, public Animal{};

int main() {	
	SampleClass *a = new SampleClass(); 
	//a->Go(5); // Compiler error for ambigouity
	//a->Go("going"); // Compiler error for missing method
	Animal* an = dynamic_cast<Animal*>(a);
	an->Go(); 
	
	Auto* at = dynamic_cast<Auto*>(a);
	at->Go(7);
}

When C# introduced dynamic type system and shared type system with C# 4, I thought it should be possible to express multiple inheritance using the new syntax. More like a forced Javascript prototypal inheritance instead of classical inheritance. However it turned out that it was even easier than that. It is relying on the runtime to operate on the types underlying with dynamic conversions, simply reflection.

Obviously it is not forced by the compiler, and you wouldn’t get intellisense but it will behave like a multiple inherited object. To achieve that the dynamic features of C# 4 has been used.

The same implementation in C# using Minherit object that has been created for reflected multiple inheritance. So in C#, it would look like this :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    public class Auto
    {
        public string Go(int a) {}            
    }
    public class Animal
    {
        public string Go() {}        
    }
    public class SampleClass : Minherit<Auto, Animal>
    {                        
        static void Main(string[] args)
        {
            dynamic sample = new SampleClass();            
            a.Go(4); // this will succeed at runtime and call the first Go(int)            
            a.Go("going"); // runtime error for missing method
            Animal an = (Animal)sample;
            Auto x = (Auto)sample;

            an.Go();
            x.Go(7);            
        }
    }

It uses dynamic sample that has come with .NET Framework 4 CTP. I actually think that sample will go to mscorlib with the final release in the System namespace

As the code got a bit long, I post it as project zip file if you are interested. http://www.codingday.com;//downloads/cs4trials.zip; C# 4 Dynamic Multiple Inheritance;

It is possible to create multiple inheritance abstraction as shown below. Here are the selected four methods to display how the GetMember and SetMember is implemented.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
  public override object Call(CallAction action, params object[] args)
        {
            var objMethod = GetMember<methodinfo>(this, action.Name).Concat(
                               GetMember<methodinfo>(base1, action.Name)).Concat(
                                   GetMember<methodinfo>(base2, action.Name));                                                     

            object result = null;
            bool executionSuccess = false;
            foreach (var item in objMethod)
            {
                try
                {                     
                    result = item.Second.Invoke(item.First, args);
                    executionSuccess = true;
                    break;
                }
                catch 
                {                    
                }
            }
            if (executionSuccess)
            {
                return result;
            }
            else
            {
                throw new MissingMethodException(action.Name);
            }                    
        }
 private IEnumerable<Pair<object, T>> GetMember<t>(object obj, string name)
        {
            return from member in obj.GetType().GetMember(name).OfType<t>()
                   select new Pair<object, T>(obj, member);
        }
        public override object GetMember(GetMemberAction action)
        {
            var property = GetMember<propertyinfo>(this, action.Name).Concat(
                                     GetMember<propertyinfo>(base1, action.Name)).Concat(
                                         GetMember<propertyinfo>(base2, action.Name)).FirstOrDefault();
            var field = GetMember<fieldinfo>(this, action.Name).Concat(
                            GetMember<fieldinfo>(base1, action.Name)).Concat(
                                GetMember<fieldinfo>(base2, action.Name)).FirstOrDefault();
            if (property != null)
            {
                return property.Second.GetValue(property.First, null);
            }
            else if (field != null)
            {
                return field.Second.GetValue(field.First);
            }
            else
            {
                throw new MissingMemberException(action.Name);
            }
            
        }
        public override void SetMember(SetMemberAction action, object value)
        {
            var properties = GetMember<propertyinfo>(this, action.Name).Concat(
                                    GetMember<propertyinfo>(base1, action.Name)).Concat(
                                        GetMember<propertyinfo>(base2, action.Name));
            var fields = GetMember<fieldinfo>(this, action.Name).Concat(
                            GetMember<fieldinfo>(base1, action.Name)).Concat(
                                GetMember<fieldinfo>(base2, action.Name));

            bool issucceess = false;
            foreach (var property in properties)
            {
                try
                {
                    property.Second.SetValue(property.First, value, null);
                    issucceess = true;
                    break;
                }
                catch { }             
            }

            if (!issucceess)
            {
                foreach (var field in fields)
                {
                    try
                    {
                        field.Second.SetValue(field.First, value);
                        issucceess = true;
                        break;
                    }
                    catch { }
                }
            }
            if (!issucceess)
            {
                throw new MissingMemberException(action.Name);
            }
        }