structs and destructors

C

codymanix

since structs are value types, is a destructor of a struct immediately
called when the struct goes out of scope? this is definitely not the case
with class-objects since they are allocated dynamically are cleaned up by
the gc at a undefined time.
 
B

Bob Powell [MVP]

A value type doesn't need a destructor (finalizer) because it's reclaimed by
the normal movement of the top of the stack. Value types that are boxed are
managed by GC but only because the GC simply reclaims the heap that they
occupy.

If you search for "struct AND finalizer" in the MSDN help you'll see about 4
articles that although they don't mention struct and finalizer in the same
sentence, have a wealth of information. In particular "Performance
Considerations for Run-Time Technologies in the .NET Framework" is an
excellent read.

--
Bob Powell [MVP]
C#, System.Drawing

September's edition of Well Formed is now available.
http://www.bobpowell.net/currentissue.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/gdiplus_faq.htm

Blog http://bobpowelldotnet.blogspot.com
 
S

Samuel Barber

Bob Powell said:
A value type doesn't need a destructor (finalizer) because it's reclaimed by
the normal movement of the top of the stack.

It's precisely because value types are "declaimed by..." that makes
destructors potentially useful. On the other hand, destructors for
reference types are of dubious value (no pun intended), because GC is
not deterministic.

Sam
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi Sam,
It's precisely because value types are "declaimed by..." that makes
destructors potentially useful. On the other hand, destructors for
reference types are of dubious value (no pun intended), because GC is
not deterministic.

IMHO the destructor are of the more importance when you are dealing with
unmanaged resources, it does not matter if the type is reference or value,
when you have to manually release any resource then you need a destructor,
otherwise the GC ( in reference types) or the stack movement ( value types )
will handle pretty well the memory, there is no need of a destructor in
these case unless you need a performance gain.


Cheers,
 
C

codymanix

A value type doesn't need a destructor (finalizer) because it's reclaimed
by
the normal movement of the top of the stack. Value types that are boxed are
managed by GC but only because the GC simply reclaims the heap that they
occupy.

struct FileWrapperRAII
{
File f;
public FileWrapperRAII(string path) { f = new File(path); }
~FileWrapperRAII() { f.Close(); }
}

when the struct is popped off the stack the file can be immediately be
closed instead
of using the "using-clause" or waiting for the GC.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top