The code I've been trying and what went wrong: http://ideone.com/cvLRLg
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class Minion
{
public static int manaCost;
public static int attack;
public static int health;
public static string cardText;
public Minion(int mana, int atk, int h, string txt)
{
manaCost = mana;
attack = atk;
health = h;
cardText = txt;
}
public void displayStats(string name)
{
Console.WriteLine(name + "\nMana Cost: " + manaCost + "\nAttack: " + attack + "\nHealth: " + health + "\n" + cardText + "\n");
}
}
class Program
{
static void Main(string[] args)
{
List<string> indexList = new List<string>();
Dictionary<string, Minion> minionList = new Dictionary<string, Minion>();
//buffer so I start at 1 and not 0
indexList.Add("MissingNo");
//make a Wolfrider card
indexList.Add("Wolfrider");
Minion Wolfrider = new Minion(3, 3, 1, "Charge");
minionList.Add(indexList[1], Wolfrider);
//make a Goldshire Footman card
indexList.Add("Goldshire Footman");
Minion GoldshireFootman = new Minion(1, 1, 2, "Taunt");
minionList.Add(indexList[2], GoldshireFootman);
//look through all my cards
for (int i = 1; i < indexList.Count(); i++)
minionList[indexList[i]].displayStats(indexList[i]);
Console.ReadLine();
}
}
}
I have been trying to teach myself C# but this has been stumping me. I want to make a Dictionary that accepts a string then returns a Minion (the new class).
A Minion accepts four arguments when it's made so I had to dedicate a line of code to making a new Minion BEFORE adding that to the Dictionary.
However, when I'm going through all the Minions that I have, for some reason the first one is giving me back the properties of the OTHER Minion.
Wolfrider
Mana Cost: 1
Attack: 1
Health: 2
Taunt
Goldshire Footman
Mana Cost: 1
Attack: 1
Health: 2
Taunt
The List is working properly because the names are correct... but the Wolfrider has the properties of the Goldshire Footman.
Is there a more efficient/optimized way to do this? If not, what have I been doing wrong?
The main issue is that your members are static
:
public static int manaCost
So basically, the last value you affect wins. Transform them into instance properties:
public int ManaCost { get; set; }
Then get rid of indexList
and directly use your Minion's name as the dictionary key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With