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?
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; }
User contributions licensed under CC BY-SA 3.0