tags:

views:

95

answers:

2
+1  Q: 

Inventory Class

Hi there,

I have created an Inventory Class but I don't know how to retrieve information from it. I know how to go over it in a foreach loop and display all items, but I don't know how to see if YoYo is in there and if it is, print the Name, Cost and Quantity to a label. Can anybody please help?

+1  A: 

Since you mention foreach, it sounds like it implements IEnumerable<T>. In which case, if you are using C# 3.0 / LINQ, something like:

var yoyo = inventory.FirstOrDefault(item => item.Name == "YoYo");
if(yoyo != null) { // found it
    Console.WriteLine(yoyo.Cost); // etc
}

You might also look at dictionaries if you have a lot of data...

Marc Gravell
+1  A: 

I hope you're going beyond an Inventory class and creating a Product class as well. Object-oriented languages are all about encapsulation and information hiding. Embed the output of the Product in a method for that object. Clients can simply call it that way instead of having to repeat it all over the place.

I'd also recommend a find method in your Inventory class that lets you search for a Product instance. You might want to search by name now, but what about cost, category, or manufacturer? Perhaps you'll want to extend it later.

I agree with Marc's dictionary recommendation, but I would advise that you made that part of Inventory's private implementation. You're adding an extra bit of abstraction that makes an Inventory something more than a mere dictionary.

I think strings and data structures are wonderful, but too often these primitives leak into code when hiding them in an object would be much better for clients. That's what I think good object-oriented design is all about.

duffymo