10

Consider the following method example:

public void MyMethod (string par1, bool par2 = "true", string par3="")
{
}

Now let's say that I call MyMethod and set par3's value to "IamString".

How could I do that without setting par2's value to true or false?

I basically want to leave par2 value to its default.

I'm asking this because in Flash's ActionScript it is possible to do that by using the keyword default so I could call MyMethod ("somestring", default, "IamString") and par2 would be interpreted as true, which is its default value. I wonder if it is possible in C# as well.

3

2 Answers 2

17
public void MyMethod (string par1, bool par2 = "true", string par3=""){}
Myclass.MyMethod(par1:"par1", par3:"par3");

By the way, this won't work: bool par2 = "true"

string par2 = "true"

or

bool par2 = true

Talking about default values, you could also use this to get the default value for a particular type:

default(T)

3
  • Thank you! And yeah, you're right bool par2 = "true" won't work. It's a mistake I've did while trying to layout a simple example.
    – IneedHelp
    Commented Aug 10, 2012 at 12:29
  • Yes, it just doesn't let me because you recently edited your answer. I will be able to accept it in 1 minute.
    – IneedHelp
    Commented Aug 10, 2012 at 12:32
  • Warning to anyone who takes this as a correct answer: using default(T) will NOT respect the default value provided in the declaration of the function being called, it will instead use the default value for that type, which for a bool will be false even though the function wants the default value to be true Commented Mar 2, 2023 at 15:47
14

You can specify this by name the parameter:

instance.MyMethod( "Hello", par3:"bla" );

Have a look here.

And there is another bug:

bool par2 = true

is correct..

2
  • Your answer is equally useful to SeToY's, but I'll accept his because I spotted it first. Nevertheless, thank you and thumbs up!
    – IneedHelp
    Commented Aug 10, 2012 at 12:35
  • This is the correct answer, see my comment on the accepted but incorrect answer Commented Mar 2, 2023 at 15:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.