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

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

<p>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 <em>is</em> statement.</p>

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

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

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

<pre><code>typeof(T).IsSerializable
</code></pre>

<p>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.</p>

[{'answer_id': 81705, 'author': 'Grad van Horck', 'author_id': 12569, 'author_profile': 'https://Stackoverflow.com/users/12569', 'pm_score': 3, 'selected': False, 'text': '<pre><code>Attribute.IsDefined(typeof (YourClass), typeof (SerializableAttribute));\n</code></pre>\n\n<p>Probably involves reflection underwater, but the most simple way?</p>\n'}, {'answer_id': 81718, 'author': 'Paul van Brenk', 'author_id': 1837197, 'author_profile': 'https://Stackoverflow.com/users/1837197', 'pm_score': 5, 'selected': False, 'text': '<p>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.</p>\n\n<p><em>Sample</em></p>\n\n<pre><code>[Serializable]\npublic class A\n{\n    public B B = new B();\n}\n\npublic class B\n{\n   public string a = "b";\n}\n\n[Serializable]\npublic class C\n{\n    public D D = new D();\n}\n\n[Serializable]\npublic class D\n{\n    public string d = "D";\n}\n\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n\n        var a = typeof(A);\n\n        var aa = new A();\n\n        Console.WriteLine("A: {0}", a.IsSerializable);  // true (WRONG!)\n\n        var c = typeof(C);\n\n        Console.WriteLine("C: {0}", c.IsSerializable); //true\n\n        var form = new BinaryFormatter();\n        // throws\n        form.Serialize(new MemoryStream(), aa);\n    }\n}\n</code></pre>\n'}, {'answer_id': 81762, 'author': 'leppie', 'author_id': 15541, 'author_profile': 'https://Stackoverflow.com/users/15541', 'pm_score': 8, 'selected': True, 'text': '<p>You have a lovely property on the <code>Type</code> class called <code>IsSerializable</code>.</p>\n'}, {'answer_id': 81833, 'author': 'Michael Meadows', 'author_id': 7643, 'author_profile': 'https://Stackoverflow.com/users/7643', 'pm_score': 3, 'selected': False, 'text': "<p>Here's a 3.5 variation that makes it available to all classes using an extension method.</p>\n\n<pre><code>public static bool IsSerializable(this object obj)\n{\n    if (obj is ISerializable)\n        return true;\n    return Attribute.IsDefined(obj.GetType(), typeof(SerializableAttribute));\n}\n</code></pre>\n"}, {'answer_id': 82260, 'author': 'Joe', 'author_id': 13087, 'author_profile': 'https://Stackoverflow.com/users/13087', 'pm_score': 3, 'selected': False, 'text': "<p>Use Type.IsSerializable as others have pointed out.</p>\n\n<p>It's probably not worth attempting to reflect and check if all members in the object graph are serializable.  </p>\n\n<p>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:</p>\n\n<pre><code>[Serializable]\npublic class MyClass\n{\n   public Exception TheException; // serializable\n}\n\npublic class MyNonSerializableException : Exception\n{\n...\n}\n\n...\nMyClass myClass = new MyClass();\nmyClass.TheException = new MyNonSerializableException();\n// myClass now has a non-serializable member\n</code></pre>\n\n<p>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.</p>\n"}, {'answer_id': 4037838, 'author': 'Mike_G', 'author_id': 52051, 'author_profile': 'https://Stackoverflow.com/users/52051', 'pm_score': 4, 'selected': False, 'text': '<p>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 :)</p>\n\n<pre><code>public static bool IsSerializable(this object obj)\n{\n    Type t = obj.GetType();\n\n     return  Attribute.IsDefined(t, typeof(DataContractAttribute)) || t.IsSerializable || (obj is IXmlSerializable)\n\n}\n</code></pre>\n'}, {'answer_id': 5913032, 'author': 'Eric', 'author_id': 741895, 'author_profile': 'https://Stackoverflow.com/users/741895', 'pm_score': 0, 'selected': False, 'text': '<p>The exception object might be serializable , but using an other exception which is not.\nThis is what I just had with WCF System.ServiceModel.FaultException: FaultException is serializable but ExceptionDetail is not!</p>\n\n<p>So I am using the following:</p>\n\n<pre><code>// Check if the exception is serializable and also the specific ones if generic\nvar exceptionType = ex.GetType();\nvar allSerializable = exceptionType.IsSerializable;\nif (exceptionType.IsGenericType)\n    {\n        Type[] typeArguments = exceptionType.GetGenericArguments();\n        allSerializable = typeArguments.Aggregate(allSerializable, (current, tParam) =&gt; current &amp; tParam.IsSerializable);\n    }\n if (!allSerializable)\n    {\n        // Create a new Exception for not serializable exceptions!\n        ex = new Exception(ex.Message);\n    }\n</code></pre>\n'}, {'answer_id': 13054478, 'author': 'sewershingle', 'author_id': 496047, 'author_profile': 'https://Stackoverflow.com/users/496047', 'pm_score': 2, 'selected': False, 'text': '<p>I took the answer on this question and the answer <a href="https://stackoverflow.com/questions/236599/how-to-unit-test-if-my-object-is-really-serializable/236698#236698">here</a> and modified it so you get a List of types that aren\'t serializable. That way you can easily know which ones to mark.</p>\n\n<pre><code>    private static void NonSerializableTypesOfParentType(Type type, List&lt;string&gt; nonSerializableTypes)\n    {\n        // base case\n        if (type.IsValueType || type == typeof(string)) return;\n\n        if (!IsSerializable(type))\n            nonSerializableTypes.Add(type.Name);\n\n        foreach (var propertyInfo in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))\n        {\n            if (propertyInfo.PropertyType.IsGenericType)\n            {\n                foreach (var genericArgument in propertyInfo.PropertyType.GetGenericArguments())\n                {\n                    if (genericArgument == type) continue; // base case for circularly referenced properties\n                    NonSerializableTypesOfParentType(genericArgument, nonSerializableTypes);\n                }\n            }\n            else if (propertyInfo.GetType() != type) // base case for circularly referenced properties\n                NonSerializableTypesOfParentType(propertyInfo.PropertyType, nonSerializableTypes);\n        }\n    }\n\n    private static bool IsSerializable(Type type)\n    {\n        return (Attribute.IsDefined(type, typeof(SerializableAttribute)));\n        //return ((type is ISerializable) || (Attribute.IsDefined(type, typeof(SerializableAttribute))));\n    }\n</code></pre>\n\n<p>And then you call it...</p>\n\n<pre><code>    List&lt;string&gt; nonSerializableTypes = new List&lt;string&gt;();\n    NonSerializableTypesOfParentType(aType, nonSerializableTypes);\n</code></pre>\n\n<p>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.</p>\n'}, {'answer_id': 25096555, 'author': 'ElektroStudios', 'author_id': 1248295, 'author_profile': 'https://Stackoverflow.com/users/1248295', 'pm_score': 1, 'selected': False, 'text': '<p>My solution, in VB.NET:</p>\n\n<p>For Objects:</p>\n\n<pre><code>\'\'\' &lt;summary&gt;\n\'\'\' Determines whether an object can be serialized.\n\'\'\' &lt;/summary&gt;\n\'\'\' &lt;param name="Object"&gt;The object.&lt;/param&gt;\n\'\'\' &lt;returns&gt;&lt;c&gt;true&lt;/c&gt; if object can be serialized; otherwise, &lt;c&gt;false&lt;/c&gt;.&lt;/returns&gt;\nPrivate Function IsObjectSerializable(ByVal [Object] As Object,\n                                      Optional ByVal SerializationFormat As SerializationFormat =\n                                                                            SerializationFormat.Xml) As Boolean\n\n    Dim Serializer As Object\n\n    Using fs As New IO.MemoryStream\n\n        Select Case SerializationFormat\n\n            Case Data.SerializationFormat.Binary\n                Serializer = New Runtime.Serialization.Formatters.Binary.BinaryFormatter()\n\n            Case Data.SerializationFormat.Xml\n                Serializer = New Xml.Serialization.XmlSerializer([Object].GetType)\n\n            Case Else\n                Throw New ArgumentException("Invalid SerializationFormat", SerializationFormat)\n\n        End Select\n\n        Try\n            Serializer.Serialize(fs, [Object])\n            Return True\n\n        Catch ex As InvalidOperationException\n            Return False\n\n        End Try\n\n    End Using \' fs As New MemoryStream\n\nEnd Function\n</code></pre>\n\n<p>For Types:</p>\n\n<pre><code>\'\'\' &lt;summary&gt;\n\'\'\' Determines whether a Type can be serialized.\n\'\'\' &lt;/summary&gt;\n\'\'\' &lt;typeparam name="T"&gt;&lt;/typeparam&gt;\n\'\'\' &lt;returns&gt;&lt;c&gt;true&lt;/c&gt; if Type can be serialized; otherwise, &lt;c&gt;false&lt;/c&gt;.&lt;/returns&gt;\nPrivate Function IsTypeSerializable(Of T)() As Boolean\n\n    Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute))\n\nEnd Function\n\n\'\'\' &lt;summary&gt;\n\'\'\' Determines whether a Type can be serialized.\n\'\'\' &lt;/summary&gt;\n\'\'\' &lt;typeparam name="T"&gt;&lt;/typeparam&gt;\n\'\'\' &lt;param name="Type"&gt;The Type.&lt;/param&gt;\n\'\'\' &lt;returns&gt;&lt;c&gt;true&lt;/c&gt; if Type can be serialized; otherwise, &lt;c&gt;false&lt;/c&gt;.&lt;/returns&gt;\nPrivate Function IsTypeSerializable(Of T)(ByVal Type As T) As Boolean\n\n    Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute))\n\nEnd Function\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/81674', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/231/']