Asad
Asad

Reputation: 21918

SQL Server unique-identifier equivalent in C#

What datatype should I use in C# to work with the SQL Server uniqueidentifier.

Do I need any conversions etc ?

Upvotes: 24

Views: 21617

Answers (3)

codekaizen
codekaizen

Reputation: 27419

System.Guid

No conversions needed.

Upvotes: 25

Kalle
Kalle

Reputation: 2293

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.

Upvotes: 2

3Dave
3Dave

Reputation: 29041

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.

Upvotes: 15

Related Questions