Jump to content

Dynamic class instantiation

- - - - -

  • Please log in to reply
2 replies to this topic

#1
Bull3t09

Bull3t09

    Newbie

  • Members
  • Pip
  • 8 posts
Okay, say I have a user defined class called ClassA. In the main function I display a menu, that allows the user to make a new instance of ClassA or exit the program. If the user selects create a new instance, how would I handle that? The program would have to somehow name the variable of data type ClassA and call it's constructor and then store it in an array. Any help would be appreciated.

#2
Momerath

Momerath

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 242 posts
If you have an array (or a List<T>) then you don't need to name the variable. To add a new ClassA to a List<ClassA> you would use:
// somewhere in your code you have a
List<ClassA> myListA = new List<ClassA>();

// then in your method you just need to do:
myListA.Add(new ClassA());


#3
Bull3t09

Bull3t09

    Newbie

  • Members
  • Pip
  • 8 posts
Ahh makes much more sense. I'm still used to C++ and just started C# about a week ago, so it's a little different. But thank you for your input!




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users