Friday, August 16, 2013

C# (C Sharp) Notes

Delegate:-
-----------
1. The Delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.
Declaration:-
delegate result-type identifier([parameters])
here:-
result-type: The result type, which matches the return type of the function.
identifier: the delegate name.
parameters: The Parameters, that the function takes.
public delegate void SimpleDelegate()
public delegate int ButtonClickHandler(object obj1, object obj2)
Instantiation:-
SimpleDelegate simpleDelegate = new SimpleDelegate(MyFuc);
Invocation:-
simpleDelegate();
Delegate Types:-
1. SingleCast Delegate:- SingleCast Delegate is one that can refer to a single method.
2. MultiCast Delegate:- MultiCast Delegate is can refer to and eventually fire off multiple methods that have the same signature.
1. SingleCast Delegate Example:-
using System;
namespace ExampleDelegate
{
 //Declaration
  public delegate void SimpleDelegate();
   class testDelegate
   {
    public static void MyDelegateFun()
{
Console.WriteLine("This text called form delegate...");
}
public static void Main()
{
//Instantiation
SimpleDelegate simpleDelegate = new SimpleDelegate(MyDelegateFun);
//Invocation
simpleDelegate();
}
   }
}
OutPut:-
This text called form delegate...
2. MultiCast Delegate:-
1. MultiCast Delegates contains list of delegates - called the invocation list - which contains delegates of the same method signature.
2. Whenever the delegate is invoked, it also invokes each delegate in its invocation list.
3. You add and remove delegates from an invocation list using overloaded += and -= operators.
 using System;
public delegate void MultcastTestDelegate();
class Test1
{
 public static void Display1()
 {
  Console.WriteLine("This is the first method");
 }
 public static void Display2()
 {
  Console.WriteLine("This is the second method");
 }
 static void Main()
 {
 //Method 1 to make Multicast
  TestDelegate t1 = new TestDelegate(Display1); //Instantiation t1 delegate
  TestDelegate t2 = new TestDelegate(Display2); //Instantiation t2 delegate
  t1 = t1 + t2; // Make t1 a multicast delegate
  t1(); //Invoke both methods through the delegate //Invocation
  Console.ReadLine();
  //Method 2 to make Multicast
  TestDelegate t1 = new TestDelegate(Display1);
  t1 += new TestDelegate(Display2); // Make t1 a multicast delegate
  t1(); //Invoke both methods through the delegate //Invocation
 }
}
OutPut:-
This is first method
This is the second method
---------------------------------

No comments:

Post a Comment

Featured Post

Azure OpenAI Chat in C# and Python

Azure OpenAI Chat in C#: // Install the .NET library via NuGet: dotnet add package Azure.AI.OpenAI --version 1.0.0-beta.5   using System; u...

Popular posts