Last active
May 12, 2022 21:21
-
-
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 (...)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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