I am trying a create a variable Guid? which represents a nullable db column. I am facing issues while assigning values. I was able to assign null to the variable easily. But when I want to assign a Guid value I have to create a new Guid? object which doesn't accept the string.
Guid? sample=new Guid?(someString); // erroing "Cannot implicitly convert string to Guid"
So I have to do like this
Guid? sample=new Guid?(new Guid(someString)); // working code
I am also assigning values conditionally.
Guid? sample=(string.IsNullOrWhiteSpace(someString))?null: new Guid?(new Guid(someString));
Why is this issue coming up with Guid ?
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.