Invalid use of the THIS keyword

The THIS keyword provides access to the current instance of a FUNCTION_BLOCK. However, there are several rules governing its proper use:

Common errors

  1. Using THIS outside of a FUNCTION_BLOCK context: The THIS keyword can only be used inside a FUNCTION_BLOCK or its METHODs or ACTIONs. It cannot be used in FUNCTIONs, PROGRAMs, or .

  2. Not dereferencing THIS to access members: When accessing members using THIS, it must be dereferenced using the ^ operator: THIS^.member.

  3. Member access position: THIS cannot be accessed as a member of another object. Expressions like x.THIS^ are invalid.

  4. Global access position: THIS cannot be used with the global access operator (.THIS^.member).

  5. Using THIS with type cast operators: The type cast operator (<type>#) cannot be used with THIS.

Examples of invalid use

// Error: Using THIS outside `FUNCTION_BLOCK` context
FUNCTION func
    THIS^.x := 2;  // Error: Invalid use of `THIS`
END_FUNCTION

// Error: Not dereferencing THIS when accessing members
FUNCTION_BLOCK fb
    THIS.x := 20;  // Error: `THIS` must be dereferenced to access its members
END_FUNCTION_BLOCK

// Error: THIS in member access position
FUNCTION_BLOCK fb
    x.THIS^.y := 20;  // Error: `THIS` is not allowed in member-access position
END_FUNCTION_BLOCK

// Error: Global access position
FUNCTION_BLOCK fb
    .THIS^.x := 20;  // Error: `THIS` is not allowed in global-access position
END_FUNCTION_BLOCK

// Error: Using THIS with type cast
FUNCTION_BLOCK fb
    p := fb#THIS;  // Error: The `<type>#` operator cannot be used with `THIS`
END_FUNCTION_BLOCK

Examples of valid use

FUNCTION_BLOCK Counter
    VAR
        count : INT;
        enabled : BOOL;
    END_VAR

    // Valid: Direct use in FUNCTION_BLOCK implementation
    METHOD increment
        IF THIS^.enabled THEN
            THIS^.count := THIS^.count + 1;
        END_IF
    END_METHOD

    // Valid: Using THIS to pass the instance to another FB
    METHOD send_to_logger : BOOL
        VAR_IN_OUT
            logger : Logger;
        END_VAR
        logger.log_counter(THIS);
    END_METHOD

    // Valid: Using THIS to compare with another instance
    METHOD equals : BOOL
        VAR_IN_OUT
            other : Counter;
        END_VAR
        equals := THIS^.count = other.count;
    END_METHOD

    ACTION my_action
        IF THIS^.enabled THEN
            THIS^.count := THIS^.count + 1;
        END_IF
    END_ACTION
END_FUNCTION_BLOCK