Skip to content

Instantly share code, notes, and snippets.

@derekantrican
Last active May 12, 2022 21:21
Show Gist options
  • Save derekantrican/8efa5da16ddd16c718db9996c444c2d3 to your computer and use it in GitHub Desktop.
Save derekantrican/8efa5da16ddd16c718db9996c444c2d3 to your computer and use it in GitHub Desktop.
An example of using a extension method to achieve a similar functionality to the ES6 spread operator (...)
using System.Collections.Generic;
namespace SpreadExample
{
public class SpreadExample
{
//Normally, this would take more lines, like:
/*
public List<string> InsertList(List<string> secondList)
{
List<string> myList = new List<string>
{
"firstItem",
};
myList.AddRange(secondList);
myList.Add("lastItem");
return myList;
}
*/
public List<string> InsertList(List<string> secondList)
{
return new List<string>
{
"firstItem",
secondList, //In ES6 you would put (...secondList)
"lastItem",
};
}
}
public static class CollectionExtensions
{
public static void Add<T>(this ICollection<T> collection, IEnumerable<T> items)
{
foreach (T item in items)
{
collection.Add(item);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment