-2

I'm trying to make an rpg style game in the console with c#. I'm assigning an array in a constructor but its telling me that's its not assigned

class Warrior
        {
            public string[] attacks, weapons, items;

            // Constructer
            public Warrior()
            {
                attacks[0] = "Basic Slash";
                weapons[0] = "Basic Sword";
                items[0] = "Basic Health Potion";
            }
        }

ive tried messing around with the access modifiers but its still not working

Adsterr
  • 7
  • 3
  • 2
    You declare array field members, but you never create the actual arrays. You need to do that before you can assign anything to them – UnholySheep Oct 26 '22 at 22:41
  • With your posted code you _should_ be getting a Null Reference Exception. – gunr2171 Oct 26 '22 at 23:09
  • You will find that you _really_ want to use Lists, not arrays. Declare each of those fields as `public List stuff = new List();` (and you may want to use _properties_ instead of _fields_). Arrays are fixed length - you need to know how many you are every going to use before you start. Lists are stretchy; you can `Add` new items to Lists – Flydog57 Oct 26 '22 at 23:31
  • By the way, if you get a _Null Reference Exception_ (which I'm sure you are getting), you should mention it in your question and say where the exception occurs. You also don't assign anything to your arrays in your constructor, the only assignments are to array items (and, since your arrays do not yet exist, that fails) – Flydog57 Oct 26 '22 at 23:33

1 Answers1

0

An array like string[] is designed to hold a fixed number of elements. You have to decide how big it should be and then instantiate it and assign it to your variable. For example, if a warrior can hold only one weapon you might do this:

class Warrior
{
    public string[] weapons = new string[1];  //Contains 1 element

    public Warrior()
    {
        weapons[0] = "Basic Sword";
    }
}

or simply

class Warrior
{
    public string[] weapons = new string[] { "Basic Sword" };  //Compiler infers number of elements is 1
}

If you don't want to decide ahead of time how big the array should be, use a List<T> instead.

class Warrior
{
    public List<string> weapons = new List<string>();

    public Warrior()
    {
        this.weapons.Add("Basic Sword");
    }
}

Note that in both cases it is not enough to declare the variable weapons; you have to initialize it with an instance too. In the example above, I created an instance using new followed by the type.

John Wu
  • 50,556
  • 8
  • 44
  • 80