473,786 Members | 2,795 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

setting private fields in a constructor

If a class uses public properties to expose private fields, and has a
constructor to initialize those fields, should the constructor set them
directly or use the set accessors? Or does it matter?

Michael Roper
Nov 15 '05 #1
9 1996
I don't think there's a general answer to this one.

If the set accessor simply sets the field and nothing more, then there's
not much odds. One might worry that the set accessor is a bit slower,
but I think that will be optimised away in most cases. However, even if
the set accessor does nothing special, there is always the issue that it
might do something in future.

If the set accessor does do something special, then its a question of
whether you want to do that special thing. As class desginer you know
what needs to be done and you can make the decisions.

For example, suppose you have a set accessor that ensures an int is in
the range 0-10, and throws an exception if not. If you call it with a
hard-coded 0 in the constructor, then you're wasting time going through
the set accessor. However, if the restriction were to change, then 0
might become invalid and you'd want to catch that.

If the set accessor were to, say, count the number of times that the
field was changed, then you certainly wouldn't want to increment that
count from the constructor, because thats initialisation, not change.

Another issue to consider is if the property is virtual. If so, then you
probably should call the set accessor to pick up any derived
functionality, but again it may depend on the context. Also, calling
virtual methods from a constructor is always dubious - less so in C#
than it was in C++, but still not great.

Regards,

Jasper Kent

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 15 '05 #2
Thanks for the thoughtful reply Jasper.

Michael Roper
Nov 15 '05 #3
Just to put in my two-cents. I almost always use the property getter /
setter within my own classes - including the constructor. If I'm doing any
sort of bounds checking / error checking then I surely want to make sure I
continue to use that, inside or outside of my class. Purely cosmetic, but I
generally think the code is easier to read - at least for me:

public MyClass()
{
Width = 10;
}

vs.

public MyClass()
{
_width = 10; // or
this.width = 10;
}

Plus, I think it helps encapsulation even more. Say you move _width and
_height into a _size or _rectangle structure, then you just change your
properties and the rest of your code still works.

There are, of course, some places where I don't use the property (for
example, maybe I need to reset a field to null within my class, but I don't
allow other classes to do that). But most of the time, I prefer to use the
property.

--
Mike Mayer
http://www.mag37.com/csharp/
mi**@mag37.com
"Jasper Kent" <ja*********@ho tmail.com> wrote in message
news:eT******** ******@TK2MSFTN GP10.phx.gbl...
I don't think there's a general answer to this one.

If the set accessor simply sets the field and nothing more, then there's
not much odds. One might worry that the set accessor is a bit slower,
but I think that will be optimised away in most cases. However, even if
the set accessor does nothing special, there is always the issue that it
might do something in future.

If the set accessor does do something special, then its a question of
whether you want to do that special thing. As class desginer you know
what needs to be done and you can make the decisions.

For example, suppose you have a set accessor that ensures an int is in
the range 0-10, and throws an exception if not. If you call it with a
hard-coded 0 in the constructor, then you're wasting time going through
the set accessor. However, if the restriction were to change, then 0
might become invalid and you'd want to catch that.

If the set accessor were to, say, count the number of times that the
field was changed, then you certainly wouldn't want to increment that
count from the constructor, because thats initialisation, not change.

Another issue to consider is if the property is virtual. If so, then you
probably should call the set accessor to pick up any derived
functionality, but again it may depend on the context. Also, calling
virtual methods from a constructor is always dubious - less so in C#
than it was in C++, but still not great.

Regards,

Jasper Kent

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 15 '05 #4
The danger comes when Width is virtual because it may attempt to do things
with objects that are not yet initalized.
"Michael Mayer" <mi**@mag37.com > wrote in message
news:un******** ******@tk2msftn gp13.phx.gbl...
Just to put in my two-cents. I almost always use the property getter /
setter within my own classes - including the constructor. If I'm doing any sort of bounds checking / error checking then I surely want to make sure I
continue to use that, inside or outside of my class. Purely cosmetic, but I generally think the code is easier to read - at least for me:

public MyClass()
{
Width = 10;
}

vs.

