15

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

new Guid?(new Guid(myString));
D Stanley
  • 149,601
  • 11
  • 178
  • 240
Ben Aston
  • 53,718
  • 65
  • 205
  • 331

2 Answers2

27

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)
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

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

Grzenio
  • 35,875
  • 47
  • 158
  • 240