Default method parameter

  • Thread starter Thread starter A.M
  • Start date Start date
A

A.M

Hi,
Do we have default method parameter in C#?

Something like this

void method1(int i = 12)
{
....
}


Thanks,
Ali
 
Hi A.M,

No, c# doesn't support default parameters. You can use method overloads for
that.

B\rgds
100
 
But C# supposed to be a modern language and that method overloading you
mentioned can implicitly be done by compiler ,so what is the logic behind
this incapability ?

Thanks for replay,
Ali
 
...
Do we have default method parameter in C#?

Something like this

void method1(int i = 12)
{
...
}

No, but you can overload the method to gain the same result as if you had
default parameter values:

void method1(int i)
{
...
}

void method1()
{
method1(12);
}

// Bjorn A
 
Ali,

I think that part of the reason for this is that overloads are a more
beneficial than default values. If you have default values, then you will
have to use the least common denominator with object types if you are going
to have multiple input types (kind of like you would have to use Object or
Variant in VB if you wanted to handle more than one type for the parameter
in your method). If you have default values and not overloads, then what
happens is you have to declare more of your methods with type-agnostic
parameters, and that's not a good thing.

Now, one can argue that you can have both overloads and default values.
So what do you do when you have the following:

public void DoSomething(int parameter = 0)

public void DoSomething()

Which one does it call? Regardless of what is actually done (or how C++
does it, because this is what it is what most answers are going to be based
on anyways), it adds confusion to the mix, and that is something I can only
guess the language designers didn't want to introduce to a new language.
Instead, they tend to take a wait-and-see approach.

Eric Gunnerson's blog entry today actually speaks about this to some
degree (watch for line wrap):

http://weblogs.asp.net/ericgu/archive/2004/01/12/57985.aspx

Hope this helps.
 
Hi Ali,

I think Nicholas's reply is useful, does it make sense to you?
If you still have anything unclear, please feel free to tell me, I will
work with you.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
Hi Ali,

Thanks for your feedback.
I am glad this group helps you. If you need further help, please feel free
to post, we will work with you.
Have a nice experience in Microsoft newsgroup!!

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
Back
Top