views:

497

answers:

4

Hi There,

I'm using Reflection to set a property value via PropertyInfo.SetValue(); The property in question is a string, and the object from which I'm getting the value is actually a GUID. I'd like to convert from a GUID to a string in the process - is there any way of defining some kind of implicit cast which will enable this? At the moment I'm getting an error:

"Object of type 'System.Guid' cannot be converted to type 'System.String'."

I guess I could do a type check and manually convert if necessary, but if there's an elegant way of doing it behind the scenes then that would be preferable!

Many thanks.


Edit: I can't really just call the .ToString() method on a GUID as I'd very much like my code to look like this:

propertyInfoInstance.SetValue(classInstance, objectWithValue, null)

where objectWithValue is an int/bool/string/GUID. This works fine for everything except a GUID, as (I think!!) there's an implicit cast available. I could do a type check beforehand and just convert the GUID to a string, but I just get that "There must be a better way..." feeling.

+3  A: 

I don't believe there is an implicit cast between string and guid. Try this:

guid.ToString();

For question 2:

if(propertyInfoInstance.PropertyType == typeof(string) && objectWithValue != null)
{
    objectWithValue = objectWithValue.ToString();
}
propertyInfoInstance.SetValue(classInstance, objectWithValue, null);

I don't think it's too messy.

Jake Pearson
+1 This is correct. There is no implicit conversion between string and guid.
Adam McKee
+3  A: 

It's my understanding (someone please correct me if this is wrong,) that you can only define implicit cast operators for your own objects.

You'll need to manually handle dumping the GUID to a string w/ guid.ToString();

Yoopergeek
Unfortunately, I think this is correct.. The key seems to be that it's not possible to define an implicit cast in this case for the reasons you give, so I'm going to have to handle this case manually - trivial code, but messy!
Jon Artus
A: 

Have you tried .ToString() on the GUID reference?

eschneider
A: 

You can write something like this:

object myValue = /* source the value from wherever */;
if (!(myValue is string)) myValue = myValue.ToString();

Then call the PropertyInfo.SetValue() with myValue.

Jon Grant