Reputation: 74470
I have the following property definition inside of a WPF Window derived class:
internal Side? Side
{
get
{
if (SideComboBox.SelectedIndex==-1)
return null;
Side side;
if (!Enum.TryParse(SideComboBox.SelectedValue as string, out side))
return null;
return side;
}
}
The function always returns null. So I figure, I'll step into it and see what's happening. Well, it turns out that the TryParse method is always returning false (i.e., causing the body of the second if statement to execute and thus returning null). I look at the value of the string to see if it in fact is a valid value for the enum and sure enough it is. Why is the parsing always failing even when valid strings are sent into TryParse?
Here is the enum definition:
enum Side
{
Buy,
Sell
}
Update: OK guys, a definite LOL moment here. It turns out that SelectedValue is actually returning the enum itself and not a string, but when I view it in the debugger it always implicitly converts it to a string. Finally, after reading your comments I decided to actually double click on the value in the watch window, only to discover to my horror that the value is MyApp.Side.Sell - an enum and not a string. So, chalk up another one for checking the result of as
to be non-null!
Upvotes: 0
Views: 346
Reputation: 181077
If you've double checked that the value is ok, you've probably made the same mistake I've made numerous times; Enum.TryParse can parse the strings Buy
and Sell
, however it can not parse the strings Side.Buy
and Side.Sell
.
Upvotes: 0
Reputation: 62265
From the code provided don't seems to me you should have a problems with that, if not
check actually the value of the SideComboBox.SelectedValue as string
code
use of Enum.TryParse overload with the parameter specifying to ignore the case, like this
Enum.TryParse(SideComboBox.SelectedValue as string, true, out side)
In this way if the string in the combo
has a different case, it will be "catched" by the way.
Hope this helps.
Upvotes: 0
Reputation: 156748
The following LINQPad program works for me:
void Main()
{
Side side;
Enum.TryParse("Buy", out side).Dump();
side.Dump();
}
public enum Side{Buy, Sell}
I'm guessing that your SelectedValue
input is not actually a valid value for the enum, even though you think it is.
Upvotes: 2