6

I've seen couple of examples with serializable attribute like this:

[Serializable()]
            public class sampleClass
            {
                public int Property1{ get; set; }
                public string Proerty2{ get; set; }

                public sampleClass() { }
                public sampleClass(int pr1, int pr2)
                {
                    pr1 = pr1;
                    Name = pr2.ToString();
                }
            }

I never had a good grasp on understanding of how this works, but from msdn:

Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.

But the problem is that in my code example I see no use for it. Just an object that is used to retrieve data from the database, nothing special. What are some other uses on when to use and when not to use serialization. For example, should I always use serializzation because it is more secure? is it goin to be slower this way?

Update: Thanks for all nice answers

user194076
  • 8,787
  • 23
  • 94
  • 154
  • Is it possible it is being stored in SessionState when using Out-of-Proc / SQL? Those session modes require serialization. – vcsjones Jun 08 '12 at 19:43
  • Not sure I'm following your question. Are you actually asking "why would I ever want to serialize an object?" – Kirk Woll Jun 08 '12 at 19:44
  • 1
    http://en.wikipedia.org/wiki/Serialization – L.B Jun 08 '12 at 19:47
  • @vcsjones, if I remove serializable attribute from a class nothing's changing. still compiles and run fine. – user194076 Jun 08 '12 at 19:49
  • 1
    @user194076 But you can't serialize it. If you don't want to do that, fine. Your question seems pointless to me. You use it when you want to do what it does: no different from any other feature. Of anything. – user207421 Jun 08 '12 at 21:54

5 Answers5

6

Serialization is useful any time you want to move a representation of your data into or out of your process boundary.

Saving an object to disk is a trivial example you'll see in many tutorials.

