I’m working on translating some code from Java to C# but am having some trouble, maybe someone out there can help?
I have problems trying to replicate anonymous interface implementations that are widely used in Java, but have no idea how to.
An example is:
List<DATA> queue1 = new ArrayList<DATA>(dataSet);
// Sort by distance to the first promoted data
Collections.sort(queue1, new Comparator<DATA>() {
@Override
public int compare(DATA data1, DATA data2) {
double distance1 = distanceFunction.calculate(data1, promoted.first);
double distance2 = distanceFunction.calculate(data2, promoted.first);
return Double.compare(distance1, distance2);
}
});
These are not inline functions, that’s anonymous classes implementing a specific interface.
C# provides delegates that you can define inline or in a separate function.
Here is an example of sorting a
List<DATA>in place using theComparison<T>delegate:Note that in order for this to work, the
distanceFunctionvariable needs to be in scope at the spot where you invokequeue.Sort. It can be a local variable defined above the invocation point, or a member variable/property of the class enclosing the function that makes the call.