A discussion came up recently at work where we were trying to discern which of the following would be better.
We have a base type for our domain, with many classes inheriting from it:
public abstract class DomainBase
{
public int BaseId { get; set; }
}
In another spot in code, we have a method that takes in a set of objects and does work based on BaseId
. It doesn't return the objects back or otherwise use the type given at all.
My question: Is it better to use a generic here, or just take in the base types?
Option A: void DoWork<TDomainBase>(List<TDomainBase> objects) where TDomainBase : DomainBase;
Option B: void DoWork(List<DomainBase> objects);
In our code these are called the same, as we never work with List<DomainBase>
that have different types i the collection (e.g. new List<DomainBase> { new Foo(), new Bar() }
). I want to say that using the generic is better, so that we don't implicitly convert objects
to their base class when passing them into the method. But I want to make sure I'm not missing something obvious here. (Or, heck, C# might just optimize all this away under the hood regardless of which option I choose!) Happy to be proven wrong.
Edited to remove incorrect statement.