-1

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

public int? GoalPR { get; set; } public int AnchorPR { get; set; } 
5
  • 2
    int? is a nullable int, which allows the value to be null. Commented Jul 3, 2013 at 20:24
  • The difference between int and int? is exactly the same as the difference between int and Nullable<int>. Commented Jul 3, 2013 at 20:26
  • @gunr2171 apologies. I tried searching for the answer. Commented Jul 3, 2013 at 20:28
  • not one person mentioned that int? is merely a short-hand for Nullable<int> o_O Commented Jul 3, 2013 at 20:30
  • @ByteBlast - uhm... yes one person did. Commented Jul 3, 2013 at 20:32

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, ok that makes a lot more sense. Thank you.
3

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

int? is just syntactic sugar for Nullable<int>

Comments

1

int? can be null.

int can't.

That's (pretty much) the only difference.

4 Comments

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 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.
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 for example.
@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.
1

int? is nullable, int is not..

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.