C# Ambiguous calls - Different return type
-
18-09-2019 - |
Question
I have 2 extension methods that convert a MongoDB document to an entity/object.
public static ProductTemplate Convert(this Document document)
{
return null;
}
public static Product Convert(this Document document)
{
return null;
}
This gives an expected ambiguous call error so I was wondering how I could fix this?
Friendly greetings,
Pickels
Solution
Functions can't be overloaded by return type. You will have to rename your functions to maybe:
ConvertToProductTemplate() and ConvertToProduct()
or turn them into one function which returns a common base class or interface. (But then the caller will have to do a cast when they get your result)
OTHER TIPS
You could make your Convert
method generic:
public static T ConvertTo<T>(this Document doc) where T : SomeBaseClassOrInterface
{
return null;
}
Then use it like so:
var document = new Document();
var temp = document.ConvertTo<ProductTemplate>(); // returns a ProductTemplate
var prod = document.ConvertTo<Product>(); // returns a Product
you could change the names:
public static ProductTemplate ConvertToProductTemplate(this Document document)
{
return null;
}
public static Product ConvertToProduct(this Document document)
{
return null;
}
I have a feeling that Product and ProductTemplate classes are related somehow (e.g. Product extends ProductTemplate). If I'm right, you can just return the base class (ProductTemplate in this case).
Tomas Lycken suggested to use generic method, which is in my opinion quite good idea, but if there's a common interface for Product and productTemplate, you can just return that interface as well instead of Product and ProductTemplate.
Example (by Tomas Lycken):
public static T ConvertTo<T>(this Document doc) where T : SomeBaseClassOrInterface
{
return null;
}
Example (by me):
public static SomeBaseClassOrInterface ConvertTo(this Document doc)
{
return null;
}
And if there's no common interface and you don't want to create a new one, please just change names :)