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?
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.
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.
static fields aren't serialized.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With