❔ Comparing Types using local var Type type
Hello, I am trying to write a method comparing types to clean up my code. I am trying to use a single method to sort through a list and pull out specific elements by type. (type being a child class of the lists type)
10 Replies
type in this case would be a class (ex: Helmet) which is a child of 'Item'
and the list is List<Item>...
You can't use the pattern matching dynamically like that but what you can do is use a little bit of reflection
Search on how to use the
IsAssignableFrom
But I'm a bit concerned about your end goal
You're aware that you can use list.OfType<Helmet>()
, right?
Although if this is a game linq might not be your ideal solutionwell that was easy lol
is this a game?
yes, would that be a big problem?
I guess I could use a overridable var within the child classes to do the check instead of type checking if that would be safer / better for a game
would there be an easy way to check my previous code for linq statements to refactor?
I mean
Linq can be slow
which version of .net are you using
I'd benchmark OfType and a simple foreach loop
or just write your own OfType based on Linq's implementation, but stop taking an
IEnumerable
and take a List
surelooks like 2.1
hmm honestly
that
now going to bed
gn
sounds good, thank you for your help!
gn
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.