Mahmood Shahrokni
Mahmood Shahrokni

Reputation: 236

Understanding the implementation of a delegate

I have been going to understand advantages of the delegate.I have read that it can be used as an instrument to pass a method as a parameter.For example assume that you have an ordering method that invokes a comparing method as a parameter.So you can choose your desired comparing method as a caller. I know and understand the whole logic but when i try to create a simple application according to this knowledge,it doesn't work. Here i have 3 classes and i am going to pass a method as a parameter but i don't know how exactly should i invoke it in my second class.

First:

class test1
    {
        public test1()
        {

        }

        public static bool Input()
        {
            return true;
        }
    }

Second :

 class test2
    {
        public test2()
        {

        }

        public void OutPut(Delegate d)
        {
            // Error !!!
            bool a = d();
            Console.WriteLine(a.ToString());
        }
    }

The Last :

 internal delegate bool Del();
    class Program
    {

        static void Main(string[] args)
        {
            Del d = test1.Input;
            test2 t2=new test2();
            t2.OutPut(d);
            Console.ReadKey();
        }
    }

Upvotes: 0

Views: 49

Answers (1)

nvoigt
nvoigt

Reputation: 77285

public void OutPut(Delegate d)

This takes a default delegate that is not what you are looking for. You explicitly declared Del for this reason:

public void OutPut(Del d) 

However, delegates are sooo 2001. Use a Func<T> for better readability:

public void OutPut(Func<bool> d)

Upvotes: 2

Related Questions