1

I cannot figure out why this is not working. Can anyone explain to me why SetValue does not set the value of my object's properties?

T row = new T();

foreach (PropertyInfo property in row.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
    Field[] dbFields = property.GetCustomAttributes(typeof(Field), false) as Field[];

    Object obj = (Int32)1000; // Arbitrary Value;
    Object castObj = Convert.ChangeType(obj, property.PropertyType);

    property.SetValue(row, castObj, null); // DOES NOT UPDATE row!! WHY!?
}

Any help is appreciated.

oleksii
  • 35,458
  • 16
  • 93
  • 163
MarkP
  • 4,168
  • 10
  • 43
  • 84
  • 1
    You're using an [evil mutable value type](http://stackoverflow.com/questions/441309/why-are-mutable-structs-evil). Don't. – SLaks Jan 03 '12 at 21:05

1 Answers1

4

It should work fine so long as T is a reference type (a class). It won't work as-is if T is a value type (a struct). The value will be boxed on each call to property.SetValue, and the existing value would remain untouched. Is it possible that that's the problem? If so, I'd urge you to avoid writing mutable value types in the first place - consider making it a reference type instead.

You could just force it to be boxed once, then unboxed once at the end - but if I were you I'd just steer well clear of mutable value types.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • This is exactly my problem, my objects are structs (I come form a C++ background and totally forgot that they are treated differently in C#). Thank you! – MarkP Jan 03 '12 at 21:00
  • @MarkP: So are you able to just change them to classes? Hopefully that should just solve your problem... – Jon Skeet Jan 03 '12 at 21:32