1

I have a doubt in scope of varibles inside anonymous functions in C#.

Consider the program below:

 delegate void OtherDel(int x);

        public static void Main()
        {
            OtherDel del2;
            {
                int y = 4;
                del2 = delegate
                {
                      Console.WriteLine("{0}", y);//Is y out of scope
                };
            }

           del2();
        }

My VS2008 IDE gives the following errors: [Practice is a class inside namespace Practice]

1.error CS1643: Not all code paths return a value in anonymous method of type 'Practice.Practice.OtherDel' 2.error CS1593: Delegate 'OtherDel' does not take '0' arguments.

It is told in a book: Illustrated C# 2008(Page 373) that the int variable y is inside the scope of del2 definition. Then why these errors.

Vinod
  • 4,138
  • 11
  • 49
  • 65

2 Answers2

4

Two problem;

  1. you aren't passing anything into your del2() invoke, but it (OtherDel) takes an integer that you don't use - you still need to supply it, though (anonymous methods silently let you not declare the params if you don't use them - they still exist, though - your method is essentially the same as del2 = delegate(int notUsed) {...})
  2. the delegate (OtherDel) must return an int - your method doesn't

The scoping is fine.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • #1 is completely correct, but #2: check out `OtherDel`'s type declaration at the top of the OP's code: `delegate void OtherDel(int x)` -- it doesn't return anything. [EDIT: this was changed in an edit to the question] – Richard May 23 '10 at 09:03
  • The answer reflects the question at the time I posted this ;p – Marc Gravell May 23 '10 at 17:51
2

The error has nothing to do with scopes. Your delegate must return an integer value and take an integer value as parameter:

del2 = someInt =>
{
    Console.WriteLine("{0}", y);
    return 17;
};
int result = del2(5);

So your code might look like this:

delegate int OtherDel(int x);
public static void Main()
{
    int y = 4;
    OtherDel del = x =>
    {
        Console.WriteLine("{0}", x);
        return x;
    };
    int result = del(y);
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928