Should I use a Delegate or a Method in .NET when it only depends on the parameters?
Everytime I need a very small Method that only uses its parameters...
Should I use declare a Delegate or a Method?
Eg: Multiply three numbers
Func<int, int, int, int> Multiply = (a,b,c) => a*b*c;
and
int Multiply(int a, int b, int c)
{
return a*b*c;
}
Edit:
I wan开发者_开发技巧t to focus this question in terms of eficiency when compiling, and readability.
I wouldn't declare a delegate rather than a method just for the sake of it. If you're just to call this directly from other code in your class, a method is more idiomatic. If it doesn't need to use any instance variables, you may want to make it a static method to make that clear.
On the other hand, if you only ever need to use it as a delegate, use a lambda expression to create that delegate (as per your first example).
If you want to call it directly and use it as a delegate, you can use a method group conversion to create a delegate easily:
int d = Multiply(a, b, c); // Normal method invocation
DoSomethingWithFunction(values, Multiply); // Method group conversion
Declare private static function if it uses only its own parameters. By declaring it static, you explicitly tell the future reader of your code (possibly you in a few months) that it's practically independent from the class it's defined in.
Lambdas and anonymous methods can be used as event handlers (bear in mind that it can cause memory leaks when used inappropriately) when it's clear what they do and moreover, they usually will not be reused.
精彩评论