-5

I have one generic method which does some operations and want to return result as string or IEnumerable<T>

  public IEnumerable<T> MyResult(string input)
  {
      // do something return string based on some
      // case or return IEnumerable<T>
  }

How do I achieve this in one method, and how do I maintain return type?

halfer
  • 19,824
  • 17
  • 99
  • 186
Neo
  • 15,491
  • 59
  • 215
  • 405
  • 2
    As you probably have found, a method can have one return type. Add an out parameter or create a DTO containing the enumerable and string and return that. – CodeCaster Jul 10 '15 at 10:48
  • You'll have to add some context. You can't do what you're suggesting, but I can't see what what you're suggesting is particularly useful. What problem are you trying to solve? – Charles Mager Jul 10 '15 at 10:49

2 Answers2

3

First of all: A method can not have multiple return types.

Even though this is bad design you could (A) add an out parameter or (B) create a DTO containing the enumerable and string and return that.

(A):

public IEnumerable<T> MyResult(string input, out string output)
{
    // do something 
}

(B):

public MyDTO MyResult(string input)
{
    // do something 
}

and

public class MyDTO 
{
    public IEnumerable<T> resultAsEnumerable {get; set;}

    public string resultAsString {get; set;}    
}
ChrisM
  • 1,148
  • 8
  • 22
  • @cubrr A DTO is a **d**ata **t**ransfer **o**bject. [link]http://martinfowler.com/eaaCatalog/dataTransferObject.html – ChrisM Jul 10 '15 at 12:28
1

You could use object as return type of your function, then you can return either a string or an IEnumerable<T> depending on the input. Something like this:

public object MyResult<T>(string input)
{
    if (true)
        return "string";
    else
        return return new List<T>() { default(T) };
}
Raidri
  • 17,258
  • 9
  • 62
  • 65