Home > OS >  Enum.TryParse doesn't accept my out parameter as an object
Enum.TryParse doesn't accept my out parameter as an object

Time:02-10

I have the following line:

var parseSortField = (BasicProfileSortableFields?)Enum.TryParse(typeof(BasicProfileSortableFields?), sortOptions.SortColumn, out BasicProfileSortableFields? sortField);

Around the out parameter, I'm getting an error that says

Argument 3: cannot convert from 'out Services.Models.BasicProfileSortableFields?' to 'out object?'

Regular parsing works but I'm trying to catch a scenario where my string is not in the mentioned enum. Also the enum I'm referencing is from a nuget package and not actually written by me if that helps.

CodePudding user response:

nullable enums can's be handled by Enum.TryParse

workaround: handle the null case with a ?: ternary conditional operator

BasicProfileSortableFields temp;
BasicProfileSortableFields? parseSortField = Enum.TryParse<BasicProfileSortableFields>(sortOptions.SortColumn, out temp) ? (BasicProfileSortableFields?)temp : null);

CodePudding user response:

There are two forms of Enum.TryParse method:

  • Non-generic ones with a Type parameter first and an out object parameter at the end
  • Generic ones without the Type parameter (because the generic type parameter is used instead) and with an out TEnum parameter at the end

Currently it looks like you're half-way between the two - but with a nullable final parameter (out TEnum? instead of out TEnum). Additionally, you're trying to cast the result of the TryParse method to the enum type - whereas actually it returns a bool saying whether or not the parsing succeeded.

I would advise using the generic forms, in code a little like Fubo's answer, but declaring the temp variable "inline" in the call:

var sortField =
    Enum.TryParse<BasicProfileSortableFields>(sortOptions.SortColumn, out var temp)
        ? temp
        : default(BasicProfileSortableFields?);

CodePudding user response:

Enum.TryParse returns a boolean, and the 3rd parameter is out object?. You may want to use Enum.Parse instead? In which case, just eliminate the third parameter, and wrap the call in a try..catch if you care to handle when the parse fails.

Also, I think you want the first parameter to be the type of your enum, not the type of a Nullable wrapper for your enum, but I could be mistaken on that.

Alternatively, to keep using TryParse, you should first check the result to see if the parse failed, and get the out parameter as an object?, which you can then cast to your target type if the parse succeeded, like this:

BasicProfileSortableFields parseSortField;

if(Enum.TryParse(typeof(BasicProfileSortableFields), sortOptions.SortColumn, out object? sortField))
{
    parseSortField = (BasicProfileSortableFields)sortField.Value;
}
else
{
    // Handle failed parse condition here
}
  • Related