473,836 Members | 1,582 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Public property or variable ?

Should I use:

Private m_Name As String

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

or just

Public Name As String

The last one just has to be faster, or am I wrong?

Stefan
Nov 21 '05 #1
9 8878
"Stefan De Schepper" <st************ ****@skynet.be> schrieb:
Should I use:

Private m_Name As String

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

or just

Public Name As String

The last one just has to be faster, or am I wrong?


If 'Name' is an attribute of the entity represented by the class, I strongly
recommend to use a property instead of a public variable.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #2
When you create a Property, you'll have a Set section to write validation
code into. If you just use a Public field any string value passed to it
must be accepted. Properties also help you create your class in a more
object oriented way since the property acts as an abstraction layer to the
internal data. In other words, you'll be creating more of a "black box" if
you use the property.
"Stefan De Schepper" <st************ ****@skynet.be> wrote in message
news:42******** **************@ news.skynet.be. ..
Should I use:

Private m_Name As String

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

or just

Public Name As String

The last one just has to be faster, or am I wrong?

Stefan

Nov 21 '05 #3
There is a major difference between the usefulness of properties and
variables. There are what the others have said about it being more object
oriented and it's true, but there are other reasons.

Let's say, for some reason, you want the Name property to be readonly, you
can't do it with the public variable, but you can with the property. Let's
say you have some bug and you want to log every action in your application,
but using a property you can add a line like Log.WriteLine(" SettingName: " &
Value) and there you go. You can't do this neither with the public variable

I hope you get the point and I hope it helps

ThunderMusic

"Stefan De Schepper" <st************ ****@skynet.be> a écrit dans le message
de news:42******** **************@ news.skynet.be. ..
Should I use:

Private m_Name As String

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

or just

Public Name As String

The last one just has to be faster, or am I wrong?

Stefan

Nov 21 '05 #4
As you can see that from the responses, people on this newsgroup don't like
fields but are stuck on properties. I find fields useful in certain
situations and would suggest you use whatever is best for you. As for the
speed, I wrote a test program to read and write to both a string field and a
stirng property where the property was stored as a private variable. I did
this for 10m cycles and found very little difference then upped it to 100m
cycles and found that reading/writing to a field is pretty consistently 120
seconds faster than reading/writing a property on my computer.
--
Dennis in Houston
"Stefan De Schepper" wrote:
Should I use:

Private m_Name As String

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

or just

Public Name As String

The last one just has to be faster, or am I wrong?

Stefan

Nov 21 '05 #5
As for your performance test, it's obvious that working with just the field
will perform better. But, if you read the responses, you'll see why we are
"stuck" on properties. They offer much more security and flexibility than
fields and in all but the most demanding situations does the performance gap
that you mention actually make a difference.
"Dennis" <De****@discuss ions.microsoft. com> wrote in message
news:FE******** *************** ***********@mic rosoft.com...
As you can see that from the responses, people on this newsgroup don't
like
fields but are stuck on properties. I find fields useful in certain
situations and would suggest you use whatever is best for you. As for
the
speed, I wrote a test program to read and write to both a string field and
a
stirng property where the property was stored as a private variable. I
did
this for 10m cycles and found very little difference then upped it to 100m
cycles and found that reading/writing to a field is pretty consistently
120
seconds faster than reading/writing a property on my computer.
--
Dennis in Houston
"Stefan De Schepper" wrote:
Should I use:

Private m_Name As String

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

or just

Public Name As String

The last one just has to be faster, or am I wrong?

Stefan

Nov 21 '05 #6
ThunderMusic,
| Let's say, for some reason, you want the Name property to be readonly, you
| can't do it with the public variable, but you can with the property.
You can make public & private fields (variables) readonly, by adorning them
with the Readonly keyword. Such as:

Public Readonly Name As String

When you use Readonly on a field you can only set the field in the
constructor.

Public Sub New(ByVal name As String)
Me.Name = name
End Sub

I use readonly fields in my classes when the value of said field is
immutable for the lifetime of that instance of the object. This ensures that
I or one of my predecessors know that the field itself is not meant to
change...

NOTE: Readonly properties with read/write fields are useful for "State"
properties such as SqlConnection.S tate where the property reports the
"state" of the object, while other methods (Open, Close) modify that
"state".

| but using a property you can add a line like Log.WriteLine(" SettingName: "
&
| Value) and there you go. You can't do this neither with the public
variable
Agreed...

