Aaron Anodide
Aaron Anodide

Reputation: 17186

Is there any utility that dynamically generates objects that implement interfaces at run time?

I've seen a ton of opensource frameworks that implement dynamic programming in C#. Is there one that can generate an implementation of an interface without there being any actual concrete class?

Specifically, suppose you have:

interface IThing {
  int Id { get; set; } 
  string Name { get; set; }
}

And you also have objects you want to map into instances of IThing:

class Foo {
  public int FooBarId { get; set; }
  public string FooBarName { get; set; }
}

My hypothetical helper would let me write something like:

IThing concreteThing = helper.Implement<IThing, Foo>()
  PropertyGetter(x => x.Id).Returns(foo => foo.FooBarId)
  PropertyGetter(x => x.Name).Returns(foo => foo.FooBarName);

I suppose in my pretend example it would put exception throwing stubs into the setters of other properties I didn't supply...

Upvotes: 2

Views: 571

Answers (2)

jbtule
jbtule

Reputation: 31799

I have an opensource framework ImpromptuInterface (in nuget) that given an interface, will generate stubs to DLR calls (recursively even). Which means you can add whatever logic you like behind it with an implementation of DynamicObject.

Upvotes: 1

user1968030
user1968030

Reputation:

see this example.By using Reflection, you can avoid having to specify every possible Type within the implementation, but then you have other drawbacks:

The owner parameter do not expose any Type-information that is expected by the function. You need to check them manually. Reflection overhead degrades performance on each call. Reflection degrades maintainability (the method has to be implemented different). Some operations (like Indexers) are tricky to handle with Reflection.In statically typed languages like C#, the interface of a class defines which operations are supported. A supported operation may be calling a method with a specified signature, or getting or setting a property, or be able to attach to a specific event. In most cases, this makes perfect sense, since the compiler is able to verify if the operations are supported by the specified type.

Upvotes: 1

Related Questions