Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# anonymously implement interface (or abstract class) [duplicate]

Tags:

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?

like image 258
pistacchio Avatar asked Jan 20 '12 12:01

pistacchio


2 Answers

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.

like image 144
Jon Skeet Avatar answered Sep 23 '22 15:09

Jon Skeet


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));
like image 8
JaredPar Avatar answered Sep 24 '22 15:09

JaredPar