by Dominic Zukiewicz
11. July 2007 15:34
Today I was testing out the XmlSerializer to see how it dealt with variables instead of properties.
I tried to read an XML file directly into code, and which was the most convenient:
XML
<myclass>
<Number1></Number1>
<Text1>Hello!</Text1>
<Decimal1>1.35262646464</Decimal1>
</myclass>
And now, lets see the 2 examples of source code
Version 1:
public class MyClass
{
public int Number1;
public string Text1;
public decimal Decimal1;
}
Version 2:
public class MyClass
{
private int number1;
public int Number1 { get { return number1; } set { number1 = value; }
private string text1;
public string Text1{ get { return text1; } set { text1= value; }
private decimal decimal1;
public decimal Decimal1{ get { return decimal1; } set { decimal1 = value; }
}
In my opinion, if you are purely reading and writing XML, and that for all your variables you are allowing read/write access, you should use public variables. Unfortuantely, as stubborn as I am, there are reasons to use properties, which I'll reference here.
http://www.codinghorror.com/blog/archives/000654.html
In summary, when reflecting through a class, public variables are accessed differently to properties. Also, changing public variables to public properties is a breaking change to code.
I recommend reading it thoroughly as it is a good argument!!
66da760a-2fb3-408a-b5ed-4e24b6778bd2|0|.0
Tags: