Make sure the parameter is serializable?

Ok, let me see if I can make this as concise as possible. I am going to pass an object an unknown type to a method that will internally use BinaryFormatter to serialize the data that it passed (I chose this because I have no idea what data is such an abstract mechanism that I could imagine). And suppose this method looks like it is currently :

 public void ProvideData(Guid providerKey, ISerializable data, string dataType)... 

Now let me suppose that I need to make sure that what is passed to me can actually be serialized, and therefore why I thought that I would need an object to implement ISerializable . However, one problem with this model is that I cannot even pass the string value, because eventhough a string is [Serializable] does not implement ISerializable .

So, what is the right way to structure this method to ensure that the value passed to me, simple or complex, is serializable?

+7
source share
1 answer

You can check using the IsSerializable property on Type .

For example:

 bool canSerialize = myParameter.GetType().IsSerializable; 

EDIT BY OP: Final Implemented Method

Below is the final implementation due to this answer (very good answer). This is just a prototype, so why there is not much in the method, but it proves the answer. It should be noted that checking for the presence of the ISerializable interface ISerializable not matter, because you will not know until you try and serialize the object, regardless of whether it has ISerializable , so I moved the wrong way.

Thanks!

 public void ProvideData(Guid providerKey, object data, string dataType) { if (!data.GetType().IsSerializable) { throw new ArgumentException("The data passed is not serializable and therefore is not valid.", "data"); } var formatter = new BinaryFormatter(); using (var fileStream = new FileStream("data.dat", FileMode.Create)) { formatter.Serialize(fileStream, data); fileStream.Close(); } } 
+11
source

All Articles