Question

Having

public static void Search(string name, int age = 21, string city = "Tehran")
{
    MessageBox.Show(String.Format("Name = {0} - Age = {1} - City = {2}", 
        name, age, city));
}

I want to call Search method using name and city parameters to keep the default value of age.

AFAIK parameter should be referred by name

Search("Mahdi", city: "Mashhad");

I want to know if it is possible to make the call without specifying value for age and also without calling city by name? I mean something like jumping over a parameter, something like :

or

Search("Mahdi",,"Mashhad");

I've seen almost similar behavior for for loop

for (int i = 0; ; i++) { some code; }

or any other syntax that matches the case?

Was it helpful?

Solution 2

Change it to

public static void Search(string name, string city = "Tehran", int age = 21)
{
    MessageBox.Show(String.Format("Name = {0} - Age = {1} - City = {2}", 
        name, age, city));
}

Now you can use it as

Search("Mahdi", "Mashhad");

Optional parameters are defined at the end of the parameter list, after any required parameters. http://msdn.microsoft.com/en-us/library/dd264739.aspx

OTHER TIPS

Simply create an overload which takes two string parameters like this:

public static void Search(string name, string city)
{
    Search(name, 21, city);
}

public static void Search(string name, int age = 21, string city = "Tehran")
{
    MessageBox.Show(String.Format("Name = {0} - Age = {1} - City = {2}", 
        name, age, city));
}

And call it like this:

Search("Mahdi", "Mashhad");

You could use a nullable int for age. Like this:

public static void Search(string name, int? age = null, string city = null)
{
    MessageBox.Show(String.Format("Name = {0} - Age = {1} - City = {2}", 
        name, age ?? 21, city ?? "Tehran"));
}

Then you could call the following combinations:

Search("Mahdi");
Search("Mahdi", 20);
Search("Mahdi", null, "Cairo");

which would use age=21 and city="Tehran" for the default values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top