Ben Aston
Ben Aston

Reputation: 55729

Converting a Guid to Nullable Guid

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

new Guid?(new Guid(myString));

Upvotes: 15

Views: 18102

Answers (2)

Grzenio
Grzenio

Reputation: 36639

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);

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1499950

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)

Upvotes: 27

Related Questions