.NET 2.0 also supported anonymous delegates, it's just that the syntax was a bit more verbose compared to lambdas, and the output type didn't work. And there were no extension methods in C # 2.0 (although you could use C # 3.0 and compile with .NET 2.0) that are the foundation of LINQ and can work on interfaces.
For comparison:
- .NET 2.0:
delegate(int i) { return (i < 5); } delegate(int i) { return (i < 5); } - .NET 3.5:
i => i < 5
.NET 2.0 also does not share common subscribed delegates ( Func and Action ), but you can also easily define them yourself (for all combinations of options that you like):
public delegate void Action<T>(T item); public delegate Tresult Func<T, Tresult>(T item);
Thus, no matter what your answer, used to simulate anonymous interfaces, can be represented using .NET 2.0 delegates due to the added verbosity. Forcing you to ask yourself: "Is it really that short to write?"
[Update]
If your interface is the only method interface, for example:
interface IFoo { string Bar(int value); } class SomeOtherClass { void DoSomething(IFoo foo); }
then you can completely get rid of it and just use the delegate instead:
class SomeOtherClass { void DoSomething(Func<int, string> bar); } new SomeOtherClass().DoSomething(delegate(int i) { return i.ToString(); });
If you have an interface with many methods that you want to implement built-in in many different places, you can use something like this:
interface IFoo { string GetSomething(); void DoSomething(int value); }
So that you can pass delegates to the DelegatedFoo inline class:
var delegated = new DelegatedFoo( delegate() { return ""; },
Using the .NET 4 syntax of C # 4.0, it would look a little cleaner due to the syntactic sweetness of lambdas and the named parameters:
var delegated = new DelegatedFoo( getStuff: () => "", doStuff: i => { } );