Reputation: 8556
I have the following enum:
public enum PageIdsOptions
{
PageID_News = 1,
PageID_Signup = 2,
PageID_AffiliateSignup = 3,
PageID_Cashier = 4,
PageID_Promotions = 5
}
and the following property:
public PageIdsOptions Hint { get; set; }
I recieved a string with this value:
string hintValue = "PageID_Signup";
And I want to assign the value of hintValue to the property Hint:
Hint = hintValue;
so that Hint will be equal to
Hint = PageIdsOptions.PageID_Signup;
How can this be done? Any help will be greatly appreciated! Thank You!
Upvotes: 3
Views: 147
Reputation: 223422
Use Enum.Parse method, (this will throw an exception if hintValue contains any invalid value)
Hint = (PageIdsOptions) Enum.Parse(typeof(PageIdsOptions), hintValue);
You can also use Enum.TryParse, (this will return a boolean if the parsing is successful or not, but no exception will be thrown)
PageIdsOptions Hint;
if (Enum.TryParse(hintValue, out Hint))
{
//Parsed successfully
}
else
{
// Parsing failed
}
Upvotes: 4
Reputation: 35766
how about
if (!Enum.TryParse(hintValue, out Hint))
{
// throw an exception because hintValue did not parse.
}
Upvotes: 0
Reputation: 13460
try
{
var value = Enum.Parse(typeof(PageIdsOptions), hintValue);
}
catch(ArgumentException e)
{
//todo
}
Upvotes: 2