Search code examples
c#funcclass-members

Should I use Func<T> in place of a private method?


I'm posting it here and not code review because I want to know if the executing program can behave differently because of this (possibly something subtle).

Is a private method:

    private int Foo()
    {
        return Bar().Bat();
    }

Any different from a private Func?

    private Func<int> Foo = () => Bar().Bat();

The only reason I'm doing it is to make the code more compact.


Solution

  • There is not much difference, but

    • you define templated type int (possibly type safe, even if it's not visible in current code provided)

    • you can use that function like a parameter to pass to another function, that you can do in the firts case too, naturally, but in first case you would need to declare a delegate type.

    • third is more compact, but the first is more readable, imo, so if you do not need some "functional" stuff, I would go for the first choice.