I normally declare an optional parameter (default value) in the Constructor's parameters like this:
public class XV
{
public XV(int startPosition = 1) // Constructor
{
this.StartPosition = startPosition;
}
public int StartPosition { get; set; } // Property
}
But then I found myself looking at old code where I've written like this:
public class XV
{
public XV( ... ) { ... } // Constructor
public XV(int startPosition) // Constructor
{
this.StartPosition = startPosition;
}
public int StartPosition { get; set; } = 1; // Property
}
What is the use of adding = 1
to the Property compared to creating an optional value in the Constructor?
Is it just to support default values for Properties not present in the Constructor?
But if so, why not add them to the Constructor in that case?
With a optional argument (1st case), you can call the function without giving a value.
new XV();
would be a valid call to a function with a optional parameter. Even if you did not define a parameterless constructor. The constructor signature would match calls ()
and (int)
. Indeed, having the ability to match more calls with one signature is a big use case for Optional Arguments.
Note that optional parameters were not around all the time. They were only added back in C# 4.0. So old code might not use it, because it simply was not a thing back then. However for constructors, constructor chaining was often used to define de-facto default values.
In the 2nd case, only (int)
calls would be valid. If you wanted to use the default value, you would have to retrieve it first. So it is hardly what I would call a "default value". "Reliable initialization" would be a better term. It is indeed useless and might be cut entirely by the compiler and JIT.
If you wanted a parameterless constructor, you would have to explicitly code one (classes start with a implicit parameterless one, but any explicit constructor disables that).