I recently came upon a static method declared as:
public class Foo
{
public static Func<HtmlHelper, PropertyViewModel, string> Render = (a, b) =>
{
a.RenderPartial(b);
return "";
};
}
Intellisense suggests the usage is (for example):
string s = Foo.Render(htmlHelper, propertyViewModel);
It would seem then that the following is equivalent:
public static string Render(HtmlHelper a, PropertyViewModel b)
{
a.RenderPartial(b);
return "";
}
A) What is the name of the first style? I realize it’s using lambdas; it’s the = sign that is tripping me up. I can’t tokenize it 😉
B) If the two code blocks are equivalent, what is the benefit of using the former over the latter?
For the most part they seem functionally equivalent. In fact you can pass around a normal method as a variable.
But there are subtle differences like being able to redefine the function to be something else. It is probably also different if you’re using reflection, e.g. it probably isn’t returned in the list of methods on the class. (Not 100% sure on the reflection part)
The following shows passing a method as a variable as well as how the 2nd way allows redefining the Func that wouldn’t be possible if it were a normal method.
This just got me thinking… if all methods were declared this way, you could have real first class functions in C#… Interesting….