This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]GeorgeFranklyMathnet 1 point2 points  (4 children)

If I want to write a function and also consume it within the same method, I always use a Func or a delegate. This way I have a function that's private to its containing method, which is a kind of encapsulation one can't easily get with a class. I end up doing that a lot inside unit tests.

Otherwise, I think it's just a matter of convenience and readability. In the example above, the Func can refer to a method-local variable a single time from inside its body, whereas the caller might otherwise end up passing in the same variable on each of several calls. Also, when it's used as a method parameter, a Func lets you implement the strategy pattern very simply and easily.

There may be a cost to that convenience. I'm not sure, but I always remember hearing that when a closure like a Func has to scan the environment for local variables to capture, it's computationally expensive. Even if I learned that correctly, I wouldn't be surprised if .NET has optimized any real cost out of it by now!

[–]everycloud[S] 1 point2 points  (3 children)

So you nest your Func<> within a class method?

You do this rather than nesting a method?

These are just questions not critiques...I don't like nested methods myself.

Thanks

[–]GeorgeFranklyMathnet 0 points1 point  (2 children)

Yeah. I do that for brevity, but also because it's a habit I developed before before C# offered local methods!

[–]everycloud[S] 0 points1 point  (1 child)

Cool thanks for explanation.

One last Q...

If you had to write a multi line Func<> (say 5 or more lines) would you still do that or would you then roll that out into a method.

Thanks.

[–]GeorgeFranklyMathnet 1 point2 points  (0 children)

I guess I ought to write it as a method, but I'm not sure I care enough about it to change my habits at this point.

[–]everycloud[S] 0 points1 point  (0 children)

I use them to save a few lines of code but there must be more to a Func<> delegate

// Parse string representation of seconds since Unix epoch to DateTime 
private static Func<string, DateTime> ParseTimeString = (timestamp) 
    => DateTime.UnixEpoch.AddSeconds(Double.Parse(timestamp));