Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guid? value ToString("N") not working

Tags:

c#

guid

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
   }
}
like image 426
Sam Avatar asked Dec 25 '22 08:12

Sam


1 Answers

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.

like image 93
Eric J. Avatar answered Jan 09 '23 21:01

Eric J.