Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an object to System Guid

Tags:

c#

Guid mainfolderid = (main.GetValue(""));

where main is a dynamic entity.

How can I convert the above mentioned main.GetValue("") to System.Guid?

The error says

Cannot implicitly convert type object to 'System.Guid'.

like image 709
Ashutosh Avatar asked Sep 27 '10 16:09

Ashutosh


People also ask

How to convert an object to Guid in c#?

try it: Guid taskid; taskid = new Guid(keyValues[i]. Value.

Can I convert a string to GUID?

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.


4 Answers

Does the GetValue method actually return a Guid typed as object? If so, then you just need to perform an explicit cast like so:

Guid mainfolderid = (Guid)main.GetValue("");

If not, does GetValue return something that can be passed to one of the constructors (ie, a byte[] or string)? In that case you could do this:

Guid mainfolderid = new Guid(main.GetValue(""));

If neither of the above are applicable then you're going to need to do some manual work to convert whatever's returned by GetValue to a Guid.

like image 136
LukeH Avatar answered Oct 16 '22 21:10

LukeH


Guid mainfolderid = new Guid(main.GetValue("").ToString());
like image 32
Dustin Laine Avatar answered Oct 16 '22 22:10

Dustin Laine


If you're using .Net 4.0, there were Parsing methods added to the Guid struct:

Guid Guid.Parse(string input)

and

bool Guid.TryParse(string input, out Guid result)

will do what you want.

like image 5
Matt Mills Avatar answered Oct 16 '22 20:10

Matt Mills


One way is to use the GUID constructor, and pass it a string representation of the GUID. This will work if the object is really a string representation of GUID. Example:

Guid mainfolderid = new Guid(main.GetValue("").ToString());
like image 1
ChessWhiz Avatar answered Oct 16 '22 20:10

ChessWhiz