What does one question mark following a variable declaration mean?
This is a nullable type. Nullable types allow value types (e.g. int
s and structures like DateTime) to contain null.
The ?
is syntactic sugar for Nullable<DateTime>
since it's used so often.
To call ToString()
:
if (timstamp.HasValue) { // i.e. is not null
return timestamp.Value.ToString();
}
else {
return "<unknown>"; // Or do whatever else that makes sense in your context
}
?
makes a value type (int
, bool
, DateTime
, or any other struct
or enum
) nullable via the System.Nullable<T>
type. DateTime?
means that the variable is a System.Nullable<DateTime>
. You can assign a DateTime
or the value null
to that variable. To check if the variable has a value, use the HasValue
property and to get the actual value, use the Value
property.