Generics without Casting
Is there any possible way to do what the code below is doing with generics, but without the casting?
14 Replies
Use T for the dictionary instead of object
But the class ItemCollection isn't generic, only the methods.
i don't think there's a way around it
I had a feeling 😢
So make it generic
Something like this instead:
Note that this code isn't thread safe.
i think the point is that the outer collection isn't generic
it's more like a bag of objects grouped by type
not really sure what the goal is
Yes, not really clear.
I basically have several objects where I want to manually create Id's for. With them all being different types, I'd like to have one class to do it. But I suppose it's not too bad just to create a generic class similar to @mtreit, and I can create an implementation for each type. Thanks for your help
can i say that this
int next = dictionary.Keys.Max() + 1;
is a bit awkwardYes you can! How would you do it?
it depends what this thing it has to be
but at least i would just keep an autoincrement id as a field of the class
so that there's no need to duplicate and examine all the keys of the dictionary to get a value
Thanks for the tips. In retrospect, I was thinking along similar lines. In fact, Max() causes an exception when the are no values 😄
In my particular case, there won't be very many items added, so I wasn't too worried about performance.
i can understand that, but to me it's kind of a yellow flag
i could maybe accept that if say there was an exception when trying add more than 10~15 items, for example
like
throw new Exception("don't use this class for large collections")
Oh I'll definitely go the route of having an autoincrement id. I agree it's better. I was mainly trying to figure out if there's a generics trick I wasn't aware of. Thanks for your input