gog
gog

Reputation: 12978

Change property type using reflection

I have a decimal Value property in my domain class:

public class Domain
{
   public decimal Value {get;set}
}

I need to assign that Value property with two database values:

obj1.Value = decimal.Parse(reader["Value"].ToString());
obj2.Value = decimal.Parse(reader["Value2"].ToString());

Then I have a comparer method which compares these two properties:

public void Compare(List<object> Domains)
{
     //get properties with reflection

     //if the properties values are different I need to set a 'string' value [DIFFERENT]           to it.       
     prop.SetValue(comparableObj, "[DIFFERENT]", null);
}

Is it possible to do?

Upvotes: 0

Views: 815

Answers (2)

JaredPar
JaredPar

Reputation: 754525

This just simply isn't possible. The type of the property Value is set to decimal at compilation time and this cannot be changed at runtime. Instead you need to focus on converting the string value into a decimal value. That or picking a more suitable type for Domain.Value.

If you go the conversion route then I suggest looking at methods like Convert.ToDecimal

Upvotes: 2

Curtis Rutland
Curtis Rutland

Reputation: 786

I don't think it's possible to change a property's type at runtime. I do know that if it were possible, it would be a bad idea.

You're better off having another field that you store the comparison result in. Then later when you need to use that "[DIFFERENT]" value, check the field that you stored the result in, and use that instead.

Upvotes: 1

Related Questions