Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing value into nullable enumeration

Tags:

c#

enums

nullable

Let's say I have this:

PriorityType? priority;
string userInput = ...;

I cannot change how this is defined: PriorityType? priority because it's actually part of a contract with another piece of code.

I tried this, but it does not work:

if (Enum.TryParse<PriorityType?>(userInput, out priority)) {

What is the correct way?

like image 391
core Avatar asked Oct 23 '15 20:10

core


3 Answers

The simplest way:

PriorityType tempPriority;
PriorityType? priority;

if (Enum.TryParse<PriorityType>(userInput, out tempPriority))
    priority = tempPriority;

This is the best I can come up with:

public static class NullableEnum
{
    public static bool TryParse<T>(string value, out T? result) where T :struct, IConvertible
    {
        if (!typeof(T).IsEnum)
            throw new Exception("This method is only for Enums");

        T tempResult = default(T);

        if (Enum.TryParse<T>(value, out tempResult))
        {
            result = tempResult;
            return true;
        }

        result = null;
        return false;
    }
}

Use:

if (NullableEnum.TryParse<PriorityType>(userInput, out priority))

The above class can be used just like Enum.TryParse except with a nullable input. You could add another overloaded function that takes a non-nullable T so that you could use it in both instances if you want. Unfortunately extension methods don't work very well on enum types (as far as I could try to manipulate it in the short time I tried).

like image 129
Ron Beyer Avatar answered Oct 18 '22 19:10

Ron Beyer


If you want it to be a single line of code, you can do it like this:

var priority = Enum.TryParse<PriorityType>(userInput, out var outPriority) ? outPriority : (PriorityType?) null;
like image 33
Moch Yusup Avatar answered Oct 18 '22 19:10

Moch Yusup


This is the same solution posted by Ron Beyer with a little refactoring:

 public static class NullableEnum
{
    public static bool TryParse<T>(string value, out T? result) where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum) throw new ArgumentException("Invalid Enum");

        result = Enum.TryParse(value, out T tempResult) ? tempResult : default(T?);

        return (result == null) ? false : true;
    }
}
like image 4
Mteheran Avatar answered Oct 18 '22 18:10

Mteheran