Can my class be serialized?

A common question asked is how do you determine if a class can be serialized? My answer is - serialize the class and then determine.

A common misconception is that if the class has the [Serializable] attribute, it can be serialized. This may or may not be the case. If any one of the fields in the class cannot be serialized, the serialization of the class fails.

If you would like to programmatically determine if a class can probably be serialized, use the following code. The code determines if the class Employee can be serialized or not:


        Employee emp = new Employee();

        if (emp.GetType().IsSerializable)


            Response.Write(emp.GetType().ToString() + " can probably be serialized");




            Response.Write(emp.GetType().ToString() + " cannot be serialized");



Dim emp As New Employee()

If emp.GetType().IsSerializable Then

    Response.Write(emp.GetType().ToString() & " can probably be serialized")


    Response.Write(emp.GetType().ToString() & " cannot be serialized")

End If

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: