20

Possible Duplicate:
C# newbie: what’s the difference between “bool” and “bool?” ?

Hi, While reading the code of the NUnit project's assert class, I came across this particular construct -

public static void AreEqual(double expected, double? actual, double delta)
{
     AssertDoublesAreEqual(expected, (double)actual, delta ,null, null);
}

In this function the second input parameter is entered as double?. The interesting thing is that this code compiles without issue in VS2010 (C# 4.0). Anyone know why this is NOT throwing an error ? Why is double? considered a valid keyword and is there any special significance to the ?.

Community
  • 1
  • 1
Nikhil
  • 3,590
  • 2
  • 22
  • 31
  • 1
    See [C# newbie: what's the difference between "bool" and "bool?" ?](http://stackoverflow.com/questions/1181491/c-newbie-whats-the-difference-between-bool-and-bool) – Matthew Flaschen Jun 07 '10 at 10:04
  • 5
    Stop downvoting the guy, it's a valid question and it's hard for someone who doesn't know the nullable operator to find the answer. Just close the question as exact duplicate. – Diadistis Jun 07 '10 at 10:07
  • 2
    What's up with those downvotes? The question mark suffix isn't very search engine friendly. – cfern Jun 07 '10 at 10:07

4 Answers4

25

double? is just shorthand for Nullable<double>; basically, a double that can be null. But the code is not very safe. If actual is null, (double)actual will throw an exception.

Gorpik
  • 10,940
  • 4
  • 36
  • 56
7

It's a nullable type. So it's a double that can also be null.

See here for more info.

Hans Olsson
  • 54,199
  • 15
  • 94
  • 116
3

I believe this means that the parameter could also be called null.

Sir Graystar
  • 703
  • 1
  • 7
  • 17
3

The syntax T? is shorthand for System.Nullable. Following line of code declares nullable type.

double? actual =null;

You can not assign null values to .NET value types (structs) including c# primitive types like int and double so in .NET 2.0 there is concept of nullable type is added to assign null value.

for example :

int? num = null;
        if (num.HasValue == true)
        {
            System.Console.WriteLine("num = " + num.Value);
        }
        else
        {
            System.Console.WriteLine("num = Null");
        }
Richard
  • 106,783
  • 21
  • 203
  • 265
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263