Reputation: 82241
I have two methods as shown below. One with no parameters and one with only optional parameters.
void GetNext(){
//implimentation
}
void GetNext(int currentindex = 0){
//implimentation
}
Now which method will be invoked when a call is given to GetNext with no argument
GetNext();
and why?
FYI : This has been asked in one of the interview.
Upvotes: 1
Views: 93
Reputation: 7352
Without parameter method GetNext()
will be called
void GetNext(){
//implimentation
}
because the preference is to call the without parameter method rather than the optional parameter overloaded method
The Overload Resolution
A method, indexer, or constructor is a candidate for execution if each of its parameters either is optional or corresponds, by name or by position, to a single argument in the calling statement, and that argument can be converted to the type of the parameter.
If more than one candidate is found, overload resolution rules for preferred conversions are applied to the arguments that are explicitly specified. Omitted arguments for optional parameters are ignored.
If two candidates are judged to be equally good, preference goes to a candidate that does not have optional parameters for which arguments were omitted in the call. This is a consequence of a general preference in overload resolution for candidates that have fewer parameters.
Upvotes: 0
Reputation: 24916
Method without optional parameter (GetNext()
) is called. Answer why can be found in MSDN:
If two candidates are judged to be equally good, preference goes to a candidate that does not have optional parameters for which arguments were omitted in the call. This is a consequence of a general preference in overload resolution for candidates that have fewer parameters.
Upvotes: 2
Reputation: 1193
void GetNext() will be called, in this case the method with the optional parameter is hidden. But if you call GetNext(1), GetNext(int currentindex = 0) will be called.
Upvotes: 0