Since .NET 4.0, the Enum
class contains also a TryParse
method. The TryParse
method, which is supported in other basic data types already since version 2.0, allows to pass in a value which will be checked if it can be converted into the defined type. Additionally an out
parameter must be passed in which contains the value converted into the datatype if the conversion was successful. If it can't be converted, false
will be returned and the out
parameter won't be changed. Without the TryParse
method, you had to use a try catch
block around the Parse
to avoid errors. The Enum.TryParse
always takes a string
as input, which it tries to convert to a valid enum
value!
public void EnumTry()
{
CheckVersion("Dotnet4");
CheckVersion("Dotnet3.5");
CheckVersion("Dotnet3");
}
public enum DotNet
{
DotNet5,
DotNet4
}
public void CheckVersion(string versionName)
{
DotNet version;
if (Enum.TryParse<DotNet>(versionName, true, out version))
{
Console.WriteLine("Version Found: "+version.ToString());
}
else
{
Console.WriteLine("Version not found!";
}
}
Also with the Enum.TryParse
, you don't have to cast anymore, because the generic method does this for you. Additionally, the method allows you to specify if upper and lower case should be ignored in the string (like the normal Parse
method). Enum.TryParse
doesn't allow you to do things which you aren't able to do before, but allows you to produce better readable, shorter code!