Hope this helps
Jay
"ThunderMus ic" <NO*******@symp atico.caSPAMATA LL> wrote in message
news:%2******** ********@TK2MSF TNGP14.phx.gbl. ..
| There is a major difference between the usefulness of properties and
| variables. There are what the others have said about it being more object
| oriented and it's true, but there are other reasons.
|
| Let's say, for some reason, you want the Name property to be readonly, you
| can't do it with the public variable, but you can with the property. Let's
| say you have some bug and you want to log every action in your
application,
| but using a property you can add a line like Log.WriteLine(" SettingName: "
&
| Value) and there you go. You can't do this neither with the public
variable
|
| I hope you get the point and I hope it helps
|
| ThunderMusic
|
| "Stefan De Schepper" <st************ ****@skynet.be> a écrit dans le
message
| de news:42******** **************@ news.skynet.be. ..
| > Should I use:
| >
| > Private m_Name As String
| >
| > Public Property Name() As String
| > Get
| > Return m_Name
| > End Get
| > Set(ByVal Value As String)
| > m_Name = Value
| > End Set
| > End Property
| >
| > or just
| >
| > Public Name As String
| >
| > The last one just has to be faster, or am I wrong?
| >
| > Stefan
| >
| >
|
|
Nov 21 '05 #7
Dennis,
| I did
| this for 10m cycles and found very little difference then upped it to 100m
| cycles and found that reading/writing to a field is pretty consistently
120
| seconds faster than reading/writing a property on my computer.

I would expect your results to be closer to zero, as there is a good chance
the JIT will inline the property Getter & Setter.

http://msdn.microsoft.com/library/de...anagedapps.asp

Did you test the Debug or Release build of your app?

Did you test from a command prompt or from Visual Studio?

If you tested the Debug build from Visual Studio, then the JIT will not
attempt to optimize the code. However if you tested the Release build from
the command line then the JIT will attempt to "fully" optimize the code.

Your numbers suggests you tested a Debug build, possible under Visual
Studio!

Try the following from a command prompt for both Debug & Release builds:

Declare Function QueryPerformanc eCounter Lib "Kernel32" (ByRef X As
Long) As Short
Declare Function QueryPerformanc eFrequency Lib "Kernel32" (ByRef X As
Long) As Short

Private Class Person

Public m_name As String

Public Sub New(ByVal name As String)
m_name = name
End Sub

Public Property Name() As String
Get
Return m_name
End Get
Set(ByVal value As String)
m_name = value
End Set
End Property
End Class

Public Shared Sub Main()
Const MaxCount As Integer = 1000000
Const format As String = "{1}: {0}"

Dim aPerson As New Person("Jay")

For outerCount As Integer = 1 To 5
Dim start, finish, frequency As Long
QueryPerformanc eFrequency(freq uency)

QueryPerformanc eCounter(start)
For innerCount As Integer = 1 To MaxCount
aPerson.Name = "Fred"
Next
QueryPerformanc eCounter(finish )
Console.WriteLi ne(format, TimeSpan.FromSe conds((finish - start)
/ frequency), "Property")

QueryPerformanc eCounter(start)
For innerCount As Integer = 1 To MaxCount
aPerson.m_name = "Fred"
Next
QueryPerformanc eCounter(finish )
Console.WriteLi ne(format, TimeSpan.FromSe conds((finish - start)
/ frequency), "Field")
Next

End Sub

For Debug builds you should see Property much larger then Field. For Release
builds you should see both numbers nearly the same.

Hope this helps
Jay


"Dennis" <De****@discuss ions.microsoft. com> wrote in message
news:FE******** *************** ***********@mic rosoft.com...
| As you can see that from the responses, people on this newsgroup don't
like
| fields but are stuck on properties. I find fields useful in certain
| situations and would suggest you use whatever is best for you. As for
the
| speed, I wrote a test program to read and write to both a string field and
a
| stirng property where the property was stored as a private variable. I
did
| this for 10m cycles and found very little difference then upped it to 100m
| cycles and found that reading/writing to a field is pretty consistently
120
| seconds faster than reading/writing a property on my computer.
| --
| Dennis in Houston
|
|
| "Stefan De Schepper" wrote:
|
| > Should I use:
| >
| > Private m_Name As String
| >
| > Public Property Name() As String
| > Get
| > Return m_Name
| > End Get
| > Set(ByVal Value As String)
| > m_Name = Value
| > End Set
| > End Property
| >
| > or just
| >
| > Public Name As String
| >
| > The last one just has to be faster, or am I wrong?
| >
| > Stefan
| >
| >
| >
Nov 21 '05 #8
Stefan,
In addition to the other comments.

