Search code examples
delphifiremonkey

Casting a JObject to a JList


To cast a JObject to a JList (or anything else, it doesn't matter, this is just an example), is just doing JList(MyJobject) a good way? I don't receive any error, but I'm not sure if it's the correct way to go.


Solution

  • When casting between different object types, you cannot use a plain type-cast. You must cast the JObject to ILocalObject and call its GetObjectID() method, and then pass that result to the Wrap() method of the destination class type, in this case TJList, eg:

    For example:

    var
      MyJobject: JObject;
      MyJList: JList;
    
    MyJobject := ...;
    MyJList := TJList.Wrap((MyJobject as ILocalObject).GetObjectID);
    

    Or simpler (which is just a wrapper for the above):

    var
      MyJobject: JObject;
      MyJList: JList;
    
    MyJobject := ...;
    MyJList := TJList.Wrap(MyJobject);
    

    See What the purpose of doing (MyJobject as ILocalObject).GetObjectID