Accessing field of out of scope class instance












0















Let's consider this class:



public class A<T>
{
private bool _flag;

public Func<T> Function { get; set; } = () => {_flag = true; return _flag; }
}


Now, let's imagine that the Function property somehow accesses the _flag field with both read and write in its body. Then if I use the class A like this:



public Func<T> SomeFunction()
{
var instance = new A();
return instance.Function;
}


My question is what really happens, because I have originally assumed the instance would be disposed by GC when the SomeFunctions returns, which would mean the _flag would cease to exist and the Function would try to access nonexistent field when eventually called from somewhere, but that isn't what happens. The code seems to work. Is the field somehow preserved in a closure?



Thanks for clarification.










share|improve this question

























  • Even not to mention the private modifier, how can a function access an instance member of a class unless it has an access to the instance itself (by parameter, closure or other class member, etc.) ? Obviously in that case it will have nothing to do with the instance created by var instance = new A(); in your example.

    – Dmytro Mukalov
    Nov 21 '18 at 13:10













  • @DmytroMukalov I edited the A class for more clarity :)

    – Tedd Parsile
    Nov 21 '18 at 13:18













  • In that case the instance will be retained as it's referenced by other object. It's not C++, an object is subject of GC not when it leaves the scope but rather when nobody else references it.

    – Dmytro Mukalov
    Nov 21 '18 at 13:36
















0















Let's consider this class:



public class A<T>
{
private bool _flag;

public Func<T> Function { get; set; } = () => {_flag = true; return _flag; }
}


Now, let's imagine that the Function property somehow accesses the _flag field with both read and write in its body. Then if I use the class A like this:



public Func<T> SomeFunction()
{
var instance = new A();
return instance.Function;
}


My question is what really happens, because I have originally assumed the instance would be disposed by GC when the SomeFunctions returns, which would mean the _flag would cease to exist and the Function would try to access nonexistent field when eventually called from somewhere, but that isn't what happens. The code seems to work. Is the field somehow preserved in a closure?



Thanks for clarification.










share|improve this question

























  • Even not to mention the private modifier, how can a function access an instance member of a class unless it has an access to the instance itself (by parameter, closure or other class member, etc.) ? Obviously in that case it will have nothing to do with the instance created by var instance = new A(); in your example.

    – Dmytro Mukalov
    Nov 21 '18 at 13:10













  • @DmytroMukalov I edited the A class for more clarity :)

    – Tedd Parsile
    Nov 21 '18 at 13:18













  • In that case the instance will be retained as it's referenced by other object. It's not C++, an object is subject of GC not when it leaves the scope but rather when nobody else references it.

    – Dmytro Mukalov
    Nov 21 '18 at 13:36














0












0








0








Let's consider this class:



public class A<T>
{
private bool _flag;

public Func<T> Function { get; set; } = () => {_flag = true; return _flag; }
}


Now, let's imagine that the Function property somehow accesses the _flag field with both read and write in its body. Then if I use the class A like this:



public Func<T> SomeFunction()
{
var instance = new A();
return instance.Function;
}


My question is what really happens, because I have originally assumed the instance would be disposed by GC when the SomeFunctions returns, which would mean the _flag would cease to exist and the Function would try to access nonexistent field when eventually called from somewhere, but that isn't what happens. The code seems to work. Is the field somehow preserved in a closure?



Thanks for clarification.










share|improve this question
















Let's consider this class:



public class A<T>
{
private bool _flag;

public Func<T> Function { get; set; } = () => {_flag = true; return _flag; }
}


Now, let's imagine that the Function property somehow accesses the _flag field with both read and write in its body. Then if I use the class A like this:



public Func<T> SomeFunction()
{
var instance = new A();
return instance.Function;
}


My question is what really happens, because I have originally assumed the instance would be disposed by GC when the SomeFunctions returns, which would mean the _flag would cease to exist and the Function would try to access nonexistent field when eventually called from somewhere, but that isn't what happens. The code seems to work. Is the field somehow preserved in a closure?



Thanks for clarification.







c# scope garbage-collection closures






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 13:20







Tedd Parsile

















asked Nov 21 '18 at 12:40









Tedd ParsileTedd Parsile

4017




