The background...
Lets say I have a class called cars. We are just going to store the car name and an ID. Lets also say I have an admin page based on an admin class that I set the total number of cars I want to create in an int called totalCars
The question: How do I dynamically create cars as fields that can be accessed from anywhere in the code, while at the same time creating a total number of cars based on the number in totalCars?
example code:
Cars car1 = new Cars();
int totalCars;
//Somehow I want to create cars objects/fields based on the
//number in the totalCars int
protected void Page_Load(object sender, EventArgs e)
{
car1.Name = "Chevy";
car1.ID = 1;
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = car1.Name.ToString();
//this is just a sample action.
}
This should de the trick:
int CarCount = 100;
Car[] Cars = Enumerable
.Range(0, CarCount)
.Select(i => new Car { Id = i, Name = "Chevy " + i })
.ToArray();
Regards GJ
Edit
If you just want to know how you would do such a thing (which you shouldn't), try this:
using System.IO;
namespace ConsoleApplication3 {
partial class Program {
static void Main(string[] args) {
Generate();
}
static void Generate() {
StreamWriter sw = new StreamWriter(@"Program_Generated.cs");
sw.WriteLine("using ConsoleApplication3;");
sw.WriteLine("partial class Program {");
string template = "\tCar car# = new Car() { Id = #, Name = \"Car #\" };";
for (int i = 1; i <= 100; i++) {
sw.WriteLine(template.Replace("#", i.ToString()));
}
sw.WriteLine("}");
sw.Flush();
sw.Close();
}
}
class Car {
public int Id { get; set; }
public string Name { get; set; }
}
}
Note the keyword partial class, this mean that you can have a class that spans multiple source files. Now you can code one by hand, and generate the other.
If you run this code it will generate this code:
using ConsoleApplication3;
partial class Program {
Car car1 = new Car() { Id = 1, Name = "Car 1" };
Car car2 = new Car() { Id = 2, Name = "Car 2" };
...
Car car99 = new Car() { Id = 99, Name = "Car 99" };
Car car100 = new Car() { Id = 100, Name = "Car 100" };
}
You can the add this code file to your solution (right click project.. add existing..) and compile it. Now you can use these variables car1 .. car100.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With