473,772 Members | 2,424 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Overloaded constructors vs. Object initializations

Hi,

I would like to get some thoughts on Overloaded constructors vs. Object
initializations . Assuming that the class supports a default constructor, is
there any reason to include overloaded constructors when you are able to use
object initialization? I see a point, to provide the overloads, if you are
developing framework code that might support the need to run ontop of 2.x
but if you are writing a sealed application / know you are only going to
deploy on 3.x or higher, then the need doesn't seem as apparent to me.
..Andreas
Aug 14 '08 #1
13 1519
On Aug 14, 3:48*pm, Andreas <Andr...@discus sions.microsoft .comwrote:
Hi,

I would like to get some thoughts on Overloaded constructors vs. Object
initializations . Assuming that the class supports a default constructor, is
there any reason to include overloaded constructors when you are able to use
object initialization?
Yes, when your object is immutable - then all your properties will be
readonly, and an object initializer cannot be used. And even for
mutable objects, there can be properties which should only be
initialized once when the object is created, and not changed
afterwards - e.g. Dictionary<,>.C omparer

Aug 14 '08 #2
I would like to get some thoughts on Overloaded constructors vs. Object
initializations . Assuming that the class supports a default constructor, is
there any reason to include overloaded constructors when you are able to use
object initialization?

Yes, when your object is immutable - then all your properties will be
readonly, and an object initializer cannot be used. And even for
mutable objects, there can be properties which should only be
initialized once when the object is created, and not changed
afterwards - e.g. Dictionary<,>.C omparer
Yes, you are right. Maybe I should have been a bit more precise by saying
"other than when you design explicitly require the use of non-default
constructor". Many times overloaded constructors have been used to make
object initialization a bit more userfriendly and to provide cleaner code,
such as