4017













  • Even not to mention the private modifier, how can a function access an instance member of a class unless it has an access to the instance itself (by parameter, closure or other class member, etc.) ? Obviously in that case it will have nothing to do with the instance created by var instance = new A(); in your example.

    – Dmytro Mukalov
    Nov 21 '18 at 13:10













  • @DmytroMukalov I edited the A class for more clarity :)

    – Tedd Parsile
    Nov 21 '18 at 13:18













  • In that case the instance will be retained as it's referenced by other object. It's not C++, an object is subject of GC not when it leaves the scope but rather when nobody else references it.

    – Dmytro Mukalov
    Nov 21 '18 at 13:36



















  • Even not to mention the private modifier, how can a function access an instance member of a class unless it has an access to the instance itself (by parameter, closure or other class member, etc.) ? Obviously in that case it will have nothing to do with the instance created by var instance = new A(); in your example.

    – Dmytro Mukalov
    Nov 21 '18 at 13:10













  • @DmytroMukalov I edited the A class for more clarity :)

    – Tedd Parsile
    Nov 21 '18 at 13:18













  • In that case the instance will be retained as it's referenced by other object. It's not C++, an object is subject of GC not when it leaves the scope but rather when nobody else references it.

    – Dmytro Mukalov
    Nov 21 '18 at 13:36

















Even not to mention the private modifier, how can a function access an instance member of a class unless it has an access to the instance itself (by parameter, closure or other class member, etc.) ? Obviously in that case it will have nothing to do with the instance created by var instance = new A(); in your example.

– Dmytro Mukalov
Nov 21 '18 at 13:10







Even not to mention the private modifier, how can a function access an instance member of a class unless it has an access to the instance itself (by parameter, closure or other class member, etc.) ? Obviously in that case it will have nothing to do with the instance created by var instance = new A(); in your example.

– Dmytro Mukalov
Nov 21 '18 at 13:10















@DmytroMukalov I edited the A class for more clarity :)

– Tedd Parsile
Nov 21 '18 at 13:18







@DmytroMukalov I edited the A class for more clarity :)

– Tedd Parsile
Nov 21 '18 at 13:18















In that case the instance will be retained as it's referenced by other object. It's not C++, an object is subject of GC not when it leaves the scope but rather when nobody else references it.

– Dmytro Mukalov
Nov 21 '18 at 13:36





In that case the instance will be retained as it's referenced by other object. It's not C++, an object is subject of GC not when it leaves the scope but rather when nobody else references it.

– Dmytro Mukalov
Nov 21 '18 at 13:36












2 Answers
2






active

oldest

votes


















0














In the interest of simplicity, I will use a Dummy class (instead of your generic A):



class Dummy
{
public int i = 0;

~Dummy()
{
Console.WriteLine("~Dummy --> " + i);
}
}


Note the finalizer, which allows us to see the exact time at which it will be collected by the GC.



Now, consider this helper function: it creates a new Dummy d, then wraps it in a function closure and returns that closure.



static Func<int> MakeFunc()
{
Dummy d = new Dummy();
Func<int> f = () => {
d.i++;
Console.WriteLine("Func invoked, d.i is now " + d.i);
return d.i;
};
return f;
}


We can call it like this:



