error message: An object reference is required for the nonstatic field ....
I am getting the error 'An object reference is required for the nonstatic field, method, or property ' when I attempt to run my client application. I am not sure what is wrong and the documentation on this error (#CS0120) in the VS.NET IDE is confusing to me. Does anyone know what I am doing wrong? MY code is below. People is a collection class and myPeople is obviously an instance of it. Because the error appears to involve the client code and not the class library with the implementation of People, I did not include that code. I could if it would be helpful. Thanks for any help.
using
System;using
PeopleLib;namespace
Ch11N01{
///<summary>/// Summary description for Class1.///</summary>class Class1{
[STAThread]
staticvoid Main(string[] args){
People myPeople =
new People();myPeople.Add("Bob",
new Person("Bob",20));myPeople.Add("Jack",
new Person("Jack",30));foreach (Person aPersonin myPeople){
Console.WriteLine(aPerson.ToString());
}
string oldestName;oldestName = GetOldest(myPeople);
Console.WriteLine("The oldest person in the collection is {0}, who " +
"is {1} years old", myPeople[oldestName].Name,
myPeople[oldestName].Age);
}
//returns the name of the oldest person from among the people in PeopleSetpublicstring GetOldest(People PeopleSet){
int ageNum = 0;string strName = "no name";foreach (Person aPersonin PeopleSet){
if (aPerson.Age > ageNum){
ageNum = aPerson.Age;
strName = aPerson.Name;
}
}
return strName;}
//GetOldest}
}
are you able to give us the line of the error in code? Does this work in the Visual Studio IDE or even on your computer?
Hi,
try making GetOldest method static (it's called from also static Main method):
public static string GetOldest(People PeopleSet)
{
...
}
Andrej
All your code seems fine but:
Try making GetOldest() method static because its called form a static method:
public static string GetOldest(People PeopleSet)
{
/////////////////////////////
}
Does this work?
Best Regards,
I haven't tried this code in any other environment than the VS .NET IDE. The error occurs in line 26, which is the line
oldestName = GetOldest(myPeople);
in the given code.
I tried making GetOldest() a static method and the code compiled but crashed with the error "Unhandled Exception: System.InvalidCastException: Specified cast is not valid." for line 20 of Main, which is the foreach line in the given code. Since aPerson is an object of the Person class and the People collection is of Person objects, this error confuses me too. Any other ideas?
Bruce
I also have got the same problem .. can anybody help please .
yaa i got a solution ...not sure is this the right way to do or not
create the instance of class Class1 and then call ur method
Class1 c1 = new Class1();
oldestName = c1.GetOldest(myPeople);
I think its because of the static method main..
>> I tried making GetOldest() a static method and the code compiled but crashed
Yes, you've solved one problem and are now hitting the next problem in your code.
>> with the error "Unhandled Exception: System.InvalidCastException: Specified cast is not valid." for line 20 of Main, which is the foreach line in the given code. Since aPerson is an object of the Person class and the People collection is of Person objects, this error confuses me too.
People is not a "collection is of Person objects". It is a collection of string/Person pairs (or at least I'm going to assume it's based on Dictionary<string, Person> since you don't actually show it to us.) The MSDN does a lousy job of explaining this (although the v2.0 docs are better than the v1.1 docs), but the enumerator for a Dictionary returns a KeyValuePair object.
What you really want there is:
foreach (Person aPerson in myPeople.Values)
{
Console.WriteLine(aPerson.ToString());
}
Below is my code for the People collection, which is based on DictionaryBase not CollectionBase and uses a string/Person pair for indexing. It compiles and I assume it is correct.
using
System; using
System.Collections; namespace
PeopleLib {
/// <summary> /// Summary description for People. /// </summary> public class People : DictionaryBase {
public void Add (string name, Person newPerson) {
Dictionary.Add(name, newPerson);
}
public void Remove (string name) {
Dictionary.Remove(name);
}
public People() {
}
public Person this[string personName] {
get {
return (Person)Dictionary[personName]; }
set {
Dictionary[personName] =
value; }
}
}
}
Your example for foreach is the foreach (on line 20 in the client code I pasted in my initial post) that compiles correctly. If there is a problem with it then I haven't encountered that problem yet. I added code based on your suggestion regarding the Value struct in Dictionary and the use of DictionaryEntry in the foreach blocks but I am still getting the same error. The new client code is below:
using
System; using
System.Collections; using
PeopleLib; namespace
Ch11N01 {
/// <summary> /// Summary description for Class1. /// </summary> class Class1 {
[STAThread]
static void Main(string[] args) {
People myPeople =
new People(); myPeople.Add("Bob",
new Person("Bob",20)); myPeople.Add("Jack",
new Person("Jack",30)); foreach (DictionaryEntry aPerson in myPeople) {
Console.WriteLine(aPerson.Value.ToString());
}
string oldestName; oldestName = GetOldest(myPeople);
Console.WriteLine("The oldest person in the collection is {0}, who " +
"is {1} years old", myPeople[oldestName].Name,
myPeople[oldestName].Age);
}
//returns the name of the oldest person from among the people in PeopleSet public string GetOldest(People PeopleSet) {
int ageNum = 0; string strName = "no name"; foreach (DictionaryEntry aPerson in PeopleSet) {
if ( ((Person)aPerson.Value).Age > ageNum) {
ageNum = ((Person)aPerson.Value).Age;
strName = ((Person)aPerson.Value).Name;
}
}
return strName; }
//GetOldest }
}
myPeople is an object of People. What does the compiler want/need in place of myPeople? I'm sorry if I am probaly misunderstanding your post.
Bruce
PS Is there a better way of posting code in these messages? The code blocks I've posted seem unsightly to me.
Your code now appears correct at first glance. Can you specify which line is causing the problem?
Also, for posting code, use [code language="C#"]\\put your code here[/code]
line 26 (oldestName = GetOldest(myPeople);) is causing the problem. I still get the same error. Sorry I haven't replied in a while. I work during the week (programming but not in C#) and I was busy in the evenings this week with my wife and daughter. Also thanks for the tip on posting code.
Bruce
Ah, the problem is that you are trying to call the instance method GetOldest from the static method Main. Static methods can only call other static methods and use static fields and properties. Add the static keyword to the GetOldest method and it should work.
It worked. Thank you very much.
Bruce
Glad you solved the problem! Please remember to mark the helpful posts in this thread as answers, even if they are your own.
I have a very similar problem, but the method I'm trying to call isn't one I wrote, it's from the Microsoft library. So I can't just make it static like that, can I? How else could I get around this problem?