Search code examples
c#scopeanonymous-methods

Anonymous methods Scope c#


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.


Solution

  • 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.