0

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?

Mahdi Tahsildari
  • 13,065
  • 14
  • 55
  • 94

3 Answers3

4

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");
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
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

nuclear sweet
  • 1,079
  • 10
  • 27
  • 1
    No I meant rational Idea :) argumentative with that meaning. Among all the answers this one is more logical, less code and everything in its place. Thanks. – Mahdi Tahsildari Mar 14 '14 at 07:37
  • 1
    @MahdiTahsildari i just missunderstand it because of my english skills, im glad that helps you. – nuclear sweet Mar 14 '14 at 07:42
1

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.

Phillip Ngan
  • 15,482
  • 8
  • 63
  • 79