sazr
sazr

Reputation: 25928

Passing Class/Instance Function as a Parameter in a Function

In C# is it possible to pass a class function(not static) as a parameter in a function?

For some reason I get a compile error inside the function download because I am passing a 'class/instance' function as the parameter.

For example:

public class MyPlane {
   Texture texture;

   virtual public void OnDownloadPlaneCallBack(WWW www) {
      // perform custom actions when/if file downloads correctly
      texture = www.texture;
   }

   virtual public void download() {
       Downloader.download("www.blah.com", OnDownloadPlaneCallBack);  // this gives a compile error? 
   }
}

public class Downloader {

    public static IEnumerator download(string url, Delegate callback) {
        WWW www = new WWW(url); 

        while(!www.isDone)
            yield return www;

         if (www.isDone) {
            callback.DynamicInvoke(www);
         }
    }
}

Upvotes: 3

Views: 3601

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

Of course you can construct delegates from instance methods: that is a very powerful feature. The problem that you are seeing has to do with a specific syntax of creating delegates - by using method groups.

You get a compile error because method groups (that's the official name for constructing delegates from "naked" method names) cannot be passed as parameters of "untyped" Delegates.

If you change the signature of your download method to accept Action<WWW>, your code will compile correctly. You could also cast your method group explicitly, like this:

Downloader.download("www.blah.com", (Action<WWW>)OnDownloadPlaneCallBack);

Upvotes: 3

Alexey Raga
Alexey Raga

Reputation: 7525

Yes.

public string CanReceiveFunction(Func<int, string> func) {
    if (func != null) return func(5);
}

public string CanConvertIntToString(int a) {
    return "here is the result: " + a;
}

public void Main() {
    var result = CanReceiveFunction(CanConvertIntToString);
    Console.WriteLine(result);
}

Upvotes: 1

Related Questions