C# Array Boxing Possible Issue Value vs Reference Types

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



I have encountered an interesting feature of C# and I'm wondering if
anyone can shed light on why this happens. If I have a method that
takes an array of objects as its parameter certain unexpected things
happen:

eg.

int[] intArray = { 4, 50, 12, 42 };
string[] strArray = { "Ab", "Cd", "Ef" };

public static void SomeFunction([params] object[] objectArray)
{ .. do something .. }


The things I have noted are:

(1) Without the params keyword in the function definition for
"SomeFunction" it will fail at compile time with a "Cannot convert from
int[] to object[]" complaint. If the params is present it will accept
arrays of value type data happily.

(2) When it is working (with 'params' keyword present) the int[] array
is then boxed as an Array rather than as an array of integers. So if I
try and do a foreach loop to print out each member of objectArray to
the console it will just print System.Int32[].

(3) This behaviour is not consistent with single parameter methods.
For exampl e if I pass an int value to a function that takes an object
(singular) then it is boxed fine and compile and run time works.

I'm assuming that arrays must be handled differently if they contain
value type data and if they contain reference type data. Why is this?
Or what am I missing?

Thanks
Neil

.



Relevant Pages

  • Re: PLEASE HELP - Fundamental C language question
    ... > int* doit{ ... > Since the array intArray is allocated on the stack ... the array intArray is an automatic object. ... At compile time, it doesn't point anywhere, because at compile time the ...
    (comp.lang.c)
  • Re: why doesnt this work? final assignments and switches
    ... lets say we have an array of names ... final int ... programming is sane - if you want a tiger property, ... > switch cases want [values known at compile time. ...
    (comp.lang.java.programmer)
  • Re: ReDim an array AFTER its loaded into another array
    ... I am not familiar with the Type Data construct, ... redim preserve alldata ... I have an array whose elements are other arrays. ... Once a "master" array is formed, it looks like the component arrays ...
    (microsoft.public.excel.programming)
  • Re: floating point values
    ... that number as an array index for a lookup table. ... This works find for double type data that are integers. ... array cannot be accessed using non-integer or literal values. ... a hash table or an associative array instead of a direct array index. ...
    (comp.soft-sys.matlab)
  • Re: dynamic declaration of struct array
    ... > Why won't the declaration of a struct array work if I do it like this: ... > 7 int main ... array variables are indeed required ... to be of a size known at compile time. ...
    (comp.lang.c)