In C #, what is `?` In type `DateTime?`

I just came across some code while working with System.DirectoryServices.AccountManagement

public DateTime? LastLogon { get; } 

What? after datetime for.

I found a link for ?? Operator (link to C #) , but this is not the same. (280Z28: Here is the correct link for Using Null Types .)

+6
c # nullable
source share
6 answers

? makes it a type with a null value (it shortens the Nullable<T> structure and applies to all value types).

Nullable Types (C #)

Note:

Related to ?? is a zero coalescence operator that is completely different.

+27
source share

? is not an operator in this case, it is part of a type. Syntax

 DateTime? 

not suitable for

 Nullable<DateTime> 

therefore, it declares that LastLogon is a property that will return a Nullable<DateTime> . See MSDN for more details.

?? that you are related is somewhat appropriate here. This is a null-coalescing operator that has the following semantics. Expression

 x ?? y 

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

+4
source share

abbreviation

 Nullable<DateTime> 
0
source share

This is a shortcut for Nullable<DateTime> . Keep in mind that methods using these types cannot be affected by COM, because they use generics, even though they look like they aren't.

0
source share

What did the others say? the syntax makes the type null.

A few key things to keep in mind when working with NULL types (taken from documents , but I thought it would be useful to call them here):

  • You typically use the read-only properties of Value and HasValue when working with types with a null value.

eg.

 int? num = null; if (num.HasValue == true) { System.Console.WriteLine("num = " + num.Value); } 
  • You can use the zero coalescence operator to assign a default value to a type with a zero value. It is very comfortable.

eg.

 int? x = null; int y = x ?? -1; 
0
source share

As others have noted ? used for declaring a value type as nullable .

This is great in two situations:

  • When retrieving data from a database with a null value stored in a field with a null value (which matches the type of the .NET value)
  • When you need to represent "not specified" or "not found."

For example, consider a class used to represent feedback from a client who was asked a series of optional questions:

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

The use of DrinksRegularly types for Age and DrinksRegularly can be used to indicate that the client has not answered these questions.

In the example you are quoting, I would take the null value for LastLogon to mean that the user has never logged in.

0
source share

All Articles