Monday, April 13, 2009

C# - A common question - Value-type vs Reference-type - Struct vs Class

Value types:
Simplest types in the .NET, they contain their data directly instead of containing a reference to the memory that stored the data. Instances of value types are stored in an area of memory called the "stack", it brings performance and minimal overhead to create, change, read, or remove them.

Three general value types:
- Built in types
(sbyte, byte, short, int, uint, long, float, double, decimal)
(char, bool, date)
- User-defined types
(structures - by "struct")
- Enumerations
(enum - symbols that have fixed values)

Structures:
You can define them by "struct" and simply they are stored on the stack and they contain their data directly. Structures are composite of other types. Structure can store multiple values and it can have methods, those methods usually works on values which are stored in the structure.

You should define a structure rather than a class, if the user defined type will perform better as a value type than a reference type. Generally structures meet all the following criteria:

* Represents a single value logically
* Has an instance size that is less than 16 bytes. (Interesting)
* Is not frequently changed after creation.
* Is not cast (Converting between types) to a reference type.

If you assign an structure to another one, it will copy data and changing value in each one, doesn't affect the values in another one cuz data of structures are stored in different places in "stack".

Question:
You pass a value type variable into a method as an arguments, the method changes the variable, when the method returns, the variable has not changed, why?
A: Passing a value type into a method, creates a copy of the data.

----------------------------------
Reference types:
Most types in .NET are reference types (a few thousand!). Reference types store the address of their data (like pointers). The actual data that the address refers is stored in an area of memory called the "heap". Garbage collection manages the memory used by the heap by disposing of items that are no longer referenced. Assigning a reference type to another doesn't copy the data because a reference type just directly store the address of data.

Class is a reference type.
C# struct/class Differences
Share/Bookmark

No comments: