Oskar Berggren
Oskar Berggren

Reputation: 5629

Comparison between IList and IList<object> - should any be preferred?

Since many years, we use generic collections most of the time. Sometimes we really do need a collection of anything (well, usually only a few different things but with no common base class). For such circumstances we can use either IList or the generic IList<object> as type for method arguments and properties.

Is there any reason to prefer one over the other? Performance characteristics?

Personally, I'm leaning towards IList<object>, as I think this makes it more clear that we really do accept "anything". When a parameter is typed as IList we cannot immediately tell if this method do accept anything, or if the lack of generics is due to history or sloppy coding.

Upvotes: 3

Views: 459

Answers (1)

Mat&#237;as Fidemraizer
Mat&#237;as Fidemraizer

Reputation: 64943

There's a good reason: LINQ and its extension methods. These aren't implemented for pre-generics era types. You will need to call Cast<T> on the IList to take advantage of LINQ!

Other point is that, since newest .NET versions support covariance and contravariance and most of generic interfaces support one or the other (f.e. IEnumerable<out T>, T is covariant), you can easily downcast or upcast interfaces' generic parameters from and to object or a less-unspecific type.

Conclusion: why generics should be prefered?

  • Generic types have better performance because they avoid a lot of casts.
  • Newer APIs rely on generic collections and interfaces.
  • There're a lot of reasons to think that mixing objects of different types in the same list could be dangerous and a bad coding/design decision. And for the few cases where you'll store any kind of object, having LINQ and many other newer APIs and features as your friend is a powerful reason to don't reinvent wheels and save a lot of time!

Upvotes: 5

Related Questions