1

Is there an easier way of converting a string into a Guid?? Just now I have this code:

if (Guid.TryParse(request.QueryStringParameters["key"], out Guid result))
{
    whateverFunction(result);
}
else
{
    whateverFunction(null);
}

I was hoping there would be an easier way such as casting to (Guid?) or doing new Guid?() however neither of them seem to work. This needs to happen a lot of times in my program, obviously I can just put it in a function and that would be fine but hoping there is a cleaner way of doing this.

Tom Dee
  • 2,516
  • 4
  • 17
  • 25

3 Answers3

4

Alternatively, you can write your code like this:

var nullableGuid = Guid.TryParse(request.QueryStringParameters["key"], out var result)
    ? result
    : (Guid?)null;

whateverFunction(nullableGuid);
Rudey
  • 4,717
  • 4
  • 42
  • 84
2

Just write your own method:

public Guid? TryParseGuid(string input)
{
   if (Guid.TryParse(input, out Guid result))
   {
       return result;
   }
   else
   {
       return null;
   }
}

You can use it the following way:

whateverFunction(TryParseGuid(request.QueryStringParameters["key"]));
SomeBody
  • 7,515
  • 2
  • 17
  • 33
1

if your application is heavily used string guids, then use extension instead :

public static class AppExtension
{
    public static Guid? ToGuid(this string source)
    {
        return Guid.TryParse(source , out Guid result) ? (Guid?) result : null;
    }
}

usage would be :

var guidStr = "6b97c671-8cc4-4712-b3df-9dad09321a36";
var guid = guidStr.ToGuid();
iSR5
  • 3,274
  • 2
  • 14
  • 13