ninja hedgehog
ninja hedgehog

Reputation: 405

Create anonymous class that implements an interface

I am wondering if there is some inline short way of creating a class implementing a interface. Just like there are the anonymous methods but with implementing interfaces.

The problem is:

interface iSomeInterface
{
  void DoIt();
}

public void myMethod(iSomeInterface param)
{
 ...
}

And I would like to use it like this:

object.myMethod(new { override DoIt() { Console.WriteLine("yay"); } } : iSomeInterface);

Any ideas?

Sorry in case its a duplicate.

Upvotes: 2

Views: 7215

Answers (4)

Tosh
Tosh

Reputation: 531

Look for the "ImpromptuInterface" NuGet package. With the combination of this package and ExpandoObject, you can do something like this

//Create an expando object and create & assign values to all the fields that exists in your interface
dynamic sigObj = new ExpandoObject();
sigObj.EmployeeKey = 1234;

//Create the object using "ActLike" method of the Impromptu class
INewSignatureAcquired sig = Impromptu.ActLike<INewSignatureAcquired>(sigObj);

Upvotes: 0

Steven
Steven

Reputation: 172646

You can create a class that wraps an Action and implements that interface:

public sealed class SomeAction : ISomeInterface
{
    Action action;
    public SomeAction (Action action) { this.action = action; }
    public void DoIt() { this.action(); }
}

This allows you to use it as follows:

object.myMethod(new SomeAction(() => Console.WriteLine("yay"));

This is of course only very practical if you are going to reuse SomeAction, but this is probably the most convenient solution.

Upvotes: 3

BlackBear
BlackBear

Reputation: 22979

That is pretty common in java but there is no way you can do it in C#. You can pass a functions or procedures as parameters though:

public void myMethod(Action act)
{
    act();
}

myMethod( () => Console.WriteLine("yay") );

Several (generic) version of Action (procedure with parameters and no return value) and Func (functions with parameters and return value) exist.

Upvotes: 0

xanatos
xanatos

Reputation: 111860

Sorry, no inline implementation of classes in C#. There are only Anonymous Types, but they don't support adding interfaces (see for example Can a C# anonymous class implement an interface?) (nor they support adding methods or fields... They only support properties).

You can use the methods of System.Reflection.Emit to generate a class at runtime, but it's long and tedious.

Upvotes: 5

Related Questions