Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does one question mark following a variable declaration mean? [duplicate]

Tags:

c#

.net

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?

like image 933
glenneroo Avatar asked Nov 23 '10 23:11

glenneroo


People also ask

What does a question mark after a variable mean?

The question mark after the variable is called Optional chaining (?.) in JavaScript. The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null.

What does a question mark after a variable mean in C#?

With C# 8, the placing of a question mark character on ANY type will now be treated as an indicator of weather a variable may or may not be null, not in terms of preventing compilation outright, but in terms of how the compiler responds and warns about it.

What does the question mark mean in TypeScript?

The question mark ? in typescript is used in two ways: To mention that a particular variable is optional. To pre-check if a member variable is present for an object.

What is the purpose of the question mark in C#?

It's the null conditional operator. It basically means: "Evaluate the first operand; if that's null, stop, with a result of null.


3 Answers

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 } 
like image 50
Cameron Avatar answered Sep 17 '22 19:09

Cameron


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

like image 30
Wesley Wiser Avatar answered Sep 19 '22 19:09

Wesley Wiser


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.

like image 25
Jacob Avatar answered Sep 20 '22 19:09

Jacob