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!!!
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.