1

Possible Duplicate:
C# using the question mark after a type, for example: int? myVariable; what is this used for?

I saw the ? operator used in many places and tried to Google and StackOverflow it but both search engine exclude it from the query and does not return any good answers.

What is the meaning of this operator? I usually see it after the type declaration like:

int? x;
DateTime? t;

What is the difference between the two following declaration of an int for example:

int? x;
// AND
int x;
Community
  • 1
  • 1
Moslem Ben Dhaou
  • 6,897
  • 8
  • 62
  • 93

7 Answers7

2

This operator is not an operator, but merely the syntactic sugar for a Nullable type:

int? x;

is the same as

Nullable<int> x;
Spontifixus
  • 6,570
  • 9
  • 45
  • 63
2

You can read this : Nullable type -- Why we need Nullable types in programming language ?

int? x;//this defines nullable int x
x=null; //this is possible
// AND
int x; // this defines int variable
x=null;//this is not possible
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
1

It is not operator, but int? is shortcut for the Nullable<int>. Nullable<> is container that allows to set some value-type variable null value as well.

nothrow
  • 15,882
  • 9
  • 57
  • 104
1

It called nullable types.

Nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying value type, plus an additional null value.

int? x;

is equivalent to

Nullable<int> x;
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
1

? operator indicates the type is nullable. For example;

int? x = null; //works properly since x is nullable

and

int x = null; //NOT possible since x is NOT nullable

Note that the way you access the value of the variable changes;

int? x = null; 
int y = 0;
if (x.HasValue)
{
    y = x.Value; // OK
}

And

y = x; //not possible since there is no direct conversion between types.
daryal
  • 14,643
  • 4
  • 38
  • 54
0

Diffrence b/w int? and int is int? can store null but int can't.

int? is called nullable operators and its used basically when working with database entities.

more info -http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=vs.80).aspx

hope this helps !!

Rahul20
  • 26
  • 3
0

That operator makes all objects that is non nullable to nullable. So it means if you will declare a variable int? x, it could be assigned like this: int? x = null. If without the ? sign, you cannot assign it with a null value.

nsutgio
  • 240
  • 2
  • 6
  • 15