50

UPDATE

Guid.TryParse is available in .NET 4.0

END UPDATE

Obviously there is no public GUID.TryParse() in .NET CLR 2.0.

So, I was looking into regular expressions [aka googling around to find one] and each time I found one there was a heated argument in the comments section about RegEx A doesn't work, use RegEx B. Then someone would write Regex C yadda yadda

So anyway, What I decided to do was this, but I feel bad about it.

public static bool IsGuid (string possibleGuid) {

    try {
      Guid gid = new Guid(possibleGuid);
      return true;    
    } catch (Exception ex) {
      return false;
    }
}

Obviously I don't really like this since it's been drilled into me since day one to avoid throwing exceptions if you can defensibly code around it.

Does anyone know why there is no public Guid.TryParse() in the .NET Framework?

Does anyone have a real Regular Expression that will work for all GUIDs?

Jack Marchetti
  • 15,536
  • 14
  • 81
  • 117
  • 3
    The try catch technique may be bad if this method is being called lots (in a tight loop) and there is a high probably of the exception being thrown. I once profiled an ASP.NET 1.1 app that did this and after upgrading it to .NET 2.0's int.TryParse, performance increased by around 30% (it was doing lots of int.Parse calls!). – RichardOD Nov 06 '09 at 16:26
  • Yeah it won't be a loop. Basically I've been getting errors of the "failed converting to uniqueidentifier" etc.. so I wanted to do something more than just check if the string being passed was empty or not. – Jack Marchetti Nov 06 '09 at 16:43
  • string Id = Guid.NewGuid().ToString(); –  Feb 13 '12 at 12:59

8 Answers8

55

There is no Guid.TryParse in CLR 2.0 and earlier. It will be available starting with CLR 4.0 and Visual Studio 2010.

As to why there wasn't. These types of questions are usually hard to answer correctly. Most likely it was an oversight or a time constraint issue. If you open up mscorlib in reflector you'll see there is actually a method named TryParse on Guid but it's private. It also throws an exception in certain cases so it's not a good equivalent to say Int32.TryParse.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
19

Guid.TryParse implementation using regular expressions.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Nice. I'd probably add in a try catch fallback in there too, just to be sure (at least until I was confident I hadn't missed anything in the Regex). – RichardOD Nov 06 '09 at 16:28
  • 1
    No, so far in my programming carrier I've never needed such functionality. – Darin Dimitrov Nov 06 '09 at 16:51
  • This will return true for all correct GUIDs, but note that there is a possibility of a type 2 error: for example, it will falsely assert that `"{CA761232-ED42-11CE-BACD-00AA0057B223)"` is a correct GUID. (Note the incorrect bracket.) In this case, the method will throw an exception when it tries to create a `Guid`. – leviathanbadger Apr 24 '13 at 01:19
10

IsGuid implemented as extension method for string...

public static bool IsGuid(this string stringValue)
{
   string guidPattern = @"[a-fA-F0-9]{8}(\-[a-fA-F0-9]{4}){3}\-[a-fA-F0-9]{12}";
   if(string.IsNullOrEmpty(stringValue))
     return false;
   Regex guidRegEx = new Regex(guidPattern);
   return guidRegEx.IsMatch(stringValue);
}
Ahmed Mansour
  • 527
  • 5
  • 13
  • 4
    The behavior is intentional, a null string is not a valid guid and hence returns false. – Partha Choudhury Jun 21 '11 at 21:00
  • 1
    Why should a method call on null always throw a Null Reference Exception? I hate null reference exceptions. I like extensions methods for that exact reason. Keeps my code clear of null checks. – argyle Jul 29 '13 at 16:58
  • 1
    The implementation is wrong. The correct is `string guidPattern = @"^[a-fA-F0-9]{8}(\-[a-fA-F0-9]{4}){3}\-[a-fA-F0-9]{12}$";` – Петър Петров Mar 30 '17 at 13:48
9

Only for .NET Framework 3.5 or earlier:

This implementation of a TryParse for Guids uses a try-catch in order to catch missformed Guids. It is implemented as extension method und must be placed in a static class:

public static bool TryParseGuid(this string s, out Guid guid)
{
    try {
        guid = new Guid(s);
        return true;
    } catch {
        guid = Guid.Empty;
        return false;
    }
}

It can be called with

string s = "{CA761232-ED42-11CE-BACD-00AA0057B223}";
Guid id;
if (s.TryParseGuid(out id)) {
    // TODO: use id
} else {
    // Sorry not a valid Guid.
}

Starting with C# 7.0 / Visual Studio 2017, you can use an inline out-variable declaration and call it with:

string s = "{CA761232-ED42-11CE-BACD-00AA0057B223}";
if (s.TryParseGuid(out Guid id)) {
    // TODO: use id
} else {
    // Sorry not a valid Guid.
}

Since .NET Framework 4.0, System.Guid provides TryParse and TryPareExact methods making the code snippets above obsolete.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
5

In terms of why there isn't one, it's an oversight. There will be a Guid.TryParse in .NET 4 (see BCL blog post for details).

bdukes
  • 152,002
  • 23
  • 148
  • 175
0

There's no TryParse functionality in the .NET Framework to my knowledge at this moment. You'll have to resort to RegEx or the try-catch option. RegEx isn't my cup of tea, so I'm sure someone else will post an answer.

Exceptions are expensive performance wise, so my vote goes to the RegEx option.

ynnckcmprnl
  • 4,382
  • 1
  • 24
  • 25
0

This should work:

@"^\{?[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}\}?$"
jheddings
  • 26,717
  • 8
  • 52
  • 65
  • That says that "{00000000-0000-0000-0000-000000000000" is a legal GUID. Do you *really* want to allow mismatched braces? And why are the hyphens optional? – Eric Lippert Nov 06 '09 at 16:47
  • 1
    This was intended to be a "quick and dirty" way to match GUID strings. To do the appropriate brace-matching and hyphen usage would be very convoluted in a regex (it would really be several expressions). According to the docs for `Guid(string)`, the hyphens are optional. – jheddings Nov 06 '09 at 16:57
0

You can write your own TryParse as a extension method for Guid. Then when the 'real' one from MS shows up, your already good to go and don't have to change.

ryber
  • 4,537
  • 2
  • 26
  • 50
  • 1
    Except that the extension method will only apply to a `Guid` instance, and the framework version will be static. – LukeH Nov 06 '09 at 16:30