C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Also: When a number is added to the int, that memory location's value is changed. No new int is created as a result of the addition.
Tip: Using value types, instead of reference types, is often a good optimization. There are counterexamples: large structs can be slower.
C# program that demonstrates value type
using System;
class Program
{
static void Main()
{
int value = 10;
value += DateTime.Today.Day;
Console.WriteLine(value);
}
}
Output
15
Structs: All values are considered structs. A struct is simply a region of bytes that can be accessed. These bytes represent values.
StructInfo: ValueType is a class, which means it is not a value type itself. It is just a representation of a value type.
ClassAnd: Because it is the base class for values, you can refer to those values through a ValueType reference variable.
C# program that uses ValueType
using System;
class Program
{
static ValueType _valueType = false;
static void Main()
{
// You can refer to System.Int32 as a ValueType.
ValueType type1 = 5;
Console.WriteLine(type1.GetType());
// You can refer to System.DateTime as a ValueType.
ValueType type2 = DateTime.Now;
Console.WriteLine(type2.GetType());
// You can refer to System.Boolean as a ValueType.
Console.WriteLine(_valueType.GetType());
// Pass as parameter.
Method(long.MaxValue);
Method(short.MaxValue);
}
static void Method(ValueType type)
{
Console.WriteLine(type.GetType());
}
}
Output
System.Int32
System.DateTime
System.Boolean
System.Int64
System.Int16
Object: This is the base class for all types. In this way it is similar to ValueType, but ValueType too is a subclass of object.
Object TypeUsually: You should use the actual value types (such as int, long, short, DateTime) and not bother with ValueType itself.
DateTimeBool: This type is sometimes not blittable. Some unmanaged systems require a four-byte boolean.
Char: This is also sometimes not blittable. It may need to be converted to an ANSI (1-byte) character.