views:

670

answers:

3

This is driving me nuts. Perhaps I'm missing something obvious?

The fieldInfo.FieldType is correct (DateTime), and the value I'm applying is also a DateTime.

for(int i=0; i<objectArray.Length; i++)
{
    FieldInfo destinationField = GetFieldInfo(i);
    object destinationValue = objectArray[i];

    destinationField.SetValue(this, destinationValue);
}

Edit: even if I set destinationValue to a literal DateTime (DateTime.Now), I still get the exception!

+1  A: 

I am assuming that you want to set a property on your object and not a field (this might be your problem). If so then the following code might help?

public class Order
{
    public DateTime OrderDateField;
    public DateTime OrderDate { get; set; }
}

object[] orders = new[] { new Order(), new Order(), new Order() };
for (int i = 0; i < orders.Length; i++)
{
    FieldInfo fieldInfo = orders[i].GetType().GetField("OrderDateField");
    fieldInfo.SetValue(orders[i], DateTime.Now);

    PropertyInfo propertyInfo = orders[i].GetType().GetProperty("OrderDate");
    propertyInfo.SetValue(orders[i], DateTime.Now, null);
}

Is that the result you were trying to achieve?

Update: The above code updates both the property and field on the Order object.

Kane
Thanks, but it is a field and not a property
James L
Ok, is the field public?
Kane
It is, but even if it weren't I should be able to set it with a valid FieldInfo reference
James L
Does the updated code help?
Kane
Thanks, I was doing something like this but I tried the literal DateTime.Now value and it still threw the error. Perhaps my object reference (this) is the problem?
James L
It might be... perhaps you can not use reflection to set a field on the same object calling the SetValue() method? Sounds plausable?
Kane
Plausble I suppose... if unlikely?
James L
A: 

Change

destinationField.SetValue(this, destinationValue);

To

destinationField.SetValue(objectArray[i], destinationValue);

There was a comment asking about the 'this' reference, but I lack the rep to reply there.

Kleinux
this doesn't make any sense... destinationValue is equal to objectArray[i]
Thomas Levesque
A: 

OK, I've figured it out.

If you ever see this Exception, there's a good chance the the FieldInfos you are using do not belong to the same object as your target. cough

Sorry for being a clot, thanks to all who helped out.

James L