Question

I just used Action<T>() and it's sibling Func<T>() today and this disturbs my mind now:

Func<T> is commented like this in the official docs:

Encapsulates a method that has no parameters and returns a value of the type specified by the TResult parameter.

Since even the comment mentions that is is a method (in C# there is nominally no such thing as functions, AFAIK), why the designers of C# did not just call that construct Meth<T> or Method<T>?

Is it probably because of the odd sound of "Meth"? But what about method, which would be very clear?

Était-ce utile?

La solution

I regard "method" as a sort of implementation detail here - whereas the mathematical concept of a function is common. (How often have you heard of delegates being described as "function pointers"?)

Note that the word "function" appears even within C# - both anonymous methods and lambda expressions are "anonymous functions".

You use Func<> when you want a function - something that returns a value, possibly given some inputs. You don't really care whether or not it's backed by a method; it's just something you can call.

I'd say that the documentation for Func<> is somewhat lacking here, rather than the choice of name. (Then there's the type system which prevents Func<void> being valid, which would make things a lot simpler in numerous situations - but that's a different matter.)

Autres conseils

I think its the other way around. Everything is a function even void MethodName is a function with a void return type.

I have always considered the terms method and function as being the same thing (as per one of my comments) however, this post; Difference between a method and a function describes the difference where;

A method is a piece of code that is called by name that is associated with an object. In most respects it is identical to a function except for two key differences.

  • It is implicitly passed the object for which it was called
  • It is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data)

I think that's the key distinction; Func<T> isn't associated with an object it is just a functional "piece of code". The fact that Func itself would be an object muddies things slightly, but you get the general idea.

I think it was inspired by functional programming. Funcs are heavily used throughout LINQ as "purely functional" methods - that is, methods that return an output for a given input without any observable side effects.

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