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

Home Posts Topics Members FAQ

Proposal: Default Parameters/Named Parameters

Why doesn't C# allow default parameters for methods?
An argument against I hear often is that the default parameters would have
to be hardbaken into the assembly, but why? The Jit can take care of this,
if the code is jitted the
"push xyz" instructions of the actual default values can be inserted.

To make things simpler and better readable I'd make all default parameters
named parameters so that you can decide for yourself why one to pass and
which not, rather than relying on massively overlaoded methods which
hopefully provide the best overload for you, for example the Image.DrawImage
method has 20 overloads.

I propose a syntax like the following:

public void Open(string path, AccessMode mode = AccessMode.Read , int
bufferSize=1024 )
{
// ...
}

As you can see, path is a regular parameter which cannot be omitted, whereas
Mode and BufferSize provide default values an can be omitted when calling
the method.
Named parameters can only be declare behind all regular parameters and if
you have params parameters (variable parameterlist) is must be declared at
the end of the parameterlist. Although you can omit the named parameters if
you pass them they should appear in the same order as they were declared for
better readability.

You could call the example method like the following:

Open("text.txt" , @mode=AccessMod e.Write, @bufferSize=512 );
Open("text.txt" , @bufferSize=512 );
Open("text.txt" , @mode=AccessMod e.Write);
Open("text.txt" );

Note that an @ sign has to appear before all named parameter so that you
have no naming conflicts with other variables in the callers context.

Additionally there can not be more that one method with the same name and
the same regular parameters to avoid ambigiuty, so:

Foo(int i, string a="");
Foo(int i, double f=1.0f);

Would not be allowed because the call Foo(100) could not be resolved.

What do you think about that? Would it even be possible to do that in the
CLR or would there have be so huge changes that it can't be done in the
future?
Nov 16 '05 #1
8 3046
Anders Hejlsberg touched on this during his (very interesting)
whiteboard talk:

http://msdn.microsoft.com/msdntv/epi...h/manifest.xml

Basically, there are several ways to implement default arguments.

The first is to have the compiler build the defaults into the method
call on the caller's side. Essentially the called method would receive
all of its parameter arguments every time and not have to worry about
missing arguments, because the caller would take care of filling in the
blank. Hejlsberg's objection to this is that it would involve compiling
the defaults into the caller, which would break all of your callers if
you ever changed the defaults.

However, you're suggesting doing it during the JIT phase, which would
remove that objection, but require changes to the IL. An interesting
idea.

The other possibility is to have the called method handle defaulting,
but this would come with a mondo speed penalty, as I think Hejlsberg
points out.

Personally, the only place I've found that really could use optional
parameters is when writing constructors. Most other methods don't
experience the kind of massive overloading that constructors do, and
the only part of writing constructor overloads that I hate is having to
copy (and maintain) the documentation on every overload.

Someone also mentions this to Hejlsberg as a compromise: allowing
sharing of XML documentation between overloaded methods / constructors.
That would make me happy enough, without changing the IL, the JITter,
and the definition of what a C# method signature looks like.

Nov 16 '05 #2
Default parameters are not needed when overloading can do the job for you.

The parameter lists scan from left to right anyway so all you have to do is
overload the function once for each extra parameter in the list.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

"cody" <de********@gmx .de> wrote in message
news:uF******** ******@TK2MSFTN GP14.phx.gbl...
Why doesn't C# allow default parameters for methods?
An argument against I hear often is that the default parameters would have
to be hardbaken into the assembly, but why? The Jit can take care of this,
if the code is jitted the
"push xyz" instructions of the actual default values can be inserted.

To make things simpler and better readable I'd make all default parameters
named parameters so that you can decide for yourself why one to pass and
which not, rather than relying on massively overlaoded methods which
hopefully provide the best overload for you, for example the
Image.DrawImage method has 20 overloads.

I propose a syntax like the following:

public void Open(string path, AccessMode mode = AccessMode.Read , int
bufferSize=1024 )
{
// ...
}

