How to pass a list as a parameter in a function

I took the list and entered some meaning into it

public List<DateTime> dates = new List<DateTime>(); DateTime dt1 = DateTime.Parse(12/1/2012); DateTime dt2 = DateTime.Parse(12/6/2012); if (dt1 <= dt2) { for (DateTime dt = dt1; dt <= dt2; dt = dt.AddDays(1)) { dates.Add(dt); } } 

Now I want to pass this list ie to dates as a parameter for some function, for example -

 somefunction(dates); 

How exactly can I achieve this?

+12
source share
5 answers

You need to do it,

 void Yourfunction(List<DateTime> dates ) { } 
+28
source
 public void SomeMethod(List<DateTime> dates) { // do something } 
+4
source

You should always avoid using List<T> as a parameter. Not only because this template reduces the ability of the caller to save data in a different kind of collection, but also the caller must first convert the data to List .

Converting IEnumerable to List costs O (n) complexity, which is absolutely unnecessary. And it also creates a new object.

TL DR You should always use the right interface, such as IEnumerable or IQueryable depending on what you want to do with your collection. ;)

A case of you:

 public void foo(IEnumerable<DateTime> dateTimes) { } 
+2
source

You can pass it as a List<DateTime>

 public void somefunction(List<DateTime> dates) { } 

However, it is better to use the most common (as usual, basic) interface, so I would use

 public void somefunction(IEnumerable<DateTime> dates) { } 

or

 public void somefunction(ICollection<DateTime> dates) { } 

You can also call .AsReadOnly() before passing the list to the method, if you do not want the method to modify the list, add or remove elements.

+1
source

I need this for Unity in C #, so I thought it might be useful for someone. This is an example of passing a list of AudioSources to any function you want:

 private void ChooseClip(GameObject audioSourceGameObject , List<AudioClip> sources) { audioSourceGameObject.GetComponent<AudioSource> ().clip = sources [0]; } 
0
source

All Articles