Reputation: 25928
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
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" Delegate
s.
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
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