I'm trying to use the propertyInfo.SetValue()
method to set an object property value with reflection, and I'm getting the exception "Object does not match target type". It doesn't really make sense (at least to me!) as I'm just trying to set a simple string property on an object with a string replacement value. Here's a code snippet - this is contained within a recursive function so there's a bunch more code, but this is the guts:
PropertyInfo fieldPropertyInfo = businessObject.GetType().GetProperties().FirstOrDefault(f => f.Name.ToLower() == piecesLeft[0].ToLower()); businessObject = fieldPropertyInfo.GetValue(businessObject, null); fieldPropertyInfo.SetValue(businessObject, replacementValue, null);
I've verified that businessObject" and
replacementValue` are both the same type by doing this comparison, which returned true:
businessObject.GetType() == replacementValue.GetType()
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
C is a structured, procedural programming language that has been widely used both for operating systems and applications and that has had a wide following in the academic community. Many versions of UNIX-based operating systems are written in C.
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
You're trying to set the value of the propertyinfo value's. Because you're overwriting the businessObject
PropertyInfo fieldPropertyInfo = businessObject.GetType().GetProperties() .FirstOrDefault(f => f.Name.ToLower() == piecesLeft[0].ToLower()); // The result should be stored into another variable here: businessObject = fieldPropertyInfo.GetValue(businessObject, null); fieldPropertyInfo.SetValue(businessObject, replacementValue, null);
It should be something like:
PropertyInfo fieldPropertyInfo = businessObject.GetType().GetProperties() .FirstOrDefault(f => f.Name.ToLower() == piecesLeft[0].ToLower()); // also you should check if the propertyInfo is assigned, because the // given property looks like a variable. if(fieldPropertyInfo == null) throw new Exception(string.Format("Property {0} not found", f.Name.ToLower())); // you are overwriting the original businessObject var businessObjectPropValue = fieldPropertyInfo.GetValue(businessObject, null); fieldPropertyInfo.SetValue(businessObject, replacementValue, null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With