[c#] how to pass list as parameter in function

I have taken a list and insert some value in 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 pass this List i.e dates as a parameter to some function like-

somefunction(dates);

How exactly can i achieve this?

This question is related to c# asp.net

The answer is


You should always avoid using List<T> as a parameter. Not only because this pattern reduces the opportunities of the caller to store the data in a different kind of collection, but also the caller has to convert the data into a List first.

Converting an IEnumerable into a List costs O(n) complexity which is absolutely unneccessary. And it also creates a new object.

TL;DR you should always use a proper interface like IEnumerable or IQueryable based on what do you want to do with your collection. ;)

In your case:

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

You can pass it as a List<DateTime>

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

However, it's better to use the most generic (as in general, base) interface possible, so I would use

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

or

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

You might also want to call .AsReadOnly() before passing the list to the method if you don't want the method to modify the list - add or remove elements.


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

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

public void SomeMethod(List<DateTime> dates)
{
    // do something
}