Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return "Functional Interface" in C#

Tags:

c#

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.

like image 532
Some_user_qwerty Avatar asked Jun 30 '17 17:06

Some_user_qwerty


People also ask

What is the return type of functional interface?

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.

Can we extend functional interface?

A functional interface can extends another interface only when it does not have any abstract method.

Which function interface returns a primitive value?

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)

Which functional interface does not return a value?

Consumer. The Java Consumer interface is a functional interface that represents an function that consumes a value without returning any value.


2 Answers

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.

like image 133
NetMage Avatar answered Sep 17 '22 16:09

NetMage


Sure, you can find constructor of generic IComparer in System.Collections.Generic.Comparer<T>.Default static property. No need to implement your own then.

like image 37
Artyom Avatar answered Sep 20 '22 16:09

Artyom