Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A field initializer cannot reference the non-static field, method, or property

Following is my code :

private BitsManager manager;
private const string DisplayName = "Test Job";       

public SyncHelper()
{
    manager = new BitsManager();
}        

BitsJob uploadBitsJob = manager.CreateJob(DisplayName, JobType.Upload);

I am getting following error :

A field initializer cannot reference the non-static field, method, or property 'BITSIntegrationModule.SyncService.SyncHelper.manager'

like image 995
Madurika Welivita Avatar asked Mar 04 '13 14:03

Madurika Welivita


People also ask

Which method Cannot initialize non static members?

In the static method, the method can only access only static data members and static methods of another class or same class but cannot access non-static methods and variables.

What is a field initializer?

Fields are initialized immediately before the constructor for the object instance is called. If the constructor assigns the value of a field, it will overwrite any value given during field declaration. For more information, see Using Constructors. Note. A field initializer cannot refer to other instance fields.


2 Answers

The line

BitsJob uploadBitsJob = manager.CreateJob(DisplayName, JobType.Upload);

can't access manager because it hasn't been set to anything yet - you could move the allocation into the constructor -

private readonly BitsManager manager;
private const string DisplayName = "Test Job";       
BitsJob readonly uploadBitsJob;

public SyncHelper()
{
  manager = new BitsManager();
  uploadBitsJob = manager.CreateJob(DisplayName, JobType.Upload);
}   
like image 200
NDJ Avatar answered Oct 25 '22 06:10

NDJ


uploadBitsJob is declared at the class level which makes it a field. Field instances can't be used to initialize other fields.

Instead, you can declare the field without initializing it:

BitsJob uploadBitsJob;

Then initialize the field in the constructor:

public SyncHelper()
{
  manager = new BitsManager();
  uploadBitsJob = manager.CreateJob(DisplayName, JobType.Upload);//here.  Now manager is initialized
}  
like image 40
P.Brian.Mackey Avatar answered Oct 25 '22 07:10

P.Brian.Mackey