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

21,255

Solution 1

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.

Solution 2

You can use Tuples (I don't like the ItemX thing but still an option). Say you need a method to return a person object, a string and a number. You can then simply code the following:

public static Tuple<Person, string, int> GetMyData()
{
    var person = GetPerson();
    var text = "Hello";
    var number = 2016;

    var result = Tuple.Create(person, text, number);
    return result;
}

Call the method and access the returned data as follows:

var data = GetMyData();
data.Item1; // person
data.Item2; // text
data.Item3; // number

In your situation, I would use a parameter to indicate which type to search.

public Tuple<int, double, string> Search(searchPattern)
{
    if (serachPattern == "double")
    {
        double myDouble = SearchDouble();
        return Tuple.Create(0, myDouble, null);
    }

    // Handle other patterns here
}

Usage:

var myDouble = Search("double").Item2;
var myString = Search("string").Item3;
var myInt = Search("int").Item1;

Solution 3

📘 Return different data value with type dynamic;


Build the Method;

    internal static dynamic Get(System.String name){
      dynamic Result = null;
      //... if(name)... switch(name)...
      Result = 0;
      Result = false;
      Result = "use code logics to apply the required Result 'type'";
      Result = new System.Windows.Controls.Button();
      //...
      return Result;
    }

Method Usage;

    System.String vartest1 = Get("make the method return String");
    System.Int32 vartest2 = Get("make the method return Int32");
    System.Boolean vartest3 = Get("make the method return Boolean");

Solution 4

To return multiple data types to a C# method you could also try a way in which you compound the method return types into a method and retrieve them individually.
Observe

   public ( int, double, string) Get(string name) {
             //...
             return (intValue, doubleValue, stringValue);
     } 
     // Once returned to the main method the code is disassembled into smaller code //variables
 public static void Main(string args[])  { 

          (int Ivals, double Dvals, string Svals) = Get(name);
          Console.WriteLine(Ivals);
          Console.WriteLine(Dvals);
          Console.WriteLine(Svals); 
} 
Share:
21,255
george b
Author by

george b

Updated on July 05, 2022

Comments

  • george b
    george b almost 2 years

    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?

  • Servy
    Servy about 10 years
    This is a duplicate of an existing answer.
  • neeKo
    neeKo about 10 years
    It's not the only way, the example in the question (one that compiles) is valid and also better since it can limit the number of return types. By the way, the question was which was the safest way, and since yours would throw runtime exception (or default values, which could be worse) for unsupported types, it definitely isn't the safest way of doing it.
  • Christos
    Christos about 10 years
    I had started to answer the question and simultaneously, I was testing it. When I submitted it, I saw the other answers. If that's a problem, I can delete it.
  • george b
    george b about 10 years
    Considering my users will be consuming this code from a DLL, what are the benefits over the second approach I proposed??? I mean in terms of the consumer, will they need to type less???, will they get a better performance???
  • D Stanley
    D Stanley about 10 years
    Benefits over what? Generics? Your first method is impossible, so unless you want to use generics you need to use the second method.