Home Ask Login Register

Developers Planet

Your answer is one click away!

flkes February 2016

Using a function as an Action argument

For my scenario I have List<T> removable that I'm using to remove items from my variable ObservableCollection<T> collection. I don't believe I can use the Except method here because I need collection to create change events.

removable.ForEach(profile => collection.Remove(profile));

Is there a better syntax for passing a function as an Action argument? In Java I would just pass in the method:



Gusman February 2016

In Java you can pass the function if the signature of the function matches, exactly as in C#, so no, there's no better way to do it if the function signature is not the same, like in Java.

But, you can always create an extension to accept any return type, like this:

public static class Extensions
    public static void ForEach<TIn, TOut>(this List<TIn> TheCollection, Func<TIn, TOut> ProcessFunction)
        TheCollection.ForEach((item) => ProcessFunction(item));

Then you can do

removable.ForEach<string, bool>(collection.Remove);

This is not faster but is more readable.

Post Status

Asked in February 2016
Viewed 3,598 times
Voted 6
Answered 1 times


Leave an answer

Quote of the day: live life