Why can't a null value be used as a default parameter with a double type?

Quick question:

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

"Additional arguments let you skip arguments for some parameters. Both methods can be used with methods, indexers, constructors , and delegates."

So instead:

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

I could do this:

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

Then why does this not work:

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

Tell me:

A value of type "null" cannot be used as a default parameter, since there are no standard conversions for input "double"

+7
c # optional-parameters
source share
2 answers

double is the type of value . Will you need to wrap it in Nullable<T> or ? for shorthand, to indicate that it is NULL.

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

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

The full answer would look something like this:

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

The obvious problem here is that instead of just passing the double value, you should pass that double? value instead double? .

I'm not sure about the exact scope of this function, but you can always refer to the default values. For example:

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

Or something like that.

+2
source share

All Articles