Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Delegates in ASP.NET C#

    • 0
    • 1
    • 1
    • 3
    • 0
    • 0
    • 0
    • 0
    • 178
    Comment on it

    Hello all,

    In C#, we use delegates, which are nothing but the type safe function pointer which means that a delegate points to a function and whenever we invoke the delegate, it will call the function for which it holds the reference.

    The signature of the delegate must match the signature of the function that delegate points to, otherwise it will give a compile time error. This is the reason delegates are called as type safe functions pointers.

    A Delegate is similar to a class, we can create an instance of it and whenever needed we can call it just by passing the function name as a parameter to the delegate constructor, and it is to the function that delegate will pint to.

    The Delegate syntax looks very much similar to a method with a delegate keyword.

    Ex :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace TestConsoleApp
    {
        public delegate int AddDelegate(int a, int b);
        class Program
        {
            static void Main(string[] args)
            {
                Program programObj = new Program();
                AddDelegate addDelegateObj = new AddDelegate(programObj.Add);
                addDelegateObj(1, 2);
            }
    
            public int Add(int input1, int input2)
            {
                return (input1 + input2);
    
            }
        }
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: