- Home /
Problem is not reproducible or outdated
Implicit Downcast warning from "List.IndexOf" ...Bad? Unavoidable?
When I try to do something like this:
gCon.ReturnFinalPos (gCon.freeLetters.IndexOf (this as Object), Vector2.Lerp (remotePos, targetPos2, 0.5));
or
if (gCon.displacedLetters.ContainsKey (gCon.freeLetters.IndexOf (this as Object)))
I get
BCW0028: WARNING: Implicit downcast from 'Object' to 'LoneLetter'.
I know what the warning means, I added the "as Object" because IndexOf in a generic list or dictionary won't take the the variable type of whatever it's a List. of, which seems stupid to me but that's how it works, it threw an error if I gave it anything other than an Object.
The closest I could find to a solution was a for ... in statement where the type is left to the compiler's imagination, but I don't think that applies to what I'm trying to do.
The reason I'm getting array indexes in the first place is so I can keep local and remote copies of an object in sync over a network with RPC calls ( for 2 players, each has an 'allMyUnits' list and an 'allYourUnits' list, whose indices and contents are mirrored crosswise in a consistent way. ) The script on the individual unit figures out its place on the game controller's local unit list, then sends that as a byte to the other player with the move order, the other player's game controller script receives the RPC and then passes the order on to the script of the matching index on the remote unit list.
Am I doing it wrong?
Answer by DESTRUKTORR · Sep 01, 2013 at 08:23 PM
http://msdn.microsoft.com/en-us/library/e4w08k17.aspx
It most certainly does take the object type with it. It's a generic method.
Generally, though, I don't like having to use IndexOf, Find, Search, Contains, etc. with standard lists. It's too costly, and there's much better collection types for those sorts of things, assuming they are an option (if not, there's usually still a method of getting around that issue).
If your object extends the class your list uses, it should need no casting. Casting is usually used when an object can be used as a child of the class it was declared as, e.g.
SuperClass obj = new SubClass();
(obj as SubClass).SubClassMethod();
Though this operation on its own is superfluous, it should illustrate my point clearly enough.
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Grab a specific item from a list 3 Answers
How to get smallest element and key from int list 1 Answer