public class Person
{
public Person()
{ }

public Person(string firstName, string lastName) : this(0, firstName,
lastName)
{ }

public Person(int age, string firstName, string lastName)
{
......
}
}
Aug 14 '08 #3
On Aug 14, 5:03*pm, Andreas <Andr...@discus sions.microsoft .comwrote:
Yes, you are right. Maybe I should have been a bit more precise by saying
"other than when you design explicitly require the use of non-default
constructor". Many times overloaded constructors have been used to make
object initialization a bit more userfriendly and to provide cleaner code
In that context, object initializers are clearly superior (more
readable as well, since property names are spelled out). Besides, with
a significant number of properties, you can't cover all permutations
anyway (I often see such half-hearted attempts in the BCL, where you
need, say, a combo of property #1+#3+#4, but you only get constructors
for #1+#2+#3 or #1+#2+#4).
Aug 14 '08 #4

"Pavel Minaev" <in****@gmail.c omwrote in message news:f0******** *************** ***********@e39 g2000hsf.google groups.com...
In that context, object initializers are clearly superior (more
readable as well, since property names are spelled out). Besides, with
a significant number of properties, you can't cover all permutations
anyway (I often see such half-hearted attempts in the BCL, where you
need, say, a combo of property #1+#3+#4, but you only get constructors
for #1+#2+#3 or #1+#2+#4).

Unless of course you have support for optional parameters, then it is very easy to have a single constructor, and also makes it easy for objects to then have a concept of "dirty" or changed after initialization.
Aug 14 '08 #5
On Aug 14, 5:25*pm, "Bill McCarthy" <B...@localhost .comwrote:
"Pavel Minaev" <int...@gmail.c omwrote in messagenews:f0* *************** *************** ***@e39g2000hsf .googlegroups.c om...
In that context, object initializers are clearly superior (more
readable as well, since property names are spelled out). Besides, with
a significant number of properties, you can't cover all permutations
anyway (I often see such half-hearted attempts in the BCL, where you
need, say, a combo of property #1+#3+#4, but you only get constructors
for #1+#2+#3 or #1+#2+#4).

Unless of course you have support for optional parameters, then it is very easy to have a single constructor, and also makes it easy for objects to then have a concept of "dirty" or changed after initialization. *
Well, CLS doesn't support optional parameters in general (so if VB
guys want to make libraries that are usable from C# and other .NET
languages, they can forget about Optional).

Also, when you have 3+ properties to initialize, constructor calls
become rather unreadable when there is no named argument support in a
language, because you don't know which argument corresponds to which
property.

Aug 14 '08 #6
Yes, when your object is immutable - then all your properties will be
readonly, and an object initializer cannot be used. And even for
mutable objects, there can be properties which should only be
initialized once when the object is created, and not changed
afterwards - e.g. Dictionary<,>.C omparer
I guess technically you don’t really need constructors at all, they
are just there to make life simpler.

For example, in your “Dictionary<,>. Comparer” example, you could allow
a user to set the “Comparer” property using object initialization at
any time, but you will have to add some more logic to throw an error
if the user tries to set the “Comparer” property once the object is in
a state where changing the value of the property would cause
problems....... phiuuuu, that can get ugly!

So I would say that constructors exist not because they are necessary
but because they can make your code simpler and more robust.

I realize that this point is obvious and I am sure you already knew
this. I am just giving my 2 cent to the original poster.

Cheers!
Aug 14 '08 #7

"Pavel Minaev" <in****@gmail.c omwrote in message
news:4c******** *************** ***********@k30 g2000hse.google groups.com...
>
>Unless of course you have support for optional parameters, then it is
very easy to have
a single constructor, and also makes it easy for objects to then have a
concept of "dirty" or changed after initialization.

Well, CLS doesn't support optional parameters in general (so if VB
guys want to make libraries that are usable from C# and other .NET
languages, they can forget about Optional).
CLS does not specify anything about Optional parameters. That is they are
neither compliant or non compliant. Optional parameters are not variable
length parameter lists, rather they are compiler trickery. The compiler
reads from the list and adds the indicated default values for you if you
don't include the parameter when calling the method. Today, all CLS
languages can use methods that have optional arguments, but either the code
has to specify all parameters all the compiler fill in the gaps for you.
Also, when you have 3+ properties to initialize, constructor calls
become rather unreadable when there is no named argument support in a
language, because you don't know which argument corresponds to which
property.
Right. Named arguments is an important part of support for optional
parameters.
BTW: Pavel,would you mine changing your post encoding to none or mime rather
than Printed Quotable. Hard to reply and have who said what clear ;)

Aug 14 '08 #8
On Aug 14, 7:10*pm, "Bill McCarthy" <B...@localhost .comwrote:
CLS does not specify anything about Optional parameters. *That is they are
neither compliant or non compliant. *Optional parameters are not variable
length parameter lists, rather they are compiler trickery. *The compiler
reads from the list and adds the indicated default values for you if you
don't include the parameter when calling the method. *Today, all CLS
languages can use methods that have optional arguments, but either the code
has to specify all parameters all the compiler fill in the gaps for you.
Well, optional parameters that you have to specify in the call hardly
count as "optional", don't they? ;)

What I meant is that CLS does not specify any standard protocol for
optional parameters (or indeed the existence of such facility in
general), and therefore you can't expect any other language to treat
the parameters as optional - thus defeating their purpose.
Right. Named arguments is an important part of support for optional
parameters.
I would argue that named arguments are quite useful even on their own
- a method call with many parameters is much more readable when they
are explicitly named in the call.
BTW: Pavel,would you mine changing your post encoding to none or mime rather
than Printed Quotable. * Hard to reply and have who said what clear ;)
I'm reading and posting via Google Groups, so I don't think it's
something under my control, unfortunately.
Aug 14 '08 #9

"Pavel Minaev" <in****@gmail.c omwrote in message
news:5b******** *************** ***********@59g 2000hsb.googleg roups.com...
On Aug 14, 7:10 pm, "Bill McCarthy" <B...@localhost .comwrote:
>CLS does not specify anything about Optional parameters. That is they are
neither compliant or non compliant. Optional parameters are not variable
length parameter lists, rather they are compiler trickery. The compiler
reads from the list and adds the indicated default values for you if you
don't include the parameter when calling the method. Today, all CLS
languages can use methods that have optional arguments, but either the
code
has to specify all parameters all the compiler fill in the gaps for you.

