#739 – Avoid Accessing an Object After Its Been Finalized

A finalizer should not create a new reference to the object being finalized.  Below is an example where doing this leads to the ability to reference the object after it’s been finalized.

This is an example of questionable code–in general, it’s dangerous to reconstitute an object after it’s been finalized.

In the Dog class, we save a reference to the object being finalized.

    public class Dog
    {
        public static Dog KeepDogRef;

        public string Name { get; set; }

        public Dog(string name)
        {
            Name = name;
        }

        ~Dog()
        {
            Console.WriteLine("Dog destructor for " + Name + " called");
            Dog.KeepDogRef = this;
        }

        public void Bark()
        {
            Console.WriteLine(Name + " : Woof");
        }
    }

In main program, we reconstitute a Dog object after it’s been finalized.

            Dog dog = new Dog("Bowser");

            WeakReference dogRef = new WeakReference(dog);

            // Unref Bowser
            dog = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();

            // Bowser is gone
            Console.WriteLine(string.Format("Object still alive: {0}", dogRef.IsAlive));

            // Hey, Bowser is alive again!
            Dog newRef = Dog.KeepDogRef;
            newRef.Bark();

739-001

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: