Home > .Net / C#, General Programming > Lambda Expressions in C#, Anonymous Functions

Lambda Expressions in C#, Anonymous Functions

Article overview

In this second part of the article, I’m going to show you what the anonymous functions are and what is their role in the Integrated Query Language. If you want to know more about the difference between anonymous functions and lambda expressions, keep reading. ;) 

Related articles:

 

What are the anonymous functions in C# ?

Introduced in C# 2.0, the anonymous functions allow us to write a method definition without its declaration;a convenience, which sets us free from the need of declaring a class method for every little piece of code we want to use. The anonymous functions are usually used in conjunction with delegates. In older version of the .Net framework, we were required to manually instantiate the delegate class passing a method as parameter like this:

OperationDelegate pointer = new OperationDelegate(operationsInstance.Addition)

This is no longer the case, since we can now use anonymous methods instead. For example:

    instance.CustomEvent += delegate
        {
            Console.WriteLine("Action performed”);
        };

or the equivalent with arguments

    instance.CustomEvent += delegate(string parameter)
         {
              Console.WriteLine("Action performed” + parameter);
         };

The above definitions will be compiled to instance methods and assigned to the custom delegate associated with the respective event. 

 

Restrictions in the use of anonymous functions in C#

The following restrictions apply to the use of anonymous methods:

  • You can declare a variable with the same name as an instance or static variable of the outer class
  • You can access instance and static variables of the enclosing class
  • You can't access any ref or out patemeters from inside the anonymous method
  • You can't declare a variable with the same name as another variable from the outer method

The anonymous functions in Java

An interesting thing to say would be how this functionality is implemented in Java. The truth is that Java does not have a default implementation for anonymous methods (or delegates, for that matter), so they use kind of a workaround to get the desired functionality. In frameworks like Swing, event handling is done by explicit instantiation of the class and method definition inside. 

    class EventHandler implements ActionListener {
        
        public void actionPerformed(ActionEvent e) {
            // event specific code
        }
    }

After that, you simply pass an object of the same class to the event listener. 

        instance.addActionListener(new ActionListener());

The good news is that you can use the so-called anonymous classes to additionally shrink this code.

        instance.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // event specific code
            }
        });

By doing this you create an object of type ActionListener (actually a subtype, ActionListener can either be a class or an interface) with a single method inside and the desired code to be executed by the event listener. This is quite similar to what happens in C# behind the scenes, but the syntax is a lot more heavy. As a former Java developer, I was quite disappointed when I found out this is not going to be fixed in Java 7.0 .

 

Introducing lambda expressions

What is the lambda expression ?

The lambda expressions are in fact shorter versions of the standard way of defining anonymous functions. Introduced with C# 3.0, they stand in the core of LINQ and allow us to declare and pass methods as parameters in an elegant and highly effective manner. 

For instance, instead of the above example with the “delegate” keyword, we can write something like this:

        context.CustomEvent += (param) => 
        {
            Console.WriteLine("Action performed” + param);
        };

and more importantly, like this:

        context.CustomEvent += (param) => Console.WriteLine("Action performed” + parameter);

 

The evolution of lambda expressions

You have probably used LINQ and you know that you can take a list and filter it by whatever criteria you want with relative ease. But let’s think for a second about how we have come to that. 

Let’s declare a list of integers and use the build-in predicates in order to find all odd numbers inside. 

        List<int> list = new List<int>() { 1, 10, 25, 25, 40, 50 };
 
        Predicate<int> predefinedDelegate = new Predicate<int>(IsOdd);
        List<int> oddNumbers = list.FindAll(predefinedDelegate);
 
        public bool IsOdd(int number)
        {
            return (number  % 2) != 0;
        }

We have a list, a predicate method, a predefined delegate and the LINQ FindAll method. If we look into the MSDN documentation, we will see that its actual declaration is 

        public List<T> FindAll(Predicate<T> match)

So far we've used the standard delegate syntax. But we can also do this using an anonymous functions in the following way:

        List<int> oddNumbers = list.FindAll(delegate(int number)
        {
            return (i % 2) != 0;
        });

The FindAll method will actually match the parameter definition with the anonymous method itself. We can use lambda expressions in order to simplify this even more:

        List<int> oddNumbers = list.FindAll(n => (n % 2) != 0);

Which is actually a shorter version for

        List<int> oddNumbers = list.FindAll((int n) => (n % 2) != 0);

You should remember that you can use lambda expressions in every place where an anonymous function or a strongly typed delegate is expected. 

 

What is a closure ?

I would also like to mention one last concept related to the topic – the closures. The closure is not a concrete element and it is not a synonym of an anonymous function or a lambda expression.
A closure is a behaviour that allows us to define an anonymous function which refers to a local variable outside that function, and not worry about that variable’s lifespan, even if the whole surrounding object is garbage collected. 

For example, in Javascript:

        function foo(x) {
          var variable = "test";
          return function anotherFunc(x) {
            alert(variable + " " + x);
          }
        }

 


That's from me on the topic of anonymous functions, I hope you learned something new today. ;)

 



Like the article ? Share it ! ;)


  1. No comments yet.
  1. No trackbacks yet.


Copyright © Developing the future 2013. Licensed under the CC> BY-NC-ND 3.0 Creative Commons license.       
Audi R8 wallpapers Sony Xperia Z4 Tablet WiFi