C
C#14mo ago
Dilly

❔ 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
Dilly
DillyOP14mo ago
private void DispType(Type type) {
foreach(var item in inventory) {
if (item is type) {
//Do stuff
}
}
}
private void DispType(Type type) {
foreach(var item in inventory) {
if (item is type) {
//Do stuff
}
}
}
type in this case would be a class (ex: Helmet) which is a child of 'Item' and the list is List<Item>...
Tarcisio
Tarcisio14mo ago
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 solution
Dilly
DillyOP14mo ago
well that was easy lol
Tarcisio
Tarcisio14mo ago
is this a game?
Dilly
DillyOP14mo ago
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?
Tarcisio
Tarcisio14mo ago
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 sure
Dilly
DillyOP14mo ago
looks like 2.1
Tarcisio
Tarcisio14mo ago
hmm honestly that now going to bed gn
Dilly
DillyOP14mo ago
sounds good, thank you for your help! gn
Accord
Accord14mo ago
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.
Want results from more Discord servers?
Add your server