C# Array Boxing Possible Issue Value vs Reference Types
- From: "Neil" <neilprice@xxxxxxxxx>
- Date: 10 Oct 2005 16:01:36 -0700
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
.
- Prev by Date: Enterprise Library - DB2 data access
- Next by Date: Re: Are byte types a smart choice?
- Previous by thread: Enterprise Library - DB2 data access
- Next by thread: SAFEARRAY & ThreadSafe
- Index(es):
Relevant Pages
|