C# Automatic Properties can have Attributes

The MSDN documentation for Automatic Properties (a C# 3 language feature) states that attributes are not valid on automatic properties. This is not true, the following code compiles and works as expected:

public class Data
{
    [XmlAttribute]
    public int SomeNumber { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        using (XmlWriter w = XmlWriter.Create(@"c:\temp\test.xml"))
        {
            XmlSerializer s = new XmlSerializer(typeof (Data));
            s.Serialize(w, new Data { SomeNumber = 5 });
        }
    }
}

Running this code results in an XML file looking roughly like this (I stripped some unneeded namespace declarations):

< ?xml version="1.0" encoding="utf-8"?>
<data SomeNumber="5" />

SomeNumber is saved as an attribute, so the XmlAttribute attribute worked correctly.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*