Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a difference between [Serializable] and [Serializable()] in c#?

I've bumped into examples using either of both notations. I can't find anything about it what tells which one is the common one, why 2 notations are allowed, and if there is actually any subtle difference between the two.

anyone an idea?

like image 808
Toad Avatar asked Nov 20 '09 14:11

Toad


People also ask

What does serializable mean in C#?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed.

What does serializable attribute do?

When you apply the SerializableAttribute attribute to a type, all private and public fields are serialized by default. You can control serialization more granularly by implementing the ISerializable interface to override the serialization process.

Why do we need serialization in C#?

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.

How do you mark a class as serializable?

The easiest way to make a class serializable is to mark it with the SerializableAttribute as follows. The following code example shows how an instance of this class can be serialized to a file. MyObject obj = new MyObject(); obj. n1 = 1; obj.


3 Answers

Nope, no functional difference.

Why the 2 different styles, you ask? The first notation is allowed for brevity. The 2nd notation is allowed because some attributes take parameters:

[Category("Foobar related methods.")]
public void Foo()
{
}

Also note that [Serializable] is really just short-hand for [SerializableAttribute()] - C# lets you omit the Attribute suffix as well as the empty constructor parens.

like image 185
Judah Gabriel Himango Avatar answered Oct 22 '22 16:10

Judah Gabriel Himango


No, there is no difference. [Serializable] is just syntactic sugar for [Serializable()] because the C# syntax lets you miss out the constructor brackets if there is a default attribute constructor.

Note that both are really syntactic sugar for [SerializableAttribute()] as attribute declarations also let you miss the Attribute suffix.

like image 30
Greg Beech Avatar answered Oct 22 '22 17:10

Greg Beech


both uses the default c'tor, there is no difference at all.

like image 6
DxCK Avatar answered Oct 22 '22 17:10

DxCK