Note that there are some explanatory texts on larger screens.

plurals
  1. POXmlSerializer requires XmlInclude for public method with generic constraint if type in another assembly AND requires that type to be serialiable!
    primarykey
    data
    text
    <p>Consider the following. You have a class that you want to serialize with XmlSerializer which has a public generic method with a type constraint where the type is in a different assembly:</p> <pre><code>using BarStuff; namespace FooStuff { public class Foo { ... public T GetBar&lt;TBar, T&gt;( string key ) where TBar : Bar&lt;T&gt; { ... } } } </code></pre> <p>You wouldn't expect the XmlSerializer to even concern itself with methods, and generally it doesn't. The following both work fine:</p> <pre><code>//private, serializer doesn't care about it private T GetBar&lt;TBar, T&gt;( string key ) where TBar : Bar&lt;T&gt; { ... } //no generic type constraint, serializer also doesn't care about it public Bar GetBar( string key ) { ... } </code></pre> <p>Also, if the type Bar is in the same assembly as Foo then the serializer will also be perfectly happy.</p> <p>When you execute the first example, if Bar is defined in a separate assembly you will get a runtime exception saying that you need to add a reference to the assembly containing Bar, <em>even if you already have that assembly in your project references</em>. You can get around this by using XmlInclude:</p> <pre><code>[XmlInclude(typeof(Bar))] public class Foo { public T GetBar&lt;TBar, T&gt;( string key ) where TBar : Bar&lt;T&gt; { ... } } </code></pre> <p>However if Bar is not serializable, and there's no reason why it should be, you'll now get a runtime exception the first time it hits something it can't serialize, such as a public property that returns an interface as its type, a class without a parameterless constructor etc.!</p> <p>Related but not as detailed: <a href="https://stackoverflow.com/questions/2361563/xmlserializer-is-throwing-invalidoperationexception-when-using-the-generic-type-c">XmlSerializer is throwing InvalidOperationException when using the generic type constraint where</a></p> <p>Also: <a href="http://connect.microsoft.com/VisualStudio/feedback/details/203076/xmlserializer-does-not-work-on-type-with-constrained-generic-method" rel="nofollow noreferrer">Microsoft's take on the problem</a></p>
    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.
 

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