0

I am trying to make a generic method, that adds an object to the given array.
I tried the below code, but I get this error: "A property, indexer or dynamic member access may not be passed as an out or ref parameter"

 public void Main()
 {
     Foo newObject = new Foo();
     AddObjectToArray<Foo>(ref _allMyData.FooArray, newObject);
 }

 public void AddObjectToArray<T>(ref T[] array, T newObject)
 {
     var list = array.ToList();
     list.Add(newObject);
     array = list.ToArray();
 }

I could solve it by removing the ref and returning the array like this:

 _allMyData.FooArray = AddObjectToArray<Foo>(_allMyData.FooArray, newObject);

But it would be much cleaner if I could only use the ref :-)
Am I missing something obvious?

nza
  • 55
  • 5
  • 3
    Why do you want such a method? It is very inefficient. If you need to add items use a `List` in the first place. And even if you need that array you could use `list.ToArray()` right at the end. – Tim Schmelter Jan 28 '15 at 08:38
  • Does that property needs to be a `FooArray` ? Why not `FooList` which uses `List`. Then you don't even need such method. – Sriram Sakthivel Jan 28 '15 at 08:39
  • a ref or out argument must be an assignable variable https://msdn.microsoft.com/en-us/library/14akc2c7.aspx – Mike Debela Jan 28 '15 at 08:50
  • It is an array because I have a ton of classes generated from an xsd, and it uses arrays for collections. – nza Jan 28 '15 at 08:55

1 Answers1

1

You can't use a property for the ref parameter. You would need to get the reference out, make the call, and put it back:

Foo[] arr = _allMyData.FooArray;
AddObjectToArray<Foo>(ref arr, newObject);
_allMyData.FooArray = arr;

So, you might want to reconsider using an array in the first place. Adding items to an array is very inefficient anyway, as you have to copy the entire array content each time.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005