I'm currently reading Deitel's book How to program C#. There is chapter where passing an array as a parameter is discussed. The following piece of code is presented:
static void ModifyArray(int[] array2)
{
for (var counter = 0; counter < array2.Length; counter)
{
array2[counter] *= 2;
}
}
My questions are:
- How does the compiler know the array2 length since it is not established?
- Still, why is not there any compilation error since an array has been created without a associated length?
- Even if passing an array without an explicit length is possible how can the condition "counter < array2.Length" be evaluated?
Many thanks,
Ivan
CodePudding user response:
Let me start with a small correction your second question. In C#, declaring parameters in a method doesn't really "create" anything new. Parameters take in a variable, which leads me to answer your first question. The compiler knows the length of the array because it knows the length of whatever array is passed into the method when the method is called. For example:
int[] myArray = new int[] { 1, 3, 5, 7, 9 };
ModifyArray(myArray) // <- the compiler knows that myArray has length of 5
This should also help to answer your third question. Also, it wouldn't really make logical sense to have a method in which you could only pass an array of a specific length, because it would make the use case of the method much more specific. In summary, arrays as parameters don't need a length because the length will be known from the array which is passed into the method.
CodePudding user response:
C# array has a default property which indicates length of the array.