-1

I want to send different kinkds of lists by reference and receive as a gereral on the tools function. After that, do a downcasting and recuperate the original type. But it is not woking. Someone have the solution to make this work?

  public Class A{
    ...
    List<A> A_List= readAList();
    saveToExcelTables(A_List,"A")
    ...
    }

    public Class B{
    ...
    List<B> B_List= readBList();
    saveToExcelTables(B_List,"B")
    ...
    }

    public Class Tools{

       public static void saveTableToExcel(List<T> obj,string typeTyoe){

          if(tableType == "A")
            {
                List<A> A_List= (A) obj;
            }
          if(tableType == "B")
            {
                List<B> B_List= (B) obj;
            }
    }
  • Possible duplicate of [explicitly cast generic type parameters to any interface](https://stackoverflow.com/questions/6407039/explicitly-cast-generic-type-parameters-to-any-interface) – Owen Pauling Dec 21 '18 at 11:16
  • 3
    Why is this tagged with Java? – Kjartan Dec 21 '18 at 11:19
  • 2
    Seems like a mis-use of generics. In fact generics apply to *any* type, not just `A` or `B`. So what would you do when someone decides to call your method with `List` for example? Or even an anonymous type? There´s nothing in `SafeTableTopExcel` you could do in this case. So don´t **pretentd** you could pass any type when you´re actually deeling only a few. Having said this you should write different method for different types or relying on a common interface all your types implement. – MakePeaceGreatAgain Dec 21 '18 at 11:21
  • What do you want to do with those lists? – MakePeaceGreatAgain Dec 21 '18 at 11:25
  • In my case I will have just 5 types that I will have to pass to this function, but I want that this method receives these Lists and identify not mattering from where (class A, class B, class C ...) it comes from. Afther that I have a code that already works that takes this list and save in an Excel Table – Matheus Sasso Dec 21 '18 at 11:53
  • But when those types don´t have anything in common there´s nothing a **generic** method can do, as there literally is nothing **generic** about those types. – MakePeaceGreatAgain Dec 21 '18 at 11:57
  • But they are all subclasses of the class OBJECT, that is why I want to use this in my favour – Matheus Sasso Dec 21 '18 at 12:12
  • If you want to work with `System.Object` why not work with it explicitly, why the need for the generic approach? `public static void saveTableToExcel(List obj,string typeTyoe) { }` – ckerth Dec 21 '18 at 13:40

1 Answers1

0

You can do it with the AS operator:

C# reference AS operator

public class Tools
{

    public static void saveToExcelTables<T>(List<T> obj, string tableType)
    {

        if (tableType == "A")
        {
            List<A> A_List = obj as List<A>;
        }
        if (tableType == "B")
        {
            List<B> B_List = obj as List<B>;
        }
    }
}