-2

I was wondering if anyone knows if you can instantiate a new object everytime a function is run?

Here is an example of what I'm trying to do. Except, I'm wondering what to do if we don't know the number of objects we want to make.

Basically, everytime a function is run, I want a new object to be instantiated. Is that possible?

Duane
  • 19
  • 5
  • Please be more specific. Why does the solution proposed in the linked thread not work for you? – Nico Schertler May 18 '18 at 21:16
  • @NicoSchertler The solution in the link doesn't work for me because I don't know the number of objects that I want to instantiate beforehand. The solution in the link assumes that you know how many objects you want to instantiate. – Duane May 18 '18 at 22:11

1 Answers1

1

Definitely, you can have a new object every time a function is called. You can have a Collection (e.g. ArrayList etc.) to store the new object.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace stackOverFlowAnswer
{
    class Program
    {
        // a collection to store all objects
        static ArrayList allObjects = new ArrayList();
        static void Main(string[] args)
        {
            // Call the object creation function whenever you want
            for (int i = 0; i < 5; i++)
            {
                createANewObject();
            }
        }

        // function that create an object at a time
        static void createANewObject()
        {
            YourObject newObject = new YourObject();
            allObjects.Add(newObject);
        }
    }

    // your object class
    class YourObject
    {

    }
}
Yuchao Zhou
  • 1,062
  • 14
  • 19
  • Wouldn't that throw some sort of error since each object would have the same name? – Duane May 18 '18 at 22:14
  • No. Not at all. If you want to sort those objects. You can write your own comparator to sort those objects base on any attributes in any order. Check this How to sort object array: https://stackoverflow.com/questions/1301822/how-to-sort-a-list-of-objects-by-a-specific-field-in-c – Yuchao Zhou May 18 '18 at 22:19