Edward Tanguay
Edward Tanguay

Reputation: 193302

Why doesn't this lambda example from the MSDN site work?

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
        }

    }

}

Upvotes: 2

Views: 497

Answers (2)

Tim Frey
Tim Frey

Reputation: 9941

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
    }

}

Upvotes: 6

JaredPar
JaredPar

Reputation: 754575

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
}

Upvotes: 6

Related Questions