Re: Public variable not the same as using a property?
- From: "PvdG42" <pvdg@xxxxxxxxxxxxx>
- Date: Fri, 14 Sep 2007 08:55:28 -0500
"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 shouldconsider 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.
.
- Follow-Ups:
- References:
- Prev by Date: Re: Public variable not the same as using a property?
- Next by Date: Re: Vb 2003 Framework 1.1
- Previous by thread: Re: Public variable not the same as using a property?
- Next by thread: Re: Public variable not the same as using a property?
- Index(es):
Relevant Pages
|