British Inside

An Englishman living in small town America

James Shaw

News

  • Copyright James Shaw 2004-2007

    Creative Commons License

    View James Shaw's profile on LinkedIn

System.Guid and SQL's uniqueidentifier

This was interesting - I had a uniqueidentifier as an output parameter from a sproc and wanted to put it into a Guid.

Guid guid = (Guid)sqlCmd.Parameters["@UserID"].Value;

No. That throws System.InvalidCastException : Invalid cast from 'System.String' to 'System.Guid'.

Ah, so it's a string, ok.

Guid guid = new Guid((string)sqlCmd.Parameters["@UserID"].Value);

Er, no. That throws System.InvalidCastException : Unable to cast object of type 'System.Guid' to type 'System.String'

Excuse me?? Is it a string or a Guid?

Well, apparently Guid's aren't your normal kind of bear. It's a class, it's a structure, it's a reference type depending on where you look. I couldn't be bothered to find the "real answer", but here's how I did the deed - kinda obvious NOW of course.

Guid guid = new Guid(sqlCmd.Parameters["@UserID"].Value.ToString()); 

The parameter value is a Guid type already you see, it's just that you cannot assign a Guid to a Guid. IMO that was a dumb first error message to show me ("can't cast string to Guid"), but all's well that ends well.


 

Posted: Wednesday, March 12, 2008 8:22 PM by James
Filed under: ,

Comments

Shawn Wildermuth said:

Guid.Parse?
# March 12, 2008 6:44 PM

Michael K. Campbell said:

Ha... I'm sure we've ALL bumped our heads into that one a few times. Sucking Guids out of DataReaders is also a bit less-than-obvious too - if I remember correctly.
# March 12, 2008 9:00 PM

Rich Mercer said:

Actually, although the DB will be returning a uniqueidentifier, "sqlCmd.Parameters["@UserID"].Value" returns "object" as it's not strongly typed. The Guid constructor only takes a "string", so that's why the first examples wouldn't work. You were trying to pass in the wrong type to the constructor, hence the compile time error. :)
# March 13, 2008 12:23 AM

James said:

what you talking about Rich? I passed in a string by casting it. If Guid's acted like a normal type that would have worked.

Shawn, there is no Guid.Parse. :D

# March 13, 2008 3:13 AM
New Comments to this post are disabled