As you can see, path is a regular parameter which cannot be omitted,
whereas Mode and BufferSize provide default values an can be omitted when
calling the method.
Named parameters can only be declare behind all regular parameters and if
you have params parameters (variable parameterlist) is must be declared at
the end of the parameterlist. Although you can omit the named parameters
if you pass them they should appear in the same order as they were
declared for better readability.

You could call the example method like the following:

Open("text.txt" , @mode=AccessMod e.Write, @bufferSize=512 );
Open("text.txt" , @bufferSize=512 );
Open("text.txt" , @mode=AccessMod e.Write);
Open("text.txt" );

Note that an @ sign has to appear before all named parameter so that you
have no naming conflicts with other variables in the callers context.

Additionally there can not be more that one method with the same name and
the same regular parameters to avoid ambigiuty, so:

Foo(int i, string a="");
Foo(int i, double f=1.0f);

Would not be allowed because the call Foo(100) could not be resolved.

What do you think about that? Would it even be possible to do that in the
CLR or would there have be so huge changes that it can't be done in the
future?

Nov 16 '05 #3
There is one situation in which _named_ parameters, as outlined by
cody, would be helpful, and that is when you have what really ought to
be two different overloads that take the same parameter types,
something like

public Page (int width, int height)

public Page (int width)

now, if you want another constructor overload for Page that creates a
Page with a default width and a given height, you're stuck.

However, I'm fairly certain that it's not worth reworking the C#
language and the IL in order to handle this one, rare case.

Nov 16 '05 #4
It strikes me that this can be done with attributes. I'll have to think
about it.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

"Bruce Wood" <br*******@cana da.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
There is one situation in which _named_ parameters, as outlined by
cody, would be helpful, and that is when you have what really ought to
be two different overloads that take the same parameter types,
something like

public Page (int width, int height)

public Page (int width)

now, if you want another constructor overload for Page that creates a
Page with a default width and a given height, you're stuck.

However, I'm fairly certain that it's not worth reworking the C#
language and the IL in order to handle this one, rare case.

Nov 16 '05 #5
Please tell me if you should have a new idea!

"Bob Powell [MVP]" <bob@_spamkille r_bobpowell.net > schrieb im Newsbeitrag
news:uV******** ******@TK2MSFTN GP12.phx.gbl...
It strikes me that this can be done with attributes. I'll have to think
about it.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

"Bruce Wood" <br*******@cana da.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
There is one situation in which _named_ parameters, as outlined by
cody, would be helpful, and that is when you have what really ought to
be two different overloads that take the same parameter types,
something like

public Page (int width, int height)

public Page (int width)

now, if you want another constructor overload for Page that creates a
Page with a default width and a given height, you're stuck.

However, I'm fairly certain that it's not worth reworking the C#
language and the IL in order to handle this one, rare case.


Nov 16 '05 #6
> Personally, the only place I've found that really could use optional
parameters is when writing constructors. Most other methods don't
experience the kind of massive overloading that constructors do, and
the only part of writing constructor overloads that I hate is having to
copy (and maintain) the documentation on every overload.


There are a lot of methods that take a lot for than 5 arguments and have
multiple overloads like the framework class Image which method DrawImage has
20 overloads!

I think this heavy overlading makes the code less readable and unnessaccary
bloated.
So if you have just 5 overloads you have to write at least 5*5 lines of code
and this is without documentation. You often do not see which overloaded
method calls which and you sometimes end up with an endless recursion. You
have also take care that the parameters ar in the same order in each method
to provide good readability.
Additionally if you do not do it clean and put additional code in the
overadloaded methods beside the call of the "main worker method" end up with
very messy code like that:

Foo(double d, string s, int i, bool b)
{
// dostuff
}

Foo(double d, string s, int i)
{
Foo(d, s, 0, false);
// do some stuff here
}

Foo()
{
Foo(0, "", 0, false);
// do some stuff here
}

Foo(double d)
{
Foo(0, "", 0, false);
// do some stuff here
}

