Click to See Complete Forum and Search --> : how can I call method class list


abab
July 6th, 2009, 03:38 AM
If I have class with static field:

public class Cart
{
private static int quantity_all_books = 0;

public int id { get; private set; }
public int quantity { get; private set; }

public Cart(int x, int y)
{
quantity_all_books++;

id = x;
quantity = y;
}
}


And I have list type of this class:

List<Cart> shopping = new List<Cart>();
shopping.Add(new Cart(53, 2));
shopping.Add(new Cart(44, 1));


How can I check value static field quantity_all_books. I have tried make this field public, write method which return value of this field. But when I write "shopping." Visual Studio don't give me on the list this field or method.

darwen
July 6th, 2009, 04:29 AM
Have a static property e.g.


public class Cart
{
private static int quantity_all_books = 0;

public static int QuantityAllBooks
{
get { return quantity_all_books; }
}
}


You gain access to static methods not by specifying them on an instance, but this way :


int quantityAllBooks = Cart.QuantityAllBooks;


Darwen.

abab
July 6th, 2009, 04:40 AM
thx very much :)

JonnyPoet
July 6th, 2009, 03:43 PM
thx very much :)
Excuse my question, but is there a specific reason to have this field quantity_all_books static ? Whats the reason behind that ? :wave:

boudino
July 7th, 2009, 02:32 AM
Yes, it strange. I think that better approach would be to read Count property of a collection where instances of Cart are stored, because without a storage, it doesn't make sence to count them.

JonnyPoet
July 7th, 2009, 04:41 AM
public class Cart
{
private static int quantity_all_books = 0; // unnecessay here
.....
}
What do you want to count ? Books ? Ok what do they have to do with Cart ? You are collecting Cart in a list so you have a Count property all the times So why not simple

List<Cart> shopping = new List<Cart>();
shopping.Add(new Cart(53, 2));
shopping.Add(new Cart(44, 1));
// now counting
int amount = shopping.Count;

It's totally unusual design to have the amount of Chart classes as a propety of that Cart class itself.

I would create a Carts class which contains all books. My rule is : Classes which ends with plural 's ' are collections of classes which have the same but singular name. Product, Products, Book, Books...
This way

public class Carts{
private List<Cart> shopping;
// Constuctor
public Carts(){
shopping = new List<Cart>();
}
// Properties
public int Count{
get { return shopping.Count;}
}
// methods
public void Add(Cart cart){
shopping.Add(cart);
}
}
Overthing your design.