473,738 Members | 2,645 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Public data members vs get/set properties

Perhaps I'm missing something obvious, but I've been curious about one of
the coding practices I see advocated. I'm a longtime C/C++ programmer
trying to learn C#, and I started looking around for coding standards/best
practices.

Several of the documents I've read require that all members be private (or
protected), and the get/set properties be provided for any elements exposed
to the outside world.

In C++ this makes perfect sense, because method syntax differs from member
syntax. Making a member variable public ties your hands, because if you
ever want to change the behavior of the member and replace it with a public
method, you break existing code.

However, one of the beauties of properties in C# is that consumers of a
class use member syntax to manipulate a property. I can declare a public
member variable and lets consumers use it. Then in the future I discover
that the implementation needs to change and that instead of permitting
direct access to a member I want to add validation, or update dependent
data, fire an event, etc. To do that I simply rename the member, make it
private, and implement get/set properties that conform to the semantics of
the old member. These of course are methods internally, so I can place any
needed logic in the method. I have to rename the member inside my class,
but the external interface doesn't change at all.

From my C++ background I have a knee jerk reaction that public data members
in a class are evil, but objectively I don't see why this is necessarily the
case in C#.

Obvious caveats:
1. If a coding standard dictates that members have a different naming
convention from properties, then it is necessary to have both.
2. If the property get/set methods are more than simple accessors that read
and write a variable, then it is necessary to use the properties. But I'd
bet that many, many properties exist that are nothing more than a single
assignment or return.

Am I missing a more fundamental reason to use properties instead of public
data members in C#?

Joe
Nov 17 '05 #1
3 10884
Joe,

Syntactically, the calls are the same, however, on the IL level, they
are vastly different. To set the value for a field, you have an IL
instruction stfld (I believe), which sets the appropriate field with the
value at the top of the stack. With setting a property, its a method call.

While it looks the same in the code, they boil down to two very
different things. Also, when you change to a property, you change the
signature of the type, and anything that is setting that field to something
will break.

You are right, many implementations of properties are nothing more than
a set to a private field and a return. However, if you ever need to change
to a property to introduce a more complex implementation, it's better to
have that done sooner than later. This is the reason for the recommendation
in the guidelines published by MS.

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Joe Fromm" <Jo*******@Pear son.com> wrote in message
news:ON******** ******@TK2MSFTN GP12.phx.gbl...
Perhaps I'm missing something obvious, but I've been curious about one of
the coding practices I see advocated. I'm a longtime C/C++ programmer
trying to learn C#, and I started looking around for coding standards/best
practices.

Several of the documents I've read require that all members be private (or
protected), and the get/set properties be provided for any elements
exposed
to the outside world.

In C++ this makes perfect sense, because method syntax differs from member
syntax. Making a member variable public ties your hands, because if you
ever want to change the behavior of the member and replace it with a
public
method, you break existing code.

However, one of the beauties of properties in C# is that consumers of a
class use member syntax to manipulate a property. I can declare a public
member variable and lets consumers use it. Then in the future I discover
that the implementation needs to change and that instead of permitting
direct access to a member I want to add validation, or update dependent
data, fire an event, etc. To do that I simply rename the member, make it
private, and implement get/set properties that conform to the semantics of
the old member. These of course are methods internally, so I can place
any
needed logic in the method. I have to rename the member inside my class,
but the external interface doesn't change at all.

From my C++ background I have a knee jerk reaction that public data
members
in a class are evil, but objectively I don't see why this is necessarily
the
case in C#.

Obvious caveats:
1. If a coding standard dictates that members have a different naming
convention from properties, then it is necessary to have both.
2. If the property get/set methods are more than simple accessors that
read
and write a variable, then it is necessary to use the properties. But I'd
bet that many, many properties exist that are nothing more than a single
assignment or return.

Am I missing a more fundamental reason to use properties instead of public
data members in C#?

Joe

