views:

96

answers:

3

Hi,

I am getting the error "A field initializer cannot reference the nonstatic field", While My code is as below:

Object selectedItem = PageVariables.slectedItemData;
MyClass selectedItems = (MyClass)selectedItem;

But the same thing works if assign the value at the constructor or in a different method , like below:

public partial class MusicPlayer : Page
{
   Object selectedItem = PageVariables.slectedItemData;
    public MusicPlayer()
      {
        InitializeComponent();
        MyClass selectedItems = (MyClass)selectedItem;
      }
}

I am just trying to understand what is the difference, Why it is looking for a static varaible declaration(in 1st case) while doesn't look for it while in a constructor or a different method!!!

+4  A: 

It isn't the static field that's the problem. It's the attempt to use the non-static field selectedItem in the initialization of another non-static field selectedItems. This is a restriction in C#.

Marcelo Cantos
Thanx, But inside the constructir(2nd case) , we are still intializing a non-static field selectedItem with another non-static field.
Subhen
+1  A: 

isn't it because the order of initilization when used as a field is not defined, ie selectedItems could be initialized before selectedItem, which would result in an error (or at least in unexpected behaviour, that selectedItems was null). In the second example the order is specific so everything is hunky dory.

Sam Holder
A: 

That restriction (A field initializer cannot reference the nonstatic field) is related to the fact that field initializers run before constructors. (From derived to base and then all constructors from base to derived)

Art Shayderov