1

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.

2
  • How does the code know what object belongs to StrLog, you've declared a public property of the class (this property is associated with a class object). Commented Nov 30, 2012 at 16:56
  • 1
    The field initializers run before the properties initializers, so StrLog isn't created yet. (Gross over simplification) Commented Nov 30, 2012 at 16:58

3 Answers 3

3

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. How do I set the value of imgData with StrLog as I had it as - public string StrLog {get; set;}. Basically, how do I set imgData to the value of the Property that I will be passing in.
Why? It doesn't make sense. Just read from StrLog whenever you need it rather than reading from imgData
1

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.

Comments

-1

Make imgData your property , same way as Strlog. and then assign . it will work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.