Chapter Contents

Previous

Next
Object Class: _instanceof

Object Class: _instanceof



Checks if an object is an instance of a given class


Syntax
Details

Syntax

return = objectName._instanceof( arg1 );

Argument Type Use Description
return Numeric Return
arg1 Character Input


Details

Examining the statically-declared (build-time) type of an object may not be an accurate description of the object at run-time. The object variable may actually contain an instance whose type is a subclass of the declared type.

For example, given the class box and its subclass redbox, the _instanceof method can determine that a variable declared as type box actually references the subclass, redbox:

/*Define box class */
box.scl
  class box;
endclass

/* Define redbox class with an additional method */
redbox.scl
  class redbox;
  rbmethod: method;
     put 'a method from a redbox';
  endmethod;
endclass;

/* An SCL entry declaring a variable of type box, */
/* but containing an object of type redbox.       */
X.scl
  init:
    dcl box b = _new_ redbox();

    if (b._instanceof('redbox')) then
      put 'Instance of redbox.';
    else
      put 'Not an instance of redbox.';
return;
The SCL code in X.scl will print "Instance of redbox" since the variable 'b' contains an instance of type redbox.

The _instanceof method can be used to check whether a cast will be successful. Given the same classes, box and redbox, the following code ensures that box b contains an instance of redbox before the cast:

X.scl
init:
  dcl box b = _new_ redbox();
  dcl redbox rb;

 if (b._instanceof('redbox')) then
    rb = b._cast('redbox');
  else
    put 'Invalid cast.';
return;
You should always use _instanceof to determine if a cast will be successful.


Chapter Contents

Previous

Next

Top of Page

Copyright 1999 by SAS Institute Inc., Cary, NC, USA. All rights reserved.