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?

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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.