Answer includes real time use of delegates in c# application without event used in software projects.
Question: Tell me the real time scenario where you have used delegates in C# application without using event.
Answer: You can explain a real time use of delegates from your software products or projects, if you have used it. However, I’ll be illustrating here, a scenario we have used delegates in C# without event that will give an idea to answer this interview question.
We had used delegate in a library, to provide network status to the client applications, so, we can distribute the library with documents to multiple clients. And clients’ applications can have their own function naming convention and pass to the delegate resides in the library to get the network status.
For example, clients functions can be BMWGetNetworkStatus() and PanasonicGetNetworkStatus() etc. Note that whatever be the client function name, we don’t have to change the code in our library to provide the status, and that should be working for every clients.
The main advantage of using delegates in c# application software here is, to decouple the client code and library code.
Real time use of delegates in C# without Event
Library Code:
In this sample, we will be using Random numbers between 1 to 4 to indicate the network status i.e. connecting, sending and receiving etc. and a Sleep() function just to illustrate network status invocation points to make the sample simple and clean.
using System.Text;
using System.Threading;
namespace NetworkLibrary
{
public delegate void StatusDelegate(int a);
public class NetworkStatus
{
public void GetNetworkStatus(StatusDelegate StatusFunc)
{
Thread.Sleep(5000);
Random r = new Random();
int status = r.Next(1, 4);
StatusFunc(status);
}
}
}
Client’s code:
Client BMW
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetworkLibrary;
namespace TestStatus
{
class Program
{
static void Main(string[] args)
{
NetworkStatus s = new NetworkStatus ();
while (true)
{
s. GetNetworkStatus(BMWGetNetworkStatus);
}
}
public static void BMWGetNetworkStatus (int a)
{
switch (a)
{
case 1:
Console.WriteLine("Connceting...");
break;
case 2:
Console.WriteLine("Sending...");
break;
case 3:
Console.WriteLine("Recieving...");
break;
default:
Console.WriteLine("Disconnecting...");
break;
}
}
}
}
Client Panasonic
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetworkLibrary;
namespace ClientTwo
{
class Program
{
static void Main(string[] args)
{
NetworkStatus s = new NetworkStatus ();
while (true)
{
s. GetNetworkStatus(PanasonicGetNetworkStatus);
}
}
public static void PanasonicGetNetworkStatus (int a)
{
switch (a)
{
case 1:
Console.WriteLine("Connceting...");
break;
case 2:
Console.WriteLine("Sending...");
break;
case 3:
Console.WriteLine("Recieving...");
break;
default:
Console.WriteLine("Disconnecting...");
break;
}
}
}
}