1

When i look i.e: for all types in an assembly implementing some interface using reflection, will the order of returned types always be the same or they can be returned in any order during different runs?

Sinatr
  • 20,892
  • 15
  • 90
  • 319
Adam Stawarek
  • 321
  • 4
  • 9
  • 4
    i don't think you should rely on their order as is - but you can just use LINQs `OrderBy()` to solve that. I'm curious as to why you'd need them ordered, though? – Franz Gleichmann May 27 '20 at 05:45
  • first type that is found determines which items are shown later on to the user. The order suddenly changed yesterday, just to return back to previous state today. – Adam Stawarek May 27 '20 at 06:14
  • 1
    At a few reflection related places in the msdn are remarks like this `The GetMembers method does not return members in a particular order, such as alphabetical or declaration order. Your code must not depend on the order in which members are returned, because that order varies.` – thehennyy May 27 '20 at 07:04
  • 2
    Since meta-data upon loading type should appears in memory similarly, I'd say you can rely on the order as long as **nothing** is changed. In other words if you get results in the certain order from a certain dll, then you should always get them in this order, unless someone will change dll or a .net framework implementation (unlikely). I had issue with enum where several constants have same values and the order of their retrieval [was deterministic](https://stackoverflow.com/a/35600294/1997232) and stay so for years. – Sinatr May 27 '20 at 07:18
  • 1
    "The order suddenly changed yesterday" - so despite having evidence that the ordering is inconsistent, you asked this question? I'm confused. – Damien_The_Unbeliever May 27 '20 at 07:23
  • @Damien_The_Unbeliever, the order of items was preserved for at least one year(the time i'm working on that project). So if this order was completly non deterministic it would rather result in many more such situations. I think the answer is in Sinatr comment, and this sudden change was caused because someone added or modified something in the module that was in the same shape since its creation. – Adam Stawarek May 27 '20 at 19:07
  • You're mistaking non-determinism and randomness. – Damien_The_Unbeliever May 28 '20 at 07:54
  • Related: https://stackoverflow.com/questions/7000711/what-is-the-order-of-returned-types-by-assembly-gettypes – riQQ Mar 08 '23 at 07:39

1 Answers1

1

Look at the documentation of Assembly.GetTypes.

Returns

Type[]

An array that contains all the types that are defined in this assembly.

There is no mentioning of any order. Therefore you should not rely on it. Event if ordering is consistent now, it might change in some future version.

If you want the result to be ordered, use OrderBy, Array.Sort, or some of the other sorting alternatives.

JonasH
  • 28,608
  • 2
  • 10
  • 23