In C#, how can I cast KeyValuePair<string, object> to KeyValuePair<object, object>? I tried the following but it does not work:

public static KeyValuePair<object, object> DoTheCast(KeyValuePair<string, object> the_obj)
{
    return (KeyValuePair<object, object>)the_obj;
}

InvalidCastException: Unable to cast object of type 'System.Collections.Generic.KeyValuePair[System.String,System.Object]' to type 'System.Collections.Generic.KeyValuePair[System.Object,System.Object]'.

1 Answers

6
Michael Randall On Best Solutions

You wont be able to cast perse, however you can just create a new one

public static KeyValuePair<object, object> DoTheCast(KeyValuePair<string, object> the_obj)    
     => new KeyValuePair<object, object>(the_obj.Key, the_obj.Value);