C# automating initializing variables?

Viewed 88

QUESTION: Is there a way to automate the initialization of variables, OR create a dictionary with multiple values? (I am using a Windows Form)

CONTEXT: I am creating a program w/ a basic UI that inputs textbook rental information. My plan was to create a "Textbook" object with the following properties:

    private String name;
    private String store;
    private String format;
    private String website;

    private Double price;

    private int timeSpan;  //in days
    private int startTime; //yyyymmdd
    private int endTime;   //yyyymmdd

My program will be comparing multiple textbooks that the user inputs.

DILEMMA: I will not know how many "Textbook" objects the user wants to create at the start. I want them to be able to add as many, whenever they would like. And for me to create an object, I need to name it. For example,

Textbook name = new Textbook();

I don't know how to assign this object a name. I thought of creating a dictionary, because the key can be a string that the user inputs, but there would be multiple values, and they would be varying in type (some String, some int, and a Double), so an Array or List wouldn't work.

Does anyone know how to do this, OR have an alternate solution to this problem?

Any help is much appreciated!! :)

1 Answers

You would typically create a model of your object. In this case:

 public sealed class Textbook
 {
    public string Name {get;set;}
    public string Store {get;set;}
    public string Format {get;set;}
    public string Website {get;set;}

    public double Price {get;set;}

    public TimeSpan TimeSpan {get;set;}  //in days
    public DateTime StartTime {get;set;} //yyyymmdd
    public DateTime EndTime {get;set;}   //yyyymmdd
}

I don't know how your form is set up, but it looks like it may be set up with a few text boxes. In that case, to instantiate a model, you would do this (for example, in a button click):

private readonly List<Textbook> _lstTextbooks = new List<Textbook>();

void OnAddTextbookButtonClicked(object sender, EventArgs args)
{
    var textbook = new Textbook
    {
        name = txtName.Text,
        store = txtStore.Text,
        format = txtFormat.Text,
        website = txtWebsite.Text,
        price = double.Parse(txtPrice.Text),
        // ...
    }
    
    _lstTextbooks.Add(textbook);
}

At this point, you have a list of textbook objects. What you do with that list is up to you.

Related