We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Friday, August 14, 2015

Delegates and Events in c#

1. What is a delegate?
Delegates are objects you can use to call the methods of other objects.
A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C function pointers, delegates are object-oriented, type safe, and secure.

  • Delegates have the following properties:
  • Delegates are like C++ function pointers but are type safe.
  • Delegates allow methods to be passed as parameters.
2. What is the main use of delegates in C#?
Delegates are mainly used to define call back methods.


3. What is a multicast delegate?
The capability of calling multiple methods on a single event is called chaining delegates. Let me give you an example to understand this further.

  • Create a new asp.net web application
  • Drag and drop a button control and leave the ID as Button1.
  • On the code behind file, add the code shown below.
4. How to use a delegate for calling a method?
To use a delegate for calling a method we need to adopt the following process:-

  •  Declaration of a delegate.
  •  Instantiate the delegate.


5. Where can we define the delegate?
Delegates can be defined either within a class or under a namespace also.

6. Do events have return type?
 No, events do not have a return type.

7. In multicast delegate the IO parameters and the return type of all the methods should be the same. Is it true or false?
It is true because delegates are type-safe.

8. Can we call multiple methods using a single delegate? Explain?
Yes, if we want to call multiple methods using single delegate all the methods should have the same IO Parameters
.
9. What is Anonymous Method?
C# 2.0 introduced the Anonymous method which provides a technique to pass a code block as a delegate parameter. It is an inline unnamed method in the code.

10. What is Lambda Expression?
Lambda Expression is simply an improvement in syntax when using Anonymous Methods.
 Syntax: Parameters => Executed Code

11. Does require the name for creating an Anonymous method?
No, An anonymous method is basically methods without a name, just the body.

12. Can we create an anonymous method without parameter and return type?
Yes, the parameter and return type are optional.

13. Can we say the anonymous method has only a body?
Yes, we can say the anonymous method has the only body without a name.

14. Does require ‘delegate’ keyword for creating an anonymous method?
Yes, an anonymous method is created using the delegate keyword.
Syntax: delegate (<paramdefinations>).

15. What is the main advantage of Lambda Operator (=>)?
If we use Lambda operator there is no need to use the delegate keyword or provide the type of the parameter. Benefits are like reducing typing.

16. Using lambda expression does require providing the type of parameter?
No, doesn’t require providing the type of parameter.

17. What is the benefit of using the Anonymous method and Lambda Expression?
Benefits are like reduced typing, i.e. no need to specify the name of the function, it’s the return type, and its access modifier as well as when reading the code you don’t need to look elsewhere for the method’s definition.

18. What is the syntax of defining the Lambda Expression and Anonymous Method?
Anonymous Method: delegate (<paramdefinations>)

19. How do we call or how many ways we can call a delegate?
Two ways: either called synchronously or asynchronously by using BeginInvoke and EndInvoke methods.

20. What is the return type of delegate?

Delegate itself a type. If it has, then the return type of a delegate must be the same as method type or vice-versa.

20. What is the event Handler?

Event handlers are nothing more than methods that are invoked through delegates.

21. How do you declare delegates?
Syntax: delegate <return type> <delegate-name> <parameter list>
Each delegate type describes the number and types of the arguments, and the type of the return value of methods that it can encapsulate. Whenever a new set of argument types or return value type is needed, a new delegate type must be declared.
delegate void Del (string str);// Declare a delegate
static void Notify (string name)// Declare a method with the same signature as the delegate.
{     Console.WriteLine("Notification received for: {0}", name);      }

22. How do you instantiate a delegate?

Del del1 = new Del(Notify);       
      or              
 
 Del del2 = Notify;   or
 
// Instantiate Del by using an anonymous method(2.0).
Del del3 = delegate(string name)
{ Console.WriteLine("Notification received for: {0}", name); };     or

// Instantiate Del by using a lambda expression(3.0).
Del del4 = name =>{Console.WriteLine("Notification received for: {0}", name); };

