dotnet / standard

This repo is building the .NET Standard
3.07k stars 428 forks source link

[question] Will Garbage Collector Collect Memebers, When Object Is Casted To Parent Type, That Is Now Inaccessible On The Type Of Reference? #1797

Closed Xyncgas closed 3 years ago

Xyncgas commented 3 years ago

In the example :

Public class ClassA{
    string a = "A2";
}
public class ClassB : ClassA{//ClassB derive from Class A
    string b = "2B";
}
Public ClassA TestSample()
{
    classB I_Have_A_Pen = new ClassB();
    Return I_Have_A_Pen;
}
void Main()
{
    var I_Have_A_Pineapple = TestSample(); //Ref:{7ED6CC5A-15F9-49F7-A762-C8B3B0B7A7F2}
}

So, at {7ED6CC5A-15F9-49F7-A762-C8B3B0B7A7F2}, I have two questions : I_Have_A_Pineapple is now ClassA but does the standard say it's actually still ClassB or I_Have_A_Pineapple.GetType()==typeof(ClassB) ?

I_Have_A_Pineapple now doesn't have access to string b which value is "2B", because it's casted to ClassA and 2B only existed as Class B member, so a while later would gc be collecting this reference and 2B is gone forever while it might only exist at this moment?

GrabYourPitchforks commented 3 years ago

The string "2B" is still reachable, as shown in the sample code below.

ClassA obj = TestSample();
Console.WriteLine(obj.a); // "A2"

ClassB castObj = (ClassB)obj; // this cast is validated at runtime
Console.WriteLine(castObj.b); // "2B"

Since the runtime knows the actual type of the backing object, and since the caller might cast the object back to the more derived type, the entire object graph is kept alive.

Xyncgas commented 3 years ago

thanks for the explainations @GrabYourPitchforks