Question

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.

Était-ce utile?

La 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.

Autres conseils

Funcs are delegates and encapsulates any methods that has equal signatur og Func. for layering I recomment that you use Private Methods

With the Func, you are actually saving a reference to an anonymous method. The compiler creates a named method out of it, and what you're doing is like saving an extra reference to it.

That being not too big of a deal, there isn't much of a difference, except the standard is naming the method. It is also more logical and readable.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top