C# The 'new' keyword on existing objects

后端 未结 9 497
一整个雨季
一整个雨季 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:40

    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.

提交回复
热议问题