Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I include a Func/Func<T> as a parameter?

Tags:

c#

.net

I acknowledge that they can be useful, but I'm trying to wrap my head around when I would actually want to have a func as a parameter of a method.

public void WeirdMethod(int myNumber, func op);

In terms of design and functionality, could someone explain to me some circumstances where I would want to consider this? Theories of "reusability" isn't going going to help me much. Real world scenarios would be best. Help me think like you lol.

Here's about all I know:

  • This would allow me to pass a delegate
  • This would allow me to use a lambda expression.

Yeap...

NOTE: I know this thread will get closed since there's no "right" answer. But I think what clicked it for me just now was "delayed calculation".

like image 766
Sinaesthetic Avatar asked Sep 24 '26 01:09

Sinaesthetic


2 Answers

  • Deferring operations until a later time. A very practical example is deferring change tracking until an object tree is fully populated. Each type or repository can tell you what it wants done, and the caller can decide when to actually do it.

  • Composition of logic (as Justin Niessner mentioned).

  • Abstraction, e.g. ("here's a contract that has inputs and ouputs, but I don't care what it's implementation is as long as it fulfills the contract). For example, you could pass a "statusWriter" Func to a method which might write to a console, debug window, log file, database, or do nothing at all. All the consuming method knows is that it consumes a type and invokes it when desired.

  • Along the same lines, passing a Func to a method allows an abstracted and simple way of allowing a where predicate to be defined by the caller. I use this paradigm frequently to support a strongly-typed filter to be applied to a result (not talking about LINQ to SQL, just filtering a list of information as the caller sees fit).

  • Elegant functional paradigms, such as this example which demonstrates recursion using anonymous functions. These constructs would be verbose/impossible without the ability to pass one function to another (especially in an abbreviated form).

like image 170
Tim M. Avatar answered Sep 26 '26 13:09

Tim M.


A general scenario is when you must pass a delayed calculation to your method. This is useful when calculating something is expensive, for example, when you cache something.

public Guid GetFromCache(string key, Func<Guid> make) {
    Guid res;
    if (!cache.TryGetValue(key, out res)) {
        res = make();
        cache.Add(key, res);
    }
    return res;
}

Now you can call this method as follows:

Guid guid = GetFromCache(myKey, () => database.MakeNewGuid());
like image 45
Sergey Kalinichenko Avatar answered Sep 26 '26 14:09

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!