Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass callback to class

Tags:

c#

delegates

I have a class in which I would like to store a function call. This function call can be invoked by the class but set by the parent class. I would like to externally supply the call to be made, including any parameters.

Something like...

public class TestDelegate
{
    public TestDelegate()
    {
        TestClass tc = new TestClass(DoSomething("blabla", 123, null));
    }

    private void DoSomething(string aString, int anInt, object somethingElse)
    {
        ...
    }
}

public class TestClass
{
    public TestClass(delegate method)
    {
        this.MethodToCall = method;
        this.MethodToCall.Execute();
    }

    public delegate MethodToCall { get; set; }
}

When the TestClass class is initialized it will call the DoSomething method of the parent class with the specified parameters. I should also mention that I do not want to require the same method signature for the method called. Meaning not always (string, int, object)

like image 407
jimmyjambles Avatar asked Sep 28 '26 15:09

jimmyjambles


2 Answers

Use the Action delegate type and create an instance of this from a closure:

public class TestClass
{
    public TestClass(Action method)
    {
        MethodToCall = method;
        method();
    }

    public Action MethodToCall { get; set; }
}

public class TestDelegate
{
    public TestDelegate()
    {
        // Uses lambda syntax to create a closure that will be represented in
        // a delegate object and passed to the TestClass constructor.

        TestClass tc = new TestClass(() => DoSomething("blabla", 123, null));
    }

    private void DoSomething(string aString, int anInt, object somethingElse)
    {
        // ...
    }
}
like image 102
cdhowie Avatar answered Sep 30 '26 06:09

cdhowie


delegate isn't the name of a type - it's a keyword used to declare delegate types, and also anonymous methods.

I suspect you actually want a specific type of delegate, such as Action, which is a delegate with no parameters and a void return type. You'll then need to change your calling code as well - because currently you're calling DoSomething before you call the constructor. Sample:

public class TestDelegate
{
    public TestDelegate()
    {
        TestClass tc = new TestClass(() => DoSomething("blabla", 123, null));
    }

    private void DoSomething(string aString, int anInt, object somethingElse)
    {
        ...
    }
}

public class TestClass
{
    public TestClass(Action method)
    {
        this.MethodToCall = method;
        this.MethodToCall.Invoke();
    }

    // Do you really need this to be writable?
    public Action MethodToCall { get; set; }
}
like image 28
Jon Skeet Avatar answered Sep 30 '26 06:09

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!