- Home /
In python you can access every object in an array at once, how do you do this in c#?
It's been a while since I used python, but I remember being able to access everything stored in an array by doing the following:
array[0:]
having the colon after the zero meant you want to reference everything stored in the array. How would I go about this in C#?
Answer by kacyesp · Sep 08, 2014 at 10:30 PM
That's just syntactic sugar. To know my knowledge, nothing like that exists in C#.
You can use a foreach loop:
int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0};
foreach (int i in numbers)
{
System.Console.WriteLine(i);
}
So I did a bit of googling (because I'm not actually familiar with python), and array[0:] returns the original array. When you use the colon like that, it returns a sublist where the number on the left is inclusive, and the number on the right of the colon is exclusive. So array[1:4] will give you elements 1,2, and 3. When you don't specify a number on the right, it inserts the length of the list. Here's a thorough explanation if you still care :P http://www.i-programmer.info/program$$anonymous$$g/python/3942-arrays-in-python.html
If you want to be able to create subarrays from any array in C#, see this post: http://stackoverflow.com/questions/943635/c-sharp-arrays-getting-a-sub-array-from-an-existing-array.
That will give you the same functionality as what you provided in python.