views:

219

answers:

3

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?

A: 

Check the same thing that CRL would use: the [Serializable] attribute.

Michael Damatov
Doesn't work. You can have that attribute and still fail at being serialized
JaredPar
Sure, successful serialization does not guarantee any success at the next time.
Michael Damatov
+10  A: 

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.

JaredPar
Serializing it sounds like a overkill. Some poeople use serialization for cloning purposes :-) ... Anyway, successful serialization does not guarantee any success at the next time.
Michael Damatov
@Toro, nope it doesn't. It only tells you if the object at the point of serialization was serializable. I don't think it's overkill though because no other way you try is guaranteed to work.
JaredPar
I would use [Serializable] and then handle an exception if it fails. You pretty much have to do that anyway. At least if it's not flagged as serializable you can avoid having to try.
Jon B
A: 

You can use the IsSerializable property of the Type class.

if(val.GetType().IsSerializable)
Jorge Villuendas
Doesn't work. I can claim to be serializable but fail at serialization.
JaredPar
And it apparently only check [Serializable] and not :ISerializable
Henk Holterman