Search code examples
c#listclassvariable-declaration

How should I declare a class type list?


I have this example method, I am actually implementing it in another solution.

I want to declare a List that is going to take a different type depending on the value of the switch(), what should SOMETHING take?

class ReportStrings
{
    string date;
    string name;
}

class ReportIntegers
{
    int number;
    int amount;
}

public void main()
{
    List<SOMETHING> LReport;

    string reportname; //let's think it has a value

    switch (reportname)
    {
        case "ReportOne": LReport = new List<ReportStrings>; break;

        case "ReportTwo": LReport = new List<ReportIntegers>; break;
    }

    Console.WriteLine(LReport.Count());    
}

Solution

  • Just use some kind of a base class and inherit from it. Then create a List of the Base class and add your items like this:

    class ReportBase { }
    class ReportStrings:ReportBase
    {
        string date;
        string name;
    }
    
    class ReportIntegers:ReportBase
    {
        int number;
        int amount;
    }
    
    public void main()
    {
        List<ReportBase> LReport;
    
        string reportname=null; //let's think it has a value
    
        LReport=GetList(reportname);
    
        Console.WriteLine(LReport.Count());    
    }
    private List<ReportBase> GetList(string reportname)
    {
       var LReport = new List<ReportBase>(); 
       switch (reportname)
        {
            case "ReportOne": 
    
              LReport.Add(new ReportStrings(){ /* ...add your values here... */};
              break;
            case "ReportTwo": 
              LReport.Add(new ReportIntegers(){ /*...add your values here... */}; 
              break;
        }
        return LReport;
    }