What is the integer reference type in C#?
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 Int16
to no avail. Do I have to use int开发者_开发百科? myVariable
?
I mentioned this because in Java there is both an 'int' type (a primitive) and 'Integer' (a reference type). I wanted to be sure that there isn't a built-in integer reference type that I could be using. I'll use 'int?' for what I'm doing.
For info, int?
/ Nullable<T>
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<int>
) but IMO this is unnecessarily verbose, and I've seen it confuse people.
Yes you should use nullable types
See Nullable
Nullable<int> Nullable<float>
or simply
int? float?
PS:
If you don't want to use ? notation or Nullable at all - simply use special structures for such a thing. For example DataTable:
var table = new DataTable();
table.Columns.Add('intCol',typeof(int));
var row = table.NewRow();
row['intCol'] = null; //
Nullable types are instances of the System.Nullable(T) struct.
Therefore int, int?, Nullable<int> are all value types, not reference types
Yes, it's the only way, as Int32/Int16/int is a primitive type (regardless of boxing/unboxing of these).
You will have to use a nullable type, i.e:
Nullable<int> 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:
- A boxed value type. This is not strongly-typed at compile-time, and involves doing a heap allocation for every type.
- 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.
- A struct wrapper that supports the concept of nullability. This is a good solution, but you have to write it yourself.
You could use System.Nullable<int>
if you hate ?
so much.
Yes. That's why Microsoft added that. People were creating their own Nullable class so they included this pattern in .NET.
The <var>?
syntax makes it nullable. If you dig a bit deeper, you'll see it's just a generic object that gets used.
If you want to do it like C++ you must use unsafe operations. Then, pointers like in C are available, but your code doesn't conform to CLR...
For using pure .NET without pointers, the ?
is the way to go.
精彩评论