Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing an Interface at Runtime

Tags:

c#

.net

Is it possible to make an already compiled class implement a certain interface at run time, an example:

public interface ISomeInterface {
    void SomeMethod();
}

public class MyClass {
    // this is the class which i want to implement ISomeInterface at runtime
}

is this possible, if yes then how ?

like image 428
Ibrahim Najjar Avatar asked Aug 01 '26 10:08

Ibrahim Najjar


2 Answers

Well almost. You can use impromptu-interface.

https://github.com/ekonbenefits/impromptu-interface

Basic example from https://github.com/ekonbenefits/impromptu-interface/wiki/UsageBasic :

using ImpromptuInterface;

public interface ISimpleClassProps
{
  string Prop1 { get;  }
  long Prop2 { get; }
  Guid Prop3 { get; }
}

var tAnon = new {Prop1 = "Test", Prop2 = 42L, Prop3 = Guid.NewGuid()};
var tActsLike = tAnon.ActLike<ISimpleClassProps>();
like image 158
lightbricko Avatar answered Aug 03 '26 01:08

lightbricko


You could use the Adapter pattern to make it appear your implementing the interface. This would look somewhat like this:

public interface ISomeInterface {
    void SomeMethod();
}

public class MyClass {
    // this is the class which i want to implement ISomeInterface at runtime
}

public SomeInterfaceAdapter{
    Myclass _adaptee;
    public SomeInterfaceAdapter(Myclass adaptee){
        _adaptee = adaptee;
    }
    void SomeMethod(){
        // forward calls to adaptee
        _adaptee.SomeOtherMethod();
    }
}

Using this would look somewhat like this:

Myclass baseobj = new Myclass();
ISomeInterface obj = new SomeInterfaceAdapter(baseobj);
obj.SomeMethod();
like image 39
Kenneth Avatar answered Aug 03 '26 00:08

Kenneth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!