6

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?

3
  • 7
    I'd say go with the second one since the first one won't compile.
    – neeKo
    Commented Feb 14, 2014 at 14:43
  • have you tried implementing your first approach? Commented Feb 14, 2014 at 14:44
  • have you looked into generic methods yet? Without any further context than what you've given, they might be relevant to your situation... edit: and looking down, it looks like the suggestion is redundant given the accepted answer. My bad! Commented Nov 27, 2021 at 18:10

6 Answers 6

13

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.

2
  • 1
    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???
    – george b
    Commented Feb 14, 2014 at 14:55
  • 1
    Benefits over what? Generics? Your first method is impossible, so unless you want to use generics you need to use the second method.
    – D Stanley
    Commented Feb 14, 2014 at 14:57
7

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;
2

📘 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");
1

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); 
} 
0

You can make that method generic, it's the only way to do it:

public T Get<T>(string name)
{
    ...
}
1
  • 2
    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.
    – neeKo
    Commented Feb 14, 2014 at 14:51
0

You could use the following approach

public T GetT<T>(string name)
{
    // Code goes here
    return T;
}

So when you pass a double you will get a double. When you pass an int, you will get an int and so on. The above approach uses generics to deal with your problem. For documentation about generics, please look here http://msdn.microsoft.com/en-us/library/ms379564%28v=vs.80%29.aspx

2
  • 1
    This is a duplicate of an existing answer.
    – Servy
    Commented Feb 14, 2014 at 14:49
  • 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.
    – Christos
    Commented Feb 14, 2014 at 14:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.