How to ignore a Serialization?

Asked

Viewed 213 times

1

I’m having trouble serializing a Socket class with BinaryFormatter, tried to use the attribute NonSerializedAttribute, but it just doesn’t work for this kind of property below.

[SerializableAttribute]
public class Connection
{
    [NonSerializedAttribute]
    public Socket Socket { get; set; }
}

I am Serializing this class in the method parameter below:

public static byte[] Serialize(object anySerializableObject)
{
     using (var memoryStream = new System.IO.MemoryStream())
     {
         (new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()).Serialize(memoryStream, anySerializableObject);
         return memoryStream.ToArray();
     }
}

If I do not ignore the serialization of the Socket class, it will give this error:

The type 'System.Net.Sockets.Socket' in the Assembly 'System, Version=4.0.0.0, Culture=neutral, Publickeytoken=b77a5c561934e089' is not marked as serializable.

What do I do to fix this problem?

  • @ramaral, you’re right. Both attributes do not work with BinaryFormatter. My answer was wrong, I erased it.

1 answer

4


That attribute cannot be applied in properties.

To apply you will need to turn the auto property into one with backing field and apply the attribute to backing field.

[NonSerialized]
private Socket socket;

public Socket Socket 
{
    get 
    {
        return socket;
    }  
    set 
    { 
        socket = value; 
    }
}

C# 7.0

[NonSerialized]
private Socket socket;

public Socket Socket 
{
    get => socket;
    set => socket = value; 
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.