Anonymous inner classes in C#

cdmckay picture cdmckay · Jan 22, 2011 · Viewed 10.7k times · Source

I'm in the process of writing a C# Wicket implementation in order to deepen my understanding of C# and Wicket. One of the issues we're running into is that Wicket makes heavy use of anonymous inner classes, and C# has no anonymous inner classes.

So, for example, in Wicket, you define a Link like this:

Link link = new Link("id") {
    @Override
    void onClick() {
        setResponsePage(...);
    }
};

Since Link is an abstract class, it forces the implementor to implement an onClick method.

However, in C#, since there are no anonymous inner classes, there is no way to do this. As an alternative, you could use events like this:

var link = new Link("id");
link.Click += (sender, eventArgs) => setResponsePage(...);

Of course, there are a couple of drawbacks with this. First of all, there can be multiple Click handlers, which might not be cool. It also does not force the implementor to add a Click handler.

Another option might be to just have a closure property like this:

var link = new Link("id");
link.Click = () => setResponsePage(...);

This solves the problem of having many handlers, but still doesn't force the implementor to add the handler.

So, my question is, how do you emulate something like this in idiomatic C#?

Answer

Matthew Manela picture Matthew Manela · Jan 22, 2011

You can make the delegate be part of the constructor of the Link class. This way the user will have to add it.

public class Link 
{
    public Link(string id, Action handleStuff) 
    { 
        ...
    }

}

Then you create an instance this way:

var link = new Link("id", () => do stuff);