What does one question mark following a variable declaration mean?

C#.Net

C# Problem Overview


Whilst playing around in an open source project, my attempt to ToString a DateTime object was thwarted by the compiler. When I jumped to the definition, I saw this:

public DateTime? timestamp;

Might someone please enlighten me on what this is called and why it might be useful?

C# Solutions


Solution 1 - C#

This is a nullable type. Nullable types allow value types (e.g. ints 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
}

Solution 2 - C#

? 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.

Solution 3 - C#

That is a shortcut for Nullable<DateTime>. Value types, like DateTime cannot be null; Nullable<> wraps the value type so that you have an object with a HasValue property and other convenient features.

Solution 4 - C#

it is nullable datetime

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionglennerooView Question on Stackoverflow
Solution 1 - C#CameronView Answer on Stackoverflow
Solution 2 - C#Wesley WiserView Answer on Stackoverflow
Solution 3 - C#JacobView Answer on Stackoverflow
Solution 4 - C#Ali TarhiniView Answer on Stackoverflow