| The last one just has to be faster, or am I wrong?
Your wrong! The JIT compiler has the option to inline the property Get & Set
routines (actually any short method). Which means the Property will execute
exactly the same as a Field! See my response to Dennis on details & a
demonstration.

http://msdn.microsoft.com/library/de...anagedapps.asp

I would be more concerned about what is "correct". The property suggests
better encapsulation, remember Encapsulation is one of the major tenants of
OO.

Properties also play nicer with System.Componen tModel,
System.Windows. Forms.PropertyG rid and COM interop.

I would not code a field or property based on perceived runtime performance.

Remember the 80/20 rule. That is 80% of the execution time of your program
is spent in 20% of your code. I will optimize (worry about performance,
memory consumption) the 20% once that 20% has been identified & proven to be
a performance problem via profiling (CLR Profiler is one profiling tool).

For info on the 80/20 rule & optimizing only the 20% see Martin Fowler's
article "Yet Another Optimization Article" at
http://martinfowler.com/ieeeSoftware...timization.pdf

Here are some thoughts on not using properties:

http://blogs.msdn.com/ericgu/archive...29/123588.aspx
Hope this helps
Jay
"Stefan De Schepper" <st************ ****@skynet.be> wrote in message
news:42******** **************@ news.skynet.be. ..
| Should I use:
|
| Private m_Name As String
|
| Public Property Name() As String
| Get
| Return m_Name
| End Get
| Set(ByVal Value As String)
| m_Name = Value
| End Set
| End Property
|
| or just
|
| Public Name As String
|
| The last one just has to be faster, or am I wrong?
|
| Stefan
|
|
Nov 21 '05 #9
You are correct in that I tested it in debug mode. As for using Properties
vs Fields, I fully understand the consequences of using one over the other so
I use what works for me in a particulair situation. I'm not a purist and I
know there are several ways to skin a cat! If I have a class that contains
something like a boolean value and it's independent of whatever else is in
the class, I see no reason to not just use a field.

--
Dennis in Houston
"Jay B. Harlow [MVP - Outlook]" wrote:
Dennis,
| I did
| this for 10m cycles and found very little difference then upped it to 100m
| cycles and found that reading/writing to a field is pretty consistently
120
| seconds faster than reading/writing a property on my computer.

I would expect your results to be closer to zero, as there is a good chance
the JIT will inline the property Getter & Setter.

http://msdn.microsoft.com/library/de...anagedapps.asp

Did you test the Debug or Release build of your app?

Did you test from a command prompt or from Visual Studio?

If you tested the Debug build from Visual Studio, then the JIT will not
attempt to optimize the code. However if you tested the Release build from
the command line then the JIT will attempt to "fully" optimize the code.

Your numbers suggests you tested a Debug build, possible under Visual
Studio!

Try the following from a command prompt for both Debug & Release builds:

Declare Function QueryPerformanc eCounter Lib "Kernel32" (ByRef X As
Long) As Short
Declare Function QueryPerformanc eFrequency Lib "Kernel32" (ByRef X As
Long) As Short

Private Class Person

Public m_name As String

Public Sub New(ByVal name As String)
m_name = name
End Sub

Public Property Name() As String
Get
Return m_name
End Get
Set(ByVal value As String)
m_name = value
End Set
End Property
End Class

Public Shared Sub Main()
Const MaxCount As Integer = 1000000
Const format As String = "{1}: {0}"

Dim aPerson As New Person("Jay")

For outerCount As Integer = 1 To 5
Dim start, finish, frequency As Long
QueryPerformanc eFrequency(freq uency)

QueryPerformanc eCounter(start)
For innerCount As Integer = 1 To MaxCount
aPerson.Name = "Fred"
Next
QueryPerformanc eCounter(finish )
Console.WriteLi ne(format, TimeSpan.FromSe conds((finish - start)
/ frequency), "Property")

QueryPerformanc eCounter(start)
For innerCount As Integer = 1 To MaxCount
aPerson.m_name = "Fred"
Next
QueryPerformanc eCounter(finish )
Console.WriteLi ne(format, TimeSpan.FromSe conds((finish - start)
/ frequency), "Field")
Next

End Sub

For Debug builds you should see Property much larger then Field. For Release
builds you should see both numbers nearly the same.

