What is the integer reference type in C#?

前端 未结 8 1178
日久生厌
日久生厌 2021-01-11 12:46

I\'d like to have an integer variable which can be set to null and don\'t want to have to use the int? myVariable syntax. I tried using int and

8条回答
  •  無奈伤痛
    2021-01-11 13:24

    You will have to use a nullable type, i.e:

    Nullable or int?
    

    The purpose of nullable type is, to enable you to assign null to a value type.

    From MSDN:

    Nullable types address the scenario where you want to be able to have a primitive type with a null (or unknown) value. This is common in database scenarios, but is also useful in other situations.

    In the past, there were several ways of doing this:

    1. A boxed value type. This is not strongly-typed at compile-time, and involves doing a heap allocation for every type.
    2. A class wrapper for the value type. This is strongly-typed, but still involves a heap allocation, and the you have to write the wrapper.
    3. A struct wrapper that supports the concept of nullability. This is a good solution, but you have to write it yourself.

提交回复
热议问题