Error during class serialization: type is not marked serializable

0

I have a class marked as [Serializable]. It has a property tha I don't wan to serialize. But at runtime I got an error during serialization. These are my classes:

public interface IMyNonSerializable
{
   ...
}
public class MyNonSerializable : IMyNonSerializable
{
   ...
}
[Serializable]
public class MySerializable
{
   public string MyProp1{get;set;}
   [NonSerialized]
   public string MyProp2{get;set;}
   public IMyNonSerializable MyNonSerializableProp{get;set;}
}

Here the code I use to serialize my MySerializable class:

    Stream stream = new MemoryStream();
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Context = new StreamingContext(StreamingContextStates.Clone);
    formatter.Serialize(stream, obj);

At runtime I got this error:

> System.Runtime.Serialization.SerializationException
  HResult=0x8013150C
  Message=Type 'MyNonSerializable' is not marked as serializable.
  Source=mscorlib

Is there a way to serialize my class avoiding to serialize my non-serializable class without implement ISerializable interface?

c#
.net
serialization
binary-serialization
asked on Stack Overflow Aug 7, 2019 by Lorenzo Isidori • edited Aug 7, 2019 by Lorenzo Isidori

1 Answer

4

Create backing field and apply the [NonSerialized] attribute to this one:

[Serializable]
public class MySerializable
{
    public string MyProp1 { get; set; }
    public string MyProp2 { get; set; }

    [NonSerialized]
    private IMyNonSerializable _myNonSerializableProp;
    public IMyNonSerializable MyNonSerializableProp
    {
        get { return _myNonSerializableProp; }
        set { _myNonSerializableProp = value; }
    }
}

If you are using C# 7.3 or later, you could use a field-targeted attribute on the auto-generated property without creating a backing field:

[field: NonSerialized]
public IMyNonSerializable MyNonSerializableProp { get; set; }
answered on Stack Overflow Aug 7, 2019 by mm8 • edited Aug 7, 2019 by mm8

User contributions licensed under CC BY-SA 3.0