Better way to write common function with parameter is different class

In my project, I have some functions like that:

func 1 (with 2 class: class1 and classs1_1):

List<class1> GetData1(class1_1 cls)
{
    List<class1> list = new List<class1>();
    cls = new cls();
    //do something for cls, like cls.GetSpecialCase();

    //fill data from cls to list, as using foreach to fill data to list

    return list;
}

func 2 (with 2 class: class2 and classs2_2):

List<class2> GetData2(class2_2 cls)
{
    List<class2> list = new List<class2>();
    cls = new cls();
    //do something for cls, like cls.GetSpecialCase();

    //fill data from cls to list, as using foreach to fill data to list

    return list;
}

How could I write a function like that (because I don't want to use a lot of functions as above):

common func (with T is class1, object cls is class1_1):

List<T> GetData(object cls)
{
    List<T> list = new List<T>();
    //how to recognize which class of cls
    if(cls == class1_1)     class1_1 other_cls = cls as class1_1;
    if(cls == class2_2)     class2_2 other_cls = cls as class2_2;
    //do something for other_cls 

    //fill data from other_cls to list
    return list;
}

I just want to pass parameter as object, and in the common function, I want to know which class I'm passing to so that I can treat to right class, and call right function.

Anyone helps me to solve this problem.

Thank you very much.

Jon Skeet
people
quotationmark

It sounds like you need:

  • An interface or abstract base class with the GetSpecialCase method
  • A generic method (with type parameters for both input and output) of

    List<TResult> GetData<T, TResult>(T item) where T : ISpecialCase<TResult>
    {
        List<TResult> list = new List<TResult>();
        var other = item.GetSpecialCase();
        // Fill list via other
        return list;
    }
    

If you can't introduce an interface or base class, you could use dynamic typing, but I'd strongly recommend that you use polymorphism to express what the different classes have in common (GetSpecialCase here) if you possibly can.

people

See more on this question at Stackoverflow