Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# The 'new' keyword on existing objects

I was wondering as to what happens to an object (in C#), once its reference becomes reassigned. Example:

Car c = new Car("Red Car"); c = new Car("Blue Car"); 

Since the reference was reused, does the garbage collector dispose / handle the 'Red Car' after it's lost its reference? Or does a separate method need to be implemented to dispose of the 'red car'?

I'm primarily wondering because there's a relatively large object that I'm going to recycle, and need to know if there is anything that should be done when it gets recreated.

like image 576
Mike Avatar asked Jul 13 '11 15:07

Mike


2 Answers

In your example, the Red Car instance of c will become eligible for garbage collection when c is assigned to Blue Car. You don't need to do anything.

Check out this (old, but still relevant) MSDN article about the .NET garbage collector. http://msdn.microsoft.com/en-us/magazine/bb985010.aspx

The first paragraph says it all:

Garbage collection in the Microsoft .NET common language runtime environment completely absolves the developer from tracking memory usage and knowing when to free memory.

like image 101
Richard Ev Avatar answered Oct 09 '22 06:10

Richard Ev


Since the reference was reused, does the garbage collector dispose / handle the 'Red Car' after it's lost it's reference?

You're looking at this in perhaps the wrong way:

c [*] ----> [Car { Name = "Red Car" }]  // Car c = new Car("Red Car") 

Then your next step:

c [*]       [Car { Name = "Red Car"  }] // No chain of references to this object    \------> [Car { Name = "Blue Car" }] // c = new Car("Blue Car") 

The GC will come along and "collect" any of these objects which have no chain of references to a live object at some point in the future. For most tasks, as long as you're using managed data, you should not worry about large objects versus small objects.

For most tasks you only worry about deterministic memory management when dealing with IDisposable. As long as you follow the best practice of using-blocks, you will generally be fine.

like image 27
user7116 Avatar answered Oct 09 '22 06:10

user7116