Reflection and other gotchas on Windows Phone 7

As you have probably read already, I've been trying to port Autofac over to the Windows Phone platform. While getting most of it up and running has been ok, thanks to ideas and some code from a few people (like Nick) things are looking up. There are however a number of cases where code in the Windows Phone environment just doesn't behave like expected. I'd like to present some of these below.

Contra and Covariance
Turn it off in resharper, simply stay away. Even though your code will compile fine, everytime the phone goes to execute, you will be sitting there scratching your head over why you are getting a 'TypeLoad' exception that seemingly blows up from nowhere.

Default value parameters
Yes they compile, but always return 'null'.

MakeArrayType()
Not sure how many people use this day to day, however in some situations, it'll work, for some types it simply returns 'null'.
Example: typeof(Func<object>).MakeArrayType()
Work around might be to use: typeof (IEnumerable<>).MakeGenericType(typeof(Func<object>));

Reflection and Non-public types
At times, this can be annoying, you can't access, instantiate, get values or do pretty much anything to a non-public member. The call will result in a variant of a MemberAccessException.

Complex Generics:
If you crack open the Autofac test suite, there's a few tests under the name 'complex generic tests' that fail on windows phone. All these tests pass if run in Resharper's test runner in Visual Studio. So here's an example of the reflected type information being returned differently, specifically in the Phone environment.

Given the code:

public interface IBase<T2, T3> { }
public class ReverseBase<T2, T1> : IBase<T1, T2> { }


Now in normal conditions,

typeof(ReverseBase<string, int>).GetInterfaces()[0].GetGenericArguments()


returns two arguments with names as you'd expect (those from IBase; T1 = int, T2 = string),
however, in WindowsPhone land (T2, T3) are returned...
So it would seem that the interface being returned is the actual interface definition, instead of the interface with the generic parameters that have been mapped to it from the implementing type.

When do IoC containers use this kind of code, it's not really that hard to imagine, as Nick explained in this post with the Parameter Binder Solver.

Read More
Differences Between Silverlight on Windows and Windows Phone

WP7 Mobile
Posted by: Brendan Kowitz
Last revised: 21 Sep 2013 12:13PM

Comments

No new comments are allowed on this post.