Good practice to use Enum values when possible?

I just wondered. Is there a difference? Is it better to use an Enum value instead of setting a property as a string directly?

Example-

camera.CameraType = Enum.CameraType.Scriptable

Versus

camera.CameraType = "Scriptable"

Just wondered using Enums is more ideal on performance, or if it really doesn’t matter.

Thanks :slight_smile:

3 Likes

The former. Don’t even worry about performance. CameraType and any other EnumItem property do not take arbitrary string values. CameraType is not a string value, but an EnumItem value. if you do typeof(camera.CameraType) you should get the latter in the output.

Technically doing it this way would be faster since there is no extra stuff going on to cast to an EnumItem.

You also can’t compare enums to strings.

print(part.Material == Enum.Material.Plastic) -- true (assume it's plastic)
print(part.Material == "Plastic") -- false

Be consistent in your code.

Oh and also intellisense autocompletes the enums so if you forget what it’s called, you have intellisense helping you :wink: unlike strings

8 Likes

Yes.
Using Enumerations (full name) is BETTER practice than using a string reference.

As for the actual difference ehhhh, Enum is just more of a surefire way of getting the state or type or class that you want.

See a previous thread on this here for reference.

3 Likes

Worth saying that regardless, the value you apply to a property that expects an EnumItem will convert itself if what you’re passing is valid. The string Plastic will be converted to Enum.Material.Plastic (which comes from the Name property of this EnumItem). Likewise, setting the Material to 256 is also valid because that’s the EnumItem’s value.

For your own sake and everyone else’s though, please use the full Enum over strings. It’s more clear what you’re doing and clarity is a gift.

Checking the Enum:

local ENUM_ITEM = Enum.Material.Plastic

print(ENUM_ITEM) -- Enum.Material.Plastic
print(ENUM_ITEM.Name) -- Plastic
print(ENUM_ITEM.Value) -- 256

Setting the material:

local part = Instance.new("Part")

part.Material = Enum.Material.Plastic -- Valid, canonical
part.Material = "Plastic" -- Valid
part.Material = 256 -- Valid
3 Likes