Chris Anderson

Chris Anderson

  • NA
  • 93
  • 9.2k

Problem with object reference and static methods

Dec 15 2020 7:40 AM
I'm trying to invoke a method from another class. Either way, having it static or non-static, I run into errors and don't know how to proceed. Animal.cs is an abstract class which complicate things when speaking of object references.

I've stripped the code down keeping the most essential parts (I think).
 
 
Application.cs
This is the class that holds a menu from which I call the static BuyToy method. 
  1. class Application  
  2.     {  
  3.         public static void Menu()  
  4.         {  
  5.         Animal.BuyToy();  
  6.         }  
  7.     }  
 
Animal.cs
Line 34 and 35 throw errors when method is static. By removing static errors disappear and I'm able to reach both the Name and Toys list. But then instead I won't be able to call the BuyToy method from Application.cs
  1. abstract class Animal  
  2.     {  
  3.         public string Name { getset; }  
  4.         public List Toys { getset; } = new List();  
  5.          
  6.         public static void BuyToy()  
  7.         {  
  8.                     Toy ball = new Ball();  
  9.                     Toy bone = new Bone();  
  10.                     Toy feather = new Feather();  
  11.                       
  12.                     Console.WriteLine("Select which toy you want to buy");  
  13.                     Console.WriteLine("[1] Ball");  
  14.                     Console.WriteLine("[2] Bone");  
  15.                     Console.WriteLine("[3] Feather");  
  16.   
  17.                     buyMenu = int.Parse(Console.ReadLine());  
  18.   
  19.                     switch (buyMenu)  
  20.                     {  
  21.                         case 1:  
  22.                             selectedToy = ball;  
  23.                             break;  
  24.                         case 2:  
  25.                             selectedToy = bone;  
  26.                             break;  
  27.                         case 3:  
  28.                             selectedToy = feather;  
  29.                             break;  
  30.                         default:  
  31.                             break;  
  32.                     }  
  33.                     Toys.Add(selectedToy); // Gives the error "An object reference is required for the non-static field, method, or property 'Animal.Toys'.   
  34.                     Console.WriteLine("You just bought a new" + selectedToy + " for" +  Name  + " fully loaded with max quality of 10");  // Gives the error "An object reference is required for the non-static field, method, or property 'Animal.Name'
  35.                     break;  
  36.                 case 2:  
  37.                     Application.Menu();  
  38.                     break;  
  39.                 default:  
  40.                     break;  
  41.             }  
  42.         }  
  43.     }  
 

Answers (6)