Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>As I was entering this question, the answers came to me, so I leave this question answered as a guide to others.</strong></p> <p>I have a function such as </p> <pre><code>T Func&lt;T&gt;(string val) {} </code></pre> <p>Inside this function I do various processing, one item of which is to convert the val to a T.</p> <p>I have another function which I use for this purpose </p> <pre><code>T ChangeType&lt;T&gt;(this object value) </code></pre> <p>This function is mainly a wrapper around Convert.ChangeType with some additional processing, to handle things that Convert.ChangeType can't do out of the box (stolen from stackoverflow elsewhere)</p> <p>Everything works great for most types, but is some cases T is a List and val is then a comma separated list of values.</p> <p>I can correctly determine if T is a List via</p> <pre><code>if (returnType.IsGenericType &amp;&amp; returnType.GetGenericTypeDefinition() == typeof(List&lt;&gt;)) </code></pre> <p>and then I can instantiate the appropriate list return type as follows</p> <pre><code>T list = (T)Activator.CreateInstance(returnType); </code></pre> <p>Now, I need to call my ChangeType on each split value from the string, and add them to the list. </p> <pre><code>var method = typeof (XmlUtil).GetMethod("ChangeType", new [] {typeof(object)}); var genericMethod = method.MakeGenericMethod(subType); var convertedItem = genericMethod.Invoke(null, new [] {item}); var subType = returnType.GetGenericArguments()[0]; </code></pre> <p>All good so far. Now I have a </p> <pre><code>dynamic list; //instantiated with a List&lt;TT&gt; var convertedItem; // which is typed as an object, instantiated with a type TT. </code></pre> <p>How do I call </p> <pre><code>list.Add(convertedItem); </code></pre> <p>the dynamic will handle the fact that I don't have a known interface for the list, but at runtime I get an error because I am trying to add an object to a list, even though the object is actually of type T as instantiated. </p> <p>The ultimate answer, is to cast the List as a non-generic IList, where you can then add object.</p> <pre><code>System.Collections.IList list2; list2 = (System.Collections.IList) list; list2.Add(convertedItem); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload