1

I wanted to know that where can we define the anonymous method (anonymous functions and lambda statement) because on some websites its written only in function and in some it is written that we can call it in class level scope.

Loofer
  • 6,841
  • 9
  • 61
  • 102
  • 2
    Note that the question doesn't really seem to be able the scope of anonymous functions, so much as where they can be declared, which aren't the same thing. – Jon Skeet Dec 11 '14 at 11:27

2 Answers2

2

You can use anonymous functions pretty much anywhere, including field initializers - but for instance field initializers, you can't use this. So for example:

public class Foo
{
    private int x;

    private Func<int> y = () => 5; // No problem
    private Func<int> z = () => x; // Disallowed, because it captures "this"
}

And of course you can use them within methods as well. I don't believe there's any situation in which you can use an anonymous function within an attribute argument, as they're not constant expressions.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

You can define anonymous method inside another method, basically when you pass it as Delegate parameter in another method.

Alex Zhukovskiy
  • 9,565
  • 11
  • 75
  • 151
  • 1
    Aside from being a confusing bit of wording, this implies (to me) that you can *only* use anonymous functions within methods, which isn't the case - see my answer for an example. – Jon Skeet Dec 11 '14 at 11:26