Are C# enums typesafe?
If not what are the implications?
Are C# enums typesafe?
If not what are the implications?
Yes they are.
The following is from http://www.csharp-station.com/Tutorials/Lesson17.aspx
Enums are strongly typed constants. They are essentially unique types that allow you to assign symbolic names to integral values. In the C# tradition, they are strongly typed, meaning that an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members are the same. Along the same lines, integral types and enums are not implicitly interchangable. All assignments between different enum types and integral types require an explicit cast.
Enums are strongly typed constants. They are essentially unique types that allow you to assign symbolic names to integral values. In the C# tradition, they are strongly typed, meaning that an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members are the same. Along the same lines, integral types and enums are not implicitly interchangable. All assignments between different enum types and integral types require an explicit cast.
Yes.
C#: enum types:
-A type-safe enumeration of named values.
-Prevents programming errors
-User can control underlying type (defaults to int)
-Also can control underlying values
Technically no because you can represent an Enum as its base value (int, long, etc). However, if you ensure that you only use the enum by its provided names, you will receive compile time errors if you change the name of an enumerated value without updating its references. In this regard yes it is type safe.
I'm late to the party here, but I wanted to throw out a little something extra ... An update to the .NET Framework Design Guidelines from Krzysztof Cwalina. In addition to the excellent tip above on checking to ensure a valid value is passed to your Enums, this provides other guidance and advice for how to use them effectively, a bunch of gotchas (especially involved Flags
enums), etc.
For those suggesting to use Enum.IsDefined to do argument validation...don't! Per Brad Abrams (from the Framework Design Guidlines Update on Enum Design):
There are really two problems with Enum.IsDefined(). First it loads reflection and a bunch of cold type metadata making it a deceptively expensive call. Secondly, as the note alludes to there is a versioning issue here.