george b george b - 3 months ago 15
C# Question

How to return multiple data types from a C# method?

I have a method that needs to return different data types based on a search. I'm considering two approaches, since I'm new to C# I don't know which is best, so please help me make my mind.

the first approach is to overload the method like this:

public int Get(string name){
//...
return intValue;
}

public double Get(string name){
//...
return doubleValue;
}

public string Get(string name){
//...
return stringValue;
}


the second approach is to have different methods for each data type like this:

public int GetInt(string name){
//...
return intValue;
}

public double GetDouble(string name){
//...
return doubleValue;
}

public string GetString(string name){
//...
return stringValue;
}


which one is the safest for C# considering this code will be published from a DLL?

Answer

The first method is not even possible. You can't overload methods by only changing their return type.

Depending on what the code does you could make it generic:

public T Get<T>(string name){
   //...
   return somegenericvalue;
}

But I suspect you'd be using reflection anyways to decide what to do, so the advantage of generics would be negated. Plus you can't limit it to just the types you mentioned (string, int, double)

The main benefit of having different methods by type is strong typing. For consumers, the list of supported types is limited, so they don't have to worry about whether the Get method supports a particular type. For the writer, you can write code for that specific type. so you don't need reflection, type checking, casting, parsing, etc. to be generic - you can write the code for just that type.

It may feel like redundant code, but you can still refactor to put common pieces into internal "helper" methods.

FYI the Framework does this in some places, so it's not unheard of:

On the flip side, there are extension methods that choose to use generic methods:

But those are typically just pass_through methods, they don;t do any conversion that would require code for specific types.