...

View Full Version : C#: A field initializer cannot reference the non-static field, method, or property...



bobleny
07-23-2009, 12:11 PM
I'm getting this error:
A field initializer cannot reference the non-static field, method, or property...

The issue has to do with this code:


namespace Words
{
public class Wordy
{
private int maxCourses = 4;

private string[] courseArray = new string[maxCourses];
}
}


The error would be on line 7 in the above code. I've underlined the "bad" word.
courseArray is an indexer array. So:


Wordy word = new wordy();

Wordy[0] = "Good Bye World!";

You get the idea.

I'm sure it is something stupid, it all most always is...

I don't understand why it is complaining, could someone explain it to me?

Thanks!

oracleguy
07-23-2009, 03:17 PM
It is basically like the error message says. You are using the maxcourses variable which isn't static. So because it isn't static and you are using to initialize a static data member, it fails. The reason for this is that maxcourses is out of scope.

If you make it static, it will work.

bobleny
07-23-2009, 06:08 PM
I thought for sure I tried that!

I don't know why the array would be static either. I didn't tell it to be static, and I would think it would be an instance array. This way there is an instance of the array for each object created. However, it does work the way that it is supposed to now.

Thanks again, oracleguy!

oracleguy
07-23-2009, 06:32 PM
I thought for sure I tried that!

I don't know why the array would be static either. I didn't tell it to be static, and I would think it would be an instance array. This way there is an instance of the array for each object created. However, it does work the way that it is supposed to now.

Thanks again, oracleguy!

I totally missed that there wasn't a static keyword on the array. If the maximum is for all instances, you can also try make maxCourses constant.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum