Reputation: 43
I am reading CLR via C# 4th edition. In the chapter covering delegates (chapter 17), it is written that:
The
FeedbackToConsole
method is defined as private inside theProgram
type, but theCounter
method is able to callProgram
’s private method. In this case, you might not expect a problem because bothCounter
andFeedbackToConsole
are defined in the same type. However, this code would work just fine even if theCounter
method 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?
Upvotes: 3
Views: 6553
Reputation: 1
as Richter and Ulugbek mentioned the code that creates delegate needs to be accessible enough to the method, wrapped by the delegate. Delegate is created within DelegateEventsDemo, that stores referenced FeedBackToConsole method. So everything is fine with enough accessibility.
Upvotes: 0
Reputation: 12797
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);
}
}
}
}
}
Upvotes: 7