1

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?

Andre Vianna
  • 1,713
  • 2
  • 15
  • 29

1 Answers1

8

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
  • 414,610
  • 91
  • 852
  • 789
  • This is true but the question remains why does this break if you insert a `.Cast()` into the chain? – AnthonyWJones Aug 28 '09 at 16:43
  • AnthonyWJones: It shouldn't break. I think OP is wrong on this. – Mehrdad Afshari Aug 28 '09 at 16:44
  • 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().ToArray()); DoSave("save", (object)values.Skip(1).Cast().ToArray()); with the same result. – Andre Vianna Aug 30 '09 at 23:15
  • 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. – Andre Vianna Aug 30 '09 at 23:17
  • Can you edit your question and post the **exact** code of the `DoSave` method? – Mehrdad Afshari Aug 30 '09 at 23:21