-1

What is the difference between 'int' and 'int?'. For example:

public int? GoalPR { get; set; }
public int AnchorPR { get; set; }
JBelter
  • 415
  • 2
  • 5
  • 13

4 Answers4

3

The int? is a nullable type, so the type that can be also null.

The main reason of introduction of this kind of types for value types, is fluent support for DataBase systems, where value: can be, can be absent and can be null.

There are actually 3 states.

So your code that interacts with the data received and sent to DB smoothly handles that kind of situations having possibility for its own value types assume null value too.

Tigran
  • 61,654
  • 8
  • 86
  • 123
3

Take a look at the documentation for Nullable<T>.

int? is just syntactic sugar for Nullable<int>

Tim
  • 14,999
  • 1
  • 45
  • 68
1

int? can be null.

int can't.

That's (pretty much) the only difference.

It'sNotALie.
  • 22,289
  • 12
  • 68
  • 103
  • That's hardly the only difference - they are different sizes and reading/writing int values is atomic, while they aren't for nullable ints. – Lee Jul 03 '13 at 20:29
  • @Lee For your first one: we're not using pointers. Second one: Sure is, unless you're using the value again, which is what most people do. – It'sNotALie. Jul 03 '13 at 20:30
  • I don't see what pointers have to do with anything, and for the second point, reading/writing nullable ints is not atomic, so multiple threads updating an `int?` field could see torn reads and writes. See [this question](http://stackoverflow.com/questions/3047280/is-int-thread-safe) for example. – Lee Jul 03 '13 at 21:10
  • @lee Why else would you need the size? Also, I know. However, when you're using ints most changes are something like `x = someOperations + x` and so on. And if you aren't using Interlocked there then you have a problem. – It'sNotALie. Jul 03 '13 at 21:11
1

int? is nullable, int is not..

Mike Marks
  • 10,017
  • 17
  • 69
  • 128