Monday, February 12, 2018

Delegates

Delegates
class Program
    {
        public delegate void SomeMethodPtr();
        static void Main(string[] args)
        {
            SomeMethodPtr obj = new SomeMethodPtr(SomeMethod);
            obj();  //or obj.Invoke();
            Console.ReadLine();
        }

        static void SomeMethod()
        {
            Console.WriteLine("Some method called");
        }
    }
When we can call a method directly, what is the use of calling a method indirectly? Basically, a delegate is a representative to communicate between 2 parties.
The actual use of delegates is callback
public class MyClass
 {
  public delegate void MyDelegate(int input);
  public void LongRunningMethod(MyDelegate _delegate)
    {
      for (int i = 0; i < 2000; i++)
       {
        _delegate(i);
        }
    }
 }
static void XyzMethod(int i)
{            Console.WriteLine(i);
}
static void Main(string[] args)
{
 MyClass obj = new MyClass();
         obj.LongRunningMethod(XyzMethod);
 Console.ReadLine();
}
In this example, we can pass data between the caller and the program with the help of delegates.
Delegates are used by framework writes so that custom logic can be injected at the time of code.

Delegate,  Anonymous Method, Action, Func, Predicate
class Program
    {
        static double fn_Prodvalues(int val1, int val2)
        {
            return val1 * val2;
        }
        static void Main(string[] args)
        {
            Delegate_Prod dpObj; double result=0;

            dpObj = new Delegate_Prod(fn_Prodvalues);    // Delegate
            result = dpObj(5, 6);

            dpObj = delegate(int x, int y) { return x * y; };    // Anonymous Method  --introduced in c# 2.0
            result = dpObj(9, 6);

            dpObj = (x, y) => x * y;  // Lambda Expression -- Introduced in c# 3.0
            result = dpObj(7, 8);

            //Action<T>  no return type
            Action<int,int> action=delegate(int x, int y){Console.WriteLine(x*y);};
            Action<int, int> action2 = (x, y) => Console.WriteLine(x*y); ;
            action2(4, 4);

            //Func<T,out TResult> has a return type
            Func<int, int, int> func = (x, y) => x * y;
            result = func(5, 6);

            //Predicate<T> T is the input type, and it returns back only boolean
            Predicate<int> predicate = delegate(int x) { return x > 10; };
            Predicate<int> predicate2 = x => x > 10;
            Console.WriteLine(predicate(9));
  
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }

Another example
static void Main(string[] args)
        {
            List<int> lst = new List<int>() { 2, 3, 4, 5, 6, 7, 4, 3, 45, 6 };
            //IEnumerable<int>result= lst.Where(x=>x>5);
            IEnumerable<int> result = lst.Where(fc); // Both Methods work
        }

        static Func<int, bool> fc = delegate(int c) { return c > 5; };


Extension Methods
An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter
using System;
namespace ExtensionMethodsExample
{
   public static class Extension
    {
       public static int WordCount(this string str)
       {
           string[] userString = str.Split(new char[] { ' ', '.', '?' },
                                       StringSplitOptions.RemoveEmptyEntries);
           int wordCount = userString.Length;
           return wordCount;
       }
    }
}

An extension method having the same name and signature like as an instance method will never be called since it has low priority than instance method.
An extension method couldn't override the existing instance methods.
An extension method cannot be used with fields, properties or events.
The compiler doesn't cause an error if two extension methods with same name and signature are defined in two different namespaces and these namespaces are included in same class file using directives. Compiler will cause an error if you will try to call one of them extension method.

No comments:

Post a Comment

Asp.net Core Continued

65 66 67 68 69 70 71 65 ASP.NET Core Identity It is a membership system Step 1 : Inherit from IdentityDbContext class instead of ...