Foo(int i)
{
Foo(0, "", i, false);
// do some stuff here
}

Foo(double d, string s)
{
Foo(d, s, i, false);
// do some stuff here
}

At the end, you have a huge piece a crap in you texteditor where you just
would have needed JUST ONE SIMPLE METHOD.
Nov 16 '05 #7
Do I need to point out that if each overload has some extra "do some
stuff here" code that isn't in the "master method" then you couldn't
code it any better using default arguments? :)

Really, for my money the only annoying thing about having to use
overloads is copying the documentation over and over again. Fix that
problem and I would be quite happy with the status quo.

Nov 16 '05 #8
> It strikes me that this can be done with attributes. I'll have to think
about it.
Iam just curious if you've got new ideas about this topic :)

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

"Bruce Wood" <br*******@cana da.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
There is one situation in which _named_ parameters, as outlined by
cody, would be helpful, and that is when you have what really ought to
be two different overloads that take the same parameter types,
something like

public Page (int width, int height)

public Page (int width)

now, if you want another constructor overload for Page that creates a
Page with a default width and a given height, you're stuck.

However, I'm fairly certain that it's not worth reworking the C#
language and the IL in order to handle this one, rare case.


Nov 16 '05 #9

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

Similar topics

31
2443
by: Brian Sabbey | last post by:
Here is a pre-PEP for what I call "suite-based keyword arguments". The mechanism described here is intended to act as a complement to thunks. Please let me know what you think. Suite-Based Keyword Arguments ----------------------------- Passing complicated arguments to functions is currently awkward in Python. For example, the typical way to define a class property winds up polluting the class's namespace with the property's get/set...
18
2288
by: Ralf W. Grosse-Kunstleve | last post by:
My initial proposal (http://cci.lbl.gov/~rwgk/python/adopt_init_args_2005_07_02.html) didn't exactly get a warm welcome... And Now for Something Completely Different: class autoinit(object): def __init__(self, *args, **keyword_args): self.__dict__.update(
14
3432
by: | last post by:
Hi, I was performing SQL UPDATE queries and I notice that they SUCCEED on the ExecuteNonQuery() call with NO exceptions raised BUT they fail at the Database. They say they succeed in the code but they fail at the database. To fix this they Parameters.Add must be called in the ORDER they are in the SQL STATEMENT. This is confusing and bad.
4
2737
by: wkaras | last post by:
I would like to propose the following changes to the C++ Standard, the goal of which are to provide an improved ability to specify the constraints on type parameters to templates. Let me say from the start that my knowledge of compiler implementation is very limited. Therefore, my suggestions may have to be rejected because they are difficult or impossible to implement. The proposal is based on the concept of "type similarity". Type...
7
4233
by: Vyssokih Max | last post by:
Hello! In C++, I can wrote: void Update(int count = 0) {...} and use it without parameters or with one parameter
28
414
by: C# Learner | last post by:
Note ---- Please use a fixed-width font to view this, such as Courier New. Problem
8
1521
by: Paddy | last post by:
Proposal: Named RE variables ====================== The problem I have is that I am writing a 'good-enough' verilog tag extractor as a long regular expression (with the 'x' flag for readability), and find myself both 1) Repeating sections of the RE, and 2) Wanting to add '(?P<some_clarifier>...) ' around sections because I know what the section does but don't really want the group.
14
3275
by: cody | last post by:
I got a similar idea a couple of months ago, but now this one will require no change to the clr, is relatively easy to implement and would be a great addition to C# 3.0 :) so here we go.. To make things simpler and better readable I'd make all default parameters named parameters so that you can decide for yourself which one to pass and which not, rather than relying on massively overlaoded methods which hopefully provide the best...
7
1073
by: python-pep | last post by:
Hi, sorry, I have these ideas for longer than 10 years, please have a look on it and comment on it. Thx. ---- This is another proposal for introducing types into Python.
0
9522
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
10443
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...
0
10216
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...
0
10002
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
6783
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
5437
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
4113
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
3728
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2921
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.