473,327 Members | 1,930 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

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 1974
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*********@hotmail.com> wrote in message
news:eT**************@TK2MSFTNGP10.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**************@tk2msftngp13.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*********@hotmail.com> wrote in message
news:eT**************@TK2MSFTNGP10.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******@encraft.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.com>
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.com> wrote in message news:MP************************@news.microsoft.com ...
Michael Roper <mi******@encraft.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**************@TK2MSFTNGP11.phx.gbl...

"Jon Skeet" <sk***@pobox.com> wrote in message news:MP************************@news.microsoft.com ...
Michael Roper <mi******@encraft.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
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
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...
4
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...
8
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; ...
3
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...
1
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,...
23
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....
5
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"...
4
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
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.