Question

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'

Was it helpful?

Solution

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);
}   

OTHER TIPS

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
}  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top