Search code examples
c#classoopinstance

How can I instantiate a class with a method (if possible) in c#?


Say you had some sort of console-application game, and inside the game you create an object which would have it's own class. How would you make an instance of that class with something like a method or function while the game might still be running.

I've looked all over the internet and haven't found anything after weeks. Normally, I would just create an array for the class and add new instances to it like so.

class MyClass 
{
   //fields and methods
}

class Program 
{
   static void Main(string[] args) 
   {
      MyClass[] myClasses = new MyClass[16];
      myClasses.SetValue(new MyClass(), 0);
   }
}

But this feels clunky and inefficient. I hope I figure this out soon.


Solution

  • There are many ways to do this. The most common and accepted way may be the FactoryPattern.

    Create your factory:

    public static class MyClassFactory
    {
    
        public static MyClass CreateNew() {
            return new MyClass();
        }
        
        public static MyClass[] CreateRange(int amount) {
            
            var myArr = new MyClass[amount];
            
            for (int i = 0; i < amount; i++)
            {
                myArr[i] = new MyClass();
            }
            
            return myArr;
        }
    }
    

    Then simply call it in your code:

    class Program 
    {
       static void Main(string[] args) 
       {
          MyClass[] myClasses = MyClassFactory.CreateRange(16);
       }
    }