2

I'm having troubles in adding into an array. I have created a class named Products:

public struct newProducts
{
    public string productBrand;
    public string productType;
    public string productName;
    public string productFlavour;
    public int productSize;
}

//Create an array of type newProducts
newProducts[] productList = new productList[];

and than I've created a function:

public newProducts AddProduct(string brand, string type, string name, string flavour, int size)
{
    //I don't know what to do here..

    return productList;
}

What I want to do is to append and store the brand, type, name, flavour and size values to the array

Basically the first time I call this function I'll enter those values and store it to index 0 and on the second call it will add them to index 1 .

Is this possible?

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Asım Gündüz
  • 1,257
  • 3
  • 17
  • 42

2 Answers2

5

You're better off using a List<T> instead of a T[]. That way, you can append values any time, without having to worry about resizing the array yourself

List<NewProduct> products = new List<NewProduct>();
products.Add(new Product { /* more code here */ });

Also, you might be coming from a lower level programming background, but as others mentioned, I'm not sure you really understand the true meaning of struct in C#. By looking at your code, you're looking for a class:

public class NewProduct
{
    public string ProductBrand { get; set; }
    public string ProductType { get; set; }
    public string ProductName { get; set; }
    public string ProductFlavour { get; set; }
    public int ProductSize { get; set; }
}

I'd suggest starting by reading Classes and Structs (MSDN) and What's the difference between struct and class in .NET?

Community
  • 1
  • 1
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
0

I've solved my issue, thank you for pointing out the differences between structures and classes, here's my approach:

I've changed the elements as Yuval described.. get and set methods..

than created a list of type newProduct class in the main form class

later on inside the main form class I created a method to insert data to the class elements and added it to the list! and it worked fine

thanks everyone in advance and sorry for my bad english

Asım Gündüz
  • 1,257
  • 3
  • 17
  • 42