1

I have a method where I can only retrieve the object type at runtime. I tried to cast it to a list of known object, but I failed.

  private string outputParamForListOrDict(IMethodReturn returnValue)
    {
        StringBuilder sb = new StringBuilder();
        String outputString = string.Empty;

        switch (returnValue.ReturnValue.GetType().GetGenericArguments()[0].Name)
        {       

            case nameof(ViewDocumentReport):

                List<ViewDocumentReport> _viewDocumentParam = (List<ViewDocumentReport>)returnValue.ReturnValue;

                //process the data here........

                return sb.ToString();

            //Other object cases

         }
    }

I got an exception below:

"Unable to cast object of type >'<TakeIterator>d__25`1[ezAcquire.RMS.Model.ViewModels.ViewDocumentReport]' to type 'System.Collections.Generic.List`1[ezAcquire.RMS.Model.ViewModels.ViewDocumentReport]'."}

I put a breakpoint in debug mode. My returnValue.ReturnValue is of System.Linq.Enumrable.<TakeIterator>

and if I expand I can see there a list of List.

List<ViewDocumentREport>

can someone explain to me what is the d_25 meant, and advice me on how should I cast it correctly during runtime?

Thanks

Keyur Ramoliya
  • 1,900
  • 2
  • 16
  • 17
csamleong
  • 769
  • 1
  • 11
  • 24
  • returnValue.ReturnValue is of object type, it doesn't have a .Cast method. Check the link below: https://msdn.microsoft.com/en-us/library/system.object_methods%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 I am using framework 4.6.2, do you come from different version ? – csamleong Jun 21 '18 at 16:34
  • Nope, I just didn't know the details of your model. You may want to cast to `IEnumerable` before trying to make it a list. – Jonathon Chase Jun 21 '18 at 16:41

1 Answers1

5

If you're quite sure your object is an IEnumerable of a type you know, you can cast the object to the IEnumerable<T> before performing a ToList.

public class Test {

}

void Main()
{
    object x = Enumerable.Range(0,100).Select(_ => new Test()).Take(15);
    List<Test> fail = (List<Test>)x; // InvalidCastException: Unable to cast object of type '<TakeIterator>d__25`1[UserQuery+Test]' to type 'System.Collections.Generic.List`1[UserQuery+Test]'.
    List<Test> pass = ((IEnumerable<Test>)x).ToList(); // No problem
}

Casting directly from IEnumerable<T> to List<T> is not a valid cast, as you've encountered. You'll need to cast your object to an IEnumerable before either feeding it into a List<T> constructor or using Linq's ToList method.

Jonathon Chase
  • 9,396
  • 21
  • 39