Question

I had a class with the following methods in c#:

public MyRetType MyMethod(String p1 = null)
 {
    MyMethod(<default values>);
 } 
public MyRetType MyMethod(String p1, String p2, MyClass1 p3, String p4 = null, MyClass2 p5 = null)
 {
    ...
 } 

I have had to add a new optional parameter. To keep backwards compatibility, I have added a couple of methods with one more parameter each, and I have rewritten the previous methods to call the new ones:

 public MyRetType MyMethod(String p1 = null, IEnumerable<int> pnew = null)
 {
    MyMethod(<default values>);
 } 
 public MyRetType MyMethod(String p1) 
 {
     return MyMethod(p1, null); 
 }

 public MyRetType Launch(String p1, String p2, MyClass1 p3, IEnumerable<int> pnew , String p4 = null, MyClass2 p5 = null)
 {
    ...
 } 
 public MyRetType MyMethod(String p1, String p2, MyClass1 p3, String p4= null, MyClass2 p5 = null)
 {
     return MyMethod(p1, p2, p3, null, p4, p5);
 }

This seems to work in c#, although I am aware that calling MyMethod with just a null would be ambiguos (it could be any of the two first methods in the last listing).

However, when trying to call MyMethod from Visual Basic, it isn't listed in intellisense. If I write it manually, I got an error: "Ambiguous call".

Why does this happen?

Was it helpful?

Solution

You need to ditch the optionals and stick to the overloads - optionals are a bit meaning less if you've already got overloads that don't have the parameter that is optional:

public MyRetType MyMethod() 
{
    return MyMethod(null,null);
}

public MyRetType MyMethod(String p1) 
{
    return MyMethod(p1,null);
}

public MyRetType MyMethod(String p1, IEnumerable<int>)
{
    MyMethod(<default values>);
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top