views:

636

answers:

3

What datatype should I use in C# to work with the SQL Server uniqueidentifier. Do I need any conversions etc ?

Thanks

+8  A: 

System.Guid.

No conversions needed.

codekaizen
Check this link if you have any other parameter data type mapping issues: http://msdn.microsoft.com/en-us/library/ms131092.aspx
Justin Niessner
+7  A: 

System.Guid

When reading nullable Uniqueidentifier columns from your database, be sure to check if the value is null before attempting to assign to a Guid instance, as Guids are not nullable. For example:

... /// using recordset rs


// generates exception if rs["my_guid"] is null
Guid g = (Guid)rs["my_guid"];

// returns Guid.Empty {0000000-.....} if db value is null
Guid g = (Guid)(rs["my_guid"] ?? Guid.Empty); 

etc.

David Lively
Just use Guid? A.K.A. Nullable<Guid> and you can assign null.
Daniel Brückner
That doesn't always work - ie, you'll have to wind up converting it to a non-nullable Guid at some point if you're passing to code that doesn't allow nullable Guids.
David Lively
Watch it: DBNull != null
Pierre-Alain Vigeant
+2  A: 

If you are getting the value from a SQLDataReader, make sure to check it against DBNull before you try to use it. Sometimes the value can be interpreted as a string as well, so you need to type New Guid(rs["my_guid"]) to make sure you have a guid to use in your code.

SilverSkin
login to comment on other answers
jinsungy
"login to comment on other answers" you see my username and icon, right? I'm logged in, but I don't have enough reputation to comment on other's posts...
SilverSkin
.Now you do. ftfy.
Chris Lively