trapemiyaの日記

hatenablogが新しくなったんで新規一転また2019年1月からちょこちょこ書いてます。C#中心のプログラミングに関するお話です。

依存関係プロパティ をコピペする時のミスによる実行時エラー

依存関係プロパティを以下のように定義したとします。

public class PersonFoo : DependencyObject
{
   #region 依存関係プロパティ dependency properties

    public static readonly DependencyProperty NameProperty =
        DependencyProperty.Register("Name", typeof(string), typeof(PersonFoo));
    public static readonly DependencyProperty AgeProperty =
        DependencyProperty.Register("Age", typeof(int), typeof(PersonFoo));

    #endregion
                     ・
                     ・
                     ・

同じように、PersonBarクラスを作成したいので、PersonFooをコピペしました。

public class PersonBar : DependencyObject
{
   #region 依存関係プロパティ dependency properties

    public static readonly DependencyProperty NameProperty =
        DependencyProperty.Register("Name", typeof(string), typeof(PersonFoo));
    public static readonly DependencyProperty AgeProperty =
        DependencyProperty.Register("Age", typeof(int), typeof(PersonFoo));

    #endregion
                     ・
                     ・
                     ・

typeof(PersonFoo)は正しくはtypeof(PersonBar)なのですが、うっかり修正し忘れてます。
このままでももちろんコンパイルは通ってしまいます。
そして実行時にPersonFooとPersonBarのインスタンスを作成しようとすると、
The type initializer for 'test2010wpf.PersonBar' threw an exception.
というエラーが発生してしまいます。同じtypeに同じ名前の依存関係プロパティを作成できないので当然ですね。
しかし、やっかいなのはこの実行時エラーが、PersonFooもしくはPersonBarのどちらかしかインスタンス化されない時は発生しないということなのです。したがってこの実行時エラーは、場合によってはアプリケーションのリリース後に発生しますので、気を付けなければなりません。