1

and sorry for the weird title.

There is my class hierarchy :

  • TimedObject
    • SpeedModifer
      • ImediateSpeedModifier
      • LinearSeedModifier
      • .. More classes ..
    • .. More classes ..

In the files, all TimedObject's instances are in the same array (so, a List<TimedObject>). I want, after the data are loaded, I want to move every SpeedModifier or child class to another array for performance issue. I already know the Enumerable.OfType<T>() function, but is this function works in my case ? So, will it work for ImediateSpeedModifier, and other SpeedModifier ?

If not, what do I need to do for my case ?

Thanks you for yours answers !

2 Answers2

3

Yes, it will work, since an object of type ImmediateSpeedModifier is a SpeedModifier.

The documentation confirms this (emphasis mine):

The OfType<TResult>(IEnumerable) method returns only those elements in source that can be cast to type TResult.

There are very few methods in the .NET framework which check for the exact dynamic type, since the ability of subtypes to be used in place of theirs supertypes is a fundamental principle of object-oriented programming. Checking for the exact type is only needed in exceptional circumstances (e.g. unit testing).

Community
  • 1
  • 1
Heinzi
  • 167,459
  • 57
  • 363
  • 519
0

Enumerable.OfType<T>() will work. So:

var list = new List<TimedObject>();
//load data into list
var filteredList = list.OfType<SpeedModifer>();
QuantumHive
  • 5,613
  • 4
  • 33
  • 55