Guid? sample = new Guid?(new Guid(someString));
This does not really make much sense. You have a nullable type to be able to store a null value. But when you are assigning a value anyway, then it won’t be null. A type’s constructor will actually never return null, so new Guid(someString)
will always return a valid Guid
—or throw an exception of course. As such, you can just assign the resulting Guid
to the variable of nullable type:
Guid? sample = new Guid(someString);
If you want to consider invalid input, e.g. if someString
is null or simply not a valid Guid
, then you can use Guid.TryParse
(.NET 4.0 or higher):
Guid? sample = null;
Guid parsed;
if (Guid.TryParse(someString, out parsed))
sample = parsed;
Note that this will allow you to remove any other check on someString
too. You can pass a null string or anything else in, and TryParse
will just return false, keeping sample
’s default value.