Delegates In C#
Delegate in C#?
·        A delegate is a type safe mechanism, which act as pointer for the method.
·        In other words, delegate will hold the reference of a method with same kind of declaration of delegate for a method.
·        When it’s an non static class, then these delegates can be called by creating instance of a class to access/ or call a method for execution
·        When it’s a static class, then these delegates can be called by directly with the class name along with the dot operator post class to access/ or call a method for execution.
·         When a method is required to be accessed through delegate then the following steps must be followed
o   Declare a delegate
o   Call by class name or with object reference

Types:
 There are three generic delegates are available such as,
1.      Func Delegate
2.      Predicate Delegate
3.      Action Delegate


Syntax:
[Access Modifier] [delegate] [void|type] [Name of Delegate] ([optional - Parameter])

Example,

  #region Delegate In c#

        public class DelegateDemo
        {
            public delegate string messageDelegate(string firstName, string lastName);
            StringBuilder stringBuilder = new StringBuilder();

            public DelegateDemo()
            {
            }

            string DisplayUserName(string fname, string lName)
            {
                return $"{fname + lName}";
            }
            public void callingMethod()
            {
                string fname = "DotNet";
                string lname = "360World";

                stringBuilder.AppendLine("==============Method Calling without Delegate Starts===============");

                string respone = DisplayUserName(fname, lname);

                stringBuilder.AppendLine($"Output  - {respone}");

                stringBuilder.AppendLine("==============Method Calling without Delegate Ends===============");


                stringBuilder.AppendLine("==============Delegate variable Output Starts===============");

                //Method name has been passed as parameter for delegate
                messageDelegate messageDelegateInstance = new messageDelegate(DisplayUserName);

                //Calling Method using Delegate
                var delegateoutput =  messageDelegateInstance(fname, lname);

                stringBuilder.AppendLine($"Output  - {delegateoutput}");

                stringBuilder.AppendLine("=============Delegate variable Output Ends==============");

                //prinitng values
                MessageBox.Show(stringBuilder.ToString());

            }
        }

        private void button11_Click(object sender, EventArgs e)
        {
            DelegateDemo delegateDemoObject = new DelegateDemo();
            delegateDemoObject.callingMethod();
        }
        #endregion

Output


Comments

Popular posts from this blog