Why is it allowed to have 2 identical method signatures apart from an optional parameter?

168 views Asked by At
public static bool TryGetDbRow(DbConnection cnctn, string indexName = null)

public static bool TryGetDbRow(DbConnection cnctn)

The 1st one won't ever be called without string as last parameter. Why is it allowed to have 2 identical method signatures apart from an optional parameter?

1

There are 1 answers

2
Geoff Appleford On

This is explained by Eric Lippert on his blog at http://blogs.msdn.com/b/ericlippert/archive/2011/05/16/optional-argument-corner-cases-part-three.aspx

When you create a method with optional parameters the method signature includes all the parameters including any optional parameters.

So in your example, these method have different signatures - the first has 2 parameters and the second has only 1. When you only have the first method, and you call the method with 1 parameter, eg

TryGetDbRow("connection");

the compiler changes it to

TryGetDbRow("connection", null);

However when you add the second method with no optional parameters, the compiler finds a match for the method with a single parameter and doesn't insert the optional parameter so the second method is called.

Optional parameters are not really optional from the method definition point of view. The compiler just applies some "syntactic sugar" to the calling code and adds in all the default values for any missing optional parameters.