Scope of variables inside anonymous functions in C#
Posted
by Vinod
on Stack Overflow
See other posts from Stack Overflow
or by Vinod
Published on 2010-05-23T07:41:47Z
Indexed on
2010/05/23
7:50 UTC
Read the original article
Hit count: 490
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.
© Stack Overflow or respective owner