+ 1

Can't call method from class?

I'm new to programming and I was wondering what I did wrong here. Here's the code: class Hero { protected string name; protected int age; protected int strength; protected int intelligence; public void Stats() { Console.WriteLine("Name: " + name); Console.WriteLine("Age: " + age); Console.WriteLine("Strength: " + strength); Console.WriteLine("Intelligence: " + intelligence); } } class Spartan : Hero { public Spartan(string name, int age, int strength, int intelligence) { this.name = name; this.age = age; this.strength = strength; this.intelligence = intelligence; } public string ChooseWeapon(string weapon) { return weapon; } } static void Main(string[] args) { Hero Spartan_1 = new Spartan("James", 40, 80, 40); Spartan_1.Stats(); Spartan_1.ChooseWeapon("Spear"); Console.ReadKey(); } Here's the error I get: 'Program.Hero' does not contain a definition for 'ChooseWeapon' and no extension method 'ChooseWeapon' accepting a first argument of type 'Program.Hero' could be found (are you missing a using directive or an assembly reference?)

3rd Jun 2017, 5:37 PM
Unknown Unknown
Unknown Unknown - avatar
3 Réponses
+ 3
Spartan_1 is a Hero object. You wrote: Hero Spartan_1 = new Spartan...; So to use the methods in the Spartan_1 class you would need to cast it to a Spartan_1 object. OR Create an empty chooseWeapon() method in the Hero class and override it with the Spartan class. This can be done with the virtual and override keyword. You'd might as well make the Hero class abstract if you want to do this. OR Create an object of type Spartan instead
3rd Jun 2017, 5:51 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
spartan_1 is of een type hero. Hero does not contain a method ChooseWeapon. So do write Spartan spartan_1 = new spartan (1,1,1,1);
3rd Jun 2017, 5:48 PM
sneeze
sneeze - avatar
0
Oh I get it now. I needed to create the object of type Spartan instead of type Hero, because the ChooseWeapon() method is only in the Spartan class. Thank you guys for helping
3rd Jun 2017, 5:59 PM
Unknown Unknown
Unknown Unknown - avatar