'Enum.TryParse doesn't accept my out parameter as an object
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.
Solution 1:[1]
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);
Solution 2:[2]
There are two forms of Enum.TryParse method:
- Non-generic ones with a
Typeparameter first and anout objectparameter at the end - Generic ones without the
Typeparameter (because the generic type parameter is used instead) and with anout TEnumparameter 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?);
Solution 3:[3]
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
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Jon Skeet |
| Solution 3 | churchid |
