views:

468

answers:

1

Hi,

I've read the topic about passing an object[] to a params object[] but I don't know why it's not working with me.

I have these too functions in a class:

...
    private void CallbackEvent(object source, CallbackEvetArgs e) { // Some event with e.Data as string
    ...
        string[] values = e.Data.Split('|');
        DoSave("save", values.Skip(1).Cast<object>().ToArray());
    ...
    }
...
    public void DoSave(string action, params object[] values) {
    ...
        string value1 = values[0];
    ...
    }
...

but instead of receiving an string in value1, value1 is receiving the whole array (string[]) and therefore an invalid casting exception.

What am I doing wrong?

+8  A: 

C# (.NET in general) arrays are covariant. You can simply pass the string[] to an object[] parameter.

DoSave("save", values.Skip(1).ToArray());

The code you posted is definitely not the exact code you tested. Cast<object> should also work correctly. This line shouldn't compile:

string value1 = values[0]; // object -> string, no implicit conversion.

Please post the exact code causing the problem.

Mehrdad Afshari
This is true but the question remains why does this break if you insert a `.Cast<object>()` into the chain?
AnthonyWJones
AnthonyWJones: It shouldn't break. I think OP is wrong on this.
Mehrdad Afshari
+1 but s/C#/CLR
JaredPar
Thanks for your answer Mehrdad but it did not work also.I've tried your proposal and values[0] is still getting a string[] and because of that I get an exception saying :"can't convert string[] to string.".When I watch over the values param at the function call It presents: values -> {+object[1]} -> {+string[1]} -> "the real value".I've tryed:DoSave("save", values.Skip(1).ToArray());DoSave("save", (object)values.Skip(1).ToArray());DoSave("save", values.Skip(1).Cast<object>().ToArray());DoSave("save", (object)values.Skip(1).Cast<object>().ToArray());with the same result.
Sir Gallahad
Ahh and I've tried DoSave("save", values[1], values[2]);That works perfect... but it totally miss the point of the intended implementation.I really don't know waht going on.
Sir Gallahad
Can you edit your question and post the **exact** code of the `DoSave` method?
Mehrdad Afshari