C# 「什麼 Datetime 竟然是 Value Type?」


  1. 說明
    1. Value Type
    2. Reference Type
    3. Struct VS Class
    4. Value Type VS Reference Type
  2. 參考資料

從 DateType 屬於 Value Type 這個事實進而探討 Struct 與 Class 的差別,以及 Value Type 與 Reference Type 的差異所在。

logo

說明

對於 Value Type 的認知有誤,以為簡單的資料類型如 Int, Float, Char 都是屬於 Value Type,而類別、物件類型的資料類型則是屬於 Reference Type。但事實上並非如此,依照 C# 規格書的定義,Value Type 實際上所包含的是 Struct Type 及 Enum Type。其中 Struct Type 包含 nullable Type 以及一些預先定義好的 Struct Type 稱為 Simple Type。Simple Type 包含了所有的數值類型(decimal, byte, short, ushort, int, uint, long, ulong, char, double, sbyte, float)以及布林類型(bool)。

而 DateTime 是屬於 Struct Type,因此也就屬於 Value Type。

另一個誤會則是不只有 Class 可以定義 Field, Property, Method,Struct 也可以有對應的定義,因此判斷 Value Type 或 Reference Type 與否,不是透過 Field, Property, Method 等功能來判斷。

查詢定義可以發現,DateTime 確實不是 Class Type 而是 Struct Type

另一個驚訝則是 String 不是 Value Type 而是 Reference Type。

Value Type

A value type is either a struct type or an enumeration type. C# provides a set of predefined struct types called the simple types. The simple types are identified through reserved words.

而雖然有 Value Type 與 Reference Type 的區分,但在 C# 世界中,所有的 Type 都是直接或間接的源自屬於 Reference Type 的 Object Type,而 Reference Type 的資料值被視為 Object 而 Value Type 則被以 Boxing 及 Unboxing 操作的方式作為 Object。

Reference Type

A reference type value is a reference to an instance of the type, the latter known as an object. The special value null is compatible with all reference types and indicates the absence of an instance.

Reference Type 包含了 Class Type, Interface Type, Array Type 以及 Delegate Type。其中經常使用的 Object, Dynamic, String 都是屬於 Class Type。

Struct VS Class

兩者的差別來自於分屬 Value Type 與 Reference Type。此外另一個特性是 Struct Type 無法為 Null,所以才有 Nullable Type 的出現,而 Reference Type 可以為 Null。

Value Type VS Reference Type

Value Type 資料是儲存於記憶體的 Stack 之中;Reference Type 則是儲存於記憶體的 Heap 之中。

參考資料

C# Types

https://dotblogs.com.tw/daniel/2018/02/22/135011