Reputation: 46322
I have the following code in my class:
public string StrLog {get; set;}
then within the same class, I have the following code:
private string imgData = StrLog;
I get the following error message:
A field initializer cannot reference the non-static field, method or property
It has a problem with:
private string imgData = StrLog;
but not sure how to resolve this.
Upvotes: 1
Views: 2122
Reputation: 1442
You are not allowed to use a non-static memeber to intialize a member variable.
You need to intialize it first by setting it up in your constructor.
eg:
imgData = null;
I would strongly encourage you to assign something (something could be null) in the constructor. It's just good form. In the example below, you will see why it is important. What if a get is executed first and the value isn't set? It should at least contain a null value.
Having said that, if you want the value of imgData to be populated with the value of your public-facing property, you need to do the following:
public string StrLog
{
get { return imgData; }
set { imgData = value; }
}
This will pass the value of StrLog into imgData, with no work required on your part.
Upvotes: 1
Reputation: 327
Make imgData your property , same way as Strlog. and then assign . it will work.
Upvotes: -1
Reputation: 48455
Basically, you cannot initialise a class level variable by using any other class level value (unless that value is static) - which is what your error is trying to tell you.
Your best option would be to assign the value in your constructor:
private string imgData = null;
public MyClass()
{
imgData = "some value";
}
In your case there is no point assigning it the value of StrLog
because StrLog
won't have a value to begin with. So you may as well just assign it null
, or an actual value form somewhere else (like my example)
Upvotes: 3