TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Chris Anderson
NA
93
9.4k
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.
class
Application
{
public
static
void
Menu()
{
Animal.BuyToy();
}
}
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
abstract
class
Animal
{
public
string
Name {
get
;
set
; }
public
List
Toys {
get
;
set
; } =
new
List
();
public
static
void
BuyToy()
{
Toy ball =
new
Ball();
Toy bone =
new
Bone();
Toy feather =
new
Feather();
Console.WriteLine(
"Select which toy you want to buy"
);
Console.WriteLine(
"[1] Ball"
);
Console.WriteLine(
"[2] Bone"
);
Console.WriteLine(
"[3] Feather"
);
buyMenu =
int
.Parse(Console.ReadLine());
switch
(buyMenu)
{
case
1:
selectedToy = ball;
break
;
case
2:
selectedToy = bone;
break
;
case
3:
selectedToy = feather;
break
;
default
:
break
;
}
Toys.Add(selectedToy);
// Gives the error "An object reference is required for the non-static field, method, or property 'Animal.Toys'.
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'
break
;
case
2:
Application.Menu();
break
;
default
:
break
;
}
}
}
Reply
Answers (
6
)
Jenkins File Using Pipeline
MVC file download