Reputation: 21
Hello everyone I am trying to cast two objects to, both, a specific type based on property reflection information. I want to do this dynamically so I don't need a bunch of switch cases and such for each type that the two objects can be in this class. Overall they will mostly be int or float. At the moment I currently tried using 'var' and 'object' keywords to hold the incoming adjustment value and the properties original value.
// .. snip
/* Get property information. */
PropertyInfo propInfo = classObj.GetType().GetProperty("property-name");
if (propInfo == null)
continue;
/* Prepare object values. */
object orgVal = propInfo.GetValue( classObj, null );
object adjVal = Convert.ChangeType( strAdjust, propInfo.GetType(), new CultureInfo("en-us"));
// .. math on objects here
// ex. orgVal += adjVal;
// .. snip
The incoming adjustment value is in a string but is either in 'int' or 'float' format so it will be easily converted. All of this works fine, it's just the casting to be allowed to adjust the original value with the new adjustment value that is the issue.
I know with .NET 4.0 there is the 'dynamic' keyword that would be able to accomplish something like this, but currently I am stuck using 3.5.
Both objects will use the type from the property information propInfo.GetType().
Any help with this would be greatly appreciated, I'm sure I'm probably overlooking a basic thing here to get this accomplished. Thanks in advance.
-CK
Edit:
Forgot to mention, sorry, this is being developed on a Zune HD, so the framework I have access to is fairly limited to what can/can't be used.
Upvotes: 1
Views: 2735
Reputation: 2027
C# 3.5 has a class called TypeConverter http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx
These provide a mechanism of converting from one type to another based on type information.
System.ComponentModel.TypeConverter GetConverter(System.Type type)
is used to get the converter and
public object TypeConverter.ConvertFrom(object value)
does the conversion. There are built in converters for basic types like int and float, and it is possible to write custom converters for your own types.
Microsoft has a guide to writing them here. http://msdn.microsoft.com/en-us/library/ayybcxe5.aspx
Upvotes: 2
Reputation: 72658
There's a couple of ways you can do this that I can think of. You can use reflection to get the "op_Addition" method (which is basically "operator +"). But the way I'd do it is via Lambdas:
var orgValueParam = Expression.Parameter(propInfo.PropertyType, "lhs");
var adjValueParam = Expression.Parameter(propInfo.PropertyType, "rhs");
var expr = Expression.Add(orgValueParam, adjValueParam);
var func = Expression.Lambda(expr, orgValueParam, adjValueParam).Compile();
var result = func(orgValue, adjValue);
Note: I haven't actually tested this, so I don't know whether it'll work for sure, but that's where I'd start...
Upvotes: 0