If your custom code is just to populate the array, C# provides several built in ways to do this (see All possible C# array initialization syntaxes).
If you want to have code execute every time you create an instance of a particular kind of object, you should make a class that represents that object (you might be able to do an extension method as well, but that would likely get confusing over time). This class might be nothing more than a wrapper around an array:
public class MyArray<T>
{
private T[] _array;
public MyArray()
{
// execute your always must run code here!
}
public ArrVal
{
get { return _array; }
set { _array = value; }
}
}
...
MyArray<int> myArray = new MyArray<int>(); // your custom code gets executed when you new up the object here
However, per best practices, you should avoid having code in a constructor that does too much work (and in my experience, having a constructor that throws exceptions can cause some problems that are hard to debug, although MSDN says it's better to throw the exception than to cover it up). If this code is going to be doing intensive work, it may be better to create a separate method (maybe something called public void Initialize()
) so that callers can new up the object more lazily.
You should also avoid trying to have this done for all arrays, because I can guarantee it'll cause problems for you or someone else down the road when they can't figure out why int[] arr = new int[3]
is doing extra stuff. You should look to properly use encapsulation here instead (i.e. creating a wrapper/extension/decorator class).
Also, it's entirely possible that one of the existing .NET classes for Collections fulfills your needs... Look into those.