I have two classes and I'm trying to call private method of class from another class.
Program.cs
namespace TestIdentity
{
internal class Program
{
private static int y = 10;
static void Main(string[] args)
{
Func<Task<int>> getter = async () => await Get();
Test test = new Test();
test.SolveAsync(getter).Wait();
}
private static async Task<int> Get()
{
Console.WriteLine("Private value y : " + y);
await Task.Delay(1000);
return 1;
}
}
}
Test.cs
namespace TestIdentity
{
internal class Test
{
public async Task SolveAsync(Func<Task<int>> func)
{
int x = await func();
Console.WriteLine("hello : " + x);
}
}
}
I wanted to know how SolveAsync method in Test class can access private method of Program class and its private properties.
Short answer: The Test class cannot see the private functions and fields by itself but you gave the references as parameters. A delegate is a (typesafe) pointer. And your
Func<Task<int>> getteris a specialized delegate. So you created a pointer to the private functionGet. This pointer is given as a parameter in yourSolveAsyncfunction.The
SolveAsyncjust calls the chunk of code located at the given Memory address without knowing that it belongs toProgramclass.Another example:
Here we call
Pow2Overridewhich has access to a local variable. Not even the classProgramcan seexoutside of theMainfunction. This again works because we provided the reference (the correspoding memory address).