Posts

Delegate, Anonymous Method and Lamda Expression in C# (Part 2/2)

Image
What are anonymous method?  Anonymous methods are similar to normal methods but they do not have a name and can be directly assigned to a delegate. These methods are not reusable components that is why they don’t have a method name. They make the code simple and more readable. One reason why we need an anonymous method is that often times a method is created so that it can be assigned to the delegate instance and called through the delegate reference. How to create an anonymous method? Anonymous methods are methods without a name which are directly created and assigned to a delegate instance. See code below where displayTime is an instance of delegate Display that accepts no parameter and has voice return type. Display displayTime = delegate (){       Console .WriteLine( DateTime .Now.ToString( "dd/mm/yyyy" )); }; delegate () mea ns that this anonymous method takes no parameter and {} defines the block of statements to be run when thi...

Delegate, Anonymous Method and Lamda Expression in C# (Part 1/2)

Image
Hello everyone, in this blog I will discuss Lamda Expression which is an important part of C# programming language. It is extensively used in LINQ, delegates and events. Before I discuss what Lamda expression is, I will first briefly discuss delegates and anonymous function because it is a kind of prerequisite for understanding Lamda Expression. What is a Delegate? In simple words, delegate holds a reference to a method or function. Once we have a reference to a method then we can call that method or function by that reference. That’s it. Why Delegate? Delegates support events and a solid pillar for event handling mechanism Delegates execute methods at runtime without having their information about its definition at compile time How to create a Delegate? Just like the way we create an instance of a class i.e. first we define a class which describes an object and create an instance of it. Similarly, we first define how a delegate would look like and then...