Reputation: 2604
Here is an example of code:
public List(int capacity = defaultCapacity) {
items = new T[capacity];
}
In C# 5 Language Specification Section 1.6.7
is written:
Instance constructors can be overloaded. For example, the List class declares two instance constructors, one with no parameters and one that takes an int parameter.
But compiled IL
for this code doesn't contain 2 constructors. It contains only this declaration:
.method public hidebysig specialname rtspecialname
instance void .ctor([opt] int32 capacity) cil managed
It means that optional parameter is CLR
level and is defined by [opt]
.
After CLR
there is no runtime that can represent this object with 2 overloaded constructors.
For Example if I am creating 2 separate constructors without optional parameter compiled IL
will contain 2 .ctor
-s.
I want to clarify, if language specification is saying that class declares two instance constructors
doesn't it mean that compiled IL
will contain 2 ctor
-s too.
Upvotes: 2
Views: 1143
Reputation: 125620
Optional parameters, no matter if used on methods or constructors, do not introduce additional overloads. Instead, optional parameters are marked with [opt], and whenever you call it without that parameter value specified that optional value will be included in your compiled code.
Because of that when you change default value of optional parameters you need to recompile all the usages, to get that new value injected into all the calls. If you don't do that old value will be used.
Update
Quote from the spec is confusing. If it talks about List<T>
defined in 1.6.7 with just one constructor, with optional parameter, than it's wrong.
Upvotes: 6