4

Is there an equivalent to Functors in C#?

C# has Func<,>, delegates and anonymous methods but aren't all of these pointers to a method?

The C++ Functor is a class and not a pointer to a method.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
4thSpace
  • 43,672
  • 97
  • 296
  • 475

2 Answers2

7

C# has Func<,>, delegates and anonymous methods but aren't all of these pointers to a method?

No. Even C# delegates are classes, implemented by the compiler for you. These generated classes (for delegates) are derived from MulticastDelegate which in turn derives from Delegate.

In short, a delegate is a syntactic sugar for a class generated by compiler.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • Ok. Would those be similar to Functors than? – 4thSpace Jun 16 '13 at 17:51
  • @4thSpace: "similar" in what sense? In C#, you cannot overload `operator()`. So if you mean that, then it is not similar. C# is a different language, it does few things differently, achieves them differently. – Nawaz Jun 16 '13 at 17:53
  • operator()? Are you referring to something different than this http://msdn.microsoft.com/en-us/library/aa288467(v=vs.71).aspx? – 4thSpace Jun 16 '13 at 17:56
  • @4thSpace: If you don't know `operator()`, then how do you know what functor is in C++? What makes a class functor in c++? – Nawaz Jun 16 '13 at 18:06
  • C++: Because the class implements operator(). – 4thSpace Jun 16 '13 at 18:47
  • @4thSpace: Yes, and C# doesn't. In fact, C# doesn't allow you to overload `operator()`. Is this clear enough now? – Nawaz Jun 16 '13 at 18:48
  • 4
    Delegates *are* similar to functors in the sense that the syntax to call the pointed-to method looks just like a normal function call. – Matthew Watson Jun 16 '13 at 18:50
  • This is purely subjective _C# is a different language, it does few things differently, achieves them differently._ and one of the worst arguments that doesn't explain anything. – t3chb0t Apr 18 '20 at 06:41
5

Both lambdas (Func<>, Action<>) and delegates (named as well as anonymous) are classes.

If you need a pointer to method (to pass it into unsafe code, for instance) you should use marshalling:

IntPtr pFunc = Marshal.GetFunctionPointerForDelegate(myDelegate);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215