-1
var newListObject =  new List<object>();
    
if(a) 
{
    newListObject = new List<AnnualObject>();
} 
else 
{
    newListObject = new List<MonthlyObject>();
}
Jonesopolis
  • 24,241
  • 10
  • 66
  • 110
  • If there's no overlap in the properties of your classes, does your implementation make sense? Whatever happens next would need to assume that the two classes have some overlap in their implementation, and if that's the case then you should extract and interface and use that as the type of newListObject and instantiate it in the if. – Shafiq Jetha Jan 14 '21 at 02:46
  • Re the linked question: note that all objects in C# are derived from `object`, so `object` is the base class for `AnnualObject` and for `MonthlyObject`. – DiplomacyNotWar Jan 14 '21 at 02:48
  • Hmmm.... I read the question very differently after it was edited... but @John is likely right that duplicate is actually the answer compared to approach I posted as an answer. – Alexei Levenkov Jan 14 '21 at 02:50
  • 1
    The only other thing that occurs to me is that, assuming `AnnualObject` and `MonthlyObject` only differ by the time period they represent, perhaps you could make the time period a property of a common object, rather than defining the object itself by its period. – DiplomacyNotWar Jan 14 '21 at 02:52

1 Answers1

2

Yes, it is very easy to do so - you need to forego compile-time type safety so by either switching to dynamic or non generic IEnumerable/IList for your variable type.

dynamic newListObject = new List<object>();

if (a)
{
    newListObject = new List<AnnualObject>();
}
else
{
    newListObject = new List<MonthlyObject>();
}

newListObject.Add(a ? new AnnualObject() : new MonthlyObject());
Console.WriteLine(newListObject[0]);

Note that generally it is not a solution for code that anyone else could look at or modify. If you need to skip type safety using language that directly allows you to do that (like JavaScript) could be better.

For C# one would likely use list of items of base class or separate lists but preserve compile-time type safety.

Alexei Levenkov
  • 96,782
  • 12
  • 124
  • 169
  • 1
    @John depending what one wants - `dynamic` let one write code as if it has types `newListObject[0].Month` directly (at cost of fancy reflection at run-time) vs. explicit casting in the code... But really no one cares what the author of the code writes purely for they own consumption as long as they don't ask others to look at the code (i.e. by posting on SO :) ) – Alexei Levenkov Jan 14 '21 at 03:01
  • That's a good point. :) I hadn't considered actually accessing the items themselves. – DiplomacyNotWar Jan 14 '21 at 03:02