I am reading CLR via C# 4th edition. In the chapter covering delegates (chapter 17), it is written that:
The
FeedbackToConsolemethod is defined as private inside theProgramtype, but theCountermethod is able to callProgram’s private method. In this case, you might not expect a problem because bothCounterandFeedbackToConsoleare defined in the same type. However, this code would work just fine even if theCountermethod was defined in another type. In short, it is not a security or accessibility violation for one type to have code that calls another type’s private member via a delegate as long as the delegate object is created by code that has ample security/ accessibility.
I am experimenting with this idea, but I'm not able to call a private method from another type. Here is my code:
namespace DelegatesEvents
{
class Program
{
public static void Main(string[] args)
{
Counter(1, 2, new FeedBack(DelegateEventsDemo.FeedBackToConsole));
Console.ReadLine();
}
private static void Counter(int p1, int p2, FeedBack feedBack)
{
for (int i = p1; i <= p2; i++)
{
if (feedBack != null)
{
feedBack(i);
}
}
}
}
}
namespace DelegatesEvents
{
internal delegate void FeedBack(Int32 val);
public class DelegateEventsDemo
{
private static void FeedBackToConsole(Int32 val)
{
Console.WriteLine("Good morning delegates" + val);
}
}
}
When I declare FeedBackToConsole as private, it can not be called in the delegate, as expected if I was trying to call it otherwise.
Where am I going wrong?
In short, it is not a security or accessibility violation for one type to have code that calls another type’s private member via a delegate as long as the delegate object is created by code that has ample security/accessibility.
DelegateEventsDemo has to create the delegate object. So we add public GetFeedBackDelegate method (you can add property as well) which returns the delegate object referencing private method.
namespace DelegatesEvents
{
internal delegate void FeedBack(Int32 val);
public class DelegateEventsDemo
{
private static void FeedBackToConsole(Int32 val)
{
Console.WriteLine("Good morning delegates" + val);
}
internal static FeedBack GetFeedBackDelegate()
{
return FeedBackToConsole;
}
}
}
And used by the code:
namespace DelegatesEvents
{
class Program
{
public static void Main(string[] args)
{
Counter(1, 2, DelegateEventsDemo.GetFeedBackDelegate());
Console.ReadLine();
}
private static void Counter(int p1, int p2, FeedBack feedBack)
{
for (int i = p1; i <= p2; i++)
{
if (feedBack != null)
{
feedBack(i);
}
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With