Properties Vs Public Variables

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!!

Tags:

Powered by BlogEngine.NET 1.5.0.7
Theme by Interakting

Interakting

A full service digital agency offering online strategy, design and usability, systems integration and online marketing services that deliver real business benefits and ensure your online objectives are met.

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar