Khalil Khalaf
Khalil Khalaf

Reputation: 9407

Why a value of type null cannot be used as a default parameter with type double?

Quick Question:

MSDN - Named and Optional Arguments (C# Programming Guide) states clearly that

"Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates."

So instead of this:

class MyClass
{

//..

public MyClass() { // Empty Constructor's Task }
public MyClass(SomeType Param1) { // 2nd Constructor's Task }
public MyClass(SomeType Param1, SomeType Param2) { // 3rd Constructor's Task }
}

I should be able to do this:

class MyClass
    {
        //..

        public MyClass(SomeType Param1 = null, SomeType Param2 = null)
        {
            if (Param1)
            {
                if (Param2)
                {
                    // 3rd constructor's Task
                }
                else
                {
                    // 2nd constructor's Task
                }
            }
            else
            {
                if (!Param2)
                {
                    // Empty constructor's Task
                }
            }

        }
    }

Then why this is not working:

public MyClass(double _x = null, double _y = null, double _z = null, Color _color = null)
{
   // ..
}

Telling me:

A value of type "null" cannot be used as a default parameter because there are no standard conversions to type 'double'

Upvotes: 13

Views: 12181

Answers (2)

Casval Zem Daikun
Casval Zem Daikun

Reputation: 126

As David explained in his answer, Double is not a nullable type. In order to assign it a null value, you'll have to convert Double to System.Nullable<double> or double?

The full answer will look something like:

public void MyMethod(double? param = null) { }

The obvious problem here is that instead of just passing it a double value, you'll instead have to pass it a double? value instead.

I'm not sure of the exact scope of this functionality but you can always refer to defaults instead. For instance:

public void MyMethod(double param = double.MinValue) 
{ 
    if (param == double.MinValue) 
        return; 
}

Or something like that.

Upvotes: 3

David L
David L

Reputation: 33815

double is a value type. You'd need to wrap it in Nullable<T> or ? for shorthand, to indicate that it is nullable.

public MyClass(double? _x = null, double? _y = null, double? _z = null, Color _color = null)
{
   // ..
}

Upvotes: 21

Related Questions