Tuesday, September 24, 2019

[Code Snippet] Example of using Delegate, Func and Action side by side in C#

Quick and dirty example of using Delegate, Func and Action
side by side in C# to show how to use function pointer  or callback in C#


Example #1  Delegate and Func side by side

     static int DoubleTheValue(int x)
        {
            return x * 2;
        }

        // delegate type should match the function signature  - DoubleTheValue
        public delegate int functionDelegateType(int x);
     
        static void Method1(functionDelegateType func)
        {
            int doubleValue = func(5);
        }


        static void Method2(Func<int, int> func) // easier syntax
        {
            int doubleValue = func(5);
        }

        static void Main(string[] args)
        {
            Method1(DoubleTheValue);

            Method2(DoubleTheValue);
        }

Example #2  Delegate and Action side by side

static void DisplayOnConsole(int x)
        {
            Console.WriteLine(x.ToString());
        }

        // delegate type should match the function signature  - DisplayOnConsole
        public delegate void functionDelegateType (int x);
        static void Method1(functionDelegateType func)
        {
            func(5);
        }

     
        static void Method2(Action<int> func) // easier syntax
        {
            func(5);
        }

     
        static void Main(string[] args)
        {
            Method1(DisplayOnConsole);
            Method2(DisplayOnConsole);
        }

Reference:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/a1ac99ed-0801-4773-a866-4223d42422cf/how-to-pass-function-as-an-argument-to-another-function-in-c?forum=csharpgeneral

.NET , C#

0 comments :

Post a Comment

 

© 2011 GIS and Remote Sensing Tools, Tips and more .. ToS | Privacy Policy | Sitemap

About Me