Home > Uncategorized > How many methods does this interface have?

How many methods does this interface have?

How many methods are defined in this interface?

public interface IFoo
    void Bar<T>(T arg);

Bar is a generic method, and so in fact it defines a family of possible methods. In a way, the interface has an infinite number of possible methods. Tomorrow some third party could reference the assembly that defines this interface and call Bar with types that haven’t even been written today.

Why is this significant? Because as a general rule, I think one-method interfaces are a complete waste of time in C# because delegates amount to much the same thing and yet are so much better supported by the language.

And yet there’s no way you’re going to replace the above with a delegate. You could try:

delegate void FooBar<T>(T arg);

Which already exists anyway, and is called Action. But that’s the same as a generic interface with a non-generic method; it’s not the same as a non-generic interface with a generic method. Suppose we want to be able to pass one of these things to a function:

void Zebra(IFoo foo)
    // I can call foo.Bar with a mixture of types:

    foo.Bar(new FileInfo("trumpet-lessons.txt"));

But how can I achieve that with a delegate?

void Zebra(Action<!!!> fooBar)

I don’t want to say what goes in the angle brackets. It’s got to be left open. So I have to “leak” the generality out into my method:

void Zebra<T>(Action<T> fooBar)

And that’s not what I want either – now each invocation of Zebra can only pass forward a single type in calls to fooBar. Which is all just another way of saying that an interface with a single generic method is a fundamentally different thing to an interface with a single non-generic method, and that’s why you can’t replace it with a delegate.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: