Safe to cast uint8 to enum and vice versa?

enum class ETileType : uint8
ENone, ESurface, ESubsurface, EPlatform, EHole, EEnd

// get a random tile

uint8 n = FMath::RandRange(1, (uint8)ETileType::EEnd - 1);
ETileType NewTile = (ETileType)n;

Is this safe? Is there a better way?
edit sorry, i cannot get this post to format correctly.

I would say this is ok assuming you don’t want to get the ENone result (because enums start from 0, not 1).

Your enum is backed by a uint8 here, so no problems with too big numbers. You use EEnd as the max range which is good because you can safely add new enumeration.

Maybe I would use static_cast here, because it’s C++ after all and later on you can easily search for casts in your project. Also maybe explicitly state what’s the start of the range. Something like that:

uint8 n = FMath::RandRange(static_cast<int>(ETileType::ESurface), static_cast<int>(ETileType::EEnd) - 1);
ETileType NewTile = static_cast<ETileType>(n);

But this is a more-or-less cosmetic change, so you decide :slight_smile: