97

I am looking for an easy way to check if an object in C# is serializable.

As we know you make an object serializable by either implementing the ISerializable interface or by placing the [Serializable] at the top of the class.

What I am looking for is a quick way to check this without having to reflect the class to get it's attributes. The interface would be quick using an is statement.

Using @Flard's suggestion this is the code that I have come up with, scream is there is a better way.

private static bool IsSerializable(T obj)
{
    return ((obj is ISerializable) || (Attribute.IsDefined(typeof (T), typeof (SerializableAttribute))));
}

Or even better just get the type of the object and then use the IsSerializable property on the type:

typeof(T).IsSerializable

Remember though this this seems to only just the class that we are dealing with if the class contains other classes you probably want to check them all or try and serialize and wait for errors as @pb pointed out.

3
  • 1
    Sorry that fails when a field in obj is not serializable, see my sample. Commented Sep 17, 2008 at 10:26
  • I think this is a much better approach: stackoverflow.com/questions/236599/…
    – xero
    Commented Aug 2, 2011 at 19:02
  • The statement "you make an object serializable by either implementing the ISerializable interface or by placing the [Serializable] at the top of the class" is false. For an object to be serializable, its class must declare the SerializableAttribute. Implementing ISerializable only gives you more control over the process.
    – Mishax
    Commented Aug 29, 2013 at 5:39

9 Answers 9

126

You have a lovely property on the Type class called IsSerializable.

3
  • 9
    This will just inform you if an attribute of Serializable is attached to your class.
    – Fatema
    Commented Dec 9, 2010 at 9:58
  • 39
    his point is that members of that object might not be serializable even though the containing type is. right? is it not the case that we must recursively drill into that objects members and check each one, if not just try to serialize it and see if it fails? Commented Jan 26, 2011 at 18:34
  • 4
    For example for a List<SomeDTO> the IsSerializable is true even if SomeDTO is NOT serializable Commented Mar 15, 2017 at 0:30
43

You're going to have to check all types in the graph of objects being serialized for the serializable attribute. The easiest way is to try to serialize the object and catch the exception. (But that's not the cleanest solution). Type.IsSerializable and checking for the serializalbe attribute don't take the graph into account.

Sample

[Serializable]
public class A
{
    public B B = new B();
}

public class B
{
   public string a = "b";
}

[Serializable]
public class C
{
    public D D = new D();
}

[Serializable]
public class D
{
    public string d = "D";
}


class Program
{
    static void Main(string[] args)
    {

        var a = typeof(A);

        var aa = new A();

        Console.WriteLine("A: {0}", a.IsSerializable);  // true (WRONG!)

        var c = typeof(C);

        Console.WriteLine("C: {0}", c.IsSerializable); //true

        var form = new BinaryFormatter();
        // throws
        form.Serialize(new MemoryStream(), aa);
    }
}
2
  • If the cost isn't too great, I think this approach is the best. It can check different serialization requirements (binary, xml). Also, an object might have a generic member that can be swapped with inherited class types that may break serialization and could change at runtime. List(Of baseclass) could have items added of subclassA which is not serializable, where baseclass and subclassB are serializable.
    – VoteCoffee
    Commented May 18, 2020 at 12:09
  • This answer uses cloning to check if the serialization can round-trip. It may be overkill in some cases though were serialization is not expected to set some members: stackoverflow.com/questions/236599/…
    – VoteCoffee
    Commented May 18, 2020 at 12:12
18

This is an old question, that may need to be updated for .NET 3.5+. Type.IsSerializable can actually return false if the class uses the DataContract attribute. Here is a snippet i use, if it stinks, let me know :)

public static bool IsSerializable(this object obj)
{
    Type t = obj.GetType();

     return  Attribute.IsDefined(t, typeof(DataContractAttribute)) || t.IsSerializable || (obj is IXmlSerializable)

}
3
  • 1
    Old question and old answers but this is VERY true! Type.IsSerializable is only a partially-functional solution. In fact, given how many use WCF and DataContracts these days, it's actually a very poor solution!
    – Jaxidian
    Commented Oct 18, 2012 at 16:52
  • What if obj comes in as null?
    – N73k
    Commented Aug 2, 2018 at 2:51
  • @N73k do a null check and return if true?
    – FredM
    Commented Jun 19, 2019 at 10:15
9

Use Type.IsSerializable as others have pointed out.

It's probably not worth attempting to reflect and check if all members in the object graph are serializable.

A member could be declared as a serializable type, but in fact be instantiated as a derived type that is not serializable, as in the following contrived example:

[Serializable]
public class MyClass
{
   public Exception TheException; // serializable
}

public class MyNonSerializableException : Exception
{
...
}

...
MyClass myClass = new MyClass();
myClass.TheException = new MyNonSerializableException();
// myClass now has a non-serializable member

Therefore, even if you determine that a specific instance of your type is serializable, you can't in general be sure this will be true of all instances.

