Question

I tried adapting this tutorial from CodeProject to try and change a dynamic which will in this case be an int to a simple Enum.

If we define the Enum like so:

public Enum MyEnum { Zero = 0, One = 1, Two = 2 }

And the contents of a method to set the value of a MyObject class which contains an MyEnum:

var baseType = propertyInfo.PropertyType.BaseType; //`propertyInfo` is the `PropertyInfo` of `MyEnum`

var isEnum = baseType != null && baseType == typeof(Enum); //true in this case

dynamic d;

d = GetInt(); 

//For example, `d` now equals `0`

if (isEnum)
    d = Enum.ToObject(propertyInfo.PropertyType, (int)d); 

//I can see from debugger that `d` now equals `Zero`

propertyInfo.SetValue(myObject, d); 

//Exception: Object does not match target type

Any ideas as to why this is happening?

Was it helpful?

Solution

"Object does not match target type" indicates that myObject is not an instance of the type that propertyInfo was obtained from. In other words, the property you are trying to set is on one type, and myObject is not an instance of that type.

To illustrate:

var streamPosition = typeof(Stream).GetProperty("Position");

// "Object does not match target type," because the object we tried to
// set Position on is a String, not a Stream.
streamPosition.SetValue("foo", 42);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top