Well, optional parameters that you have to specify in the call hardly
count as "optional", don't they? ;)
Sure, but that doesn't stop people susing them, much like doing VSTO stuff
in C# today

>
What I meant is that CLS does not specify any standard protocol for
optional parameters (or indeed the existence of such facility in
general), and therefore you can't expect any other language to treat
the parameters as optional - thus defeating their purpose.


CLS doesn't, but CLI does, specifically partition II section 15.4 and
15.4.1.4. Really, it's a bit like adding support for UInt32 as an
intrinsic CIL, except that is actually prohibited by CLS. ;)
>Right. Named arguments is an important part of support for optional
parameters.

I would argue that named arguments are quite useful even on their own
- a method call with many parameters is much more readable when they
are explicitly named in the call.

Yep (with moderation <g>)
>BTW: Pavel,would you mine changing your post encoding to none or mime
rather
than Printed Quotable. Hard to reply and have who said what clear ;)

I'm reading and posting via Google Groups, so I don't think it's
something under my control, unfortunately.

Ah okay. Maybe I need a better newsreader then ;)

Aug 14 '08 #10

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

Similar topics

1
2382
by: andrea_gavana | last post by:
Hello NG, I am trying to port a useful class from wxWidgets (C++) to a pure Python/wxPython implementation. In the C++ source code, a unique class is initialized with 2 different methods (???). This is what it seems to me. I have this declarations: class wxFoldWindowItem { private: wxWindow *_wnd;
42
5808
by: Edward Diener | last post by:
Coming from the C++ world I can not understand the reason why copy constructors are not used in the .NET framework. A copy constructor creates an object from a copy of another object of the same kind. It sounds simple but evidently .NET has difficulty with this concept for some reason. I do understand that .NET objects are created on the GC heap but that doesn't mean that they couldn't be copied from another object of the same kind when...
1
2225
by: masood.iqbal | last post by:
I have a few questions regarding overloaded typecast operators and copy constructors that I would like an answer for. Thanks in advance. Masood (1) In some examples that I have seen pertaining to casting class A to class B, the implementation of the
3
1598
by: hazz | last post by:
The following classes follow from the base class ' A ' down to the derived class ' D ' at the bottom of the inheritance chain. I am calling the class at the bottom, "public class D" from a client app with; D m_D = new D(tkn); public class A : MarshalByRefObject public A () <--------------------- public class B : A public B () <----------------------
3
1711
by: Vera | last post by:
I built a class in VB.NET that has an overloaded constructor. It can either accept nothing, a string or an object Public Sub New( MyBase.New( End Su Public Sub New(ByVal strName As String MyBase.New( '... Do init with strNam End Su
7
1500
by: cmay | last post by:
Can someone quick shed some light on this issue I am having? I wanted to create 2 constructors for my object, one that takes an ID value and one that takes a datarow. If ID value is provided, it is going to get the info from the database and populate itself. If a datarow is provided, then it will use the row to populate itself. So, I wanted to have the "by ID" function get a datarow from the
12
5816
by: st_ev_fe | last post by:
I've noticed that when constructing a subclass, the base class get's it's contructors called. Is there some way to avoid this? The base class has one variable, which gets initialised to 0. The subclass's constructor sets this variable to a real value. So first the variable is set to 0, the variable is never used before it once again gets set to a real value. It's a waste. Any ideas anyone?
3
1933
by: jerry.teshirogi | last post by:
I have the following class and main: ////////////////////////////////////////////////////////// #include <iostream.h> class myVector { public: double x, y, z:
0
9619
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...
0
9454
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
10261
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10038
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
9911
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...
1
7460
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
6713
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
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
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

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.