public static void Main()
{
Console.WriteLine("1");

Func<int> f = MakeFunc();
f();

Console.WriteLine("2");


Output:



1
Func invoked, d.i is now 1
2


We can force a garbage collection cycle:



    GC.Collect();
GC.WaitForPendingFinalizers();

Console.WriteLine("3");


Output:



3


Note how we still haven't seen the finalizer running! The Dummy object is still alive, being held by the function closure.



In fact, we can continue to call the function:



    f();

Console.WriteLine("4");


Output:



Func invoked, d.i is now 2
4


That Dummy instance will be finalized when we drop the reference and force another garbage collection cycle:



    f = null;

GC.Collect();
GC.WaitForPendingFinalizers();

Console.WriteLine("5");


Output:



~Dummy --> 2
5


P.S.: Here I am using GC.Collect() for demonstration purposes. It's generally unnecessary (and inadvisable) to call it like this in production code.






share|improve this answer































    0














    The GC will not remove the instance if there are still references to it. And a Func<> containing a reference to a field will hold a reference to the object (closure).






    share|improve this answer
























    • Thanks for clarification! :)

      – Tedd Parsile
      Nov 21 '18 at 13:23











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53412238%2faccessing-field-of-out-of-scope-class-instance%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    In the interest of simplicity, I will use a Dummy class (instead of your generic A):



    class Dummy
    {
    public int i = 0;

    ~Dummy()
    {
    Console.WriteLine("~Dummy --> " + i);
    }
    }


    Note the finalizer, which allows us to see the exact time at which it will be collected by the GC.



    Now, consider this helper function: it creates a new Dummy d, then wraps it in a function closure and returns that closure.



    static Func<int> MakeFunc()
    {
    Dummy d = new Dummy();
    Func<int> f = () => {
    d.i++;
    Console.WriteLine("Func invoked, d.i is now " + d.i);
    return d.i;
    };
    return f;
    }


    We can call it like this:



    public static void Main()
    {
    Console.WriteLine("1");

    Func<int> f = MakeFunc();
    f();

    Console.WriteLine("2");


    Output:



    1
    Func invoked, d.i is now 1
    2


    We can force a garbage collection cycle:



        GC.Collect();
    GC.WaitForPendingFinalizers();

    Console.WriteLine("3");


    Output:



    3


    Note how we still haven't seen the finalizer running! The Dummy object is still alive, being held by the function closure.



    In fact, we can continue to call the function:



        f();

    Console.WriteLine("4");


    Output:



    Func invoked, d.i is now 2
    4


    That Dummy instance will be finalized when we drop the reference and force another garbage collection cycle:



        f = null;

    GC.Collect();
    GC.WaitForPendingFinalizers();

    Console.WriteLine("5");


    Output:



    ~Dummy --> 2
    5


    P.S.: Here I am using GC.Collect() for demonstration purposes. It's generally unnecessary (and inadvisable) to call it like this in production code.






    share|improve this answer




























      0














      In the interest of simplicity, I will use a Dummy class (instead of your generic A):



      class Dummy
      {
      public int i = 0;

      ~Dummy()
      {
      Console.WriteLine("~Dummy --> " + i);
      }
      }


      Note the finalizer, which allows us to see the exact time at which it will be collected by the GC.



      Now, consider this helper function: it creates a new Dummy d, then wraps it in a function closure and returns that closure.



      static Func<int> MakeFunc()
      {
      Dummy d = new Dummy();
      Func<int> f = () => {
      d.i++;
      Console.WriteLine("Func invoked, d.i is now " + d.i);
      return d.i;
      };
      return f;
      }


      We can call it like this:



      public static void Main()
      {
      Console.WriteLine("1");

      Func<int> f = MakeFunc();
      f();

      Console.WriteLine("2");


      Output:



      1
      Func invoked, d.i is now 1
      2


      We can force a garbage collection cycle:



          GC.Collect();
      GC.WaitForPendingFinalizers();

      Console.WriteLine("3");


      Output:



      3


      Note how we still haven't seen the finalizer running! The Dummy object is still alive, being held by the function closure.



      In fact, we can continue to call the function:



          f();

      Console.WriteLine("4");


      Output:



      Func invoked, d.i is now 2
      4


      That Dummy instance will be finalized when we drop the reference and force another garbage collection cycle:



          f = null;

      GC.Collect();
      GC.WaitForPendingFinalizers();

      Console.WriteLine("5");


      Output:



      ~Dummy --> 2
      5


      P.S.: Here I am using GC.Collect() for demonstration purposes. It's generally unnecessary (and inadvisable) to call it like this in production code.






      share|improve this answer


























        0












        0








        0







        In the interest of simplicity, I will use a Dummy class (instead of your generic A):



        class Dummy
        {
        public int i = 0;

        ~Dummy()
        {
        Console.WriteLine("~Dummy --> " + i);
        }
        }


        Note the finalizer, which allows us to see the exact time at which it will be collected by the GC.



        Now, consider this helper function: it creates a new Dummy d, then wraps it in a function closure and returns that closure.



        static Func<int> MakeFunc()
        {
        Dummy d = new Dummy();
        Func<int> f = () => {
        d.i++;
        Console.WriteLine("Func invoked, d.i is now " + d.i);
        return d.i;
        };
        return f;
        }


        We can call it like this:



        public static void Main()
        {
        Console.WriteLine("1");

        Func<int> f = MakeFunc();
        f();

        Console.WriteLine("2");


        Output:



        1
        Func invoked, d.i is now 1
        2


        We can force a garbage collection cycle:



            GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine("3");


        Output:



        3


        Note how we still haven't seen the finalizer running! The Dummy object is still alive, being held by the function closure.



        In fact, we can continue to call the function:



            f();

        Console.WriteLine("4");


        Output:



        Func invoked, d.i is now 2
        4


        That Dummy instance will be finalized when we drop the reference and force another garbage collection cycle:



            f = null;

        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine("5");


        Output:



        ~Dummy --> 2
        5


        P.S.: Here I am using GC.Collect() for demonstration purposes. It's generally unnecessary (and inadvisable) to call it like this in production code.






        share|improve this answer













        In the interest of simplicity, I will use a Dummy class (instead of your generic A):



        class Dummy
        {
        public int i = 0;

        ~Dummy()
        {
        Console.WriteLine("~Dummy --> " + i);
        }
        }


        Note the finalizer, which allows us to see the exact time at which it will be collected by the GC.



        Now, consider this helper function: it creates a new Dummy d, then wraps it in a function closure and returns that closure.



        static Func<int> MakeFunc()
        {
        Dummy d = new Dummy();
        Func<int> f = () => {
        d.i++;
        Console.WriteLine("Func invoked, d.i is now " + d.i);
        return d.i;
        };
        return f;
        }


        We can call it like this:



        public static void Main()
        {
        Console.WriteLine("1");

        Func<int> f = MakeFunc();
        f();

        Console.WriteLine("2");


        Output:



        1
        Func invoked, d.i is now 1
        2


        We can force a garbage collection cycle:



            GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine("3");


        Output:



        3


        Note how we still haven't seen the finalizer running! The Dummy object is still alive, being held by the function closure.



        In fact, we can continue to call the function:



            f();

        Console.WriteLine("4");


        Output:



        Func invoked, d.i is now 2
        4


        That Dummy instance will be finalized when we drop the reference and force another garbage collection cycle:



            f = null;

        GC.Collect();
        GC.WaitForPendingFinalizers();

        Console.WriteLine("5");


        Output:



        ~Dummy --> 2
        5


        P.S.: Here I am using GC.Collect() for demonstration purposes. It's generally unnecessary (and inadvisable) to call it like this in production code.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 21 '18 at 13:24









        Pedro LMPedro LM

        694310




        694310

























            0














            The GC will not remove the instance if there are still references to it. And a Func<> containing a reference to a field will hold a reference to the object (closure).






            share|improve this answer
























            • Thanks for clarification! :)

              – Tedd Parsile
              Nov 21 '18 at 13:23
















            0














            The GC will not remove the instance if there are still references to it. And a Func<> containing a reference to a field will hold a reference to the object (closure).






            share|improve this answer
























            • Thanks for clarification! :)

              – Tedd Parsile
              Nov 21 '18 at 13:23














            0












            0








            0







            The GC will not remove the instance if there are still references to it. And a Func<> containing a reference to a field will hold a reference to the object (closure).






            share|improve this answer













            The GC will not remove the instance if there are still references to it. And a Func<> containing a reference to a field will hold a reference to the object (closure).







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 21 '18 at 13:11









            Klaus GütterKlaus Gütter

            2,59221422




            2,59221422













            • Thanks for clarification! :)

              – Tedd Parsile
              Nov 21 '18 at 13:23



















            • Thanks for clarification! :)

              – Tedd Parsile
              Nov 21 '18 at 13:23

















            Thanks for clarification! :)

            – Tedd Parsile
            Nov 21 '18 at 13:23





            Thanks for clarification! :)

            – Tedd Parsile
            Nov 21 '18 at 13:23


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53412238%2faccessing-field-of-out-of-scope-class-instance%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to change which sound is reproduced for terminal bell?

            Can I use Tabulator js library in my java Spring + Thymeleaf project?

            Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents