I am new to C# and just learned that objec开发者_开发知识库ts can be null in C# but int
can't.
Also how does nullable int (int?
) work in C#?
int
is a primitive type and only ReferenceType
s (objects) are nullable. You can make an int
nullable by wrapping it in an object:
System.Nullable<int> i;
-or-
int? i;
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/using-nullable-types
An int is a value type. It is really of type Int32. Objects that can be nullable are reference types. At a basic level the difference is that a value type will store the value with the variable where a reference type will store a reference to the value. A reference can be null, meaning that it doesn't point to a value. Where a value type always has a value.
Nullable wraps a value type to allow you to have the option of being null. Using int? is just a compiler shortcut to declare a nullable type.
You can have a nullable int by using int? or Nullable<int>
both are exactly the same thing.
Value types like int
contain direct values rather than references like ReferenceType
. A value cannot be null but a reference can be null which means it is pointing to nothing. A value cannot have nothing in it. A value always contain some kind of value
Nullable or Nullable types are special value types which in addition to normal values of value types also support additional null value just like reference types
Objects are reference types and they can reference nothing or NULL, however int is a value type, which can only hold a value, and cannot reference anything.
Primitive int type cannot express null in its binary representation, but Nullable<int>
added an extra byte to express the null information of this value.
精彩评论