In C#, what is the `?` in the type `DateTime?` [duplicate]

半腔热情 提交于 2019-12-05 08:02:19

The ? makes it a nullable type (it's shorthand for the Nullable<T> Structure and is applicable to all value types).

Nullable Types (C#)

Note:

The ?? you linked to is the null coalescing operator which is completely different.

The ? is not an operator in this case, it's part of the type. The syntax

DateTime?

is short for

Nullable<DateTime>

so it declares that LastLogon is a property that will return a Nullable<DateTime>. For details, see MSDN.

The ?? that you linked to is somewhat relevant here. That is the null-coalescing operator which has the following semantics. The expression

x ?? y

evaluates to y if x is null otherwise it evaluates to x. Here x can be a reference type or a nullable type.

shorthand for

Nullable<DateTime>

It's a shortcut for Nullable<DateTime>. Be aware that methods using these types can't be exposed to COM as they are use generics despite looking like they don't.

As others have mentioned this ? syntax makes the type nullable.

A couple of key things to keep in mind when working with nullable types (taken from the docs, but I thought it would be helpful to call them out here):

  • You commonly use the read-only properties Value and HasValue when working with nullable types.

e.g.

int? num = null;
if (num.HasValue == true)
{
    System.Console.WriteLine("num = " + num.Value);
}
  • You can use the null coalescing operator to assign a default value to a nullable type. This is very handy.

e.g.

int? x = null;
int y = x ?? -1;

As others have mentioned, ? is used for declaring a value type as nullable.

This is great in a couple of situations:

  • When pulling data from a database that has a null value stored in a nullable field (that maps to a .NET value type)
  • When you need to represent "not specified" or "not found".

For example, consider a class used to represent feedback from a customer who was asked a set of non-mandatory questions:

class CustomerFeedback
{
    string Name { get; set; }
    int? Age { get; set; }
    bool? DrinksRegularly { get; set; }
}

The use of nullable types for Age and DrinksRegularly can be used to indicate that the customer did not answer these questions.

In the example you cite I would take a null value for LastLogon to mean that the user has never logged on.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!