Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8108025
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T00:57:51+00:00 2026-06-06T00:57:51+00:00

I am wondering whether I can use the this keyword inside a C# lambda,

  • 0

I am wondering whether I can use the this keyword inside a C# lambda, although actually I know that I can but I want to make sure that this isn’t a bad thing or will produce subtle issues later on.

Having read the rules on variable scope for lambdas, I can see that:

A variable that is captured will not be garbage-collected until the
delegate that references it goes out of scope.

So this leads me to assume that an object instance (this) will also be captured. To test this I wrote this contrived example which is what I want to approximately aim for in my real code – written in LINQPad, hence why I have the Dump() method calls:

void Main()
{
    Repository repo = new Repository();
    Person person = repo.GetPerson(1);

    person.ID.Dump("Person ID - Value Assigned");
    person.Name.Dump("Person Name - Lazily Created");
}

class Person
{
    public Person(Lazy<string> name)
    {
        this.name = name;
    }

    public int ID { get; set; }

    private Lazy<string> name;
    public string Name
    {
        get { return name.Value; }
    }
}

class Repository
{
    public Person GetPerson(int id)
    {
        // Setup person to lazily load a name value
        Person person = new Person(
            new Lazy<string>(
                () => this.GetName()    // <--- This I'm not sure on...
            )
        );
        person.ID = id;
        return person;
    }

    public string GetName()
    {
        return "John Smith";
    }
}

This runs and gives me the correct output so accessing this from within a lambda clearly works. What I am wanting to check though is:

  • Does this follow the same variable scope rules as local variables, meaning that the this reference is kept in memory until the lambda is not used anymore? It would appear so from my little experiment but if anyone can give further details I’d be interested.
  • Is this advisable? I do not want to get into the situation later where this pattern could cause problems.
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T00:57:52+00:00Added an answer on June 6, 2026 at 12:57 am

    There is nothing wrong with using this in a lambda, but as you mention, if you do use this (or if you use it implicitly, by calling any nonstatic member function or using a nonstatic member variable) then the garbage collector will keep the object that this refers to alive at least as long as the delegate is alive. Since you pass a lambda to Lazy, this implies that the Repository will be alive at least as long as the Lazy object is alive (even if you never call Lazy.Value).

    To demystify it a bit, it helps to look in a disassembler. Consider this code:

    class Foo {
        static Action fLambda, gLambda;
    
        int x;
        void f() {
            int y = 0;
            fLambda = () => ++y;
        }
        void g() {
            int y = 0;
            gLambda = () => y += x;
        }
    }
    

    The standard compiler changes this to the following (try to ignore the <> extra angle brackets). As you can see, lambdas that use variables from inside the function body are transformed into classes:

    internal class Foo
    {
        private static Action fLambda;
        private static Action gLambda;
        private int x;
    
        private void f()
        {
            Foo.<>c__DisplayClass1 <>c__DisplayClass = new Foo.<>c__DisplayClass1();
            <>c__DisplayClass.y = 0;
            Foo.fLambda = new Action(<>c__DisplayClass.<f>b__0);
        }
        private void g()
        {
            Foo.<>c__DisplayClass4 <>c__DisplayClass = new Foo.<>c__DisplayClass4();
            <>c__DisplayClass.<>4__this = this;
            <>c__DisplayClass.y = 0;
            Foo.gLambda = new Action(<>c__DisplayClass.<g>b__3);
        }
    
        [CompilerGenerated]
        private sealed class <>c__DisplayClass1
        {
            public int y;
            public void <f>b__0()
            {
                this.y++;
            }
        }
        [CompilerGenerated]
        private sealed class <>c__DisplayClass4
        {
            public int y;
            public Foo <>4__this;
            public void <g>b__3()
            {
                this.y += this.<>4__this.x;
            }
        }
    
    }
    

    If you use this, whether implicitly or explicitly, it becomes a member variable in the compiler-generated class. So the class for f(), DisplayClass1, does not contain a reference to Foo, but the class for g(), DisplayClass2, does.

    The compiler handles lambdas in a simpler manner if they don’t reference any local variables. So consider some slightly different code:

    public class Foo {
        static Action pLambda, qLambda;
    
        int x;
        void p() {
            int y = 0;
            pLambda = () => Console.WriteLine("Simple lambda!");
        }
        void q() {
            int y = 0;
            qLambda = () => Console.WriteLine(x);
        }
    }
    

    This time the lambdas don’t reference any local variables, so the compiler translates your lambda functions into ordinary functions. The lambda in p() does not use this so it becomes a static function (called <p>b__0); the lambda in q() does use this (implicitly) so it becomes a non-static function (called <q>b__2):

    public class Foo {
        private static Action pLambda, qLambda;
    
        private int x;
        private void p()
        {
            Foo.pLambda = new Action(Foo.<p>b__0);
        }
        private void q()
        {
            Foo.qLambda = new Action(this.<q>b__2);
        }
        [CompilerGenerated] private static void <p>b__0()
        {
            Console.WriteLine("Simple lambda!");
        }
        [CompilerGenerated] private void <q>b__2()
        {
            Console.WriteLine(this.x);
        }
        // (I don't know why this is here)
        [CompilerGenerated] private static Action CS$<>9__CachedAnonymousMethodDelegate1;
    }
    

    Note: I viewed the compiler output using ILSpy with the option “decompile anonymous methods/lambdas” turned off.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am wondering whether what I want can be acheived by using Yahoo pipes
I'm now wondering whether we can make some sort of SSL server based on
I am wondering whether you can make a button, function like a HTML Radio
I am wondering whether I can upgrade a basic IoC container I am using
I was wondering whether or not I can extend the Enum type in C#
I wondering whether use a webView to create a complex text area done with
I was wondering whether anyone knows of any tools available that perform the task
I'm wondering whether anyone has been able to use the Microsoft Chart control in
I know we can use perror() in C to print errors. I was just
I know that you can get the username of the currently logged in user

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.