0

I would like to make some property of a class visisble (scope, access modifier) only by the XML serializer. I'm not sure about the best way to hide some properties from the consumers of a class without over engineering.

Let's see an exemple:

public class MyClass
{
    [XmlIgnore]
    public Version Version { get; set; }

    /// <summary>
    /// Do not used. This is a dummy property for XML serialization.
    /// </summary>
    [XmlAttribute(AttributeName = nameof(Version))]
    public string XmlVersion
    {
        get => Version.ToString();
        set => Version = new Version(value);
    }
}

This kind of code allows me to use a class which is not designed to be serialized (System.Version isn't because its properties are readonly).

I would like that the consumers of my class see only Version but not the XmlVersion property.

Edit : If it's possible, I'd like those properties to be hidden even in the project where the class is so my co-worker won't use those dummy properties too. I know I can use ObsoleteAttribute to give information why they should be avoided but those properties will still be usable which isn't the behavior I'm looking for.

Nk54
  • 751
  • 7
  • 15
  • 1
    Not sure this has an easy answer. Is `DataContractSerializer` an option? Otherwise you’d be stuck with `IXmlSerializable` Or `ObsoleteAttribute` – Mitch Dec 12 '20 at 00:13
  • I am not sure If I understand the question right, but I will give it a shot. Can't you just make the `XmlVersion` private instead of public? – Dawid Wawrzynczyk Dec 12 '20 at 00:15
  • 2
    @DavidWawrzynczyk, XmlSerializer requires a public accessor to any property to be set. It was written in a time of partially trusted assemblies – so it is quite limited. (Must also have public ctor). – Mitch Dec 12 '20 at 00:17
  • 1
    Only public members are serialized by `XmlSerializer`. See [c#: how to hide a field which is used only for XML serialization retrocompatibility?](https://stackoverflow.com/q/47571925/3744182) for confirmation and workarounds. In fact I think this is a duplicate, agree? – dbc Dec 12 '20 at 00:35
  • Yeah, the property must be public to be serialized. I've tried internal / internal protected etc. But it throws an exception : property won't be serialized if not public. (I thought I could encapsulate those class in an assembly and keep things internal but it's not possible). @Mitch maybe that's an option. Too bad my needs are not as easy as it should :) – Nk54 Dec 12 '20 at 21:41

0 Answers0