Amir
Amir

Reputation: 2416

How to check if the field in the class is serializable?

I am working on my own implementation of JSON serializer and I need to get all serializable fields of the class.

For example, I have class like this:

[Serializable]
class TestClass
{
    public int i;
    public string s;

    [NonSerialized]
    public string ignore;
}

So I don't want to serialize ignore. In this code I try to print all serializable fields:

foreach (FieldInfo field in typeof(TestClass).GetFields())
{
    if (field.FieldType.IsSerializable) 
    {
        Console.WriteLine (field.Name);
    }
}

Eventually ignore is printed as well as others. What am I doing wrong?

Upvotes: 0

Views: 1372

Answers (1)

vcsjones
vcsjones

Reputation: 141638

FieldType.IsSerializable checks if the type of the field is serializable, not the field itself. Instead, use IsNotSerialized off of the FieldInfo:

if (!field.IsNotSerialized)
{
    Console.WriteLine(field.Name);
}

It's worth pointing out that the NonSerialized attribute gets special treatment by the compiler. Unlike most attributes, this ones does not actually get emitted into CIL, rather it is a flag on the field, so checking for the existence of the attribute may not work. Instead, it is appropriate to check the field's flag directly.

Upvotes: 1

Related Questions