Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a Guid to Nullable Guid

Tags:

c#

guid

nullable

Is this an idiomatic way to convert a Guid to a Guid??

new Guid?(new Guid(myString));
like image 886
Ben Aston Avatar asked Feb 04 '10 11:02

Ben Aston


People also ask

Can GUID be nullable?

A Guid is a struct , those can't be null.

Can I convert a string to GUID?

The Parse method trims any leading or trailing white space from input and converts the string representation of a GUID to a Guid value. This method can convert strings in any of the five formats produced by the ToString(String) and ToString(String, IFormatProvider) methods, as shown in the following table.

What is the value of GUID empty?

You can use these methods to get an empty guid. The result will be a guid with all it's digits being 0's - " 00000000-0000-0000-0000-000000000000 ". In newer C# versions, default(Guid) and default are the same, too.


2 Answers

No, this is:

Guid? foo = new Guid(myString);

There's an implicit conversion from T to Nullable<T> - you don't need to do anything special. Or if you're not in a situation where the implicit conversion will work (e.g. you're trying to call a method which has overloads for both the nullable and non-nullable types), you can cast it:

(Guid?) new Guid(myString)
like image 103
Jon Skeet Avatar answered Sep 22 '22 22:09

Jon Skeet


just cast it: (Guid?)(new Guid(myString))

there is also an implicit cast, so this would work fine as well: Guid? g = new Guid(myString);

like image 26
Grzenio Avatar answered Sep 21 '22 22:09

Grzenio