クラスの用途が明確で、呼び出し元クラスがどんな呼び出ししてくるかわかんない、ならコンストラクタで歯止めすれば自クラスはしんどくないよねw
規定サイズの配列をもつクラスのコンストラクタで、配列サイズを必ず受け取って、それが規定内でないなら例外しようと思ったの。
ま、そう考えた経緯はこの例外クラス、TypeInitializationException を見つけたからなんだけど。
https://docs.microsoft.com/ja-jp/dotnet/api/system.typeinitializationexception?view=netstandard-2.0
今回の場合、InnerExceptionに ArgumentOutOfRangeException を仕掛けるのも筋だよね。
で、つくってみた。中身は-1で初期化なw どっかの話で書いた一行コードw
public class TypeInitSampleWithList
{
private int[] _myList;
public int[] MyList => _myList;
public TypeInitSampleWithList(int size)
{
if ((size < 1) || (16 < size))
{
throw new System.TypeInitializationException (typeof(TypeInitSampleWithList).FullName,
new System.ArgumentOutOfRangeException());
}
_myList = Enumerable.Repeat(1, size).Select(f => -1).ToArray();
}
}
んでもって、テストコードは2つ。ふつーにインスタンス返すのと、例外するのと。NUnitって書くコード少なくていいわぁ。
[Test]
public void SampleConstructorTest([Range(2,16)]int prm1)
{
TypeInitSampleWithList act = new TypeInitSampleWithList(prm1);
Assert.NotNull(act);
Assert.AreEqual(act.MyList.Length, prm1);
Assert.IsTrue(act.MyList.All(f => f == -1));
}
[Test]
public void SampleConstructorExceptionTest([Values(-1, 0, 17)]int prm1)
{
TypeInitializationException ex = Assert.Throws<TypeInitializationException>(() => new TypeInitSampleWithList(prm1));
Assert.AreEqual(ex.TypeName, typeof(TypeInitSampleWithList).FullName);
Assert.That(ex.InnerException, Is.TypeOf<ArgumentOutOfRangeException>());
}
作ってビルドしたらそのまま自動実行。dotnet test コマンド様様v

結果はグリーンだよ。うひょひょ。