C# anonymously implement interface (or abstract class)

pistacchio picture pistacchio · Jan 20, 2012 · Viewed 10.3k times · Source

In Java it is possible to extend an interface with an anonymous class that you can implement on the fly. Example:

Runnable myRunnable = new Runnable()
{
    @Override
    public void run() { /**/ }
}

(More on: http://www.techartifact.com/blogs/2009/08/anonymous-classes-in-java.html#ixzz1k07mVIeO)

Is this possible in C#? If not, what are viable alternatives without having to rely on implementing a plethora of subclasses?

Answer

Jon Skeet picture Jon Skeet · Jan 20, 2012

No, you can't do that in C# - but typically the alternative design approach is to use a delegate instead. In the example you've given, Runnable is usually represented using ThreadStart, and you can use an anonymous method or lambda expression:

ThreadStart start = () =>
{
    // Do stuff here
};

Or if you just have a method to run, with the right signature, you can use a method group conversion:

ThreadStart start = MethodToRunInThread;

Or in the Thread constructor call:

Thread t = new Thread(MethodToRunInThread);
t.Start();

If you really need to implement an interface, you'll have to really implement it (possibly in a private nested class). However, that doesn't come up terribly often in C#, in my experience - normally C# interfaces are the kind which would naturally demand a "real" implementation anyway, even in Java.