So I'm beginning to learn about object oriented programming and I'm having some trouble understanding the relationship between all these elements.
I'm building a simple text game with RPG style fights.
For this I have several classes, including one for :
Weapons :
class Weapon
{
private string _name;
private int _mindamage;
private int _maxdamage;
public string Name { get { return _name; } set { _name = value; } }
public int MaxDamage { get { return _maxdamage; } set { _maxdamage = value; } }
public int MinDamage { get { return _mindamage; } set { _mindamage = value; } }
public Weapon(int mindamage, int maxdamage, string name)
{
this._name = name;
this._mindamage = mindamage;
this._maxdamage = maxdamage;
}
}
Characters :
class Character
{
private string _name;
private int _life;
private Weapon _weapon;
public string Name { get { return _name; } set { _name = value; } }
public int Life { get { return _life; } set { _life = value; } }
public Weapon Weapon { get { return _weapon; } set { _weapon = value; } }
public Character(string name, Weapon weapon)
{
_name = name;
_weapon = weapon;
_life = 100;
}
And the one that I'm struggling with : It's a class that represents a group of characters in a list :
class Company
{
private int _size;
private List<Character> _members;
public int Size { get { return _size; } set { _size = value; } }
public List<Character> Members { get { return _members; } set { _members = value; } }
public Company(string[] names, Weapon[] weapons)
{
int length = names.Length;
List<Character> _members = new List<Character>();
for (int i = 0; i < length; i++)
{
_members.Add(new Character(names[i], weapons[i]));
Console.WriteLine("added {0} to character list", _members[i].Name);
}
Console.WriteLine("characters {0} and {1} exist after the for", _members[0].Name, _members[1].Name);
_size = length;
}
}
This code compiles perfectly fine but when it executes it throws me an error in my Program.cs class if I try to access a Character's Name inside my list, for example :
static void Main(string[] args)
{
Weapon anduril = new Weapon(55, 80, "Anduril");
Weapon hache = new Weapon(25, 60, "hache");
Weapon lame = new Weapon(30, 50, "lame");
Weapon arc = new Weapon(30, 40, "arc");
string[] gentils = { "Aragorn", "Legolas", "Gimli" };
string[] méchants = { "Lurtz", "Berserk", "UrukA" };
Weapon[] armes = { anduril, arc, hache };
Weapon[] armes2 = { lame, lame, arc };
Company Communauté = new Company(gentils, armes);
Company Uruks = new Company(méchants, armes2);
Console.WriteLine(Communauté.Members[0].Name);
The last line throws me a null object error.
As you can see I put some Console.WriteLine
calls in my Company
constructor to be sure that the constructor was actually adding Character
to a List
, and it works. So were is the problem ?
Is it something with the way I wrote the getter/setter for Members ?