Answer the question
In order to leave comments, you need to log in
How to pass a function in c#?
I'm trying to pass a function, I don't understand a little how to do this correctly:
namespace coordinates
{
class Example
{
public string name;
public Delegate mainFunc;
public Example(string name, Delegate callback)
{
this.name = name;
this.mainFunc = callback;
}
public void init()
{
this.mainFunc();
}
}
}
Answer the question
In order to leave comments, you need to log in
namespace coordinates
{
class Example
{
public string Name;
public Action MainFunc;
public Example(string name, Action callback)
{
Name = name;
MainFunc = callback;
}
public void Init()
{
MainFunc?.Invoke();
}
}
}
var r = new Example("Example name", () => Console.WriteLine("Example MainFunc"));
Delegate
(capitalized) is a static class that contains methods for working with delegates. The delegate itself must be declared through the delegate keyword (with a small letter), as a class or interface. For example:
In this case, you can only use a specific delegate type, just like you use a specific one , etc., and not the class keyword itself. In the example above, the delegate type would be . To pass a function reference using a delegate, the signatures of the function and the delegate must match exactly. In the case of the above example , the function must also return and accept .
In your case, the delegate type should be: You can assign a reference to your method to this delegate .
But there is no need to declare a delegate type in this case. In Net. Framework already has a number of delegates, just for such purposes. This Func
and Action
.
You can just replace the word Delegate
with Action
in your code and it should work.
using System;
namespace TOSTER
{
class Program
{
static void Main(string[] args)
{
var example = new Example("example 1", () => { return "Result"; });
var result = example.init();
Console.WriteLine(result);
Console.ReadKey();
}
}
class Example
{
private readonly string _name;
private readonly Func<string> _del;
public Example(string name, Func<string> callback)
{
_name = name;
_del = callback;
}
public string init()
{
return _del.Invoke();
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question