Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

like image 848
Khalil Khalaf Avatar asked Jul 20 '16 18:07

Khalil Khalaf


People also ask

Can null be assigned to a variable of type double?

It is imperative to note that null can only be assigned to reference types. We cannot assign null to primitive variables e.g int, double, float, or boolean. If we try to do so, then the compiler will complain.

Can't have a value of null because of its type but the implicit default value is null?

The reason this happens is because with null safety enabled, your non-nullable parameter factor or key cannot be null . In the function and the constructor, these values might be null when the function is called without the named parameter: calculate() or Foo() .

Which kind of parameters Cannot have a default value?

An IN OUT parameter cannot have a default value. An IN OUT actual parameter or argument must be a variable.

What is the default value of nullable type in C#?

The default value of a nullable value type represents null , that is, it's an instance whose Nullable<T>. HasValue property returns false .


1 Answers

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)
{
   // ..
}
like image 157
David L Avatar answered Sep 19 '22 11:09

David L