1

I need an advise on the best way to simulate multiple inheritance for a C# class that needs to be extended with support for dynamics.

I have a class MainClass needs not to be dependent on DLR - all its properties and methods are statically compiled. It has plenty of overloaded operators. It is some sort of DSL.

ExtendedClass is basically a MainClass with support for C# dynamics, e.g. in addition to all MainClass features it needs to overload DynamicObject's TryGetMember/TryInvokeMember, so clients may use it with extended properties evaluated at runtime.

Here comes a problem of DynamicObject being a class, not an interface. So ExtendedClass must only derive from DynamicObject which means it should basically duplicate all MainClass functionality.

I guess believe this is not uncommon situation (two similar classes, one must derive from some system class, thus making it impossible to reuse functionality by inheriting one from another). Is there any smarter way of dealing with this situation than straightforward approach: add MainClass as a member field to ExtendedClass, duplicate all its methods/properties and simple forward it to the contained instance of MainClass?

Vagif Abilov
  • 9,835
  • 8
  • 55
  • 100

1 Answers1

1

It's hard to say with such a very generic description. The common pattern I'm familiar with is:

public class MainClass{
      foo bar();
      more stuff {get;set;}
      ....
}

public class ExtendedClass:MainClass{
      protected class Helper:DynamicObject{ ...}
      private Helper _helper;
      public Extended(){
          _helper= new Helper(this);
      } 

      public dynamic Extend {
         get{ return _helper};
      }
}

That way your dynamic properties or methods have their own namespace if you will by requiring to call Extend first to sort of trampoline.

jbtule
  • 31,383
  • 12
  • 95
  • 128
  • But I am looking now at IDynamicMetaObjectProvider, won't it solve this problem? According to the docs, this is the exact case when I can add dynamics to a class that inherits from another class. – Vagif Abilov Aug 01 '13 at 16:16
  • It is, but it's a lot of work. If you want to go down that road, I'd be totally interested in the result. – jbtule Aug 01 '13 at 17:56
  • Looking into it now. My expressions are not that complex, hopefully it won't be that hard. But I see it's going to take its time. – Vagif Abilov Aug 01 '13 at 20:07