0

Let's say there are different Contracts C1, C2, C3,.... Cn.

Now I have a method which looks like below:

public List<Cn> M(string param1, string param2)
{
   switch(param2)
     case value1:
          var list1 = new List<C1>();
          list.Add(new C1());
          return list;
          break;
     case value2:
          var list2 = new List<C2>();
          list.Add(new C2());
          return list2;
          break;
     default:
          return null;
          break;
}

This method calls a DB method which fetches data based on the param2 and create list of specific objects and returns the same. Now for different values of param2 it will send list of different Type of objects. How to achieve this? In generic or some other approach, any help would be appreciated.

Update:

C1 and C2 may be different in structure.

Class C1
{
   int i;
   string j;
}
Class C2
{
   string i;
   string j;
}
Arijit Saha
  • 33
  • 1
  • 5

5 Answers5

0

You can try to change the returned list into list of object instead

public List<object> M(string param1, string param2){
    //code here
}
jmaghuyop
  • 115
  • 1
  • 9
0

What is common between your contracts? make it an interface and let all contract classes implement that interface.

Your method signature will look something like

public IEnuemerable<ICommonInterface> M(string param1 ,string param2)
{

}
Yogi
  • 9,174
  • 2
  • 46
  • 61
Jayee
  • 542
  • 5
  • 15
0

I would suggest you may make use of marker interface.

public interface IContract{}

public class C1: IContract{
  ...
}
public class C2: IContract{
  ...
}

public List<IContract> M(string param1, string param2){
 ...
}
shole
  • 4,046
  • 2
  • 29
  • 69
0

create the instances of the desired type, you need use system.activator.

here is a link to an answer to your question. Get a new object instance from a Type

Community
  • 1
  • 1
jeff
  • 3,269
  • 3
  • 28
  • 45
0

I think this helps you.

 public List<T> M<T>(string param1, string param2)
 {
    switch(param2)
      case value1:
      var list1 = new List<C1>();
      list.Add(new C1());
      return list;
      break;
 case value2:
      var list2 = new List<C2>();
      list.Add(new C2());
      return list2;
      break;
 default:
      return null; // Here you can not return null try to return something apart form null.
      break;
 }