Share via


Using params keyword

Let’s say you have a class and you want to store a collection of strings in that class. How would your method look like which would let you add a string to the class?

    1: public class SampleClass
    2:  {
    3:      private List<string> myList = null; 
    4:  
    5:      public SampleClass()
    6:      {
    7:          myList = new List<string>(); 
    8:      }
    9:  }

There are a couple of ways you could write the method; it also depends on what are you trying to achieve. Below are some of the samples how you could do this (yes, I know, there are probably million other ways to do this :)):

    1: public void AddItem(string item)
    2: {
    3:     // Do something 
    4: }
    5:  
    6: public void AddItems(List<string> items)
    7: { 
    8:     // Do something 
    9: }
   10:  
   11: public void AddItems (string [] items) 
   12: {
   13:     // Do something 
   14: }

Every method above has it’s benefits and drawbacks – I have to pass in an array of string, I can only pass in one string a the time, sometimes I want to pass in 3 strings and sometimes 1 – why can’t I use one method only?).

There’s a keyword called “params” you could use to solve this problem – with this keyword you can pass in as many parameters as you like; for example all calls below are made to the same method:

    1: SampleClass my = new SampleClass();
    2: my.AddItems("One"); 
    3: my.AddItems("One", "Two");
    4: my.AddItems("One", "Two", "Three"); 

And here’s how the method would look like:

    1: public void AddItems(params string[] items)
    2: {
    3:     foreach (string item in items)
    4:     { 
    5:         // Do something
    6:     }
    7: }