Quantcast
Viewing all articles
Browse latest Browse all 102

C#: Enum.TryParse() succeeds when passing "-1" even if the enum doesn't contain that value

I want to print the value of an enum only if its gets parsed correctly. As stated in Enum.TryParse() docs:

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. The return value indicates whether the conversion succeeded.

Returns
Boolean
true if the conversion succeeded; false otherwise.

Now, considering the example below, I would expect that the call succeeds only if I try to parse strings like "first" or "1", which are name/values of TestEnum.

But if I try to parse the string "-1", the call still succeeds and I get -1 as value, how's that even possible??

Example:

using System;public class HelloWorld{    public enum TestEnum    {        first = 0,        second = 1,        third = 2    }    public static void Main(string[] args)    {        TestEnum testEnum;        bool res;        res = Enum.TryParse("first", out testEnum);        if (res)            Console.WriteLine ("TEST 1 - res: " + res.ToString() +", value: " + testEnum.ToString());        res = Enum.TryParse("third", out testEnum);        if (res)            Console.WriteLine ("TEST 2 - res: " + res.ToString() +", value: " + testEnum.ToString());        res = Enum.TryParse("1", out testEnum);        if (res)            Console.WriteLine ("TEST 3 - res: " + res.ToString() +", value: " + testEnum.ToString());        res = Enum.TryParse("-1", out testEnum);        if (res)            Console.WriteLine ("TEST 4 - res: " + res.ToString() +", value: " + testEnum.ToString());        res = Enum.TryParse("fourth", out testEnum);        if (res)            Console.WriteLine ("TEST 5 - res: " + res.ToString() +", value: " + testEnum.ToString());    }}

Output:

TEST 1 - res: True, value: firstTEST 2 - res: True, value: thirdTEST 3 - res: True, value: secondTEST 4 - res: True, value: -1        // <-- How??

Link to the code: https://onlinegdb.com/1MIOnOFl6


Viewing all articles
Browse latest Browse all 102

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>