Sometimes
you may want to call the private method declared in one class in another class
in c#. Technically it is not possible to access private members of a class
outside the class in c#. Either you will need to modify the access specifier of
the class member from private to something else. However if say you are not allowed to change
the access specifier of private method but still want to provide a mechanism to
enable calling of private method in another class? How can w achieve this in
c#? It is very well possible in C# with the help of Delegates.
Delegates
are nothing but pointer to method. If you want to get value of private variable,
we can declare a public property similarly if you want to call private method outside
the declaring class we can use public property returning delegate (or pointer
to the method).
Following
construct depicts how delegates can be used to access private method outside a
class. Let’s say I have a class A having private method as below –
public class A
{
private string ReturnString(string s)
{
return "This is returned from
private method of class A=" + s;
}
}
Now I
want to call the private method “ReturnString” of class A. Declare a delegate
above the class A definition as below –
namespace DelegateToAccessPrivateDemo
{
public delegate string GetPrivateMethodOutput(string);
public class A
{
private string ReturnString(string s)
{
return "This is returned from
private method of class A=" + s;
}
}
}
Now
we need to declare a public property inside class A which will return the
object of delegate GetPrivateMethodOutput. Therefore class A becomes as shown –
public delegate string GetPrivateMethodOutput(string s);
public class A
{
private string ReturnString(string s)
{
return "This is returned from
private method of class A=" + s;
}
public GetPrivateMethodOutput MyPrivateMethodOutput
{
get
{
return new GetPrivateMethodOutput(ReturnString);
}
}
}
To
test the functionality of delegate write following code in Console application’s
Program.cs main method –
static void Main(string[] args)
{
GetPrivateMethodOutput privateMethod = null;
A a = new A();
privateMethod = new GetPrivateMethodOutput(a.MyPrivateMethodOutput);
Console.WriteLine(privateMethod("!!Learned
use of delegate!!"));
Console.ReadLine();
}
The
output is as follows –
Hope
this helps in understanding the advantage of delegate in accessing private method
of a class.
Cheers…
Happy
Delegating!!
Thank you
ReplyDeletegood example and more simple way...hats off!!!
ReplyDeletethanks
ReplyDelete