I was looking through some code the other day and I saw something like (int?) and I dont think Ive ever see that before. What does it mean when you use a ? after a type?
7 Answers
It is short for Nullable<T>.
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#
- 1
- 1
- 106,488
- 23
- 218
- 262
-
And the parenthesis is for casting, but you probably knew that. – Svish Mar 09 '11 at 13:12
-
I thought the OP used the parentheses as a kind of quotation-marks. But casting makes sense too. To decide that we'd need more context. – CodesInChaos Mar 09 '11 at 13:14
-
I understand casting, thats not a problem (obviously you didnt know I knew that) so I apologize if I was a bit vague. My main concern was in fact the Nullable portion. The "syntactic sugar" is so difficult to google. Thanks again. – Leroy Jenkins Mar 09 '11 at 13:38
-
I agree. Not being able to search for them makes even otherwise trivial problems annoying. – CodesInChaos Mar 09 '11 at 13:58
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.
- 116
- 5
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.
- 171,043
- 40
- 335
- 443
- 57,867
- 14
- 111
- 145
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
- 5,619
- 35
- 48