开发者

Extension method question. Why do I need to use someObj = someObj.somemethod();

开发者 https://www.devze.com 2023-01-01 13:16 出处:网络
I have a simple extension method that I would like to use to add an item to an array of items. public static T[] addElement<T>(this T[] array, T elementToAdd)

I have a simple extension method that I would like to use to add an item to an array of items.

public static T[] addElement<T>(this T[] array, T elementToAdd)
{
    var list = new List<T>(array) { elementToAdd };
    return list.ToArray();
}

this works ok, but when I use it, I am having to set the array equal to the return value. I see that I am returning an Array. I likely want this method to be void, but I would like the item added. Does anyone have any ideas on what I need to do , to make this work the way I am w开发者_如何转开发anting?

Instead of someArray = someArray.addElement(item), I just want to do someArray.addElement(item) and then someArray be ready to go. What am I missing here?


Built-in arrays have a fixed size and so can't be modified in this way. If you want a dynamically-sized array, use a List<T>.


If you could use ref extension methods then it would be possible, but not a good way to do things at all. Thankfully they are not supported.

If you absolutely must have something like this you can use a static method with a ref parameter:

public static class ArrayHelp {
    public static void addElement<T>(ref T[] array, T elementToAdd)
    {
        Array.Resize(ref array, array.Length + 1);
        array[array.Length - 1] = elementToAdd;
    }
}

But this is just as ugly (if not more so) than your current solution.


It's not possible. The only way to resize an array is by creating a new one. If you need to frequently add items to an array, use a List, they are designed for this purpose.

0

精彩评论

暂无评论...
验证码 换一张
取 消