I just ran across some code while working with System.DirectoryServices.AccountManagement
public DateTime? LastLogon { get; }
What is the ? after the DateTime for.
I found a reference for the ?? Operator (C# Reference), but it's not the same thing. (280Z28: Here is the correct link for Using Nullable Types.)
The ?
makes it a nullable type (it's shorthand for the Nullable<T>
Structure and is applicable to all value types).
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
andHasValue
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.
来源:https://stackoverflow.com/questions/2072482/in-c-what-is-the-in-the-type-datetime