Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Function type in C#?

Tags:

I like to know if in C# there is a Function type like in AS3 for example. I would like to do somnthing like this (but in C#):

private function doSomething():void {     // statements }  var f:Function = doSomething f() 
like image 232
Lucas Gabriel Sánchez Avatar asked Aug 21 '09 17:08

Lucas Gabriel Sánchez


1 Answers

Yes, they're called delegates in .NET, not function types.

You use the reserved keyword delegate to define new ones, and there's 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()); 

There's 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 doesn't, 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 doesn't.

In your case, this would work:

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

Note that in this last case, you don't have to declare DoSomethingDelegate.

like image 119
Lasse V. Karlsen Avatar answered Sep 28 '22 03:09

Lasse V. Karlsen