Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between myArray.GetValue(2) and myArray[2] in C#?

Tags:

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();
        }
    }
}
like image 605
Jakub Gause Avatar asked Apr 14 '17 14:04

Jakub Gause


People also ask

What does GetValue do in c#?

GetValue() Method in C# is used to gets the value of the specified element in the current Array.

What does GetValues return?

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.

What is multidimensional array in C#?

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.


1 Answers

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.

like image 98
Smeegs Avatar answered Sep 21 '22 10:09

Smeegs