Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I / Should I serialize a constant variable in a C# class?

I am implementing the ISerializable interface for my class.

I have a constant variable in the class like:

public const decimal Cost = 3.2M

When I implement the GetObjectData method, can I / should I serial this variable?

like image 359
Jason Avatar asked Dec 19 '13 15:12

Jason


People also ask

Which variables Cannot be serialized?

In Java, serialization is a concept using which we can write the state of an object into a byte stream so that we can transfer it over the network (using technologies like JPA and RMI). But, static variables belong to class therefore, you cannot serialize static variables in Java.

How do you avoid variables to serialize?

You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows. If possible, make an object that could contain security-sensitive data nonserializable. If the object must be serialized, apply the NonSerialized attribute to specific fields that store sensitive data.

Do static fields get serialized?

static fields aren't serialized.

Why use a constant instead of a variable?

Constants are used when you want to assign a value that doesn't change. This is helpful because if you try to change this, you will receive an error. It is also great for readability of the code. A person who reads your code will now know that this particular value will never change.


3 Answers

When I implement the GetObjectData method, can I / should I serial this variable?

Absolutely not.

Even if you did write it out, it's not like you could change the value of the constant when you read it back in again.

More generally, you shouldn't serialize static fields at all (and const implies static). Anything static is not part of the state of an instance, and it's the data within the instance that you're trying to serialize.

like image 192
Jon Skeet Avatar answered Sep 30 '22 04:09

Jon Skeet


Will it ever change? Presumably not (it can't). Then why would you bother serializing it? You couldn't even deserialize it again if you wanted to, but even if you could, it would always have the same value in it.

like image 28
neminem Avatar answered Sep 30 '22 04:09

neminem


Why should you? The value will never change unless you change your code.

Personally, I only serialize public properties, so constants would not be included.

like image 33
gunr2171 Avatar answered Sep 30 '22 04:09

gunr2171