2

As a newbie in C#, I am trying to figure out why I have to put CardNumber as such as static in order to fit into the formatted string....

If I didn't add static string CardNumber but use string CardNumber;, the code would report an error with the last CardNumber underlined. The error goes: A field initializer cannot reference the non-static field, method, or property 'WriteXML.CardNumber'.

I know there are tons of static and non-static comments and questions out there. None of them seems to directly explain, "if using non-static in a formatted string, then _ will happen, or then _ won't make any sense". If duplicate, please kindly point out the resource at least. I really appreciate it!

class WriteXML
{
    static string CardNumber;
    static string ExpMo;
    static string ExpYr;
    static string FirstName;
    static string LastName;
    string xmlContent =
        string.Format("<CardNumber>{0}</CardNumber>" +
        "<ExpMo>{1}</ExpMo>" +
        "<ExpYr>{2}</ExpYr>" +
        "<FirstName>{3}</FirstName>" +
        "<LastName>{4}</LastName>", 
            CardNumber, ExpMo, ExpYr, FirstName, LastName);
}
1
  • 2
    why would you want to generate xml from a static class?
    – DLeh
    Jul 30, 2015 at 17:48

4 Answers 4

7

Field initializers run before the object is fully constructed, so they can't access other fields in the same object because those fields might not be initialized yet. The order that field initializers run in is not guaranteed.

For example, if you had something like:

public class Foo
{
    string someField = "foo";
    string someOtherField = someField + "bar";
}

Then the initialization of someOtherField can't happen until someField has been initialized.

So you have to initialize someOtherField somewhere else, once the object has been constructed and all the field initializers have run. One place would be the constructor:

public class Foo
{
    string someField = "foo";
    string someOtherField;   // can't initialize yet

    public Foo()
    {
        someOtherField = someField + "bar";
    }
}

Another alternative, especially if someOtherField isn't supposed to be writable, would be to use a property:

public class Foo
{
    string someField = "foo";
    )string SomeProperty
    {
        get { return someField + "bar"; }
    }
}

This defers working out what SomeProperty is until you actually try and access it and, as a bonus, if someField is changed after construction, then SomeProperty will automatically synch up to the new value.

For example:

var f = new Foo();
Console.WriteLine(f.SomeProperty);   // displays "foobar"
                                     // assuming we'd marked it public
f.someField = "la";                  // assuming we'd made that public  too!
Console.WriteLine(f.SomeProperty);   // displays "labar"
3

The answer to this question is found in C# Language Specification:

A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference this in a variable initializer, as it is a compile-time error for a variable initializer to reference any instance member through a simple-name.

In your code below, xmlContent is an instance field that has a variable initializer than references instance members CardNumber, ExpMo, ExpYr, FirstName, LastName. They are instance members when you omit the static field modifier. So it is not up to the spec, and hence the compile-time error.

string xmlContent =
        string.Format("<CardNumber>{0}</CardNumber>" +
        "<ExpMo>{1}</ExpMo>" +
        "<ExpYr>{2}</ExpYr>" +
        "<FirstName>{3}</FirstName>" +
        "<LastName>{4}</LastName>", 
            CardNumber, ExpMo, ExpYr, FirstName, LastName);

See @Matt Burland's answer how to work around this issue.

1

I am not really sure what you are trying to achieve, but maybe this code will help you.

public class Foo
{
    string CardNumber { get; set;}
    string ExpMo { get; set; }
    string ExpYr { get; set; }
    string FirstName { get; set; }
    string LastName { get; set; }

    public String WriteXml()
    {
        string xmlContent =
        string.Format("<CardNumber>{0}</CardNumber>" +
        "<ExpMo>{1}</ExpMo>" +
        "<ExpYr>{2}</ExpYr>" +
        "<FirstName>{3}</FirstName>" +
        "<LastName>{4}</LastName>",
        CardNumber, ExpMo, ExpYr, FirstName, LastName);

        return xmlContent;
    }
}
1

I'll try to quote and complete your desired explanation sentence:

If using a non-static reference in a formatted string (more general, in another non-static field), then that string/field will not be able to access it because it needs in the first palce a reference to an initialized object (non-static means that it can have different values based on different objects where the field lives in). Using a static field it can access anytime without needing an initialized object.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.