C# The 'new' keyword on existing objects

后端 未结 9 492
一整个雨季
一整个雨季 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条回答
  •  -上瘾入骨i
    2020-12-28 13:31

    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.

提交回复
热议问题