What is CastChecked <>()

There doesn’t seem to be anything online about CastChecked.
Can someone explain for future readers?

Probably an internal function to check if cast function fails or succeeds

All you have to do is

AMyClass* cl = Cast<AMyClass>(Other);

and unreal does the asserts behind your back :stuck_out_tongue:

CastChecked is exactly what it says, it’s a checked cast. It’s the equivalent of:

ptrA = Cast< type >( ptrB );
check( ptrA != nullptr );

It’s not an internal function but you do have to be pretty sure that the cast is going to succeed.

4 Likes

Yep basically in another word.

Use Cast() if nullptrs and incorrect types in your results are an expected behaviour.
UseCastChecked() if you want to throw an error immediately if the cast fails.

This is not entirely accurate. There is an enum parameter that you can pass to CastChecked that allows for nullptr inputs to not trip the check. It’s common for the case of “if this pointer is valid, it should always be X, but it’s okay if it’s not valid to start”.

The usage of castchecked can be seen here - here. Essentially, it is the same as a cast, but with a preliminary check. This variant will not work if the pointer type does not match or the object pointer is null.

That is a horrible link to document CastChecked as it is 99% unrelated to casting.

Also I posted less than a week ago that “object pointer is null.” is not true. You can use CastChecked with nullptrs and not get a check if that is what is desired.

(Since this is still the thread that comes up for the top search results for CastChecked I think it’s important that inaccurate information corrected for later readers).

1 Like