0
votes

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?

1
Put the [NonSerialized] above your public IMyNonSerializable MyNonSerializableProp? - CodeCaster
[NonSerialized] can be applied on field only. - Lorenzo Isidori
Why do you state this: "It has a property that I cannot mark [NonSerialized] because it is not serializable at all."? - mororo
@moro91 edited my question, it was a little bit confused. Thanks. - Lorenzo Isidori
@LorenzoIsidori a: it is not supported in .NET Core (and even when it works, has huge problems because of assembly movements), severely limiting your path forward, b: it is a known security hole, c: it is incredibly brittle re versioning - it will hurt you as you move forward: the only questions are 1) when and 2) how badly - Marc Gravell

1 Answers

4
votes

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; }