delegate and methods access level

  • Thread starter Thread starter puzzlecracker
  • Start date Start date
P

puzzlecracker

Sort of new to internal of delegates.

My question is when you create a delegate instance, does the
surrounding block must be able to see/access method you want delegate
to take on. Here is concrete example:

namespace Test

public delegate string MyDelegate (int x);
class A {

private string IamPrivate(int x)
{
System.WriteLine("I am private {0}, get lost!",x);
}
}


class B{

private MyDelegate _d = new MyDelegate (Test.IamPrivate);

public void Foo()
{
d(10);
}

}

If this is allowed (hopefully not), anyone with ease can circumvent
the encapsulation of csharp. Is it?

Well, in nutshell, I am trying to better understand delegate/events in
the context of a class access level. Explanations are welcome.

Thanks
 
puzzlecracker said:
Sort of new to internal of delegates.

My question is when you create a delegate instance, does the
surrounding block must be able to see/access method you want delegate
to take on. Here is concrete example:

namespace Test

public delegate string MyDelegate (int x);
class A {

private string IamPrivate(int x)
{
System.WriteLine("I am private {0}, get lost!",x);
}
}


class B{

private MyDelegate _d = new MyDelegate (Test.IamPrivate);

public void Foo()
{
d(10);
}

}

If this is allowed (hopefully not), anyone with ease can circumvent
the encapsulation of csharp. Is it?

Well, in nutshell, I am trying to better understand delegate/events in
the context of a class access level. Explanations are welcome.

Thanks

I suppose that you were trying to use the method in the A class? There
is no member IamPrivate in the Test namespace...

The code that creates the delegate instance has to have access to the
method. The code that uses the delegeate doesn't need to know where the
method is defined.
 
Does this compile?

int a = "Hello";

I hope not!

My point is you took the time to type it into your newsreader, you could
just have easily typed it into VS and checked what happened!
 
Back
Top