More commonly, serialization is used to transfer data to and from a web service, or to persist data to or from a database.

Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • Why save an object to a disk then? – user194076 Jun 08 '12 at 19:47
  • One example: To save user configuration (represented in the application by an object) for an application that does not use a database backend. – Eric J. Jun 08 '12 at 19:48
  • 3
    @user194076: For example you can implement a game's save feature with this method, by saving the state of the game objects at a time instant and then rebuilding them when the game is loaded. – Tudor Jun 08 '12 at 19:48
  • @Tudor, Well, this is an asp.net application. I can store the same info in the viewstate or cookies, or whatever. correct. The same thing? – user194076 Jun 08 '12 at 19:51
  • @user194076: Ok, are you asking for examples where serialization is useful in general or in your particular application? – Tudor Jun 08 '12 at 19:51
  • Storing data in the viewstate is an example of serialization (in the generic computer science meaning), though I do not believe that you need to use the [Serializable] attribute at any point for that. However, if you want to place an object in Session, I do believe it must be serializable by the default serializer for your application http://stackoverflow.com/questions/743441/session-state-serialization – Eric J. Jun 08 '12 at 19:54
  • @EricJ., Thanks Eric.So,from what I udnerstood, we can name different types of serialization "a converter". Object to binary, object to xml, etc. – user194076 Jun 08 '12 at 20:01
  • 4
    @user194076 yes, that is exactly what a serializer is. – Marc Gravell Jun 08 '12 at 20:05
  • @user194076 viewstate maybe used for store serialization but cookie, naah, you are storing it wrong, use WebStorage for these things. – Anirudha Gupta Sep 22 '18 at 10:25
  • Hi, all. I have a question for the serialization. I use [EF Core](https://learn.microsoft.com/en-us/ef/core/saving/basic). Since The data will be inserted in the database when calling `SaveChanges`. I don't see any process of serialization. So how to explain it?@EricJ. – Bigeyes Jan 19 '23 at 14:38
5

Several answers have covered the reasons of why you might want to use serialization in general. You seem to also want to know why a specific class has attribute [Serializable] and you are wondering why that may have been done.

With ASP.NET the default Session state storage is InProc which allows you to store any object as a reference and leave it on the heap. This is the best performing way to store session state, however, it only works if you are using a single worker thread or if all your session state could be rebuilt automatically if the worker thread were to change (unlikely). For the other state storage modes (StateServer and SQL Server) all the session state objects must be serializable as the ASP.NET engine will first serialize these objects using binary serialization before sending them to the storage medium.

In your case, you may be using InProc. One reason though to still mark all classes that are used in session state as Serializable and test them that way is that you may have a need to change this in the future (for example, to use a Web Farm). If you do not design your session state classes with this in mind it will be quite difficult to do the migration in the future.

Also, just because you can remove the Serializable attribute and the program "works" in one environment does not mean that it will work in another environment. For example, it may work fine for you under Visual Studio test web server (which always uses InProc session state mode) instance and even in a development IIS instance but then, perhaps a production IIS instance is setup to use a different storage mode.

These environmental/configuration differences are not necessarily limited to ASP.NET applications. There are other application engines that may do this or even standalone applications that do (it is not difficult to build this kind of configurable environment).

Finally, you may be working with a library which may be consumed by different applications. Some may need to store state in a serializable manner and others may not.

Because of these factors it is often a very good idea, at least when building a library, to consider marking simple value classes or state management classes with [Serializable]. Keep in mind that this increases the work for testing these classes and there are limits to what can be serialized (i.e. a class that contains a socket reference or open file reference may not be a good candidate for serialization as open external resources cannot be serialized) so do not overuse this.

You asked if using [Serializable] will be slower. No, it will not be. This attribute has no direct affect on performance. However, if the application environment is changed to serialize the object, then yes, performance will be affected. It is the act of serializing and deserializing that is slower than just storing the object on the heap. [Note that some routines could be written to look for the Serializable attribute and then choose to serialize but this is rare; usually it is like ASP.NET and left up to an administrator or user to decide if they want to change the store medium.]

Kevin Brock
  • 8,874
  • 1
  • 33
  • 37
3

The MSDN quote you provide explains when serialization is useful: for transporting or storing data. Writing to a file is serialization, and serialization is required t send an object over a network.

If you are just populating the object in a single application, perhaps from a database, then indeed: serialization is not a concern at all. Imaging a class for serialization has no impact on security or performance: if you don't need it, don't worry about it.

Note also that [Serializable] mainly relates to BinaryFormatter, but there are actually many more serializers than that. For example: you might want to expose your object via JSON or XML - both of those require serialization, but neither requires [Serializable].

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Isn't populating the object from the database just another form of serialization? Whether you use an automatic serializer like DataContractSerializer or move fields to and from a database by hand, you're still serializing...? – Eric J. Jun 08 '12 at 19:52
  • 2
    @Eric it is a form of *persistence* / *materialization*, yes, but I wouldn't personally call that serialization/deserialization. I don't think a RDBMS fits the usual definition of serialization, although it is not uncommon to serialize an object and then store that as a BLOB in either a RDBMS or NoSQL store. – Marc Gravell Jun 08 '12 at 19:54
  • Semantics, I suppose. The Wikipedia article does not make that distinction, and indeed one could implement something that implements ISerializable that stores data in a database. – Eric J. Jun 08 '12 at 19:58
  • 1
    @Eric it (the wiki article) does try to be clear that it is referring to a file, buffer or socket :p implementing ISerializable and not writing to the stream provided would be: a broken serialization. – Marc Gravell Jun 08 '12 at 20:03
  • I assumed (wrongly) that ISerializable is used for serialization generally. Found your related answer and learned something new today http://stackoverflow.com/questions/810974/what-is-the-point-of-the-iserializable-interface – Eric J. Jun 08 '12 at 20:15
  • 1
    @Eric indeed, I've spent obscene amounts of time writing serialization code :p if it helps, I also have a database materialization library amongst my pet projects, so I'm pretty happy in my understanding of the difference between the two. – Marc Gravell Jun 08 '12 at 20:18
  • @Marc, ha ha. Calling (the super-awesome) Dapper-dot-net a "pet" project is a nice touch. ;) – Kirk Woll Jun 09 '12 at 02:36
0

Simple example: Imagine you have a custom shape to store application settings.

namespace My.Namespace
{
    [Serializable]
    public class Settings
    {
        public string Setting1 { get; set; }

        public string Setting2 { get; set; }
    }
}

You could then have a file an xml file as such:

<?xml version="1.0" encoding="utf-8" ?>
<Settings>
  <Setting1>Foo</Setting1>
  <Setting2>Bar</Setting2>
</Settings>

Using XmlSerializer you could simply serialize and deserialize your settings.

It is also necessary for your shape to be Serializable if you wish to stuff it into ASP.NET ViewState

These are very basic examples but demonstrate it's usefulness

0

What are some other uses on when to use and when not to use serialization.

Let me give you one practical example. In one of my application, I was given XML schemas (XSD files) for request and response XML files. I need to parse the request XML file, process and save the information back into several tables. Later I need to prepare response XML file accordingly and send it back to our client.

I used Xsd2Code to generate C# classes based on the schema. So parsing the request XML file is simply deserializing it to the generated request class object. Then I can access properties from the object the way it appears in request XML file. While generating response XML file is simply serializing from the generated response class object which I populate in my code. This way I can work with C# objects rather than XML files. I hope it makes sense.

For example, should I always use serializzation because it is more secure

I don't think this is related to security in any way.

Anil Vangari
  • 570
  • 7
  • 12