In the previous post copying values among object we saw the charm of looping. We’d managed to copy values of the objects from one to another without even knowing their properties. This is just a simple extension of it.
Actually the problem arises when we need to convert the value we are assigning to the property so that if matches the type of property. For example, consider the case we need to assign the value “true” to a Boolean variable. Now since the value “true” is of type string, therefore the assignation would be like assassination. There is a simple process though to check the type of the property, so that the value we are assigning it, can be converted into the proper type.
In context of the code of the post copying values among object we can figure out type of our property itemDestination like:
1: var destinationPropertyType = itemDestination.PropertyType();
Now since we know the type of the property we are going to set the value of, we can cast the value of the source property so as to match with the type of the destination property.
1: var originalValue = itemSource.GetValue(source, new object[] {}), new object[] {});
2: var castedValue = Convert.ChangeType(originalValue, destinationPropertyType);
The variable castedValue now possess the converted value as per the property type of the destination. This process comes in handy when we are copying value between objects which are not of same type. So we need to first convert the values to a proper format before assigning them.
0 comments