beginner: array --> function
-
hello!!! looked on the net but couldn't find an answer yet.... in c++ i used pointers to hand an array over to a function. what is the equivalent in c#? say i want to pass a simple int[]. how does it work with >return<. so far i declered an array in the class as private, similar to a global variable. however i don't think this is the way forward. many thanks in advance, Dominik
-
hello!!! looked on the net but couldn't find an answer yet.... in c++ i used pointers to hand an array over to a function. what is the equivalent in c#? say i want to pass a simple int[]. how does it work with >return<. so far i declered an array in the class as private, similar to a global variable. however i don't think this is the way forward. many thanks in advance, Dominik
Since C# is garbage-collected, you don't need to worry about passing pointers and dealing with memory, like you did in C++: simply pass the array as an argument or return it on a function and the framework will clean it automatically when you're not using it anymore. See this sample function:
int[] doubleValues(int[] values) { int[] retval = new int[values.Length]; for (int i = 0; i < values.Length; i++) retval[i] = values[i] * 2; return retval; }
-
Since C# is garbage-collected, you don't need to worry about passing pointers and dealing with memory, like you did in C++: simply pass the array as an argument or return it on a function and the framework will clean it automatically when you're not using it anymore. See this sample function:
int[] doubleValues(int[] values) { int[] retval = new int[values.Length]; for (int i = 0; i < values.Length; i++) retval[i] = values[i] * 2; return retval; }
thanks Daniel, i am already aware of the garbage collection and memory management. however, is there not a more efficient way to pass arrays to a function??? a pointer takes 4 bytes, whilst my 1k array of a class using doubles takes much more memory. thanks, Dominik
-
thanks Daniel, i am already aware of the garbage collection and memory management. however, is there not a more efficient way to pass arrays to a function??? a pointer takes 4 bytes, whilst my 1k array of a class using doubles takes much more memory. thanks, Dominik
dkoder wrote: however, is there not a more efficient way to pass arrays to a function??? a pointer takes 4 bytes, whilst my 1k array of a class using doubles takes much more memory. Actually, you're not passing a copy of the array: just like in C++, you're passing a pointer to the array. In C#, everything, but the native types (int, char, double, float, decimal) are pointers under the hood. Try changing the array inside the function and you'll see that what you're passing is actually a pointer. Yes, even I am blogging now!