Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I parse invalid values to an Enum in .NET?

Tags:

c#

.net

enums

Why is this even possible? Is it a bug?

using System;

public class InvalidEnumParse
{
    public enum Number
    {
        One,
        Two,
        Three,
        Four
    }

    public static void Main()
    {
        string input = "761";
        Number number = (Number)Enum.Parse(typeof(Number), input);
        Console.WriteLine(number); //outputs 761
    }
}
like image 822
Ward Werbrouck Avatar asked Feb 03 '10 09:02

Ward Werbrouck


People also ask

How to use enum parse?

Parse<TEnum>(String, Boolean)Converts the string representation of the name or numeric value of one or more enumerated constants specified by TEnum to an equivalent enumerated object. A parameter specifies whether the operation is case-insensitive.

Can we assign value to enum in C#?

You can assign different values to enum member. A change in the default value of an enum member will automatically assign incremental values to the other members sequentially. You can even assign different values to each member.


2 Answers

That's just the way enums work in .NET. The enum isn't a restrictive set of values, it's really just a set of names for numbers (and a type to collect those names together) - and I agree that's a pain sometimes.

If you want to test whether a value is really defined in the enum, you can use Enum.IsDefined after parsing it. If you want to do this in a more type-safe manner, you might want to look at my Unconstrained Melody project which contains a bunch of constrained generic methods.

like image 60
Jon Skeet Avatar answered Oct 13 '22 10:10

Jon Skeet


If you have a enum with [Flags] attribute, you can have any value combination. For instance:

[Flags]
enum Test
{
    A = 1, 
    B = 2,
    C = 4,
    D = 8
}

You could to do this:

Test sample = (Test)7;
foreach (Test test in Enum.GetValues(typeof(Test)))
{
    Console.WriteLine("Sample does{0} contains {1}",
        (sample & test) == test ? "": " not", test);
}
like image 35
Rubens Farias Avatar answered Oct 13 '22 09:10

Rubens Farias