Call Girls in Dwarka Mor Delhi Contact Us 9654467111
PROGRAMMING USING C#.NET SARASWATHI RAMALINGAM
1. UNIT III – PROGRAMMING
USING C#.NET
R SARASWATHI
SRI AKILANDESWARI WOMENS COLLEGE
2. DELEGATES AND EVENTS
Delegates – Declaring a Delegate – Defining
Delegate Methods – Creating and Invoking
Delegate Objects – Multicasting with
Delegates – Events – Event Sources –Event
Handlers – Events and Delegates.
3. Delegates
• Pass a function as a parameter.
• The delegate is a reference type data type that defines the
method signature.
• You can define variables of delegate, just like other data
type, that can refer to any method with the same signature as
the delegate.
• Delegate just contains the details of a method.
• A delegate is a class that encapsulates a method signature.
• Although it can be used in any context, it often serves as the
basis for the event-handling model in C# and .NET.
4. Delegates
• Provides a good way to encapsulate the methods.
• Delegates are the library class in System namespace.
• These are the type-safe pointer of any method.
• Delegates are mainly used in implementing the call-back methods
and events.
• Delegates can be chained together as two or more methods can be
called on a single event.
• It doesn’t care about the class of the object that it references.
• Delegates can also be used in “anonymous methods” invocation.
5. Delegate
• There are three steps involved while
working with delegates:
– Declare a delegate
– Set a target method
– Invoke a delegate
6. Delegate
Singlecast delegate
• Singlecast delegate point to single method at a time. In
this the delegate is assigned to a single method at a
time. They are derived from System.Delegate class.
Multicast Delegate
• When a delegate is wrapped with more than one method
that is known as a multicast delegate.
• In C#, delegates are multicast, which means that they
can point to more than one function at a time. They are
derived from System.MulticastDelegate class.
7. Declaring a Delegate
[access modifier] delegate [return type] [delegate
name]([parameters])
• modifier: It is the required modifier which defines the access
of delegate and it is optional to use.
• delegate: It is the keyword which is used to define the
delegate.
• return_type: It is the type of value returned by the methods
which the delegate will be going to call. It can be void. A
method must have the same return type as the delegate.
• delegate_name: It is the user-defined name or identifier for
the delegate.
• parameter_list: This contains the parameters which are
required by the method when called through the delegate.
8. Declaring a Delegate
Example:
// "public" is the modifier
// "int" is return type
// "delegate1" is delegate name
// "(int G, int F, int G)" are the parameters
public delegate int delegate1(int G, int F, int
G);
public delegate void MyDelegate(string msg);
public delegate void DelegateExample();
9. Creating and Invoking
Delegate Objects
• After declaring a delegate, a delegate object is created
with the help of new keyword.
• Once a delegate is instantiated, a method call made to
the delegate is pass by the delegate to that method.
• The parameters passed to the delegate by the caller are
passed to the method, and the return value, if any, from
the method, is returned to the caller by the delegate.
• When creating a delegate, the argument passed to
the new expression is written similar to a method call,
but without the arguments to the method.
10. Creating and Invoking
Delegate Objects
• public delegate void printString(string s);
...
– printString ps1 = new
printString(WriteToScreen);
– printString ps2 = new printString(WriteToFile);
11. Creating and Invoking
Delegate Objects
Delegate1 GFG = new Delegate1(Geeks);
// here,
// " Delegate1 " is delegate name.
// "GFG" is instance_name
// "Geeks" is the calling method.
12. Delegate
public delegate void MyDelegate(string msg);
// declare a delegate
// set target method
MyDelegate del = new MyDelegate(MethodA);
// or
MyDelegate del = MethodA;
// or set lambda expression
MyDelegate del = (string msg) => Console.WriteLine(msg);
// target method
static void MethodA(string message)
{
Console.WriteLine(message);
}
13. using System;
namespace GeeksForGeeks {
class Geeks {
public delegate void addnum(int a, int b);
public delegate void subnum(int a, int b);
public void sum(int a, int b)
{
Console.WriteLine("(100 + 40) = {0}", a + b);
}
public void subtract(int a, int b)
{
Console.WriteLine("(100 - 60) = {0}", a - b);
}
public static void Main(String []args)
{
Geeks obj = new Geeks();
addnum del_obj1 = new addnum(obj.sum);
subnum del_obj2 = new subnum(obj.subtract);
del_obj1(100, 40);
del_obj2(100, 60);
//del_obj1.Invoke(100, 40);
//del_obj2.Invoke(100, 60);
} }}
15. Multicasting with Delegates
• Multicasting of delegate is an
extension of the normal
delegate(sometimes termed as Single
Cast Delegate).
• It helps the user to point more than
one method in a single call.
16. Multicasting with Delegates
Properties:
• Delegates are combined and when you
call a delegate then a complete list of
methods is called.
• All methods are called in First in First
Out(FIFO) order.
• ‘+’ or ‘+=’ Operator is used to add the
methods to delegates.
• ‘–’ or ‘-=’ Operator is used to remove the
methods from the delegates list.
17. Multicasting with Delegates
• Multicasting of delegate should have a
return type of Void otherwise it will
throw a runtime exception.
• Also, the multicasting of delegate will
return the value only from the last
method added in the multicast.
• Although, the other methods will be
executed successfully.
18. using System;
delegate int NumberChanger(int n);
namespace DelegateAppl
{
class TestDelegate { static int num = 10;
public static int AddNum(int p)
{
num += p; return num;
}
public static int MultNum(int q)
{
num *= q;
return num;
}
public static int getNum()
{
return num;
}
static void Main(string[] args)
{
//create delegate instances NumberChanger nc;
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
NumberChanger nc = nc1;
nc += nc2; //calling multicast
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}} }
19. Events
• An event is a notification sent by an object to signal the
occurrence of an action. Events in .NET follow
the observer design pattern.
• The class who raises events is called Publisher, and the
class who receives the notification is called Subscriber.
• There can be multiple subscribers of a single event.
• Typically, a publisher raises an event when some action
occurred.
• The subscribers, who are interested in getting a
notification when an action occurred, should register
with an event and handle it.
20. Events
• In C#, an event is an encapsulated delegate.
• It is dependent on the delegate.
The delegate defines the signature for the event
handler method of the subscriber class.
22. Events
public delegate void Notify(); // delegate
public class ProcessBusinessLogic
{
public event Notify ProcessCompleted; // event
public void StartProcess()
{
Console.WriteLine("Process Started!");
// some code here..
OnProcessCompleted();
}
protected virtual void OnProcessCompleted() //protected virtual
method
{
//if ProcessCompleted is not null then call delegate
ProcessCompleted?.Invoke();
} }
23. Events
using System;
namespace SampleApp
{
public delegate string MyDel(string str);
class EventProgram
{
event MyDel MyEvent;
public EventProgram()
{
this.MyEvent += new MyDel(this.WelcomeUser);
}
public string WelcomeUser(string username)
{
return "Welcome " + username;
}
static void Main(string[] args)
{
EventProgram obj1 = new EventProgram();
string result = obj1.MyEvent("Tutorials Point");
Console.WriteLine(result);
24. Event Sources
• Provides the ability to create events for
event tracing for Windows (ETW).
– Public class EventSource : Idisposable
• InheritanceObject
• EventSource
• DerivedMicrosoft.Extensions.Logging.
EventSource.LoggingEventSource
• ImplementsIDisposable
25. using System.Diagnostics.Tracing;
using System.Collections.Generic;
namespace Demo1
{
class MyCompanyEventSource : EventSource
{
public static MyCompanyEventSource Log = new MyCompanyEventSource();
public void Startup()
{ WriteEvent(1); }
public void OpenFileStart(string fileName){ WriteEvent(2, fileName); }
public void OpenFileStop() { WriteEvent(3); }
}
class Program
{
static void Main(string[] args)
{
string name = MyCompanyEventSource.GetName(typeof(MyCompanyEventSource));
IEnumerable<EventSource> eventSources = MyCompanyEventSource.GetSources();
MyCompanyEventSource.Log.Startup();
// ...
MyCompanyEventSource.Log.OpenFileStart("SomeFile");
// ...
MyCompanyEventSource.Log.OpenFileStop();
} } }
26. Event Handlers
• An event can be declared in two steps:
– Declare a delegate.
– Declare a variable of the delegate
with event keyword.
Example: Declaring an Event
• public delegate void Notify(); // delegate
public class ProcessBusinessLogic {
• public event Notify ProcessCompleted; //
event }
27. Event Handlers
public class ProcessBusinessLogic {
public event Notify ProcessCompleted;
// event
public void StartProcess() {
Console.WriteLine("Process Started!");
// some code here..
OnProcessCompleted();
}
protected virtual void OnProcessCompleted() //protected
virtual method
{ //if ProcessCompleted is not null then call delegate
ProcessCompleted?.Invoke();
} }
28. Event Handlers
Example: Consume an Event
class Program
{
public static void Main()
{
ProcessBusinessLogic bl = new ProcessBusinessLogic();
bl.ProcessCompleted += bl_ProcessCompleted;
// register with an event
bl.StartProcess(); } // event handler
public static void bl_ProcessCompleted()
{
Console.WriteLine("Process Completed!");
} }