Re: Public variable not the same as using a property?

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



On Fri, 14 Sep 2007 08:55:28 -0500, "PvdG42" <pvdg@xxxxxxxxxxxxx>
wrote:

"dgk" <dgk@xxxxxxxxxxxxx> wrote in message
news:k82le35h7tu7ap35tc23bpfr7gf32ordfi@xxxxxxxxxx
If I have a class with a public variable, isn't this the same as a
private variable with a property? ie, isn't this:

Public Class MyTest
Public MyVar as String
End Class

the same as this:

Public Class MyTest
Private _MyVar as String
Property MyVar
Get
Return _MyVar
End Get
Set (byval value as String)
_MyVar = value
End Set
End Property
End Class


I always thought so, in fact, I thought that the complier converted
the first into the second.

Yet, when I try to databind a generic list of MyTest to a gridview
using the first syntax, it fails. When I use the second syntax it
succeeds.

Does anyone know why?

From a design perspective, they are very different. And IMHO, you should
consider the difference.
If you declare the variable as public, you are giving unrestricted access to
that variable to code outside the class, thus exposing the variable to
potential corruption and breaking encapsulation. By declaring the variable
private, then supplying a public property in your class, you have the
opportunity and ability to control access to that variable by either not
providing a Set block, or by adding logic in the Set block that will
disallow illogical values.

Well sure, but if you don't care what comes in or goes out, then it's
a lot cleaner to just declare a public variable. Also quicker to type.
One line instead of six or seven (even if using a snippet).

One of the things I don't like about VB is that Readonly on the
property. I mean, if there's no Set, then it's readonly. I'm sure they
did that for a reason but I can't figure out why.


Well, anyway, if you're planning on using Databind, don't use public
properties.
.



Relevant Pages