© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
23 replies
triplemocha

❔ 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);
        }
        /// <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
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); 
        }
        /// <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;
    class Array2D<T>
    {
        private T[] m_array;
        private int m_width, m_height;
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ How can you create a string that creates random characters?
C#CC# / help
3y ago
❔ How can i acces to a Method that is internal?
C#CC# / help
3y ago
can i create like that generic?
C#CC# / help
4y ago
how can i add a function/method to a class that can be changed upon construction?
C#CC# / help
3y ago