user3048027
user3048027

Reputation: 387

Error in cast List<dynamic> to IEnumerable<Tuple<string,string>>

I am facing an issue while casting an API response type. The API returns List<object> in a particular format code given below

using System;
using System.Collections.Generic;       
        
public class Program
{
    public static void Main()
    {
        dynamic tupleStringList;
        tupleStringList = new List<dynamic>{Tuple.Create("a","b"),Tuple.Create("c","d")}; // this data will come API which I have no control
        IEnumerable<Tuple<string,string>> test = (IEnumerable<Tuple<string,string>>) tupleStringList;// here we need to cast as another internal function which use it as IEnumerable<Tuple<string,string>>
    }
}

The error I am getting is given below

Run-time exception (line 9): Unable to cast object of type 'System.Collections.Generic.List`1[System.Object]' to type 'System.Collections.Generic.IEnumerable`1[System.Tuple`2[System.String,System.String]]'.

Stack Trace:

[System.InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[System.Object]'`` to type 'System.Collections.Generic.IEnumerable`1[System.Tuple`2[System.String,System.String]]'.]  
   at CallSite.Target(Closure,CallSite,Object )  
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at Program.Main() :line 9

Upvotes: 0

Views: 310

Answers (1)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61952

I suggest tupleStringList.Cast<Tuple<string, string>>(), maybe like:

(IEnumerable<Tuple<string, string>>)(tupleStringList.Cast<Tuple<string, string>>())

(This needs a using System.Linq; directive.)

Ralf has a point in the comments (see Extension method and dynamic object): If extensions methods are not considered for the binding of a dynamic expression, cast to nongeneric IEnumerable first. For example:

var tupleStringListCast = (IEnumerable)tupleStringList;
var test = tupleStringListCast.Cast<Tuple<string, string>>();

Or call Cast<TResult>() with usual static call syntax:

var test = (IEnumerable<Tuple<string, string>>)(Enumerable.Cast<Tuple<string, string>>(tupleStringList));

However, it assumes the pairs are really of type Tuple<,>.

Upvotes: 1

Related Questions