views:

152

answers:

4

Hi,

I have an method that takes in an observable collection (returned from a webservice) of objects and analyzes them according to their attributes.

Here is the code snippet from the method

private double analyze(ObservableCollection mobjColl) {

        FieldInfo fi = null;

        foreach (MyApp.MyObj oi in mobjColl)
        {

        if(oi.pressure.Equals("high"){

            fi = oi.GetType().GetField("air");

            .....
        }
        }
        return someval;
    }

My problem is that the fieldinfo fi is always null. I can access every field of the object (within foreach) using the objects name however the fieldinfo object is never populated. I even tried using GetFields method but it does not return an array...

P.S : the object fields are public. Using bindingflags in getfield didnt help either.

+1  A: 

GetField/GetFields without BindingFlags only look for public fields. My guess is "air" is a private field.

Instead try this:

oi.GetType().GetField("air", BindingFlags.Instance | BindingFlags.NonPublic);

Tinister
Hi,,I forgot to mention ... the fields are public.. I tried using binding flags but that didnt work either.....thanx
A: 

Is the field air private? If so you'll have to use the overload of GetField which accepts the BindingFlags parameter and specify NonPublic

fi = oi.GetType().GetField("air", BindingFlags.NonPublic | BindingFlags.Instance);
JaredPar
A: 

If the field isn't public, you may need to use BindingFlags as by default only public fields are included.

fi = oi.GetType().GetField("air", BindingFlags.Instance | BindingFlags.NonPublic);
g .
+1  A: 

I don't believe objects returned from web services expose public fields. You might be thinking of properties instead. If you try GetProperty("air") you'll probably get something back.

Tinister
that worked.... thanks