Alexandre Bell
Alexandre Bell

Reputation: 3241

How to identify types with the serialization attribute?

I need to define a method parameter that should ideally only accept object arguments that have been decorated with the Serializable attribute. The method task is to persist the object argument into a XML document.

I understand I can eventually check for SerializationException, but i'd rather be able to neatly define this as a part of the method contract. So, is there any way I can isolate types that have been decorated with this attribute?

Upvotes: 2

Views: 157

Answers (3)

aligray
aligray

Reputation: 2832

One option is to use the IsSerializable property of the Type class:

public void Serialize(object obj)
{
    if (obj.GetType().IsSerializable)
    {
        // do work
    }
}

Upvotes: 5

Reddog
Reddog

Reputation: 15579

You can use the GetCustomAttributes function on the type of the object.

    public void Serialize(object itemToSerialize)
    {
        var hasAttribute = itemToSerialize.GetType().GetCustomAttributes(typeof(SerializableAttribute), true).Any();

        // Do stuff.
    }

However, don't forget that normal serialization supports ISerializable too. So therefore, the IsSerializable property on the type is probably more appropriate.

Edit I think you are after a manner to have the compiler enforce the parameter have the attribute. There is no way to do this. You would have to use a runtime check as above and throw an exception.

Generics would typically be your friend for this type of task, and in this case, you could use a generic parameter where the type implements ISerializable, but as you are aware that would exclude cases where serialization is declared rather than implemented.

Upvotes: 2

Frank Boyne
Frank Boyne

Reputation: 4570

If you could further restrict things so that only objects that implement ISerializable are allowed then you could use generics to get compile-time checking

public void Serialize<T>(T obj) where T : ISerializable
{
    // Do work
}

Unfortunately this doesn't count as an answer to your question because not every Serializable class implements ISerializable

Upvotes: 0

Related Questions