Why would the cast (to a System.Guid type) statement be invalid (second line in try block)?
For example, suppose I have a string with a value of "5DD52908-34FF-44F8-99B9-0038AFEFDB81". I'd like to convert that to a GUID. Is that not possible?
Guid ownerIdGuid = Guid.Empty; try { string ownerId = CallContextData.Current.Principal.Identity.UserId.ToString(); ownerIdGuid = (Guid)ownerId; } catch { // Implement catch }
Program to convert string into guid in . Net Framework using C# Guid. Parse method. This method contains two parameters string as an input and if this method returns true then result parameter contains a valid Guid and in case false is returned result parameter will contain Guid.
A GUID is a 16-byte (128-bit) number, typically represented by a 32-character hexadecimal string.
The Parse method trims any leading or trailing white space from input and converts the string representation of a GUID to a Guid value. This method can convert strings in any of the five formats produced by the ToString(String) and ToString(String, IFormatProvider) methods, as shown in the following table.
An integer uses 32 bits, whereas a GUID is 128 bits - therefore, there's no way to convert a GUID into an integer without losing information, so you can't convert it back. EDIT: you could perhaps store the GUID into a GUIDs table where you assign each a unique integer ID.
Try this:
Guid ownerIdGuid = Guid.Empty; try { string ownerId = CallContextData.Current.Principal.Identity.UserId.ToString(); ownerIdGuid = new Guid(ownerId); } catch { // implement catch }
Try this:
ownerIdGuid = Guid.Parse(ownerId);
ownerId
is a string, you cannot cast it to a Guid
directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With