Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface-implementing anonymous class in C#? [duplicate]

Tags:

Is there a construct in C# which allows you to create a anonymous class implementing an interface, just like in Java?

like image 598
RandyTek Avatar asked Mar 22 '12 14:03

RandyTek


People also ask

Can Anonymous classes be implemented an interface?

No, anonymous types cannot implement an interface. We need to create your own type. Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first.

What is an anonymous class?

An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final. Like a nested class, a declaration of a type (such as a variable) in an anonymous class shadows any other declarations in the enclosing scope that have the same name.

Can you instantiate an interface C#?

An interface can't be instantiated directly. Its members are implemented by any class or struct that implements the interface. A class or struct can implement multiple interfaces.


2 Answers

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)); 
like image 121
Servy Avatar answered Sep 21 '22 13:09

Servy


No. C# doesn't support anonymous classes (except anonymous types which can't define methods).

like image 29
oxilumin Avatar answered Sep 18 '22 13:09

oxilumin