4 ms·
I'm not sure there is one. They're useful in C# as a way of defining a function within another function (which sometimes makes for more readable code). For exam
by d4nt 14y ago
I'm not sure there is one. They're useful in C# as a way of defining a function within another function (which sometimes makes for more readable code). For example:
public int CountRelevantItems(IEnumerable<Thing> things)
{
// Non-trivial filter that you don't want in a where lamdba
Func<Thing, bool> isRelevant = (t) =>
{
...
}
return things.Where(t => isRelevant(t)).Count()
}
But in Python you can already define functions inside of functions so you have a better solution:
def CountRelevantThings(things):
def isRelevant(thing):
...
return len(filter(isRelevant, things))
- mhurron 14y ago> They're useful in C# as a way of defining a function within another function (which sometimes makes for more readable code) Why wouldn't you just create another function in the same class?
- d4nt 14y agoJust personal preference really, if your "isRelevant" filter was only ever going to be used by your "CountRelevantItems" method you might consider it more readable to have the logic of isRelevant right there in the CountRelevantItems method rather than elsewhere in the class.