Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between casting using (Object as TClass) and TClass(Object)

Got an issue where MyObj.classnameis(TMyClass.classname) is true and TMyClass(MyObj) works but (MyObj as TMyclass).doSomething throws a conversion error.

I don't really want any help with that junk, although if you want to put it in the comments that'd be super. I just would like to know what the difference between Obj as Class and Class(Obj) is.

like image 479
Peter Turner Avatar asked Mar 15 '10 19:03

Peter Turner


1 Answers

An as-cast checks the actual object type to make sure the cast is valid, and raises an exception if it's not. A "hard cast" (TMyClass(MyObj) style) does not check, it just tells the compiler to assume the cast is valid.

If you've got a situation where ClassNameIs returns true but the as-cast fails, that means you have two different classes in two different units with the same name, and the as-cast is trying to cast to the wrong one. This also means that your hard-cast is casting to the wrong one, which could potentially lead to memory corruption.

Run a full project search for "TMyclass =" to see where your multiple declarations are, and either rename one of the classes or use a full definition (obj as MyUnit.TMyClass) so the compiler will know which class you're trying to cast to.

like image 146
Mason Wheeler Avatar answered Sep 22 '22 04:09

Mason Wheeler