❔ How can I create a fill method that creates unique elements?

I have the following 2D array method that is for basic types and references.

        /// <summary>
        /// Fills the array with the given value.
        /// </summary>
        /// <param name="value">The value to fill with.</param>
        public void Fill(T value)
        {
            Array.Fill(m_array, value);
        }

This works when I want basic types and every reference value pointing to the same object. I want to keep this method for those, which is the most common.

However, I need a similar one that makes every element unique using new. For example, every Wall object in the array is unique. Each wall has its own properties. I do want the method generic so it allows any object of a class.

Here's the idea:

        /// <summary>
        /// Fills the array with unique values.
        /// </summary> 
       public void FillNew(T value)
        { 
            for (int i = 0; i < Size; i++)
                m_array[i] = new T(value); 
        }


Again, this is just example code of what I want to see happen, but it has a compile error that T does not have a new() constraint. Is there a good solution to this?

For reference, my class is written as this:

    class Array2D<T>
    {
        private T[] m_array;
        private int m_width, m_height;
Was this page helpful?