23. How do you call a delegate?
del1(“achal”);
Console.WriteLine(Name is: {0}", Notify())

24. Explain about BeginInvoke method of delegates?

The BeginInvoke method initiates the asynchronous call. It has the same parameters as the method that you want to execute asynchronously, plus two additional optional parameters. The first parameter is an AsyncCallback delegate that references a method to be called when the asynchronous call completes. A second parameter is a user-defined object that passes information into the callback method. BeginInvoke returns immediately and does not wait for the asynchronous call to complete. BeginInvoke returns an IAsyncResult, which can be used to monitor the progress of the asynchronous call.

25. Explain about EndInvoke method?

The EndInvoke method retrieves the results of the asynchronous call. It can be called any time after BeginInvoke. If the asynchronous call has not completed, EndInvoke blocks the calling thread until it completes. The parameters of EndInvoke includes the out and ref parameters of the method that you want to execute asynchronously, plus the IAsyncResult returned by BeginInvoke.

26. Which areas are delegates commonly used?

Multithreading, Event handling

27. Only one method can be called using a delegate?

No. delegate can be called one or more than one method at a time.

28. Delegates are type-safe if yes how?

Yes. Delegates' type must match with the function type & vice-versa.

29. by using delegates Application performance increases?

Yes.

30. What is the main difference between pointer and delegate?

Delegates: It is a function pointer used to store the address of a function type.
Pointer: It is a variable used to store the address of a variable.

31. The signature of delegate need not be same as the signature of the method that is it true?

False, the signature of the delegate must be the same as the method which delegate points to.

32. What is a publisher in the Event?

A publisher is an object that contains the definition of the event and the delegate. The event-delegate association is also defined in this object. A publisher class object invokes the event and it is notified to other objects.         
.
33. What is a subscriber in the Event?
Subscriber is an object that accepts the event and provides an event handler. The delegate in the publisher class invokes the method (event handler) of the subscriber class.    


34. Whether delegate objects are mutable or immutable?
Once a delegate is created, the method it is associated with never changes; delegate objects are immutable.

35. Difference between event and field?
Difference between events and fields is that an event can be placed in an interface while a field cannot.


36. What is an object sender, event args e?       
An "objects any source" parameter indicating the source of the event, and an "e" parameter that encapsulates additional information about the event. The type of the "e" parameter should derive from the EventArgs class.

37. Which namespace Delegate inherited from?

Delegate inherited from: System.delegate and System.MulticastDelegate.

38. What are the properties of the delegate?

1. Method: Gets the method represented by the delegate.
 2. Target: Gets the class instance on which the current delegate invokes the instance method.

39. What is the difference between method overloading and delegate?
In the context of method overloading, the signature of a method does not include the return value. But in the context of delegates, the signature does include the return value.

40. What are the properties of the event?

  • The publisher determines when an event is raised; the subscribers determine what action is taken in response to the event.
  • An event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers.
  • Events that have no subscribers are never raised.
  • Events are typically used to signal user actions such as button clicks or menu selections in graphical user interfaces.
  • When an event has multiple subscribers, the event handlers are invoked synchronously when an event is raised. To invoke events asynchronously.
41. What do you mean by EventArgs?
Represents the base class for classes that contain event data, and provides value to use for events that do not include event data.

42. What are the methods of EventArgs?

Equals (Object): Determines whether the specified object is equal to the current object. (Inherited from Object.)
Finalize: Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
GetHashCode: Serves as the default hash function. (Inherited from Object.)
GetType: Gets the Type of the current instance. (Inherited from Object.)
MemberwiseClone: Creates a shallow copy of the current Object. (Inherited from Object.)
ToString: Returns a string that represents the current object. (Inherited from Object.

43. What is Event?
Events provide a generally useful way for objects to signal state changes that may be useful to clients of that object. Events are an important building block for creating classes that can be reused in a large number of different programs.

44.  What is the order of events in a web form?

  • nit;
  • Load; 
  • Cached postback events;
  • Prerender;
  • Unload;
45. Can we have shared events?
Yes, we can have shared events for only shared methods that can raise shared events.

46. What is an Object sender in the event?
Object Sender is a parameter called Sender that contains a reference to the control/object that raised the event. Those two parameters (or variants of) are sent, by convention, with all events. e an instance of EventArgs including, in many cases, an object which inherits from EventArgs.

47. What is the importance of delegates and events in designing large applications?
The use of delegates and events in the design of a large application can reduce dependencies and the coupling of layers. This allows you to develop components that have a higher reusability factor.

48. What are the methods of delegate class?

  •  Slone(): Creates a shallow copy of the delegate.
  •  ToString(): Returns a string that represents the current object.
  •  Finalize(): Allows an object to try to free resources and other cleanup operations before it is reclaimed by garbage collection.
  • GetType(): Gets the type of the current instance.
49. Can we directly use the event declared in a base class from a derived class?
We can create a protected invoking method in the base class that wraps the event. By calling or overriding this invoking method, derived classes can invoke the event indirectly.

50. Can we declare an event instruct?
Yes, Structs can also contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types.

51. Advantage & Disadvantage of event?
Advantages: Ease of development, Flexibility, Simplicity and suitable for graphical interfaces. Disadvantages: Complex, Hard to control, Time consuming to get event loops and event handlers running.

52. Why callback methods use delegates?
This ability to refer to a method as a parameter makes delegates ideal for defining callback methods. For example, a sort algorithm could be passed a reference to the method that compares two objects. Separating the comparison code allows the algorithm to be written in a more general way.

53. Difference between delegate and event?
A delegate is similar to a function pointer in C/C++. It holds a reference to a method and to an object instance (if the method is non-static). Delegates are usually multicast, i.e. they hold references to several object/method pairs.
An event is a notification mechanism, based on delegates. The only thing it exposes publicly is a pair of methods (add/remove) to subscribe to or unsubscribe from the notification. A delegate type is used to define the signature of the handler methods, and the lists of subscribers are (usually) stored internally as a delegate.

54. What are the Different ways to raise the event?
-With the Help of eventHandler()
-Using empty delegatean empty anonymous delegate as a “default listener” so that the event would never be “null”.
-Using Extension Methods. (Adding an extension method Raise() the event type class).

55. How to prevent NullReferenceException of Event?
NullReferenceException means: Object reference not set to an instance of an object.
e.g:    int[] numbers = null;                         //int[] numbers = newint[3];                            
          int n = numbers[0];                          s//int n = numbers[0];
 
56. How does delegate differ from an event?
Delegate is an abstract strong pointer to a function or method while events are
higher level of encapsulation over delegates. Events use delegates internally.
Reasons:  Actually, events use delegates at the bottom. But they add an extra layer on the
delegates, thus forming the publisher and subscriber model.
• As delegates are functioned to pointers, they can move across any clients. So
any of the clients can add or remove events, which can be confusing. But events
give the extra protection/encapsulation by adding the layer and making it a
publisher and subscriber model.

57. What is the difference between method overloading and delegate?
In the context of method overloading, the signature of a method does not include the return value. But in the context of delegates, the signature does include the return value.

58. What is the difference between Func delegate and lambda expression?
They're the same, just two different ways to write the same thing. The lambda syntax is newer, more concise and easy to write.

59. Can events have access to modifiers?
Delegates behave like classes and structs. By default, they have internal access when declared directly within a namespace, and private access when nested.
Yes, Events can be marked as public, private, protected, internal, or protected internal. These access modifiers define how users of the class can access the event.

60. When to Use Delegates Instead of Interfaces?
Both delegates and interfaces enable a class designer to separate type declarations and implementation. A given interface can be inherited and implemented by any class or struct. A delegate can be created for a method on any class, as long as the method fits the method signature for the delegate. An interface reference or a delegate can be used by an object that has no knowledge of the class that implements the interface or delegate method. 


No comments: