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?
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With