Using delegates to call back methods

            1. An important note about private method calling.

            2. What does covariance and contra-variance mean?

Note. Using delegates we can call private methods even if they are not defined in the class. It’s not a security issue as long as the delegate object was created by code that has ample security.

 

Example 1:

    class Test

    {

        public delegate void CallBackDelegate();

 

        public static void CallOurMethod(CallBackDelegate cbf)

        {

            if (cbf != null)

                cbf();

        }

    }

 

    class Program

    {       

        static void Main(string[] args)

        {

            Test.CallBackDelegate callBackFunc = new Test.CallBackDelegate(StaticMethod);

            Test.CallOurMethod(callBackFunc);

        }

 

        private static void StaticMethod()

        {

            Console.WriteLine("Private method called from another class");

        }

    }

Covariance allows us to define a method which return type is a derived from the delegate’s return type.

Contra-variance allows us to define a method which parameter type is a base of the delegate’s parameter type.

 

Example 2:

    class Program

    {

        private delegate Stream CovarianceTest();

        private delegate void ContravarianceTest(Stream stream);

 

        static void Main(string[] args)

        {

            CovarianceTest covTest = new CovarianceTest(CovarianceTestMethod);

            ContravarianceTest contraVarianceTest = new ContravarianceTest(ContravarianceTestMethod);

        }

 

        //Covariance allows us to define a method which return type is a derived from the delegate’s return type

        private static FileStream CovarianceTestMethod() { return null; }

 

        //Contra-variance  allows us to define a method which parameter type is a base of the delegate’s parameter type

        private static void ContravarianceTestMethod(Object t) { }

 

    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s