Skip to content

ABAP Keyword Documentation →  ABAP - Reference →  Assignments →  Setting References →  ASSIGN →  ASSIGN - casting_spec →  Casting Examples 

Field Symbols - Casting

This example demonstrates how casting with implicit and explicit type specification is carried out.

Other versions: 7.31 | 7.40 | 7.54

Source Code

    TYPES: BEGIN OF t_date,
              year  TYPE n LENGTH 4,
              month TYPE n LENGTH 2,
              day   TYPE n LENGTH 2,
           END OF t_date.

    FIELD-SYMBOLS: <fs1> TYPE t_date,
                   <fs2> TYPE ANY,
                   <fs3> TYPE n.

    SKIP.
    WRITE: / 'sy-datum', sy-datum.
    SKIP.
    ULINE.
    SKIP.

<span class="blue">*------- Casting with implicit typing ------------</span>

    ASSIGN sy-datum TO <fs1> CASTING.

    WRITE: / 'Year  ', <fs1>-year,
           / 'Month ', <fs1>-month,
           / 'Day   ', <fs1>-day.

    SKIP.
    ULINE.
    SKIP.

<span class="blue">*------- Casting with explicit typing ------------</span>

    ASSIGN sy-datum TO <fs2> CASTING TYPE t_date.

    DO.
      ASSIGN COMPONENT sy-index OF STRUCTURE <fs2> TO <fs3>.
      IF sy-subrc <> 0.
        EXIT.
      ENDIF.
      WRITE: / 'Component', (1) sy-index, ' ', <fs3>.
    ENDDO.

Description

In the first part of the main method, an implicit casting is carried out. The field symbol <fs1> is completely typed with the local program type t_date. Using the CASTING addition of the ASSIGN statement, the field sy-datum can be treated as a structure. Without the CASTING addition assigning would not be possible, because sy-datum is not compatible with the type of the field symbol.

In the second part of the main method, an implicit casting is carried out. The field symbol <fs2> is completely generic. Using the CASTING addition of the ASSIGN statement, a cast is carried out for the field sy-datum of the local program type t_date. The field symbol <fs2> can now be treated like a structure but does not recognize components. For this reason, it must be assigned component by component to a further field symbol <fs3>.