How to pass a delegate to another class

In my main class “A” I declared a function and delegated a call to this function, I want to pass my delegate to another class “B”, but how does class B know what type the delegate is?

class A

public delegate void SendInfo(string[] info); SendInfo sendInfo = new SendInfo(SendInformation); //I have a function SendInformation B b = new B(); b.SetDelegate(sendInfo); 

class B

 public delegate void SendInfo(string[] info); //I know this is wrong but how will SendInfo SendInformation; //this class know what SendInfo is? public void SetDelegate(SendInfo sendinfo) //What type is this parameter? { sendinfo.GetType(); SendInformation = sendinfo; } 

Thanks,

Eamonna

+7
source share
3 answers

When you declare a delegate in class A, you declare it as a subtype of class A. So it is of type ClassA.SendInfo , for example. In class B you can use

 public void SetDelegate(ClassA.SendInfo sendinfo) 

Alternatively, declare the delegate outside the code for class A, then it will just be a different type that you can reference by name ( SendInfo ).

+10
source

Why are you declaring two separate types of delegates with the same signature? Declare one type of delegate (if you really need to - use the Func and Action families where possible) outside of any other classes, and use it everywhere.

You should know that when writing:

 public delegate void SendInfo(string[] info); 

which really declares a type - and you can declare that type directly in the namespace; he must not be a member of another type.

+10
source

Just declare the delegate once right inside your namespace and not inside the class.

+4
source

All Articles