Search code examples
c#.netc#-4.0extension-methodsoverloading

How do I return string as well as IEnumerable<T> from same method in C#?


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?


Solution

  • 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;}    
    }