Reputation:
I'm looping through the Session keys and adding entries and their values to a Hashtable, which I'm then serializing. The problem I'm having is there is an object on the Session that is not serializable, and it shouldn't be serialized anyway. I'm looking around, and plenty of built-in types don't implement the ISerializable attribute, so testing for that doesn't work:
if (val is ISerializable)
{
...
}
So, how do I test for this? Does this make sense?
Upvotes: 2
Views: 495
Reputation: 2330
You can use the IsSerializable property of the Type class.
if(val.GetType().IsSerializable)
Upvotes: 0
Reputation: 755457
There is only one guaranteed way to determine if an object is serializable. Serialize it and see if the operation succeeds.
I know that seems a bit overkill but there are just so many different ways that serialization can be broken. There are two items in Metadata you can check to see if a type claims serializability (ISerializable and [Serializable]) but this is just a claim. It can and is broken in so many different ways.
The problem is that in the .Net world the act of declaring the ability to be serialized and actually serializing are 2 separate distinct actions. It's perfectly possible (and legal) to do one but not the other. Take this for example
[Serializable]
public class Foo {
public Object Field1;
}
This class claims to be serializable and may very well be. It all depends on the value actually stored in Field1. No amount of metadata inspection on the type will every tell you whether it can actually be serialized. All you can do is try and see if it suceeds.
Upvotes: 10
Reputation: 15633
Check the same thing that CRL would use: the [Serializable]
attribute.
Upvotes: -1