1

I am learning C#. I saw something like the code below. My questions are: how do you know what to put inside the [ ]? Do you have to add them manually one by one or there is a tool (such as visual studio) to do that? It is not just limited to xml, of course. I searched online, it is attribute annotion. Is there any good reference to read?

    [XmlRoot("Logs")]
    public class LogConfig {

        [XmlArray("Servers")]
        [XmlArrayItem("Server")]
        public Server[] servers{
         set; get;   
        }

        public LogConfig(){
        }        
    }
ericyoung
  • 621
  • 2
  • 15
  • 21

2 Answers2

1

Attributes are normal classes, which means you can define your own! For an example of how to do that, see here. What you put in the [] is the name of the class. What you put in the () is defined by what properties the attribute class has.

For example (this is from the MSDN article linked above), for the attribute class below:

[System.AttributeUsage(System.AttributeTargets.Class)]
public class Author : System.Attribute
{
    private string name;
    public double version;

    public Author(string name)
    {
        this.name = name;
        version = 1.0;
    }
}

You can add this attribute to a class like so:

[Author("P. Ackerman", version = 1.1)]
class SampleClass
{
    // P. Ackerman's code goes here...
}

For a list of already defined attributes in the .NET framework, see the bottom of this page.

vlad
  • 4,748
  • 2
  • 30
  • 36
0

Do you have to add them manually one by one

Yes.

You learn about these attributes and how to apply them.


Some tools can generate classes from XSD or JSON which may contain attributes like the above, but if you are writing the class, you will need to add the attributes yourself.

No tool can guess at how a class will map to an XML structure.

Oded
  • 489,969
  • 99
  • 883
  • 1,009