string strName = \"John\";
public enum Name { John,Peter }
private void DoSomething(string myname)
{
case1:
if(myname.Equals(Name.John) //returns false
{
For some reason, the given solutions didn't workout for me. I had to do in a slighly different way:
Name myName;
if (Enum.TryParse<Name>(nameString, out myName))
{
switch (myName) { case John: ... }
}
Hope it helps someone :)
One solution could be to get the type of the enum, and then the types name.
myname.Equals(Enum.GetName(typeof(Name)))
http://msdn.microsoft.com/en-us/library/system.enum.getname.aspx
If you using .NET4 or later you can use Enum.TryParse. and Enum.Parse is available for .NET2 and later
// .NET2 and later
try
{
switch (Enum.Parse(typeof(Names), myName))
{
case John: ...
case Peter: ...
}
}
// .NET4 and later
Name name;
if (Enum.TryParse(myName, out name))
switch (name)
{
case John: ...
case Peter: ...
}
You can use the Enum.TryParse() method to convert a string to the equivalent enumerated value (assuming it exists):
Name myName;
if (Enum.TryParse(nameString, out myName))
{
switch (myName) { case John: ... }
}
You can parse the string value and do enum comparisons.
Enum.TryParse: See http://msdn.microsoft.com/en-us/library/dd783499.aspx
Name result;
if (Enum.TryParse(myname, out result))
{
switch (result)
{
case Name.John:
/* do 'John' logic */
break;
default:
/* unexpected/unspecialized enum value, do general logic */
break;
}
}
else
{
/* invalid enum value, handle */
}
If you are just comparing a single value:
Name result;
if (Enum.TryParse(myname, out result) && result == Name.John)
{
/* do 'John' logic */
}
else
{
/* do non-'John' logic */
}
I think you're looking for the Enum.Parse()
method.
if(myname.Equals(Enum.Parse(Name.John)) //returns false
{
}