Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Converting string into nullable Guid?

Tags:

c#

guid

nullable

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.

like image 583
Tom Dee Avatar asked Aug 06 '26 13:08

Tom Dee


2 Answers

Alternatively, you can write your code like this:

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

whateverFunction(nullableGuid);
like image 70
Rudey Avatar answered Aug 08 '26 01:08

Rudey


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"]));
like image 40
SomeBody Avatar answered Aug 08 '26 01:08

SomeBody



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!