Eyal
Eyal

Reputation: 4763

Set a value of ilist<T> members

I have the following classes:

public class Products
{
    public int Id { get; set; }      
    public string ProductName { get; set; }
    public int Price { get; set; }

    public IList<ProductFiles> ProductFiles { get; set; }                     
}

public class ProductFiles
{
    public int NumberOfFiles { get; set; }
    public int NumberOfShops { get; set; }
}

Here I am trying to set the value of the property NumberOfFiles (member of ProductFiles):

public Products CountProductFiles(int productId)
{    
    DB_utilities db = new DB_utilities();
    object[] spParams = new object[] { productId};

    Products product = new Products();

    using (var reader = db.procSelect("[Products_CountFiles]", spParams))
    {
        reader.Read();
        {
            Products _products = new Products 
            {                        
                ProductName = (string)reader["ProductName"],
                Price = (double)reader["Price"],

                // I am trying to do something like this but this does not work:
                ProductFiles.NumberOfFiles = (int)reader["NumberOfFiles"]  
            };

            Products = _products ;
        }
    }

    return Products;
}

How can I set the value of the prop NumberOfFiles? Or is the entire concept wrong?

Upvotes: 0

Views: 3057

Answers (3)

Ric
Ric

Reputation: 13248

As ProductFiles is a collection of ProductFiles, you need to do this

Products p = new Products();
p.ProductFiles = new List<ProductFiles>();
p.ProductFiles.Add(new ProductFiles() { NumberOfFiles  = 1 }); // or some other defined value.

The collection needs to be initialized before adding objects to it. In your example, you do not treat ProductFiles as a collection, that is why you get the error.

Upvotes: 2

CinCout
CinCout

Reputation: 9619

In this example, Products::ProductFiles is a list.
Hence, in order to set the value of NumberOfFiles, do something like this:

ProductFiles[i].NumberOfFiles = //whatever you want to set it to.

But, before doing all this, do not forget to instantiate the List variable. Otherwise, it will itself be NULL.

Upvotes: 0

SLaks
SLaks

Reputation: 887837

The point of a collection is that it can contain zero or more items. You need to put an instance in the collection. You also need to create a collection to ensure that the collection itself is not null.

new Product { 
    Files = new List<ProductFile>() { 
        new ProductFile {
            FileCount = 42
        }
    }
}

Upvotes: 1

Related Questions