C# Add extension Append method to class array of type T

user5825579

Using this answer to the question "How to add a string to a string[] array? There's no .Add function" I am trying to use this answer to write an generic extension to append elements to an generic array. Only using the Array.Resize() method works well and the sample below adds an extra element to my string array

string[] array = new string[] { "Foo", "Bar" };
Array.Resize(ref array, array.Length + 1);
array[array.Length - 1] = "Baz";

But when I try to use the ArrayExtension method described below, the method does resize my array inside the method but when it returns the array is unchanged?

My extension class

public static class ArrayExtensions
{
    public static void Append<T>(this T[] array, T append)
    {
        Array.Resize(ref array, array.Length + 1);
        array[array.Length - 1] = append;    // < Adds an extra element to my array
    }
}

Used as follows

string[] array = new string[] { "Foo", "Bar" };
array.Append("Baz");

When the method returns, the added element does not exist. What am I missing?

UPDATE

As pointed out, this question has been asked and answered here before. I will accept the previous question "Changing size of array in extension method does not work?" as an answer to my question.

UPDATE 2

Since if a return method is used in the extension method it does violate the expected behaviour of similar classes in the framework that Append() to modify the object itself, I did some changes to the extension method to prevent it from being falsely used. Thanks @NineBerry for pointing this out.

I also added params T[] add to allow for adding multiple elements at once.

public static class ArrayExtensions
{
    /// <summary>
    /// Creates a copy of an object array and adds the extra elements to the created copy
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="array"></param>
    /// <param name="add">Elemet to add to the created copy</param>
    /// <returns></returns>
    public static T[] CopyAddElements<T>(this T[] array, params T[] add)
    {
        for (int i = 0; i < add.Length; i++)
        {
            Array.Resize(ref array, array.Length + 1);
            array[array.Length - 1] = add[i];
        }
        return array;
    }
}

Usage

string[] array = new string[] { "Foo", "Bar" };
array = array.CopyAddElements("Baz", "Foobar");
for (int i = 0; i < array.Length; i++)
{
    System.Console.Write($"{array[i]} ");
}

/* Output
 *  Foo Bar Baz Foobar
*/
NineBerry

Array.Resize creates a new array. That's why you have to pass the array using the ref keyword to Array.Resize. So, after returning from Array.Resize, the variable array references a different object.

There is no way to use an extension method to do what you are trying to do.

Why not simply use a List<> instead of an array? Using Array.Resize is a very costly operation. It means allocating new memory and copying over the data from the old array to the new array each time it is called to increase the array length.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Extension method on Nullable<T> not called unless generic type is set explicitly

From Dev

Extension Method On Casted Type

From Dev

Extension method to check if an object is sub class of T

From Dev

Java 8 add extension/default method to class

From Dev

Can't create default closure parameter in Array extension method in Swift

From Dev

C++ : Add a method to a base class interface

From Dev

Why can't I call an extension method from a base class of the extended type‏?

From Dev

C++ way to assign an array of char to a T* in a const method of a class

From Dev

Extension method for IEnumerable<T> which returns type of -this-

From Dev

Can't omit the extension type argument when calling generic extension method with mutually constrained type parameters

From Dev

Forward declaration of objective-c class extension method

From Dev

Swift: How to add a class method in 'String" extension

From Dev

is it possible to write an extension method only for List<T> where T is a class that inherits from class K

From Dev

How to Write Generic Extension Method to Convert Type in C#

From Dev

How to add an extension method?

From Dev

Can't add extension method to an abstract class in C#

From Dev

C# Add extension method to instance of class?

From Dev

Calling an extension method on a member variable of type T of class<T>

From Dev

c# method won't add to list in class

From Dev

Call a method of a derived class from an array of pointers of type base class. (C++)

From Dev

If value is empty don't add class attr upon append

From Dev

Extension Method with Generic Type

From Dev

Add extension method to List

From Dev

Nullable nested type in extension method in C#

From Dev

ForEach List<T> Extension method - Value Or Reference Type?

From Dev

C++: Append to front, add to back array of int's

From Dev

one generic class create generic extension with expression<T,bool> method

From Dev

Why isn't jQuery append method working when passing parent class to add a child input?

From Dev

extension method for List<T> with both constraints class and struct

Related Related

  1. 1

    Extension method on Nullable<T> not called unless generic type is set explicitly

  2. 2

    Extension Method On Casted Type

  3. 3

    Extension method to check if an object is sub class of T

  4. 4

    Java 8 add extension/default method to class

  5. 5

    Can't create default closure parameter in Array extension method in Swift

  6. 6

    C++ : Add a method to a base class interface

  7. 7

    Why can't I call an extension method from a base class of the extended type‏?

  8. 8

    C++ way to assign an array of char to a T* in a const method of a class

  9. 9

    Extension method for IEnumerable<T> which returns type of -this-

  10. 10

    Can't omit the extension type argument when calling generic extension method with mutually constrained type parameters

  11. 11

    Forward declaration of objective-c class extension method

  12. 12

    Swift: How to add a class method in 'String" extension

  13. 13

    is it possible to write an extension method only for List<T> where T is a class that inherits from class K

  14. 14

    How to Write Generic Extension Method to Convert Type in C#

  15. 15

    How to add an extension method?

  16. 16

    Can't add extension method to an abstract class in C#

  17. 17

    C# Add extension method to instance of class?

  18. 18

    Calling an extension method on a member variable of type T of class<T>

  19. 19

    c# method won't add to list in class

  20. 20

    Call a method of a derived class from an array of pointers of type base class. (C++)

  21. 21

    If value is empty don't add class attr upon append

  22. 22

    Extension Method with Generic Type

  23. 23

    Add extension method to List

  24. 24

    Nullable nested type in extension method in C#

  25. 25

    ForEach List<T> Extension method - Value Or Reference Type?

  26. 26

    C++: Append to front, add to back array of int's

  27. 27

    one generic class create generic extension with expression<T,bool> method

  28. 28

    Why isn't jQuery append method working when passing parent class to add a child input?

  29. 29

    extension method for List<T> with both constraints class and struct

HotTag

Archive