What does the ? operator mean in C# after a type declaration?
Asked Answered
L

7

11

I have some C# code with the following array declaration. Note the single ? after Color.

private Color?[,] scratch;

In my investigating I have found that if you you have code such as:

int? a;

The variable a is not initialized. When and where would you use this?

Lumbricoid answered 27/5, 2013 at 13:5 Comment(4)
If you were doing some mathematic calculations based upon a users input, you would want to make sure that they have entered a number so that the equation doesn't use the default valueKettle
How did you add nullable tag beside you don't know what is ? mean?Tyrolienne
I'm always amazed to see, that when the question is simple, there are lots of duplicate answers.Ionic
possible duplicate of What does "DateTime?" mean in C#?Greenburg
C
21

? is just syntactic sugar, it means that the field is Nullable. It is actually short for Nullable<T>.

In C# and Visual Basic, you mark a value type as nullable by using the ? notation after the value type. For example, int? in C# or Integer? in Visual Basic declares an integer value type that can be assigned null.

You can't assign null to value types, int being a value type can't hold null value, int? on the other hand can store null value.

Same is the case with Color, since it is a structure (thus value type) and it can't hold null values, with Color?[,] you are making an array of nullable Color.

For your question:

The variable 'a' is not initialized. When and where would you use this?

By using ? with variable doesn't make it initialized with null or any other value, it is still has to be initialized.

int? a = null; 

int b = null;//error since b is not nullable
Cacao answered 27/5, 2013 at 13:6 Comment(3)
What about in a statement. client?.Close(); ?Cowan
If it’s merely syntactic sugar, how are ? and Nullable<T> interchangeable?Chrissie
@dakab, at compile time they change, for example, int? will become Nullable<int>Cacao
F
4

It means that the type defined is nullable. Check out this link for more info.

With nullables you can do:

int? i = null;

And of course do null checks:

if (i == null)
{
    // do stuff here ...
}
Fanaticize answered 27/5, 2013 at 13:6 Comment(0)
P
0

This means that the object can have a null-value in Addition to their normal range.

From MSDN:

Nullable types are instances of the Nullable struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, a Nullable, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value.
...

Example

class NullableExample
{
    static void Main()
    {
        int? num = null;

        // Is the HasValue property true? 
        if (num.HasValue)
        {
            System.Console.WriteLine("num = " + num.Value);
        }
        else
        {
            System.Console.WriteLine("num = Null");
        }

        // y is set to zero 
        int y = num.GetValueOrDefault();

        // num.Value throws an InvalidOperationException if num.HasValue is false 
        try
        {
            y = num.Value;
        }
        catch (System.InvalidOperationException e)
        {
            System.Console.WriteLine(e.Message);
        }
    }
}
Paramecium answered 27/5, 2013 at 13:7 Comment(0)
B
0

Color? refers to a Nullable Color and is equivalent to Nullable<Color>.

Color c = null;//ERROR Color is a struct, cannot be null!
Color? c = null;//OK

Nullable Types

Bibbs answered 27/5, 2013 at 13:7 Comment(0)
C
0

The syntax T? is shorthand for System.Nullable, where T is a value type. The two forms are interchangeable.

http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=vs.80).aspx

Christos answered 27/5, 2013 at 13:8 Comment(0)
M
0

Its a Nullable Structure

http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx

Also a duplicate https://stackoverflow.com/questions/5407552/what-does-question-mark-after-a-type-name-mean-in-c

Maris answered 27/5, 2013 at 13:8 Comment(1)
You cannot search questions with just '?'. That is why there is a duplicate.Lumbricoid
I
0

The ? operator signifies that the value type immediately preceding the operator may have the value null.

One way to think of it, and by no means a formal definition, is its an "exception" to how the value would "normally" be assigned a value.

A classic use case of the operator is in a simple controller in a web app. Suppose we have a typical DB that stores a list of movies. We can access the details of these movies by adding into the URL the following:

.../Movies/Details?MovieName=TopGun

, or,

.../Movies/Details?MovieName=DieHard

But what if we wanted to see the details of a movie where the value of MovieName is not defined? What will you show on your HTML page? Well, this controller will notify us of a bad request:

Check this out:

// GET: Movies/Details/5
public ActionResult Details(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Movie movie = db.Movies.Find(id);
    if (movie == null)
    {
        return HttpNotFound();
    }
    return View(movie);
}
Incarnation answered 29/4, 2021 at 20:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.