How can I cast the result of an ExecuteScalar command to a GUID structure without first using .ToString() to pass to the constructor of the GUID?
The reason for doing this is performance and not creating thousands of unnecessary string objects in memory.
It is possible using a reader and the GetGUID Method but I can not see any references to how to achieve the same when using a scalar value.
Update: I also need to handle DBNull Values
Assuming that your sql statement cannot return DBNull.Value, then yes you can:
EDIT: Now that we know you need to handle nulls…. 🙂
I can think of two ways to handle nulls – use a nullable Guid and set it to null, or use a regular Guid and have it set to Guid.Empty if your SQL statement returns null.
Consider some form of helper function or extension method which checks for DBNull.Value.
or
Then call
Note – this will choke if your SQL command returns a datatype other than UniqueIdentifier.