Good afternoon, comrades! Suppose we have some static extension method of the form:

public static string[] Method(this string[] Arr) { Некоторые действия со входным массивом...; return Arr; } 

My problem is this: is it possible to somehow change the initially transmitted Arr array so that I don’t have to register

 Arr = Arr.Method(); 

And it was enough only

 Arr.Method(); 

Just with the keyword this refuses to work most of the other keywords that could contribute to this! What could you think of in this situation?

  • What does "change" mean? Arrays are a reference type, you can change it without any ref / out (if the type is mutable by design). Another thing is, if you want to assign a different value to a variable, then it is right to reassign it semantically. - free_ze

1 answer 1

Extensions work the same way as with simple static methods. Simply process your Arr inside the Method() extension Method() . You pass the reference type to the extension.

In this case, it would be better to make an extension with a void return type.

Ps. In this case, I would advise using ICollection<string> instead of string[] .

For the "permission" to add an item, you can bring the collection to the list using IEnumerable.ToList() :

 var values = new string[]{ "val1", "val2" }; var valueCollection = values.ToList(); valueCollection.AddItem(); 

In this case, the extension will be something like this:

 public static void AddItem(this IList<string> target) { target.Add("another item"); } 

Protest!

  • That's all the fun that I first tried to do void. At the end, I assigned a new value to the passed array. But, alas, it didn’t reflect on the original array at all - Kir_Antipov
  • one
    @Kir_Antipov your "at the end" rewrites the link to the incoming array to the resulting one. You should work with the incoming array as if you have a static method - vitidev
  • @vitidev, doh. Right. And how can you expand the existing array without overwriting its reference? - Kir_Antipov
  • 3
    @Kir_Antipov array has a finite size and will not expand itself without creating a new array. So you have to create a new one and return it. Any assignment will simply create a new link, about which no one from outside will know. - vitidev
  • @vitidev, but sorry. Thank! - Kir_Antipov