locked
static members and GC RRS feed

  • Question

  •  

       I'm having a class with a static member, and i'm guessing that the whole class(initialized) doesn't get collected by the GC because of the static member. Is that true? Anyway, i went ahead and made a separate static class with that static member to hold my reference, going after the MSDN advice that i all member are static i should make class static as well. I also read on the singleton design pattern it doesn't match my need in this case. MSDN also said that i should't make static classes just to make vars global, however if that first object doesn't get reclaimed because of that static member is a waste of memory. What do you think?
    Friday, December 7, 2007 7:35 AM

Answers

  • Hi

     

    The static field in a static class is same as the static field in a non-static class. The GC can only collect the objects which have not any reference to them. If the object is not useful in your application, you can set its reference to null, to make sure that GC can collect the object. For example, the following code shows we can set the static field to null.

     

    Code Block

    static class StaticTest

    {

        public static readonly string FilePath = GetFilePath();

        static string GetFilePath()

        {

            // get the file path and return the path

        }

    }

    class Test

    {

        void Clear()

        {

            StaticTest.FilePath = null;

        }

    }

     

     

    Best Regards,

    Wei Zhou

    Monday, December 10, 2007 8:32 AM

All replies

  • Hi

     

    The static field in a static class is same as the static field in a non-static class. The GC can only collect the objects which have not any reference to them. If the object is not useful in your application, you can set its reference to null, to make sure that GC can collect the object. For example, the following code shows we can set the static field to null.

     

    Code Block

    static class StaticTest

    {

        public static readonly string FilePath = GetFilePath();

        static string GetFilePath()

        {

            // get the file path and return the path

        }

    }

    class Test

    {

        void Clear()

        {

            StaticTest.FilePath = null;

        }

    }

     

     

    Best Regards,

    Wei Zhou

    Monday, December 10, 2007 8:32 AM
  •    Ok that confirms it, i'll use static helper classes along with my usual classes that need to set a global member but not to exist as an object just for that all the way.

    Monday, December 10, 2007 5:48 PM