C# The 'new' keyword on existing objects

2019-02-02 03:05发布

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.

9条回答
一夜七次
2楼-- · 2019-02-02 03:29

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.

查看更多
霸刀☆藐视天下
3楼-- · 2019-02-02 03:31

The garbage collector will handle cleanup for the red car when it is not longer rooted (not reachable). You, the developer, don't generally have to worry about cleaning up memory in .Net.

There are three caveats that need to be mentioned:

  1. It won't happen right away. Garbage collection will happen when it happens. You can't predict it.
  2. If the type implements IDisposable, it's up to you to make sure the .Dispose() method is called. A using statement is a good way to accomplish this.
  3. You mentioned it's a large object. If it's more than 85000 bytes it will stored in a place called the Large Object Heap, which has very different rules for garbage collection. Allowing this kind of object to be recycled frequently can cause problems.
查看更多
Rolldiameter
4楼-- · 2019-02-02 03:35

If there are no other references to Red car, it will be collected by the GC on its next cycle. You don't need anything extra (unless it's a class that has streams etc. that need to be disposed)

查看更多
登录 后发表回答