public MyClass()
{
_width = 10; // or
this.width = 10;
}

Plus, I think it helps encapsulation even more. Say you move _width and
_height into a _size or _rectangle structure, then you just change your
properties and the rest of your code still works.

There are, of course, some places where I don't use the property (for
example, maybe I need to reset a field to null within my class, but I don't allow other classes to do that). But most of the time, I prefer to use the property.

--
Mike Mayer
http://www.mag37.com/csharp/
mi**@mag37.com
"Jasper Kent" <ja*********@ho tmail.com> wrote in message
news:eT******** ******@TK2MSFTN GP10.phx.gbl...
I don't think there's a general answer to this one.

If the set accessor simply sets the field and nothing more, then there's
not much odds. One might worry that the set accessor is a bit slower,
but I think that will be optimised away in most cases. However, even if
the set accessor does nothing special, there is always the issue that it
might do something in future.

If the set accessor does do something special, then its a question of
whether you want to do that special thing. As class desginer you know
what needs to be done and you can make the decisions.

For example, suppose you have a set accessor that ensures an int is in
the range 0-10, and throws an exception if not. If you call it with a
hard-coded 0 in the constructor, then you're wasting time going through
the set accessor. However, if the restriction were to change, then 0
might become invalid and you'd want to catch that.

If the set accessor were to, say, count the number of times that the
field was changed, then you certainly wouldn't want to increment that
count from the constructor, because thats initialisation, not change.

Another issue to consider is if the property is virtual. If so, then you
probably should call the set accessor to pick up any derived
functionality, but again it may depend on the context. Also, calling
virtual methods from a constructor is always dubious - less so in C#
than it was in C++, but still not great.

Regards,

Jasper Kent

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!


Nov 15 '05 #5
Michael Mayer writes:
I almost always use the property getter/setter
within my own classes - including the constructor.


I like this approach, and the encapsulation point you made later also
appeals. However, I'm having trouble getting the behavior I'd like (or
expect) from properties in a couple of regards.