Hope this helps
Jay


"Dennis" <De****@discuss ions.microsoft. com> wrote in message
news:FE******** *************** ***********@mic rosoft.com...
| As you can see that from the responses, people on this newsgroup don't
like
| fields but are stuck on properties. I find fields useful in certain
| situations and would suggest you use whatever is best for you. As for
the
| speed, I wrote a test program to read and write to both a string field and
a
| stirng property where the property was stored as a private variable. I
did
| this for 10m cycles and found very little difference then upped it to 100m
| cycles and found that reading/writing to a field is pretty consistently
120
| seconds faster than reading/writing a property on my computer.
| --
| Dennis in Houston
|
|
| "Stefan De Schepper" wrote:
|
| > Should I use:
| >
| > Private m_Name As String
| >
| > Public Property Name() As String
| > Get
| > Return m_Name
| > End Get
| > Set(ByVal Value As String)
| > m_Name = Value
| > End Set
| > End Property
| >
| > or just
| >
| > Public Name As String
| >
| > The last one just has to be faster, or am I wrong?
| >
| > Stefan
| >
| >
| >

Nov 21 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
6876
by: Will Gillen | last post by:
I know this has probably been asked before, but I can't seem to find a solid answer in any of the archives. First, before my question, please forgive my limited knowledge of the event lifecycle and page loading/rendering lifecycle.... Ok, now for the question: I have an ASPX page (page.aspx), and I have a UserControl (control.ascx). The UserControl has one textbox on the control, and one button control. I have added a public property...
0
1509
by: student | last post by:
In Summary: Create an object - dont set one of its Enum Type properties and make sure it does not appear in XML Object Serialization. Strings function as hoped for but Enums do not Heres my problem broken down to simplest form I have the following ENUM ----------------------------------------------
4
1272
by: funVB2005fun | last post by:
I am not quite sure what I am getting into but I would like to have a loop that read from a flat file to create some public properties in a class. I am going after this to try and create more general software that others could benefit from vs hardcoding things that relate only to my processes. example property that I would want to generate: The idea would be to read from a file that "AGE" is needed and that it is and Integer and then to...
2
1883
by: Richard | last post by:
I'm trying to open a form based on the value that I am passing through to it. I'm trying to open the Deals form on the basis of a sellerid that I am trying to pass through to that second form. At the push of a button on the first form: Dim cfrmDeals As New frmDeals cfrmDeals.SellerNo = Convert.ToInt32(txtSellerID.Text) cfrmDeals.Visible = True cfrmDeals.Activate()
2
3209
by: miben | last post by:
I need to set a variable returned by a readonly property in a class by another class. So the only way to set that value is from a specific class and function. Public Sub Main Dim setter As New GoingToSetYou Dim item As New ToBeSet setter.NewItem(item) Dim sValue As String = item.Value
4
1353
by: Jon Paal | last post by:
I have a public property in my server control and I want to populate it with values generated by the control. When I assign the value of the property to a function in the control, which creates the values, I get a compilation error that says the function doesn't have all the other property values to work with. So, how do I populate the arraylist as a public property, so I can use it in my web page ? ========== code in use ==========...
3
2272
by: jbeteta | last post by:
Hello, I have a problem declaring variables. I need to create an object oRpte as ReportClass on WebForm1.aspx and be able to use its value on WebForm2.aspx. For declaring the property oRpte() on WebForm1.aspx, I use "Public Property" and I declare variable _oRpte as Friend Shared. That's my problem. If I don't declare _oRpte as Friend Shared, I can't use WebForm1.oRpte() on other webpage. If I declare _oRpte as Friend Shared, I can use...
6
9173
by: =?Utf-8?B?SmF5IFBvbmR5?= | last post by:
I am trying to access a Public property on a Master Page from a Base Page. On the content pages I have the MasterType Directive set up as follows: <%@ MasterType virtualpath="~/Master.master" %> On the Master Page I have a public property exposed: Public Property ErrorMessage() As String Get Return txtError.InnerText End Get
0
993
by: abev | last post by:
I am still trying to get my arms around properties and why I should use them more. But I just cannot understand when I should be using properties as opposed to just declaring a 'public shared' variable? For example, if I am creating an MDI app and I want to store the CustomerID that gets passed between various Customer Detail forms, why not just set the CustomerID variable to the customerid on the MDI parent?
0
9668
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10546
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10589
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10254
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9371
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7790
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5825
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4015
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3112
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.