If I try to convert a nullable GUID ToString(), it works nicely but I try to remove the "hyphens" from the GUID by myGuid.ToString("N")
I get an IntelliSense error that reads: "No overload for method ToString method takes one arguments".
However, if I try to convert a regular (non-nullable) GUID to string with N formatter, it works fine.
Any idea how to make it work?
public void DoSomething(Guid regularGuid, Guid? nullableGuid)
{
if(nullableGuid != null)
{
var string1 = regularGuid.ToString("N"); // This works
var string2 = nullableGuid.ToString(); // This works also
var string3 = nullableGuid.ToString("N"); // This does NOT work
}
}
Nullable<T>
, which your Guid?
is, does not provide an overload for .ToString(string)
. It only provides the parameterless overload that every object has.
You can get what you want by using
var string4 = nullableGuid.Value.ToString("N");
This is guaranteed to work as you previously checked that nullableGuid is non-null.
Using C# 6 you could also write
var string4 = nullableGuid?.Value.ToString("N");
without the need for the separate null check.
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