2

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?

Leroy Jenkins
  • 2,680
  • 6
  • 25
  • 33

7 Answers7

13

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#

Community
  • 1
  • 1
CodesInChaos
  • 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
6

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.

5

int? is syntactic sugar for Nullable<int>.

CheeZe5
  • 975
  • 1
  • 8
  • 24
4

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.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
alexn
  • 57,867
  • 14
  • 111
  • 145
3

it means Nullable, so our value-type variable can be null

Andrey
  • 5,906
  • 4
  • 24
  • 30
3

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

Maverik
  • 5,619
  • 35
  • 48
3

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

Fermin
  • 34,961
  • 21
  • 83
  • 129