One, I seem unable to assign different access modifiers for the set and get
of a property. For example, I might like to have a private setter
(something I'd do on behalf of the class client in the constructor, say) and
a public getter.

Two, I can't stick the private field associated with a property in the
property itself (thereby enforcing property-only access to the field even
within the class, and enhancing encapsulation).

I'm sure there's a good reason I can't do these things, but it seems like
they'd be nice to have.

Michael Roper
Nov 15 '05 #6
Michael Roper <mi******@encra ft.com> wrote:
Michael Mayer writes:
I almost always use the property getter/setter
within my own classes - including the constructor.
I like this approach, and the encapsulation point you made later also
appeals. However, I'm having trouble getting the behavior I'd like (or
expect) from properties in a couple of regards.

One, I seem unable to assign different access modifiers for the set and get
of a property.


Indeed. That's being fixed in the next version of C#.
For example, I might like to have a private setter
(something I'd do on behalf of the class client in the constructor, say) and
a public getter.
Absolutely.
Two, I can't stick the private field associated with a property in the
property itself (thereby enforcing property-only access to the field even
within the class, and enhancing encapsulation).

I'm sure there's a good reason I can't do these things, but it seems like
they'd be nice to have.


I don't think there *is* a good reason, I'm afraid - I've put in the
latter as a feature request, but I don't know whether or not it'll be
heeded. For the benefit of serialization etc, it would probably be
worth having an extra attribute which allowed methods to access
property-scoped variables, but that (and some naming restrictions) are
the only wrinkles I can see.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #7
Thanks for your response Jon. I find the traffic in this group rather
overwhelming--I don't know how you do it!

Jon Skeet writes:
One, I seem unable to assign different access
modifiers for the set and get of a property.


Indeed. That's being fixed in the next version of C#.


That'll help. Is there a definitive "next version of C#" doc/timeline to be
had?

Michael Roper
Nov 15 '05 #8

"Jon Skeet" <sk***@pobox.co m> wrote in message news:MP******** *************** *@news.microsof t.com...
Michael Roper <mi******@encra ft.com> wrote:
Michael Mayer writes: One, I seem unable to assign different access modifiers for the set and get
of a property.


Indeed. That's being fixed in the next version of C#.


Jon, Are you sure about this? Any references?

Willy.


Nov 15 '05 #9


"Willy Denoyette [MVP]" <wi************ *@pandora.be> wrote in message news:em******** ******@TK2MSFTN GP11.phx.gbl...

"Jon Skeet" <sk***@pobox.co m> wrote in message news:MP******** *************** *@news.microsof t.com...
Michael Roper <mi******@encra ft.com> wrote:
Michael Mayer writes: One, I seem unable to assign different access modifiers for the set and get
of a property.


Indeed. That's being fixed in the next version of C#.


Jon, Are you sure about this? Any references?

Willy.

Jon, Did some research myself, and you were right, this feature is planned for the next release of C# and VB.NET.

Willy.
Nov 15 '05 #10

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

Similar topics

0
5209
by: Sean Anderson | last post by:
ODBC under System DSN Setup Access Driver give it the DSN (Data Source Name) MSA Click on Select and point to the myfile.mdb (your database file)
3
4899
by: CSDunn | last post by:
Hello, I currently have an Access 2003 ADP Report/Subreport set up in which I have 12 subreports in a single main report that are located in a group header called 'PermnumHeader' (Permnum would be the same as a numeric 'StudentID'). All subreports initially have their visible property set to 'No'. I have a macro that evaulates the current value of a field in the detail section of the main report called 'Grade' and a field in the same...
4
9665
by: Emil | last post by:
Can somebody tell me what would be the syntax for having an if statement and setting the selected index of a radiobuttonlist? This is my first project using ASP.net and I use C#. I have a repeater with like a table layout and in the last column I want to have three radio buttons (for each row in repeater). The value of the radio button should be calculated from a value from the dataset. How can I do that? When I try to use a variable...
8
1510
by: pauldepstein | last post by:
I am writing a program which looks at nodes which have coordinates which are time-dependent. So I have a class called node which contains the private member declarations int date; int month; (I want to consider the month as part of the information contained in the node, as well as the date.) The node class also contains public member function void set_month(int) which sets the month according to the date given.
3
6799
by: swengtoo | last post by:
In his book "More Effective C++", Scott Meyer suggests in "Item 4" to "Avoid gratuitous default constructors". To summarize his claims against default constructors for "the right classes" he states that: ================== START QUOTE ============= "A default constructor is the C++ way of saying you can get something for nothing. Constructors initialize objects, so default constructors initialize objects without any information from...
1
3878
by: simon | last post by:
I have an unbound RTF2 control in an Access 2003 form which I set to show either unformatted text or else text with words and sentences highlighted. I do this by setting the PlainText property, getting back the rtfText and then adding the highlighting strings and resetting rtfText as below: sqry = "Select * from TextContent where FileID = " & ID Set rs = CurrentDb().OpenRecordset(sqry, dbOpenSnapshot) With rtfUnformatted ..rtfText = ""
23
2609
by: Ben Voigt | last post by:
I have a POD type with a private destructor. There are a whole hierarchy of derived POD types, all meant to be freed using a public member function Destroy in the base class. I get warning C4624. I read the description, decided that it's exactly what I want, and ignored the warning. Now I'm trying to inherit using a template. Instead of "destructor could not be generated because a base class destructor is inaccessible", I now have an...
5
4517
by: giddy | last post by:
Hi , I'm probably just doing something a little silly. I get a System.Configuration.ConfigurationErrorsException! This is my config file: <configSections> <section name="qConfig" type="QuickBuild.QConfig , QuickBuild" /> </configSections> <qConfig PathToDevEnv="D:\Microsoft Visual Studio 8\Common7\IDE\devenv.exe"
4
1686
by: =?Utf-8?B?YmlsbCB0aWU=?= | last post by:
I'm perusing a class that seems to utilize a nested class for private fields. In a nutshell, it looks as follows: public class Foo { public Property1 { get/set Bar.field1 }
0
9497
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
10164
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
10110
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
9962
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
8992
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...
0
6748
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
5398
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
4067
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
3670
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.