So one of the topics I have been telling myself to understand a bit better is delegates, and I think tonight I understand a bit more. Firstly a delegate can be described in simple terms as a type that references a method. So for instance you would have a class with a method that you would like to maybe re-use in another class without having implement it again. In this instance you might want to use a delegate. A delegate must have the same signature as the method it references, and you use the Delegate keyword for that. I created a very basic example to illustrate its use:

    delegate string Del(string myString);
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            Del d = p.Myname;
            d += p.MySurname;

            Console.WriteLine(d("Fredrik"));
            Console.WriteLine(d("Erasmus"));
        }
        string Myname(string myString)
        {
            return myString;
        }
        string MySurname(string myString)
        {
            return myString;
        }
    }
  • Share/Bookmark

Tags: ,

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Get Adobe Flash playerPlugin by wpburn.com wordpress themes