0

I'm having problem with a school assignment in C#.

I include only a part of the code here, I hope that it suffices.

I'm creating an array of the Bottle class with index 25. The Bottle class contains three properties.

Now I need to get and set values in the array, but I don't manage to.

See my example below. Where am I doing wrong? The program doesn't show any errors but the compilation does not succeed. If any more code would be necessary I'm happy to give it!

public class Sodacrate
{
    private Bottle[] bottles;
    public Sodacrate() // Constructor for handling new sodas in the soda crate.
    {
        bottles = new Bottle[25];

        bottles[0].Brand = "Fanta";
        bottles[0].Price = 15;
        bottles[0].Kind = "Soda";
    }
}


public class Bottle
{
    private string brand;
    private double price;
    private string kind;

    public string Brand
    {
        get { return brand; }
        set { brand = value; }
    }

    public double Price
    {
        get { return price; }
        set { price = value; }          
    }

    public string Kind
    {
        get { return kind; }
        set { kind = value; }
    }

}
Max
  • 488
  • 8
  • 19
  • if your _compilation_ would not succeed there must be an error you could show us. i guess your code compiles but when you run it you _do get an error_: a `NullReferenceException` for the reasons explained by QiMata. – René Vogt Apr 17 '16 at 15:24

2 Answers2

2

There is no object at the zero index of the array. What you are doing is setting up memory for the array here:

bottles = new Bottle[25];

Then what you are doing is trying to set properties on the first object in that array here:

bottles[0].Brand = "Fanta";
bottles[0].Price = 15;
bottles[0].Kind = "Soda";

What is missing is the following:

bottles[0] = new Bottle();

So to summarize here is what you are doing:

//Give me a box big enough to hold 25 bottles
//Set the brand on the first bottle

This is what you should be doing:

//Give me a box big enough to hold 25 bottles
//Put the first bottle in the box
//Set the brand on the first bottle
QiMata
  • 216
  • 1
  • 7
0

Because Bottle is a reference type, so this statement will create an array contains 25 element with value is default value of reference type which is null.

bottles = new Bottle[25];

So, you must assign value to bottle[0] before use it. like this:

bottles[0] = new Bottle();
Sỹ Lê
  • 133
  • 2
  • 8