Question

I'm sure this is an easy question for experienced programmers, but I've never had to do this before - Suppose I have a custom object looking as follows:

public class MyClass
{       
    public Dictionary<string,string> ToDictString()
    {
        Dictionary<string,string>  retval = new Dictionary<string,string>;
        // Whatever code
        return retval;
    }

    public Dictionary<string,int> ToDictInt()
    {
        Dictionary<string,int>  retval = new Dictionary<string,int>;
        // Whatever code
        return retval;
    }

}

So, in my code, I can write something as follows:

MyClass FakeClass = new MyClass();
Dictionary<string,int> MyDict1 = FakeClass.ToDictInt();
Dictionary<string,string> MyDict2 = FakeClass.ToDictString();

And that works fine, but what I would like to be able to do is have a single method in MyClass called, say ToDict() that could return either type of dictionary depending on the return type expected

So, for example, I would have:

MyClass FakeClass = new MyClass();

// This would be the same as calling ToDictInt due to the return type:
Dictionary<string,int> MyDict1 = FakeClass.ToDict();

// This would be the same as calling ToDictString due to the return type:
Dictionary<string,string> MyDict2 = FakeClass.ToDict();    

So, one method name, but it knows what to return based upon the variable that is to be returned... How would I write the method in my class to do I do that?

Thank you so much!!

Was it helpful?

Solution

This is not possible. The overload resolution algorithm does not take the context of the method invocation expression into consideration, and so it would result in an ambiguity error in the example that you've mentioned.

You'll need to have two different method names (or a difference in the parameter list) for the methods to have a different return type.

OTHER TIPS

You can use generics to achieve something close to what you want

public Dictionary<string,T> ToDict<T>()
{
    Dictionary<string,T>  retval = new Dictionary<string,T>();
    // Whatever code
    return retval;
}

You would need to specify the type parameter when using it

var result = myClass.ToDict<int>();

This moves the return type qualifier from the method name to a type parameter, and is the closest you can get due to the issues mentioned by @Servy.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top