0
[Serializable]
public struct Foo
{
    public string Info { get; }
}

[Serializable]
public class ExceptionA : Exception
{
    public IEnumerable<Foo> Foos { get { return _foos; } }

    private List<Foo> _foos;
}

The C# compiler will complain that "Field _foos is a member of type ExceptionA which is serializable but is of type System.Collection.Generic.List which is not serializable"

How can I solve it? (Don't suppress CA2235, don't mark it as [NonSerialized])

Peng Deng
  • 43
  • 8
  • Field _foos is a member of type ExceptionA which is serializable but is of type System.Collection.Generic.List which is not serializable – Peng Deng Feb 01 '18 at 08:57
  • Why do you want to serialize your private field? – Samvel Petrosov Feb 01 '18 at 08:58
  • I just want to make the custom Exception serializable... – Peng Deng Feb 01 '18 at 09:02
  • Possible duplicate of [How to Serialize List?](https://stackoverflow.com/questions/5005900/how-to-serialize-listt) – amarsha4 Feb 01 '18 at 09:17
  • You *do* need to mark the field as `[NonSerialized]` since the default mechanism simply won't apply, then use the appropriate attributes for [custom serialization](https://learn.microsoft.com/dotnet/standard/serialization/custom-serialization) to serialize it yourself (by converting to/from an array, most likely, as those are serializable). Note that it's increasingly less relevant to actually have serializable exceptions, despite what code checkers may say -- unless you're actively using AppDomains, there's little need to bother. – Jeroen Mostert Feb 01 '18 at 09:30

0 Answers0