Reputation: 53
When I run the windows form application it shows initializer cannot reference the nonstatic field method or property
.
string lia = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
StreamReader fileitem=new StreamReader(Path.Combine(lia,"dataset.txt")); //Error line
I thin, it can not recognize lia
as string.
Any idea?
Upvotes: 2
Views: 4847
Reputation: 1502496
I thin, it can not recognize lia as string.
No, it's recognizing it just fine - but as the error says, you can't use the value of one instance variable within the initializer for another.
The simplest fix is usually to put the initialization in the constructor instead:
public class Foo
{
// TODO: Fix names to be more conventional and friendly
string lia = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
StreamReader fileitem;
public Foo()
{
fileitem=new StreamReader(Path.Combine(lia,"dataset.txt"));
}
}
On the other hand, it's not clear that these should be fields at all... we don't have enough context to be sure, but perhaps you should consider whether these should be local variables within a method, instead of instance fields declared in a class?
Upvotes: 8