tags:

views:

37

answers:

1

I am trying to use reflection to get all the (settable) properties in my POCO (which take a string argument, for now, but I plan to expand to other types), and set them to something arbitrary. (I need to make sure the .Equals method is implemented properly.)

I have some code in my unit tests that looks something like this (where t is the object under test, and u is a default version of that object):

foreach(var property in t.GetType().GetProperties())
{
    var setMethod = property.GetSetMethod();
    var type = setMethod.GetParameters()[0].GetType();
    if(typeof(string).IsAssignableFrom(type))
    {
        setMethod.Invoke(t, new object[] {"a"});
        Assert.IsFalse(t.Equals(u));
        Assert.IsFalse(t.GetHashCode() == u.GetHashCode());
    }                    
}

The place where this fails is where I say typeof(string).IsAssignableFrom(type). The code inside the if { ... } block never runs. How would I properly code up this part of the test?

+4  A: 

You have confused ParameterInfo.GetType() with ParameterInfo.ParameterType. You should have:

var type = setMethod.GetParameters()[0].ParameterType;

.GetType() returns the Type of the current object, in this case ParameterInfo, which is obviously not what you want.

Kirk Woll
Works perfectly; thanks! I guess this is what happens when you use IntelliSense too much and the documentation too little. ;-)
Mike