A curious C# syntax with a question mark

private enum E_Week
{
   Mon = 0,
   Tue,
   . . .
}

What does the following code mean?

E_Week? week= null;

Is it equal to the following code? What is the function of the '?' sign here?

E_Week week= null;

Solution 1:

Your code is using what's called a nullable type. An enum, much like an int or a DateTime, is what is known as a "value type", which is required to always have some value. Nullable types allow you to treat value types as if they do allow null values.

For example, this code is invalid and won't compile because enums cannot be null:

E_Week week = null;

But this code is valid:

E_Week? week = null;

And it's exactly the same as this:

Nullable<E_Week> week = null;

Solution 2:

E_Week? is equivalent to Nullable<E_Week>

See here for more information on Nullable types.

Solution 3:

The most significant difference is that the second statement doesn't work ;) The ? sign basically gives you the possibility of setting a value type (in this case enum) to null, which is normally not possible..