Thursday, March 22, 2012

Structure vs class

in vb.net you can define a structure...what exactly is this, why would I want to use it and what is the advantage as opposed to a class?

Thanks!

Hi,

structure is a value type, while a class is a reference type. Types that developers use most often are value types (such as Integer), while most types in .NET Framework Base Class Library are reference types (classes)

Difference is that reference type is allocated from the managed heap (New operator you use to instantiate it returns the memory address of the object, this is what happens under the covers).E.g with reference types you are given a reference to the object on the managed heap. And reference types are subject to garbage collection.

Value types on the other hand are allocated on thread's stack, it has no pointer to instance, the variable is the instance itself. Therefore value types are lighter for the CLR than reference types (value types are not GC'd). But they also have limitations, and in scenarios where they are needed to treat like an object (which causes boxing and unboxing), they can also cause performance overhead.

Here's also a quick list to see their differences:
http://msdn2.microsoft.com/en-US/library/2hkbth2a(VS.80).aspx

0 comments:

Post a Comment