Value Types
Value Types - (Built-in, User defined, Enumerations)
Value types are on the stack. When copied, the entire value is copied onto the stack again, so doubling the space used on the stack.
Built-in Types
(see table below) (All built in numeric types are 'value' types.)
Numeric Built-in types:
| Type |
Alias(C#) |
Bytes |
Range |
| System.SByte |
sbyte |
1 |
-128-127 |
| System.Byte |
byte |
1 |
0-255 |
| System.Int16 |
short |
2 |
-32,768 - 32767 |
| System.Int32 |
int |
4 |
-2147483648 - 2147483647 |
| System.UInt32 |
uint |
4 |
0 - 4294967295 |
| System.Int64 |
long |
8 |
-9223372036854775808 - 9223372036854775807 |
| System.Single |
float |
8 |
-3.402823E+38 - 3.402823E+38 |
| System.Double |
double |
8 |
-1.79769313486232E+308 - 1.79769313486232E+308 |
| System.Decimal |
decimal |
16 |
-79228162514264337593543950335 - 79228162514264337593543950335 |
*The runtime is optimized for the 32 bit int types so use them when possible.
*The runtime is optimized for 'double' so use it for floating point operations when possible.
Other Built-in value types (non numeric)
| Type |
Alias(C#) |
Bytes |
Range |
| System.Char |
char |
2 |
single unicode characters |
| System.Boolean |
bool |
4 |
True/False |
| System.IntPtr |
(none) |
Platform dependent |
Pointer to mem address |
| System.DateTime |
date |
8 |
1/1/0001 12:00:00 AM to 12/31/9999 11:59:59 PM |
There are 300 more value types in the Framework, but above are the most common.
User-defined Types
Structs - Similar to class but stored on the stack.
Structs should:
- Logically represent a single value
- Has an instace size less than 16 bytes
- Will not be changed after creation
- Will not be caset to reference type
You can convert a struct to a class by changing the keyword 'struct' to 'class', and then it will be allocated on the managed heap instead of the stack. Structs generally perform better than classes if the size is 16 bytes or less.
Enumerations
// C#
enum Titles: int {Mr, Ms, Mrs, Dr};
represents a list for the developer to choose from.
-simplify code readability
-provides safety when users need to choose from specific values.
More on Value types:
You don't use the 'new' keyword when creating an instance (int i = 0;)
Best to assign a value when constructing, but not required.
New in .Net 2.0 - Nullable types
Nullable<int> i = null;
or
int? i = null;
With nullable types, you can use the 'HasValue' property to see if its null or not
if(i.HasValue)
//do something