delegate static and instance methods

We can use delegate for static and non static methods, as shown in the following example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication10
{
        struct Currency
        {
            public uint Dollars;
            public ushort Cents;

            public Currency(uint dollars, ushort cents)
            {
                this.Dollars = dollars;
                this.Cents = cents;
            }

            public override string ToString()
            {
                return string.Format("${0}.{1,2:00}", Dollars, Cents);
            }

            public static string GetCurrencyUnit()
            {
                return "Dollar";
            }

    }


    class Program
    {
        private delegate string GetAString();

        static void Main(string[] args)
        {
                int x = 40;

            GetAString firstStringMethod = x.ToString;
            //  GetAString firstStringMethod = new GetAString(x.ToString);

            Console.WriteLine("String is {0}", firstStringMethod());
            
          Currency  balance = new Currency(34, 50);
            

             // firstStringMethod references an instance method
                firstStringMethod = balance.ToString;

                Console.WriteLine("String is {0}", firstStringMethod());

            // firstStringMethod references a static method
            //firstStringMethod = new GetAString(Currency.GetCurrencyUnit);

            firstStringMethod = Currency.GetCurrencyUnit;
            Console.WriteLine("String is {0}", firstStringMethod());
    

        }
    }
}

 

Tags:,

Add a Comment

Your email address will not be published. Required fields are marked *