C# extension method, get rid of ref keyword
I have written a little extension method to add a value to the beginning of a List.
Here is the code;
public static class ExtensionMethods
{
public static void AddBeginning<T>(this List<T> item, T itemValue, ref List<T&开发者_运维百科gt; currentList)
{
List<T> tempList = new List<T> {itemValue};
tempList.AddRange(currentList);
currentList = tempList;
}
}
So that I can add the value to the beginning of the list, I have to use the ref keyword.
Can anybody suggest have to amend this extension method to get rid of the ref keyword?
You can just call currentList.Insert(0, itemValue); to insert into the beginning.
Edit:
Note - this code will modify the list instance whereas the original code left the list intact and produced a new list with the additional data inserted at the beginning.
public static void AddBeginning<T>(this List<T> currentList, T itemValue)
{
currentList.Insert(0, itemValue);
}
It really helps to read the docs for the class you're using.
Also, I would suggest just using Insert directly, instead of this extension method.
Use the List Insert method and supply the index that you want the new value (0) added at?
加载中,请稍侯......
精彩评论