20

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?

0

2 Answers 2

20

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is a feature I miss from time to time, especially because my interfaces are often narrow (role interfaces) and adhere to the Interface Segregation Principle. It would be convenient when I could register a delegate in my DI configuration, while the rest of the application could still depend on that interface (instead of a Func<T>), without having to create some sort of proxy class that wraps that delegate and implement that interface.
8

As Jon pointed out this is not possible in C#.

One alternate pattern in C# though is to use a combination of a factory and a delegate to allow on the fly implementations of an interface. Essentially the factory takes in a delegate for each method of the interface and uses them as the backing implementation. For example, here's a version for IComparable<T>.

public static class ComparableFactory {
  private sealed ComparableImpl<T> : IComparable<T> {
    internal Func<T, T, int> _compareFunc;
    public int Compare(T left, T right) {
      return _compareFunc(left, right);
    }
  }
  public IComparable<T> Create<T>(Func<T, T, int> compareFunc) {
    return new ComparableImpl<T>() { _compareFunc = compareFunc };
  }
}

...

IComparable<Person> impl = CompareableFactory.Create<Person>(
  (left, right) => left.Age.CompareTo(right.Age));

1 Comment

Very cool, +1! But as a good practice, better to just roll the named class..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.