I am not sure whether it is what you want, but I can propose to you the following wrapper class:
public class FixedArrayHolder<T>
{
public FixedArrayHolder(Int32 fixedLength, T[] array)
{
if (fixedLength < 0)
throw new ArgumentOutOfRangeException();
if (array == null)
throw new ArgumentNullException();
this.FixedLength = fixedLength;
this.Array = array;
}
public Int32 FixedLength
{
get;
private set;
}
private T[] m_array;
public T[] Array
{
get
{
return this.m_array;
}
set
{
if (value == null)
throw new ArgumentNullException();
if (value.Length != this.FixedLength)
throw new ArgumentException();
this.m_array = value;
}
}
public static implicit operator T[](FixedArrayHolder<T> fixedArray)
{
if (fixedArray == null)
return null;
return fixedArray.Array;
}
}
You can use this class in place of standard arrays:
// Works
var array = new FixedArrayHolder<Int32>(3, new Int32[] { 1, 2, 3 });
// Works
array.Array = new Int32[] { 3, 4, 5 };
// Fails
array.Array = new Int32[] { 1, 2, 3, 4 };
P.S.: You can extend it with some indexer and IEnumerable, IList members to allow more streamlined access to elements if it is required.
int[] array = { 1, 2, 3 }?