Accessing field of out of scope class instance











up vote
0
down vote

favorite












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 at 13:10












  • @DmytroMukalov I edited the A class for more clarity :)
    – Tedd Parsile
    Nov 21 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 at 13:36















up vote
0
down vote

favorite












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 at 13:10












  • @DmytroMukalov I edited the A class for more clarity :)
    – Tedd Parsile
    Nov 21 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 at 13:36













up vote
0
down vote

favorite









up vote
0
down vote

favorite











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 at 13:20

























asked Nov 21 at 12:40









Tedd Parsile

3817




3817












  • 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 at 13:10












  • @DmytroMukalov I edited the A class for more clarity :)
    – Tedd Parsile
    Nov 21 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 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 at 13:10












  • @DmytroMukalov I edited the A class for more clarity :)
    – Tedd Parsile
    Nov 21 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 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 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 at 13:10














@DmytroMukalov I edited the A class for more clarity :)
– Tedd Parsile
Nov 21 at 13:18






@DmytroMukalov I edited the A class for more clarity :)
– Tedd Parsile
Nov 21 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 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 at 13:36












2 Answers
2






active

oldest

votes

















up vote
0
down vote













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 at 13:23


















up vote
0
down vote













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





















    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',
    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








    up vote
    0
    down vote













    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 at 13:23















    up vote
    0
    down vote













    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 at 13:23













    up vote
    0
    down vote










    up vote
    0
    down vote









    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 at 13:11









    Klaus Gütter

    1,034512




    1,034512












    • Thanks for clarification! :)
      – Tedd Parsile
      Nov 21 at 13:23


















    • Thanks for clarification! :)
      – Tedd Parsile
      Nov 21 at 13:23
















    Thanks for clarification! :)
    – Tedd Parsile
    Nov 21 at 13:23




    Thanks for clarification! :)
    – Tedd Parsile
    Nov 21 at 13:23












    up vote
    0
    down vote













    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

























      up vote
      0
      down vote













      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























        up vote
        0
        down vote










        up vote
        0
        down vote









        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 at 13:24









        Pedro LM

        38817




        38817






























             

            draft saved


            draft discarded



















































             


            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

            Contact image not getting when fetch all contact list from iPhone by CNContact

            count number of partitions of a set with n elements into k subsets

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks