struct a
{
public string str;
}
a bb = new a();
class a
{
public string str;
}
a bb = new a();
Is it correct to say that classes are always garbage collected? Are structs kept in memory (forever)?
struct a
{
public string str;
}
a bb = new a();
class a
{
public string str;
}
a bb = new a();
Is it correct to say that classes are always garbage collected? Are structs kept in memory (forever)?
EDIT -> Answer updated following discussion on comments, and link shared by Rob
struct
are value types. Usually No separate memory is allocated for them on heap. Usually No need of Garbage Collection.
There are however exceptions. Memory allocation is not guranteed to be stack allocated for value types or heap allocated for reference type. Read this answer to other SO question and The Stack in An Implementation Detail for detail information.
If struct
has some reference type as member variable, then the reference type will be garbage collected (in next garbage collection trigger) once struct
goes out of scope and the reference type has no more accessible roots to it.
If your example, you have used string
as reference type. String
are handled differently using intern pool.
Yes. If struct
is a field of a object of reference type, then it is stored in the heap, then it is subject to Garbage Collection
If your question is whether the string will remain in memory in the struct example, the answer is no. Members of structs are subject to garbage collection when they leave scope, just like any other objects.
The .NET GC uses a mark-and-sweep approach, where it examines objects that are pointed to by static fields, existing objects, and local variables on the stack, among others.
Since structs in local variables are located on the stack, they are swept as normal. Structs in object members on the heap are also swept as the GC goes through the object tree. Same goes for static members.
In short, structs are swept in the same manner as classes. The only difference between them is the way they are stored. Structs are stored per-variable, while classes are stored as a reference. Both ways are subject to the GC.
If I know correctly, yes in C# they both are Garbage Collected.
Whether stored in heap or stack depends on lifetime of the variable/instance not the type.
One thing to consider is when more complicated situations such as subscribed events handler resides in the instance of class, in that case Garbage Collector can skip collecting and the instance can resides in memory. But above examples will probably be collected since only one string type declared.