System.Reflection.AmbiguousMatchException from xaml in Windows Phone

September 3, 2014

Lately I ran into a tricky bug inside a Windows Phone application. Sometimes an unhandled exception was thrown that caused the application to crash.

Looking into the logs showed that the exception was System.Reflection.AmbiguousMatchException which is caused when the reflection mechanism finds more than one option for a member in a class.

TL;DR; – Don’t bind in xaml to a property with new modifer 

The reason for the exception was that one of the team members decided to derive a class from some entity – lets call the entity Person.

public class Person
    public int Age { get; set; }

The team member noticed that there are times that Person don’t have an age, so he decided to create a derived class – AgelessPerson.
The only problem is that Age property isn’t virtual, so he decided to use the new modifer 

class AgelessPerson : Person
    public new int? Age { get; set; }

Inside the application we have a View that binds to a list of Person, and sometimes we get an object of type AgelessPerson.
When the Windows Phone xaml engine tries to bind to the Age property it finds 2 options – the nullable one and the not-nullable one – the engine cant decide which one to choose so it raises AmbiguousMatchException.

Conclussion: don’t use the new modifer. especially in properties that are being binded bound by xaml

I found that WPF doesn’t suffer from that problem but all the variations of Windows Phone does (8/8.1/silverlight/RT )

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>