First I would like to say that I have some background in Java and I'm now learning C#.
I've the following interface:
interface IComparer<T> {
bool Equals(T a, T b)
}
And I want to implement the following method:
static IComparer<T> Compare(...) { }
If this were Java, I would simply return a lambda expression implementing a custom method that receives two T
, and return a bool
, but this isn't valid in C#.
Is there a way to solve this problem without having to create a new class that implements IComparer
?
PS: I don't want to use anything from the C# library that implements the "Equals" method, I'm aware that it exists, I just want to understand how to return something like "functional interface" from Java in C#.
Thanks.
Consumer The consumer interface of the functional interface is the one that accepts only one argument or a gentrified argument. The consumer interface has no return value. It returns nothing.
A functional interface can extends another interface only when it does not have any abstract method.
LongSupplier Functional Interface : This primitive LongSupplier Functional Interface always returns value in primitive-type long only and it is not required to declare while defining LongSupplier (or lambda expression)
Consumer. The Java Consumer interface is a functional interface that represents an function that consumes a value without returning any value.
I think the "functional interface" concept in Java is parallel to a delegate type in C#:
public delegate bool IComparer<T>(T a, T b);
static IComparer<T> Compare<T>() {
return (a,b) => a.Equals(b);
}
Note that Compare<T>
doesn't take any parameters, it doesn't need any to return an IComparer<T>
.
You can use it like:
var e = Compare<int>();
var ans = e(1,2); // ans is false
However, unlike the functional interface in Java which seems to describe an object of an anonymous class, a delegate describes a single method.
Sure, you can find constructor of generic IComparer
in System.Collections.Generic.Comparer<T>.Default
static property. No need to implement your own then.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With