Vagif Abilov
Vagif Abilov

Reputation: 9991

Implementing DynamicObject functionality on a class that extends another class

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?

Upvotes: 1

Views: 125

Answers (1)

jbtule
jbtule

Reputation: 31799

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.

Upvotes: 1

Related Questions