Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an array's SetValue method vs. the [] indexers

I noticed that arrays have the SetValue method, which seems a little out of place when you could just use the indexers. Is there some special purpose for SetValue? The MSDN article didn't seem to say what SetValue was for, just how to use it. Which method would be more efficient to use as far as speed goes?

like image 861
Thick_propheT Avatar asked May 16 '12 21:05

Thick_propheT


People also ask

What is the use of SetValue ()?

SetValue(Object, Object, Object[]) Sets the property value of a specified object with optional index values for index properties.

How do you set a value in an array?

Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.

Which of the following options can be used for accessing the nth element of an array named arr?

If you want to access the nth element without knowing the index, you can use next() n times to reach the nth element.

What is the need of index in an array?

The index indicates the position of the element within the array (starting from 1) and is either a number or a field containing a number.


1 Answers

Sometimes all you have of an array is that it's an Array. The Array class does not have indexers, so the best way to set/get element values on it is via the GetValue and SetValue methods. For example:

private void M(Array array) 
{
    array[0] = 5;         // <-- Compiler error
    array.SetValue(5, 0); // <-- Works
}
like image 171
Kirk Woll Avatar answered Oct 28 '22 18:10

Kirk Woll