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.
Alternatively, you can write your code like this:
var nullableGuid = Guid.TryParse(request.QueryStringParameters["key"], out var result)
? result
: (Guid?)null;
whateverFunction(nullableGuid);
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"]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With