delegate and methods access level


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
 
Ad

Advertisements

G

Göran Andersson

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.
 
Ad

Advertisements

P

Peter Morris

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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top