0

The title says it all, consider this program:

using System;
using System.Xml.Serialization;

public interface ITest
{
    public sealed class Test //: ITest
    {
        public string TestString { get; set; }
    }
    
    string TestString { get; }
}

public sealed class Test : ITest
{
    public string TestString { get; set; }
}

public class Program
{
    public static void Main()
    {
        var serializer1 = new XmlSerializer(typeof(Test));
        Console.WriteLine($"{nameof(serializer1)} created.");
        var serializer2 = new XmlSerializer(typeof(ITest.Test));
        Console.WriteLine($"{nameof(serializer2)} created.");
    }
}

The output is:

serializer1 created.
Unhandled exception. System.NotSupportedException: Cannot serialize interface ITest.
   at System.Xml.Serialization.TypeDesc.CheckSupported()
   at System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo source, Boolean directReference, Boolean throwOnError)
   at System.Xml.Serialization.TypeScope.ImportTypeDesc(Type type, MemberInfo memberInfo, Boolean directReference)
   at System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo source, Boolean directReference, Boolean throwOnError)
   at System.Xml.Serialization.ModelScope.GetTypeModel(Type type, Boolean directReference)
   at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace)
   at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
   at System.Xml.Serialization.XmlSerializer..ctor(Type type)

But ITest.Test is not an interface, it is a (concrete) sealed class!!

What's going on? is it a bug maybe?

Valentino Miori
  • 477
  • 1
  • 7
  • 16
  • *is it a bug maybe?* -- looks like it. I can round-trip `ITest.Test` with `DataContractSerializer` (see https://dotnetfiddle.net/5qnULQ) so it's clearly not impossible for it to be done by `XmlSerializer` also. But nested types inside interfaces were only recently implemented in c# 8.0 as a part of the default interface methods enhancement, so it's not that surprising that `XmlSerializer` doesn't account for them correctly in checking for serializability. See [Why can't an interface contain types?](https://stackoverflow.com/q/16151614/3744182). – dbc Apr 20 '22 at 15:53
  • But other than, maybe, enums, I can't really recommend nesting types inside interfaces. An interface is *implemented* by a class it doesn't *contain* a class. – dbc Apr 20 '22 at 15:54

0 Answers0