0

I have this code:

SendNotificationClass sendNotifClass = new sendNotificationClass();

but I want to define the function from it called "SendNotification"

so instead of

SendNotificationClass sendNotifClass = new sendNotificationClass();
SendNotifClass.SendNotification();

i want to do it like this:

var sendNotif = new SendNotificationClass().SendNotification;
sendNotif(...)

how?

Jabberwocky
  • 768
  • 7
  • 18
  • In your particular case (assuming that the return type of the method is `void`), it would be `Action sendNotif = new sendNotificationClass().SendNotification;`. If the method have a return type (say, `int`), then you should use `Func sendNotif = ...`. – 41686d6564 stands w. Palestine Oct 26 '20 at 13:16
  • create a delegate that has a matching signature with SenNotification method. Then invoke it. – Ercan Peker Oct 26 '20 at 13:17

2 Answers2

0

You can define an anonymous delegate by changing your syntax slightly:

var sendNotif = () => (new sendNotificationClass()).SendNotification();
sendNotif()

If sendNotif requires parameters (as implied by your use of an ellipsis), then you just need to add them to the delegate definition:

var sendNotif = (x, y, Z) => (new sendNotificationClass()).SendNotification(x, y, z);
sendNotif(a, b, c)
D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

You have a lot of different options. Just to name of few:

void SendNotification()

public delegate void NotifDelegate();

...
var sendNotifClass = new SendNotificationClass();
NotifDelegate sendNotif1 = new NotifDelegate(sendNotifClass.SendNotification);
NotifDelegate sendNotif2 = sendNotifClass.SendNotification;

Action sendNotif3 = delegate { sendNotifClass.SendNotification(); };
Action sendNotif4 =  () => sendNotifClass.SendNotification();
Action sendNotif5 = sendNotifClass.SendNotification;

Usage

sendNotif1.Invoke(); //Either
sendNotif1(); //Or
...
sendNotif5.Invoke(); //Either
sendNotif5(); //Or

bool SendNotification(string email)

public delegate bool NotifWithParamDelegate(string param1);
...

NotifWithParamDelegate notifWithParam1 = new NotifWithParamDelegate(sendNotifClass.SendNotification);
NotifWithParamDelegate notifWithParam2 = sendNotifClass.SendNotification;

Func<string, bool> notifWithParam3 = delegate (string email) { return sendNotifClass.SendNotification(email); };
Func<string, bool> notifWithParam4 = email => sendNotifClass.SendNotification(email);
Func<string, bool> notifWithParam5 = sendNotifClass.SendNotification;

Usage

bool isSuccess = notifWithParam1.Invoke("a@b.c"); //Either
bool isSuccess = notifWithParam1("a@b.c"); //Or
...
bool isSuccess = notifWithParam5.Invoke("a@b.c"); //Either
bool isSuccess = notifWithParam5("a@b.c"); //Or
Peter Csala
  • 17,736
  • 16
  • 35
  • 75