What is the integer reference type in C#?

前端 未结 8 1211
日久生厌
日久生厌 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:25

    For info, int? / Nullable is not a reference-type; it is simply a "nullable type", meaning: a struct (essentially and int and a bool flag) with special compiler rules (re null checks, operators, etc) and CLI rules (for boxing/unboxing). There is no "integer reference-type" in .NET, unless you count boxing:

    int i = 123;
    object o = i; // box
    

    but this creates an unnecessary object and has lots of associated other issues.

    For what you want, int? should be ideal. You could use the long-hand syntax (Nullable) but IMO this is unnecessarily verbose, and I've seen it confuse people.

提交回复
热议问题