Is there a construct in C# which allows you to create a anonymous class implementing an interface, just like in Java?
Asked
Active
Viewed 1.7k times
24
-
related http://stackoverflow.com/questions/191013/can-a-c-sharp-anonymous-class-implement-an-interface – mcabral Mar 22 '12 at 14:39
-
You're confusing lambda expressions (anonymous functions) with anonymous classes. It makes no sense for a function to implement interfaces – dtech Mar 22 '12 at 14:40
3 Answers
32
As has already been stated, no, this is not possible. However, you can make a class that implements the desired interface and accepts a lambda in it's constructor so that you can turn a lambda into a class that implements the interface. Example:
public class LambdaComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, T, bool> _lambdaComparer;
private readonly Func<T, int> _lambdaHash;
public LambdaComparer(Func<T, T, bool> lambdaComparer) :
this(lambdaComparer, EqualityComparer<T>.Default.GetHashCode)
{
}
public LambdaComparer(Func<T, T, bool> lambdaComparer,
Func<T, int> lambdaHash)
{
if (lambdaComparer == null)
throw new ArgumentNullException("lambdaComparer");
if (lambdaHash == null)
throw new ArgumentNullException("lambdaHash");
_lambdaComparer = lambdaComparer;
_lambdaHash = lambdaHash;
}
public bool Equals(T x, T y)
{
return _lambdaComparer(x, y);
}
public int GetHashCode(T obj)
{
return _lambdaHash(obj);
}
}
Usage (obviously doing nothing helpful, but you get the idea)
var list = new List<string>() { "a", "c", "a", "F", "A" };
list.Distinct(new LambdaComparer<string>((a,b) => a == b));

Servy
- 202,030
- 26
- 332
- 449
-
2
-
2this is the best solution for this problem i have seen yet, genius – Willem D'Haeseleer Nov 22 '12 at 09:42
-
1very cool solution. The main drawback is you have to create a base class for every interface. Is there any simple way to make it generic? – Louis Rhys Apr 16 '13 at 03:29
-
1@LouisRhys Simple, no. You'd need to create the new concrete type at compile time by emitting the IL code for it directly. It would be be fairly difficult to do. – Servy Apr 17 '13 at 13:36
-
-
1@nawfal Yeah, the pattern has been floating around for a while. I've seen it used a number of times in various places. – Servy Apr 19 '13 at 18:29
6
No. C# doesn't support anonymous classes (except anonymous types which can't define methods).

oxilumin
- 4,775
- 2
- 18
- 25
2
No, a Lambda Expression can not implement any additional interfaces than it already does.
You're also comparing the wrong things. I'm guessing you really meant to ask if anonymous types in C# can implement interfaces. The answer to that is also no.

Justin Niessner
- 242,243
- 40
- 408
- 536