tags:

views:

156

answers:

2

What do I have to do to the following lambda example to get it to work?

ERROR: Only assignment, call, increment, decrement, and new object expressions can be used as a statement

http://msdn.microsoft.com/en-us/library/bb397687.aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace TestLambda
{
    class Program
    {
        static void Main(string[] args)
        {
            delegate int del(int i);
            del myDelegate = x => x * x;
            int j = myDelegate(5); //j = 25
        }

    }

}
+6  A: 

It's not legal to define a type as a method body statement in C#. You'll need to move the delegate outside the method in order to get that to compile. For example

    delegate int del(int i);

public static void Main(string[] args) {

    del myDelegate = x => x * x;
    int j = myDelegate(5); //j = 25
}
JaredPar
Or even better, just use Func<int,int> ;-p
Marc Gravell
@Marc, yes. I think that if you could essentially typedef a Func<>,Action<> at an assembly level, it would go a long way to preventing people from creating new delegate types when a simple Func<>,Action<> would do.
JaredPar
+6  A: 

You need to declare the delegate outside of the method:

class Program
{
    delegate int del(int i);

    static void Main(string[] args)
    {            
        del myDelegate = x => x * x;
        int j = myDelegate(5); //j = 25
    }

}
Outlaw Programmer