226

I did not find the TryParse method for the Guid. I’m wondering how others handle converting a guid in string format into a guid type.

Guid Id;
try
{
    Id = new Guid(Request.QueryString["id"]);
}
catch
{
    Id = Guid.Empty;
}
leppie
  • 115,091
  • 17
  • 196
  • 297
DanH
  • 2,703
  • 3
  • 19
  • 10

6 Answers6

378
new Guid(string)

You could also look at using a TypeConverter.

leppie
  • 115,091
  • 17
  • 196
  • 297
  • 3
    Specifically, a GUIDConverter, which is built in. http://msdn.microsoft.com/en-us/library/system.componentmodel.guidconverter.aspx – Joseph Ferris Dec 08 '08 at 19:11
  • 3
    TypeDescriptor.GetConverter(typeof(Guid)) – leppie Dec 08 '08 at 19:34
  • @leppie can you tell me the pros and cons of using GUID as string rather then using as DataTyps GUID – cracker Jul 01 '14 at 04:27
  • I can tell you example: @cracker When you are making API and you wanna filter something by Guid (since its primary key in a table) what will you send from the front in a request? Most likely a string in URL, but on back in the controller you would most like wanna use it as Guid. As for speed comparison: https://stackoverflow.com/questions/713109/performance-using-guid-object-or-guid-string-as-key – DanteTheSmith Jul 13 '17 at 13:03
  • I would recommend @juFo answer with `TryParse()` or `TryParseExact()`. If you supply an invalid Guid you will get the following exception when trying to access it in a comparison or similar otherwise: FormatException: `Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).` – Ogglas Aug 13 '21 at 12:51
148

use code like this:

new Guid("9D2B0228-4D0D-4C23-8B49-01A698857709")

instead of "9D2B0228-4D0D-4C23-8B49-01A698857709" you can set your string value

TouchBoarder
  • 6,422
  • 2
  • 52
  • 60
Behrooz
  • 2,437
  • 3
  • 21
  • 31
32
Guid.TryParse()

https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparse

or

Guid.TryParseExact()

https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryparseexact

in .NET 4.0 (or 3.5?)

BCdotWEB
  • 1,009
  • 1
  • 14
  • 35
juFo
  • 17,849
  • 10
  • 105
  • 142
  • I had been using Guid.Parse, but I see Guid.TryParse will return a boolean indicating if it was successful. That would be better. – Rich Mar 23 '18 at 19:40
8

This will get you pretty close, and I use it in production and have never had a collision. However, if you look at the constructor for a guid in reflector, you will see all of the checks it makes.

 public static bool GuidTryParse(string s, out Guid result)
    {
        if (!String.IsNullOrEmpty(s) && guidRegEx.IsMatch(s))
        {
            result = new Guid(s);
            return true;
        }

        result = default(Guid);
        return false;
    }

    static Regex guidRegEx = new Regex("^[A-Fa-f0-9]{32}$|" +
                          "^({|\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\))?$|" +
                          "^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$", RegexOptions.Compiled);
Brian Rudolph
  • 6,142
  • 2
  • 23
  • 19
3

Unfortunately, there isn't a TryParse() equivalent. If you create a new instance of a System.Guid and pass the string value in, you can catch the three possible exceptions it would throw if it is invalid.

Those are:

  • ArgumentNullException
  • FormatException
  • OverflowException

I have seen some implementations where you can do a regex on the string prior to creating the instance, if you are just trying to validate it and not create it.

Joseph Ferris
  • 12,576
  • 3
  • 46
  • 72
0

If all you want is some very basic error checking, you could just check the length of the string.

              string guidStr = "";
              if( guidStr.Length == Guid.Empty.ToString().Length )
                 Guid g = new Guid( guidStr );