Accessing private method of another class using Func<Task<T>>

77 Views Asked by At

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.

1

There are 1 best solutions below

0
lorenz albert On

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>> getter is a specialized delegate. So you created a pointer to the private function Get. This pointer is given as a parameter in your SolveAsync function.

The SolveAsync just calls the chunk of code located at the given Memory address without knowing that it belongs to Program class.

Another example:

class Program
{
    static void Main(string[] args)
    {
        int x = 2;

        MyMath.Pow2Override(ref x);

        Console.WriteLine($"x = {x}");
    }
}

static class MyMath
{
    public static void Pow2Override(ref int x)
    {
        x *= x;
    }
}

Here we call Pow2Override which has access to a local variable. Not even the class Program can see x outside of the Main function. This again works because we provided the reference (the correspoding memory address).