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:15

Garbage collector will take care of disposing of Car object

查看更多
男人必须洒脱
3楼-- · 2019-02-02 03:17

The GC will pick up your Red Car object and dispose of it.

You can call a custom destructor or implement IDisposable if you have resources that need to be released when the original object is no longer used.

查看更多
做个烂人
4楼-- · 2019-02-02 03:20

You create a new object and assign a reference to it to your variable c. At the same time the previous object (the "red car") is now not referenced anymore and may be garbage collected.

查看更多
聊天终结者
5楼-- · 2019-02-02 03:24

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.

查看更多
Fickle 薄情
6楼-- · 2019-02-02 03:27

In case Car holds some native resources you'll want to implement IDisposable and dispose of it properly before reusing the variable.

查看更多
beautiful°
7楼-- · 2019-02-02 03:27

I think you should implement the IDispose interface to clean up unmanaged resources

public class car : IDispose 
查看更多
登录 后发表回答