Link to home
Start Free TrialLog in
Avatar of wenyonk
wenyonk

asked on

A field initializer cannot reference the nonstatic field, method, or property

Can someone please help with this error.  Below is the Class Member Declaration and Class Method.  

Error:
A field initializer cannot reference the nonstatic field, method, or property 'App.uccPictureViewer.OpenPictureImage()'

Class Member Declaration:
private ThreadStart _openThreadStart = new ThreadStart(OpenPictureImage);

Class Method
 private void OpenPictureImage()
 {
     ...
 }


If I change class method to static I receive 15 additional errors.

The VB Code Converted from is as follows:
Private _openThread As System.Threading.Thread
Private _openThreadStart As New ThreadStart(AddressOf OpenPictureImage)

    Private Sub OpenPictureImage()
       ....
    End Sub
Avatar of devsolns
devsolns

Yeah static methods cannot access instance data.  You would need to mark your member object static as well.

private static ThreadStart _openThreadStart = new ThreadStart(OpenPictureImage);

I will tell you I would not make this static.  Anyone you have static methods accessing static member data you need to implement thread synchronization.  When multiple threads call the same static method it pushes different copies onto the stack so everything is fine.  things change when that static method interacts with static members because multiple threads can access that same member.  yeah its no different with instance methods and members but your more likely to run into issues because its shared throughout your app.

i have seen many nasty bugs when folks use static classes/members in asp.net applications and don't realize that each worker thread processing the request is accessing the same piece of data!
ASKER CERTIFIED SOLUTION
Avatar of Thogek
Thogek
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The MSDN documentation's short note explaining the compiler message you're currently getting: http://msdn.microsoft.com/library/en-us/cscomp/html/vcerrCompilerErrorCS0236.asp
Avatar of wenyonk

ASKER

Would it be something like this (without the type in the constructor)?

Class Member Declaration:
    private ThreadStart _openThreadStart;

Within the Class Contructor Method:
        _openThreadStart = new ThreadStart(OpenPictureImage);

Class Method
    private void OpenPictureImage()
    {
        ...
    }
That looks right, offhand.  (Yeah, if your _openThreadStart variable's a class-level field, you don't want to redeclare it in the constructor. :-)

See if something like that works for ya.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial