Dear Friends,
how can I make an array of classes in c#?
please give me a typical syntax. tnx...
Dear Friends,
how can I make an array of classes in c#?
please give me a typical syntax. tnx...
I personally prefer to use lists rather than arrays.
Suppose you have this class:
I would create a list that can hold different cars:Code:using System.Drawing; namespace MyProgram { public class Car { public Color Color; public string Make; public string Model; } }
Then you can create a method that creates your different "cars" and adds them to the list:Code:List<Car> NewCars = new List<Car>();
Hope that helps. Of course, you would be better off setting up a constructor and passing the information that is needed to make that instance of the class, rather than making everything public, but I used this just to demonstrate the idea.Code:private void CreateCar(Color color, string make, string model) { Car car = new Car(); car.Color = color; car.Make = make; car.Model = model; NewCars.Add(car); }
If you want to make an array of classes it would be like this:
Code:Car[] carArray = new Car[10]; for(int i = 0;i < carArray.Length;++i) carArray[i] = new Car();
If you understand what you're doing, you're not learning anything.
Last edited by Phyxashun; 10-27-2010 at 11:15 AM. Reason: Fixing what I wrote
Thank you for anwsering to me.
If you want to do that, you just need to make sure your array is of a common base type:
If, for instance, you had a Mustang class that derived from a Ford class that derived from a Car class.Code:Car[] carArray = new Car[10]; carArray[0] = new Ford(); carArray[1] = new Mustang(); carArray[2] = new Chevy(); ...
If you understand what you're doing, you're not learning anything.
I apologize if this is beyond the scope of your question, but how about you use a factory pattern?
Exploring the Factory Design Pattern
"Hence to fight and conquer in all your battles is not supreme excellence;
supreme excellence consists in breaking the enemy's resistance without fighting."
Art of War Sun Tzu