How to pass a delegate to another class
Asked Answered
S

4

9

In my main class 'A' I have declared a function and delegate to call that function, I want to pass my delegate to another class 'B' but how will 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,

Eamonn

Sturgeon answered 31/3, 2011 at 15:57 Comment(0)
M
11

When you declare the delegate 'in' class A, you declare it as a sub-type of class A. So it's of type ClassA.SendInfo for example. In class B you could use

public void SetDelegate(ClassA.SendInfo sendinfo)

Alternatively, declare the delegate outside of the code for class A - then it will simply be another type you can reference by name (SendInfo).

Mulish answered 31/3, 2011 at 15:59 Comment(0)
C
11

Why are you declaring two separate delegate types with the same signature? Declare a single delegate type (if you really have to - use the Func and Action families where possible) outside any other classes, and use that everywhere.

You need to be aware that when you write:

public delegate void SendInfo(string[] info);

that really is declaring a type - and you can declare that type directly in a namespace; it doesn't have to be the member of another type.

Chou answered 31/3, 2011 at 15:59 Comment(1)
Like Jon mentions, Action<string[]> would be a good type to use for the delegate instead of defining a new one.Trebuchet
T
7

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

Tantalizing answered 31/3, 2011 at 16:0 Comment(0)
T
0

You can do this with using static.

class A contains delegate declaration.

public delegate void SendInfo(string[] info);

class B contains delegate type usage.

using static ClassA.SendInfo;

public void SetDelegate(SendInfo sendinfo)
{
    ...
}
Tauro answered 12/1, 2023 at 11:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.