Saturday, 6 March 2010

Random Silverlight Exception: System.TypeInitializationException


I was stuck with a Silverlight exception in my code base for almost 2 days. I had no idea what was wrong, let alone get down to fixing it. Fervent googling did not yield desired results either. I did eventually fix it, in fact it was trivial, the problem however is the fact that Visual Studio 2008 gives the most retarded messages, especially when your bug lies at the point where xaml and code meet.
The exception that turns up is
System.TypeInitializationException: The type initializer for '_insert_your_type_here' threw an exception ---> System.ArgumentException: Default value type does not match type of property. 

All it turned out to be was a ‘double’ and ‘int’ mis-match in my case, i.e. the default value used to initialize a dependency property did not match the type the dependency property was initialized to be off. I group my constants in one place in a separate class so that a change in one place is reflected across the application aka no magic values. I had made a mistake by making my default declaration of double type and the dependency property of integer type, hence the error. Here are the code snippets in question.
Constant:
internal static readonly double Divisions = 0;

Dependency property:
        public int Divisions
{
get { return (int)GetValue(DivisionsProperty); }
set { SetValue(DivisionsProperty, value); }
}
public static readonly DependencyProperty DivisionsProperty =
DependencyProperty.Register("Divisions", typeof(int), typeof(Axis),
new PropertyMetadata(DefaultAxisProperties.Divisions, new PropertyChangedCallback(OnDivisionsChanged)));

private static void OnDivisionsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((Axis)d).OnDivisionsChanged(e);
}

protected virtual void OnDivisionsChanged(DependencyPropertyChangedEventArgs e)
{
}



I eventually fixed this with the help of svn diff, comparing the last working version of the class with the current one. Instead of ploughing through 4-5000 lines of code and about 500 lines of xaml, the diff reduced it too a few small hot spots that had changed between the versions, and made eventually spotting this bug possible.

Maybe the exception makes it obvious what was wrong, it wasn’t the case for me though, maybe it was just one of those things you get stuck with.

No comments:

Post a Comment