Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforcing serializable from an interface without forcing classes to custom serialize in C#

I have an interface that defines some methods I would like certain classes to implement.

public interface IMyInterface
{
    MethodA;
    MethodB;
}

Additionally I would like all classes implementing this interface to be serializable. If I change the interface definition to implement ISerializable as below...:

public interface IMyInterface : ISerializable
{
    MethodA;
    MethodB;
}

...all classes must now explicitly implement serialization as far as I am aware, since if you implement ISerializable you must implement the GetObjectData member (and the necessary constructor to deserialize).

How can I insist classes using my interface be serializable, but without forcing them to custom implement serialization?

Thanks, Will

like image 773
WillH Avatar asked Dec 11 '08 17:12

WillH


People also ask

What is custom serialization?

Custom serialization is the process of controlling the serialization and deserialization of a type.

Why serializing?

Serialization allows the developer to save the state of an object and re-create it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions such as: Sending the object to a remote application by using a web service.

When we should use serialization?

Usually used in Hibernate, JMS, JPA, and EJB, serialization in Java helps transport the code from one JVM to another and then de-serialize it there. Deserialization is the exact opposite process of serialization where the byte data type stream is converted back to an object in the memory.

What is serializable interface in Java?

Serializable is a marker interface (has no data member and method). It is used to "mark" Java classes so that the objects of these classes may get a certain capability. The Cloneable and Remote are also marker interfaces. The Serializable interface must be implemented by the class whose object needs to be persisted.


1 Answers

There does not seem to be a way to do this, but I wish there were.

Note two things though:

  • The Serializable attribute can not be inherited from a base class, even if the base class is marked as abstract.

  • You don't technically need the Serializable attribute, IF you are using an XmlSerializer because it does not make use of object graphs.

like image 173
Thrash505 Avatar answered Nov 08 '22 18:11

Thrash505