Property and Global Variable

S

shapper

Hello,

I have a class as follows:

public class SupplierRepository : ISupplierRepository {
public String Path { get; set; }
private readonly XDocument context = XDocument.Load(Path);
public SupplierRepository(String path) {
Path = path;
}
}

I get the error:
A field initializer cannot reference the non-static field, method, or
property

I understand that I can make it work using:
public static String Path { get; set; }

But is this the way to do this?

Basically I need to define the path when I initialize a
SupplierRepository instance and then load the document to be used in
all the class methods ...

Thanks,
Miguel
 
S

Stephany Young

public class SupplierRepository : ISupplierRepository
{

public string Path { get; set; }

private XDocument context;

public SupplierRepository(string path)
{
this.Path = path;
this.context = XDocument.Load(this.Path);
}

}
 
S

shapper

Hello,

I have a class as follows:

public class SupplierRepository : ISupplierRepository {
    public String Path { get; set; }
    private readonly XDocument context = XDocument.Load(Path);
    public SupplierRepository(String path) {
      Path = path;
    }

}

I get the error:
A field initializer cannot reference the non-static field, method, or
property

I understand that I can make it work using:
    public static String Path { get; set; }

But is this the way to do this?

Basically I need to define the path when I initialize a
SupplierRepository instance and then load the document to be used in
all the class methods ...

Thanks,
Miguel

When I add "Static" I don't get any error but when I run my project I
get the error:
Exception Details: System.ArgumentNullException: Value cannot be null.

On the following code line:
private readonly XDocument context = XDocument.Load(Path);

What am I doing wrong?

Basically I would like to create a global variable, context, that is
available for all class methods and that uses a property value, Path,
to load the file.
Maybe I should this some other way?

Thanks,
Miguel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top