my problem is as follows:
Im building a console application which asks the user for the numbers of objects it should create and 4 variables that have to be assigned for every object.
The new objects name should contain a counting number starting from 1.
How would you solve this?
Im thinking about a class but im unsure about how to create the objects in runtime from userinput. Is a loop the best way to go?
What kind of class, struct, list, array …. would you recommend. The variables in the object are always the same type but i need to name them properly so I can effectivly write methods to perform operations on them in a later phase of the program.
Im just learning the language and I would be very thankful for a advice on how to approach my problem.
If I understand your problem correctly:
This doesn’t quite do what you described. Add in keyboard input and stuff 🙂 Most of this code needs to be in some kind of
Mainmethod to actually run, etc.In this case, I’ve chosen a
classto hold your 4 variables. I have only implemented 3 though, and I’ve implemented them as properties, rather than fields. I’m not sure this is necessary for your assignment, but it is generally a good habit to not have publically accessible fields, and I don’t want to be the one to teach you bad habits. See auto-implemented properties.You mentioned a
struct, which would be an option as well, depending on what you want to store in it. Generally though, a class would be a safer bet.A loop would indeed be the way to go to initialize your objects. In this case, a
forloop is most practical. It starts counting at0, because we’re putting the objects in an array, and array indexes in C# always start at0. This means you have to usei + 1to assign to the object number, or the objects would be numbered 0 – 9, just like their indexes in the array.I’m initializing the objects using object initializer syntax, which is new in C# 3.0.
The old fashioned way would be to assign them one by one:
Alternatively, you could define a constructor for
MyClassthat takes 3 parameters.One last thing: some people here posted answers which use a generic List (
List<MyClass>) instead of an array. This will work fine, but in my example I chose to use the most basic form you could use. A List does not have a fixed size, unlike an array (notice how I initialized the array). Lists are great if you want to add more items later, or if you have no idea beforehand how many items you will need to store. However, in this case, we have the keyboard input, so we know exactly how many items we’ll have. Thus: array. It will implicitly tell whoever is reading your code, that you do not intend to add more items later.I hope this answered some questions, and raised some new ones. See just how deep the rabbit hole goes 😛