Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Enum.TryParse (.NET 4.0)

0.00/5 (No votes)
15 Jun 2010 1  
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.

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!

C#
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!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here