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:

[code language=”c#”]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 }); } } }[/code]

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

[code language=”xml”]< ?xml version=”1.0” encoding=”utf-8”?> [/code]

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