DEV Community

Discussion on: Delegate methods in C#. A practical example

Collapse
 
zacharypatten profile image
Zachary Patten

Firstly, you are not limited to Action and Func. Those are built in types in .NET, but you can declare your own delegates. Your article seems to sugguest Action and Func are the only options.

delegate void MyDelegate(int i);

Secondly, you are NOT calling your func multiple times. It is calling it once and Enumerable is duplicating that first return value multiple times.

If you want to call the func multiple times, you should do something like:

void Repeat(Func<T> func, int count, Action<T> action)
{
    for (int i = 0; i < count; i++)
    {
        action(func());
    }
}

Thirdly, your code doesn't offer anything practical. It is just an unnecessary wrapper around an Enumerable function.

I actually rarely write more than 20 lines of code before using delegates. Here are some practical examples of where I use delegates if you are curious...

You can use them to cache runtime compilation:

public static T Add<T>(T a, T b) => AddImplementation<T>.Function(a, b);

internal static class AddImplementation<T>
{
    internal static Func<T, T, T> Function = (T a, T b) =>
    {
        ParameterExpression A = Expression.Parameter(typeof(T));
        ParameterExpression B = Expression.Parameter(typeof(T));
        Expression BODY = Expression.Add(A, B);
        Function = Expression.Lambda<Func<T, T, T>>(BODY, A, B).Compile();
        return Function(a, b);
    };
}

You can use them to abstract functionality to write generic and reusable code as I am doing in graph path finding algorithms here:

github.com/ZacharyPatten/Towel/blo...

You can use them to cache reflection:

gist.github.com/ZacharyPatten/16be...

I even use them in data structures. For example, I use a comparison delegate on my Heap data structure so that you can control how the heap compares it's items (source code available in same GitHub project).

Even "Array.Sort()" has an overload that takes a delegate. I use that one all the time.

Collapse
 
leanwit profile image
Leandro

Hello Zachary.

Thanks for your comment and feedback, it's very useful.
I've edited the post in order to fix the two first points that you mention.

Otherwise, this article doesn't show the best way to use delegates, instead of that it shows a very simple example that I saw in a public repository.