Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NonSerialized attribute creating error

I am trying to serialize an object that has a nested class. I have tagged the nested class with the [NonSerialized] attribute but I receive an error:

Attribute 'NonSerialized' is not valid on this declaration type. It is only valid on 'field' declarations.

How do I omit the nested class from serialization?

I have included some code that may show what I am trying to do. Thanks for any help.

[Serializable]
public class A_Class
{
    public String text { get; set; }

    public int number { get; set; }
}

[Serializable]
public class B_Class
{
    [NonSerialized]
    public A_Class A { get; set; }

    public int ID { get; set; }
}

public  byte[] ObjectToByteArray(object _Object)
{
    using (var stream = new MemoryStream())
    {
        var formatter = new BinaryFormatter();
        formatter.Serialize(stream, _Object);
        return stream.ToArray();
    }
}

void Main()
{
    Class_B obj = new Class_B()

    byte[] data = ObjectToByteArray(obj);
}
like image 774
Brad Avatar asked Mar 29 '11 15:03

Brad


People also ask

What is NonSerialized in C#?

The NonSerialized attribute marks a variable to not be serialized.

What does non serialized mean?

Serialized inventory models have individual serial units, each of which have their own unique barcode. Non-serialized inventory models do not have individually barcoded units. Detailed examples of both serialized and non-serialized models are shown below.

What is serializable attribute in C#?

This attribute is used in the class definition to indicate that a class can be serialized. By default, all fields in the class are serialized except for the fields that are marked with a NonSerializedAttribute . It is not necessary to use this attribute if a given type implements the System.

What is serialization and Deserialization in C#?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.


2 Answers

The error tells you everything you need to know: NonSerialized can only be applied to fields, but you are trying to apply it to a property, albeit an auto-property.

The only real option you have is to not use an auto property for that field as noted in this StackOverflow question.

like image 65
DocMax Avatar answered Oct 20 '22 09:10

DocMax


Also consider XmlIgnore attribute on the property:

http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributes.xmlignore.aspx

IIRC, properties are ignored automatically for binary serialization.

like image 21
Aeonymous Avatar answered Oct 20 '22 09:10

Aeonymous