Nov 17 '05 #2
>
While it looks the same in the code, they boil down to two very
different things. Also, when you change to a property, you change the
signature of the type, and anything that is setting that field to something will break.


Ah, that makes sense. So public properties maintain source compatibility,
but not binary compatibility.
Nov 17 '05 #3
Joe Fromm <Jo*******@Pear son.com> wrote:
While it looks the same in the code, they boil down to two very
different things. Also, when you change to a property, you change the
signature of the type, and anything that is setting that field to

something
will break.


Ah, that makes sense. So public properties maintain source compatibility,
but not binary compatibility.


They don't even maintain source compatibility - you can pass a field by
reference, but not a property (in C#, anyway). Also, anything using
reflection will see the difference, of course.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #4

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

Similar topics

10
5787
by: Zap | last post by:
Widespread opinion is that public data members are evil, because if you have to change the way the data is stored in your class you have to break the code accessing it, etc. After reading this (also copied below for easier reference): http://groups.google.it/groups?hl=en&lr=&safe=off&selm=6beiuk%24cje%40netlab.cs.rpi.edu&rnum=95 I don't agree anymore.
3
1550
by: ectoplasm | last post by:
I'd like to ask for advice on the following. I have a data structure of network elements ('NetworkElement' base class & derived classes like Server, Area, Cell, etc.) The network elements are organised under a network topology ('NetworkTopology' class). The problem is that the properties (data members) of network elements depend on things such as: 1) technology of the network topology, 2)
8
4016
by: Allen Anderson | last post by:
Just curious if there is a way to hide a public member inherited from another class. I know you can 'new' to give it your own version, but is there a way to make it no longer public period? I would like the base class version to stay there, just be protected instead. I can't make the baseclass version protected because there are times when the baseclass can be used by itself.
6
1895
by: darrel | last post by:
I'm still not quite sure how best to handle the passing of data between controls. This is a method I'm using at the moment: I have an XML file that contains a variety of page-centric variables. I have one control that loads the XML file, reads through it, and grabs the variables it needs. It then sets these to PUBLIC variables. Then, other usercontrols simply request that variable.
4
2515
by: louise raisbeck | last post by:
Resending this as own topic as didnt get answer from original. Would be grateful for a response from anyone that knows. Thanks. Hi there, I found your post really helpful..but i wondered if, once I have exposed a public property containing the value of a textbox in a user control..how do I grab this from the calling page? I cant think of the syntax, since my page doesnt know the contents of the class (and therefore, the public...
18
2752
by: Joel Hedlund | last post by:
Hi! The question of type checking/enforcing has bothered me for a while, and since this newsgroup has a wealth of competence subscribed to it, I figured this would be a great way of learning from the experts. I feel there's a tradeoff between clear, easily readdable and extensible code on one side, and safe code providing early errors and useful tracebacks on the other. I want both! How do you guys do it? What's the pythonic way? Are...
9
2359
by: Rudy | last post by:
Hello All! I'm a little confused on Public Class or Modules. Say I have a this on form "A" Public Sub Subtract() Dim Invoice As Decimal Dim Wage As Decimal Static PO As Decimal Invoice = CDec(txbInv.Text) Wage = CDec(txbTotWage.Text)
86
4637
by: jopperdepopper | last post by:
Hi, finally giving php 5 a go, and going over the new approach to classes. Can someone clarify the public, private and protected to me? I quote the php manual: "The visibility of a property or method can be defined by prefixing the declaration with the keywords: public, protected or private. Public declared items can be accessed everywhere."
0
1186
by: pvishweshwar | last post by:
Hi All, am developing one application in which i have to retrieve the msolap dimension members properties data.In this till now am able to get the member values properly.But the problem is am not able to retrieve the properties values.Can any one help on this. am sending that part of code how am retrieving the member data. For intDimCount = 0 To cst.Axes(0).DimensionCount - 1
0
8968
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
9259
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
9208
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
8208
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
6750
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
6053
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4569
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3279
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2744
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.