Is there any difference between using myArray.GetValue(2) and myArray[2]?
For example:
namespace ConsoleApplication16
{
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[] { 1, 2, 3, 4 };
Console.WriteLine(numbers.GetValue(3));
Console.WriteLine(numbers[3]);
Console.ReadLine();
}
}
}
GetValue() Method in C# is used to gets the value of the specified element in the current Array.
The GetValues method returns an array that contains a value for each member of the enumType enumeration. If multiple members have the same value, the returned array includes duplicate values.
The multidimensional array is also known as rectangular arrays in C#. It can be two dimensional or three dimensional. The data is stored in tabular form (row * column) which is also known as matrix. To create multidimensional array, we need to use comma inside the square brackets.
GetValue
will return type object while using the index will return the type specific with the array.
You can see in this fiddle (code below) that the variable val1
can have a string stored in it, but val2
can only be used as an integer.
public static void Main()
{
int[] numbers = new int[]{1, 2, 3, 4};
var val1 = numbers.GetValue(3);
var type = val1.GetType();
var val2 = numbers[3];
Console.WriteLine(type.ToString());
val1 = "hello";
type = val1.GetType();
Console.WriteLine(type.ToString());
}
This will result in boxing and unboxing, which won't have an effect on a small code snippet, but if used in large scale it could potentially affect performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With