Click here to Skip to main content
Licence CPOL
First Posted 15 Jun 2010
Views 6,044
Bookmarked 6 times

Enum.TryParse (.NET 4.0)

By | 15 Jun 2010 | Technical Blog
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.
A Technical Blog article. View original blog here.[^]

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!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Mattia Baldinger

Software Developer

Switzerland Switzerland

Member

Follow on Twitter Follow on Twitter


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120517.1 | Last Updated 15 Jun 2010
Article Copyright 2010 by Mattia Baldinger
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid