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'
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.
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() .
An IN OUT parameter cannot have a default value. An IN OUT actual parameter or argument must be a variable.
The default value of a nullable value type represents null , that is, it's an instance whose Nullable<T>. HasValue property returns false .
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)
{
// ..
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With