What is (<type>?)?
I was looking through some code the other day and I saw something like (int?) and I dont think Ive ever see that before. W开发者_如何学Gohat does it mean when you use a ? after a type?
It is short for Nullable<T>
.
Nullable types in C#
This is a generic struct that can wrap a value-type to add the value null
. To make the use of this type more convenient C# adds quite a bit of compiler-magic. Such as the short-name T?
, lifted operators,...
The following thread on SO is interesting too: ? (nullable) operator in C#
It's a variation/alternative of the Nullable<Type>
. Have seen it used a lot with DateTime to avoid the default DateTime value which gives an error in DB columns related to dates. Quite useful actually.
int? is syntactic sugar for Nullable<int>
.
That is the shorthand syntax for Nullable<T>
(or in your case Nullable<int>
).
This is used when you need value types to be null, such as int
, Boolean
and DateTime
.
it means Nullable, so our value-type variable can be null
the ? after the type implies that the type can have null
value besides its normal values.
I've seen the use mostly for database related types where you have Nullable
columns
As other people have said int?
is short for Nullable<int>
.
This article is a couple of years old now but it's a good explanation of nullable types
精彩评论