tags:

views:

52

answers:

1

I am trying to write my first WCF Service. Right now I just want to take a bunch of properties of an object and write them to SQL Server. Not all the property values will always be set so I would like to receive the object on the service side, loop through all the properties on the object and if there are any of a string datatype that are not set, set the value to "?". All the properties of object are defined of type string

I am trying the following code found here but get the error "Object does not match target type." on the line indicated below

        foreach (PropertyInfo pInfo in typeof(item).GetProperties())
        {
            if (pInfo.PropertyType == typeof(String))
            {
                if (pInfo.GetValue(this, null) == "")
                //The above line results in "Object does not match target type."
                {
                    pInfo.SetValue(this, "?", null);
                }
            } 
        }

How should I be checking if a property of string type on an object has not been set?

+2  A: 

The value returned from PropertyInfo.GetValue is object. However, since you know the value is a string (because you checked in the line above) you can tell the compiler "I know this is a string" by doing a cast:

if (pInfo.PropertyType == typeof(String))
{
    string value = (string) pInfo.GetValue(this, null);
    if (value == "")
    {

Also, I would add an extra null check in there, just in case the value is null or empty. Luckily, there's the string.IsNullOrEmpty method for that:

if (pInfo.PropertyType == typeof(String))
{
    string value = (string) pInfo.GetValue(this, null);
    if (string.IsNullOrEmpty(value))
    {
Dean Harding