Question

The code below runs fine on .Net 3.5:

PropertyInfo propertyInfo = typeof(int?).GetProperty("Value");
int? i = 5;
object o = propertyInfo.GetValue(i, null);

After running, o is of type int and has the value 5. Which is OK.

When I run the same code on .Net Compact Framework 3.5, I get an InvalidProgramException on the last line.

  • Why does that happen?
  • Is there anything I can do about it?
  • Is this a bug in .Net CF?

What I am doing currently is determining whether the Type I am dealing with is a System.Nullable<T> and the property I am getting has the name "Value" and then handle that case explicitly. But I would like to know whether there is a more simple solution.

The code I am writing parses an expression tree (we use a mono dll that implements System.Linq.Expressions on .Net CF). The problem occurs when I use reflection to get the value of a ConstantExpression that represents a nullable constant.

Was it helpful?

Solution

  • Why does that happen?
    Specifically because when you query it i is an int, not a nullable (go ahead and do i.GetType() and see what I mean) so the CF sees you trying to read a property that doesn't exist on the object you passed in
  • Is there anything I can do about it?
    It depends on your use-case. In this exact scenario, probably not - the framework behaves the way it does, and you're not able to change it. That said, I use nullable types in the OpenNETCF ORM, so I went and looked at how that works, and they "key" seems to be that the nullable types I support are properties in a class in my usage. So this works:

    class Foo
    {
        public int? i { get; set; }
    }
    
    static class Program
    {
        static void Main()
        {
            var f = new Foo();
            var p = f.GetType().GetProperty("i", 
                BindingFlags.Instance | BindingFlags.Public);
            f.i = 5;
            var v = p.GetValue(f, null);
            p.SetValue(f, 3, null);
        }
    }
    
  • Is this a bug in .Net CF?
    It's definitely a behavior difference. You'd have to look at the ECMA spec to see how it's supposed to behave. It's possible that it's actually not right on the desktop, or that the behavior isn't actually defined so neither one is "right" or "wrong". Amazingly, I've seen cases where the CF was right and the desktop was not.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top