Search code examples
c#.net-3.5

Assigning a function from another class to an event handler


Consider the following situation. I have 4 classes in different cs files:

class0.cs
class1.cs
class2.cs
class3.cs

I want the last 3 classes to be fixed(use them in a dll) and only change the class0 from where I use the dll.

So in class0 I want to define a function that will be executed when an event occurs. For example:

public void callStart(Object x, EventArg e){...}

This event should be responded by an object of class3. There is a relashionship between this classes.

class0 use an instance of class1
class1 use an instance of class2
class2 use an instance of class3

So my plan is pass the function callStart as a parameter of the constructor so it can reach the object of class3:

So the constructor of each class is something like this:

public class1(...., Func<Object,EventArg> callStart){
...
c2 = new class2(..., callStart);
}

public class2(...., Func<Object,EventArg> callStart){
...
c3 = new class3(..., callStart);
}

public class3(...., Func<Object,EventArg> callStart){...

OnCall += callStart;
}

The compiler in Visual Studio 2015 tell me that an Func<Object,EventArg> can't be turned into an EventHandler<EventArg>, but I can assign a public void function to the EventHandler if I define it directly in class3.cs.

I apologize if my description of the problem is confusing. I feel that my brain cells are entangled.


Solution

  • Following @Peter's suggestions it was fairly easy to solve this problem. First I changed the Func<Object,EventArg> argument for an Action<Object,EventArg>. Then I changed the event subscription from OnCall += callStart; to OnCall += (sender, e) => callStart(sender, e);.

    In the example of this question the resulting code is:

    public class1(...., Action<Object,EventArg> callStart){
    ...
    c2 = new class2(..., callStart);
    }
    
    public class2(...., Action<Object,EventArg> callStart){
    ...
    c3 = new class3(..., callStart);
    }
    
    public class3(...., Action<Object,EventArg> callStart){...
    
    OnCall += (sender, e) => callStart(sender, e);
    }