Typically the main use of the question mark is for the conditional, x ? "yes" : "no"
.
But I have seen another use for it but can't find an explanation of this use of the ?
operator, for example.
public int? myProperty
{
get;
set;
}
Typically the main use of the question mark is for the conditional, x ? "yes" : "no"
.
But I have seen another use for it but can't find an explanation of this use of the ?
operator, for example.
public int? myProperty
{
get;
set;
}
int?
it's shorthand forNullable<int>
, the two forms are interchangeable.Nullable<T>
is an operator that you can use with a value typeT
to make it acceptnull
.In case you don't know it: value types are types that accepts values as
int
,bool
,char
etc...They can't accept references to values: they would generate a compile-time error if you assign them a
null
, as opposed to reference types, which can obviously accept it.Why would you need that? Because sometimes your value type variables could receive null references returned by something that didn't work very well, like a missing or undefined variable returned from a database.
I suggest you to read the Microsoft Documentation because it covers the subject quite well.
To add on to the answers above, here is a code sample
This would give a compilation error:
Notice that there is no compilation error for NullableTest. (note the ? in the declaration of t2)
practical usage:
It is a shorthand for
Nullable<int>
.Nullable<T>
is used with value types that cannot be null.it declares that the type is nullable.