Is there a Function type in C#?

Is there a Function type in C#?

Yes, theyre called delegates in .NET, not function types.

You use the reserved keyword delegate to define new ones, and theres plenty that are predefined in the class libraries.

To define one that matches your example:

public delegate void DoSomethingDelegate(Object param1, Object param2);

Then to assign it:

DoSomethingDelegate f = DoSomething;
f(new Object(), new Object());

Theres also two generic types of delegate types defined in the base class library, one for methods that return a value, and one for those who doesnt, and they come with variations over how many arguments you have.

The two are Func<..> for methods that return a value, and Action<..> for methods that doesnt.

In your case, this would work:

Action<Object, Object> f = DoSomething;
f(new Object(), new Object());

Note that in this last case, you dont have to declare DoSomethingDelegate.

The concept of delegates in .NET are exactly what you are looking for.

There are examples on the linked page, as well as many tutorials and in-depth explanations of how they are implemented and used. Google away!

Is there a Function type in C#?

They (references to functions) are called delegates

Heres a wonderful primer: http://www.akadia.com/services/dotnet_delegates_and_events.html

Leave a Reply

Your email address will not be published.