6
Attribute.IsDefined(typeof (YourClass), typeof (SerializableAttribute));

Probably involves reflection underwater, but the most simple way?

0
5

Here's a 3.5 variation that makes it available to all classes using an extension method.

public static bool IsSerializable(this object obj)
{
    if (obj is ISerializable)
        return true;
    return Attribute.IsDefined(obj.GetType(), typeof(SerializableAttribute));
}
2

I took the answer on this question and the answer here and modified it so you get a List of types that aren't serializable. That way you can easily know which ones to mark.

    private static void NonSerializableTypesOfParentType(Type type, List<string> nonSerializableTypes)
    {
        // base case
        if (type.IsValueType || type == typeof(string)) return;

        if (!IsSerializable(type))
            nonSerializableTypes.Add(type.Name);

        foreach (var propertyInfo in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
        {
            if (propertyInfo.PropertyType.IsGenericType)
            {
                foreach (var genericArgument in propertyInfo.PropertyType.GetGenericArguments())
                {
                    if (genericArgument == type) continue; // base case for circularly referenced properties
                    NonSerializableTypesOfParentType(genericArgument, nonSerializableTypes);
                }
            }
            else if (propertyInfo.GetType() != type) // base case for circularly referenced properties
                NonSerializableTypesOfParentType(propertyInfo.PropertyType, nonSerializableTypes);
        }
    }

    private static bool IsSerializable(Type type)
    {
        return (Attribute.IsDefined(type, typeof(SerializableAttribute)));
        //return ((type is ISerializable) || (Attribute.IsDefined(type, typeof(SerializableAttribute))));
    }

And then you call it...

    List<string> nonSerializableTypes = new List<string>();
    NonSerializableTypesOfParentType(aType, nonSerializableTypes);

When it runs, nonSerializableTypes will have the list. There may be a better way of doing this than passing in an empty List to the recursive method. Someone correct me if so.

1

My solution, in VB.NET:

For Objects:

''' <summary>
''' Determines whether an object can be serialized.
''' </summary>
''' <param name="Object">The object.</param>
''' <returns><c>true</c> if object can be serialized; otherwise, <c>false</c>.</returns>
Private Function IsObjectSerializable(ByVal [Object] As Object,
                                      Optional ByVal SerializationFormat As SerializationFormat =
                                                                            SerializationFormat.Xml) As Boolean

    Dim Serializer As Object

    Using fs As New IO.MemoryStream

        Select Case SerializationFormat

            Case Data.SerializationFormat.Binary
                Serializer = New Runtime.Serialization.Formatters.Binary.BinaryFormatter()

            Case Data.SerializationFormat.Xml
                Serializer = New Xml.Serialization.XmlSerializer([Object].GetType)

            Case Else
                Throw New ArgumentException("Invalid SerializationFormat", SerializationFormat)

        End Select

        Try
            Serializer.Serialize(fs, [Object])
            Return True

        Catch ex As InvalidOperationException
            Return False

        End Try

    End Using ' fs As New MemoryStream

End Function

For Types:

''' <summary>
''' Determines whether a Type can be serialized.
''' </summary>
''' <typeparam name="T"></typeparam>
''' <returns><c>true</c> if Type can be serialized; otherwise, <c>false</c>.</returns>
Private Function IsTypeSerializable(Of T)() As Boolean

    Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute))

End Function

''' <summary>
''' Determines whether a Type can be serialized.
''' </summary>
''' <typeparam name="T"></typeparam>
''' <param name="Type">The Type.</param>
''' <returns><c>true</c> if Type can be serialized; otherwise, <c>false</c>.</returns>
Private Function IsTypeSerializable(Of T)(ByVal Type As T) As Boolean

    Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute))

End Function
1
  • 1
    I like this, because as other answerers have noted, the attributes and properties mean nothing. You can stick the ISerializable attribute on any class, Type.IsSerializable is faulty, but most of all: the objects it references might actually be unserializable subclasses. The only way is to try. But I would refine it a bit to TrySerialize function so a succesful Serialization wouldn't need to be done twice.
    – Wolfzoon
    Commented Dec 22, 2020 at 22:53
0

The exception object might be serializable , but using an other exception which is not. This is what I just had with WCF System.ServiceModel.FaultException: FaultException is serializable but ExceptionDetail is not!

So I am using the following:

// Check if the exception is serializable and also the specific ones if generic
var exceptionType = ex.GetType();
var allSerializable = exceptionType.IsSerializable;
if (exceptionType.IsGenericType)
    {
        Type[] typeArguments = exceptionType.GetGenericArguments();
        allSerializable = typeArguments.Aggregate(allSerializable, (current, tParam) => current & tParam.IsSerializable);
    }
 if (!allSerializable)
    {
        // Create a new Exception for not serializable exceptions!
        ex = new Exception(ex.Message);
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.