Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

C# provide Default Parameter?

0 views
Skip to first unread message

Scott C. Reynolds

unread,
Sep 11, 2003, 9:38:36 AM9/11/03
to
LongRunner wrote:

> Hihi,
> Can C# provide Default Parameter? It seem cannot support.
> But what is the meaning of "Optional" in the following document?
>
> ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.1033/vsintro7/html/vxlrfaddfolderm
> ethod.htm
>
>
>
>
I ran into this a while ago, and couldn't find a satisfactory
answer...however, most would probably say that the "proper" way to do it
anyway is to provide two overloaded methods, one that takes the optional
parameter, and one that doesn't:

private void SomeFunc(int x, int y)
{
//Do Stuff
}
private void SomeFunc(int x)
{
//set y to default
int y = 1;
//Then do stuff.
}

that way yu can use each method as needed

Karin

unread,
Sep 11, 2003, 9:31:03 AM9/11/03
to
Hi,
Why not just overload the function?

Ex

MyFunction(string A)
{
MyFunction(A,"Default string");
}

MyFuction(string A, string B)
{
...
}

/K

"LongRunner" <longr...@netvigator.com> wrote in message
news:#hrTYZGe...@TK2MSFTNGP11.phx.gbl...

Morten Wennevik

unread,
Sep 11, 2003, 9:44:26 AM9/11/03
to
There is no default parameter in C#, but you can implement one with

void Method1(int a, int b, int c)
{
}

void Method2(int a, int b)
{
int c = 42;
Method1(a, b, c);
}

--
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/

Nicholas Paldino [.NET/C# MVP]

unread,
Sep 11, 2003, 9:50:14 AM9/11/03
to
Scott and LongRunner,

The proper way to do this (as Scott) in C# is through overloading.

If you look at the IL for an optional parameter, you will notice methods
that have parameters with the Optional attribute attached to them (or
rather, there is an IL identifier that is set when the Optional attribute is
applied). Also, you will notice that the parameter is initialized with the
default value in the body of the method.

It is just a choice of the language designers to not include optional
parameters, most likely because they were thought to be ambiguous.


--
- Nicholas Paldino [.NET/C# MVP]
- nicholas...@exisconsulting.com

"Scott C. Reynolds" <sreyn...@hotmail.com> wrote in message
news:wV_7b.137375$3o3.9...@bgtnsc05-news.ops.worldnet.att.net...

Stefano "WildHeart" Lanzavecchia

unread,
Sep 11, 2003, 10:00:58 AM9/11/03
to
> It is just a choice of the language designers to not include optional
> parameters, most likely because they were thought to be ambiguous.

Also because:
- there are versioning problems
- it's hard to have them supported in every language (let's not forget .NET
is supposed to be "language neutral" to a certain extent).

--
WildHeart'2k3


0 new messages