Unable to understand "A field initializer cannot reference the nonstatic field" Error?

Posted by Subhen on Stack Overflow See other posts from Stack Overflow or by Subhen
Published on 2010-03-29T08:05:40Z Indexed on 2010/03/29 8:13 UTC
Read the original article Hit count: 431

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about Silverlight