Validate a String to be in Guid Format in .net C#

Initially, I was using a wrong mechanism to validate a string to be in GUID format. I was doing the following:

string wrongString = String.Empty;
bool IsCorrectGuid = false;
    Guid guid = new Guid(wrongString);
    IsCorrectGuid = true;

However, try-catch is an expensive process so, if you have huge no. strings to validate and most of them will not be a Guid then, this is a very bad way of validation.

The correct way is to use Regex, and if you are working on .Net 4.0 or higher then, you can also use the Guid.TryParse method to achieve the same goal. Following I have demonstrated to validate the string in both ways.


string correctString = Guid.NewGuid().ToString();
Guid guid;
bool guidResTrue = Guid.TryParse(correctString, out guid);


string correctString = Guid.NewGuid().ToString();

//returns true for correct format, case in-sensitive
Regex isGuid = new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);
bool guidResTrue = isGuid.IsMatch(correctString.ToUpper());

Of course, Guid.TryParse should be the preferred way of doing it if, you’re using .Net 4.0 or higher.