0

I'm migrating a library from .net framework 4.5.2 to .net core 2.2. I need to use an XmlIgnore on a DateTime, which worked fine in .net framework, but I can't get it to work in .net core.

So far, I've tried using NonSerialized instead of XmlIgnore which of course didn't work since my DateTime object is not a field. I've also looked into using the DataContractSerializer isntead as well.

[Serializable]
[XmlRoot(ElementName = "DELIVERY")]
public class Delivery
{
    [XmlIgnore]
    public DateTime DeliveryDate { get; set; }

    [XmlElement]
    public string DeliveryDateString
    {
        get
        {
            return DeliveryDate.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture) ?? string.Empty;
        }

        set
        {
            DateTime dt;
            if (DateTime.TryParseExact(value, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out dt))
            {
                DeliveryDate = dt;
            }
        }
    }
}

Error CA2235: Field DeliveryDate is a member of type Delivery which is serializable but is of type System.DateTime which is not serializable
techin424
  • 1
  • 1
  • Do you need the class to be serializable or just read/written as `XML`? If the latter then remove the `Serializable` attribute. It's not needed for `XML` – Simply Ged Sep 17 '19 at 00:02
  • `Serializable` will read/write the whole object and applies to `BinaryFormatter` (plus some others) and has nothing to do with XML. Read [this answer](https://stackoverflow.com/a/50991360) for more details. – Simply Ged Sep 17 '19 at 00:05
  • 1
    Possible duplicate of [What is \[Serializable\] and when should I use it?](https://stackoverflow.com/questions/5877808/what-is-serializable-and-when-should-i-use-it) – Simply Ged Sep 17 '19 at 00:08
  • `[Serializable]` has nothing to do with `Xmlignore` – Fabio Sep 17 '19 at 00:43
  • 1
    Can't reproduce on .NET Core 2.2.6, see https://dotnetfiddle.net/M9047W. On this version `DateTime` is serializable. Is the error being generated by the compiler or some code analyzer? There seems to be some issue with this for Microsoft Code Analysis, version 2.6.0.6241303, see [False positives in CA2235 #1510](https://github.com/dotnet/roslyn-analyzers/issues/1510). – dbc Sep 17 '19 at 15:06
  • If this is a bug in the analyzer, easiest workaround is to remove `[Serializable]` as recommended in [this answer](https://stackoverflow.com/a/50833829) to [Field is member of a type which is serializable but is of type which is not serializable](https://stackoverflow.com/q/50833769). Please let us know whether that works for you, or you need a solution in which `Delivery` remains `[Serializable]`. – dbc Sep 17 '19 at 15:15

0 Answers0