0

i was wandering if there is a way to pass an array to a function that is used on its members( kind of like how you pass the "this" parameter to object).

instead of this:

void public foo(A[] arr){}
void main(){
arr[i].foo(arr);
}

this:

void public foo(A[] arr){}
void main(){
arr[i].foo();
}

edit: arr is array of A, foo belongs to A sorry for bad explanation first question.

asked Apr 20, 2020 at 9:19
8
  • You could create an extension method. Commented Apr 20, 2020 at 9:21
  • 2
    If you go down the extension method route, I suspect you will want arr.foo() not arr[i].foo(). Commented Apr 20, 2020 at 9:22
  • Sounds like you want to just do a foreach over the array and call foo on each item? foreach(A a in arr)foo(a); Or am I misunderstanding the question? Commented Apr 20, 2020 at 9:24
  • You mean like this, void public foo(data_type var) { .... } void main() { foo(arr[i]) } Commented Apr 20, 2020 at 9:28
  • @JohnathanBarclay an extension method wont do because i want it to run on the objects inside the array and not the array itself Commented Apr 20, 2020 at 9:35

1 Answer 1

1

So... if I understand correctly. You want to call an item in the array, with a reference to the array.

But you don't want to pass that reference to the array?

I can only think of a working solution where you make a new class that encapsulates the array[] and create an add method, that upon adding handles the reference binding. (so passing a ref of itself to the added object). So that the items in the array hold a reference to the array.

or maybe you can do some nifty stuff using indexers:

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/indexers/

Hope this helps!

answered Apr 20, 2020 at 9:46

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.