C# The 'new' keyword on existing objects

后端 未结 9 459
一整个雨季
一整个雨季 2020-12-28 13:25

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         


        
相关标签:
9条回答
  • 2020-12-28 13:56

    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.
    0 讨论(0)
  • 2020-12-28 13:57

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

    0 讨论(0)
  • 2020-12-28 13:57

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

    public class car : IDispose 
    
    0 讨论(0)
提交回复
热议问题