Chris Carberry
Chris Carberry

Reputation: 29

Class with multiple objects or list

I am new to OOP and C# so have what is potentially a noob question.

Looking at classes all the code I see requires the object names to be hardcoded. Say for example we don't know how many Customers a user will enter and what their names are. So how does that work with creating instances of a class?

Is it the case that you would only create one class of customer as a data type (with methods as required) and store them in say a list? Or can a class hold multiple instances of an object but create them and name them dynamically in relation to user input?

I've not quite got my head around how a class works with holding records in memory etc.

Upvotes: 1

Views: 5687

Answers (4)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112752

Note that a class is a type. You can think of it as template used to create objects (also called instances of this class). So, you can have many different objects of the same class.

You can differentiate between different objects of the same class by assigning them to different variables:

Customer a = new Customer { Name = "customer a" };
Customer b = new Customer { Name = "customer b" };

This has its limits, of course, as you do not want to declare one thousand variables when you have one thousand customers!

Here, collections come into play. Store the customers in a collection. There are many different collection types. Probably the 2 most popular are List<T> and Dictionary<TKey, TValue>.

List<T> where T is a type (Customer in your case):

List<Customer> customers = new List<Customer>();

Customer c = new Customer { Name = "My first customer" };
customers.Add(c);

// You can re-use the same variable for another customer.
c = new Customer { Name = "My second customer" };
customers.Add(c);

// Or skip the temporary variable alltoghther.
customers.Add(new Customer { Name = "My third customer" });

The customer in the list can be accessed through a zero-based index

Customer c = list[5]; // Get the 6th customer

Lists can also be enumerated:

foreach (Customer cust in customers) {
    Console.WriteLine(cust.Name);
}

Dictionary<TKey, TValue>: dictionaries allow you to lookup a customer by a key, e.g. a customer number.

Dictionary<string, Customer> customers = new Dictionary<string, Customer>();

Customer c = new Customer { Id = "C1", Name = "My first customer" };
customers.Add(c.Id, c); // The Id is used as key, the customer object as value.

Then you can get it back with

Customer c = customers["C1"];

This throws an exception if the supplied key is not existing. To avoid an exception you can write:

string id = "XX";
if (customers.TryGetValue(id, out Customer cust)) {
    Console.WriteLine(cust.Name);
} else {
    Console.WriteLine($"Customer '{id}' not found");
}

    

Upvotes: 3

Michael Puckett II
Michael Puckett II

Reputation: 6749

To help you understand a class first.

A class is a blueprint of what the data will look like. If you were to build, a house for example, you would first make the blueprints. Those prints could be used to make many houses that look that same. The differences in those houses vary in areas such as color, wood, brick, or vinyl, and if is has carpet or not. This is just an example but let's make this house into a class (blueprint) and then let's make several of those houses into actual individual objects; finally let's reference all of those in the same location (using a list).

First let's decide what our house options are, the things that set them apart. It's color, exterior, and with or without carpet. Here we will make color a string (text) for simplicity, the exterior as an enum ( so the options are hard coded), and the carpet or not a bool (true or false).

First let's make the enum since it is separate than a class but used within a class.

public enum Exterior { Brick, Vinyl, Wood }

Now let's make the class (the blueprint).

public class House 
{
    public string Color { get; set; }
    public Exterior Exterior { get; set; }
    public bool HasCarpet { get; set; }
}

Now that we have the blue print let's actually make some houses. When we make them we need to have a way to locate them in memory so we assign them to a variable. Let's pretend we are in a console app and this is the first few lines of the main method.

var house1 = new House();
var house2 = new House();
var house3 = new House();

Now we have 3 individual houses in memory and can get to any of them by referencing house1, house2, or house3. However, these houses are still built identical and unfortunately have no color (since the string Color is empty), are default to Brick (since the first enum is Brick), and have no carpet (since HasCarpet defaults to false).

We can fix this by referencing each house object reference and assigning these values like so...

house1.Color = "Red";
house1.Exterior = Exterior.Wood;

We could have given the classes a constructor that required these values as parameters to start with or we can do it a simpler way inline (thanks to the power of C# syntax).

var house1 = new House()
             {
                 Color = "Red",
                 Exterior = Exterior.Wood
             };

We could also give it carpet but since this house isn't going to have any and it defaults to false I've left it out.

Ok, so let's say we have all 3 houses built via our blueprint. Let's now store them together in a List. First we need to make the List into an object and reference that also.

var houses = new List<House>();

Now let's add the houses to the list.

houses.Add(house1);
houses.Add(house2);
houses.Add(house3);

Now houses is a reference to all of our house objects. If we want to get to a house in the list we could use an index (starting at 0) and get that location in the list. So let's say that house2 needs to have carpet but we want to use the list now to reference it. Note: There are quite a few ways to reference the items in a list, this one is elementary.

houses[1].HasCarpet = true;

I did this on my phone, hopefully there are no errors. My intentions are to clearly answer your question and educate and help you better understand classes.

Upvotes: 1

Cetin Basoz
Cetin Basoz

Reputation: 23867

Most likely, you would use an IEnumerable<Customer>. A Customer class in real life is related with a database.

When dealing with databases, Linq comes to mind which would use an IQueryable<Customer> (inherited from IEnumerable). As need arises you would also use other collection types like List<Customer>, Dictionary<...> etc

Upvotes: 0

Felipe Augusto
Felipe Augusto

Reputation: 8184

If you will iterate throught the objects in some moment I'd use a List.

As mentioned by @wazz you should store them in a list, like so:

List<Customer> customers = new List<Customer>();

Then you can start working with the list, adding new instances, removing etc.

You can check more information at the docs.

Upvotes: 5

Related Questions