views:

36

answers:

2

I'm wondering why the IntPtr type is not supported by the XmlSerializer implementation. When I try to serialize a class including a field of IntPtr type, the serialization fails telling me that IntPtr is not supported, and ignore that member.

To workaround this, I translate the IntPtr value to a Int64... but is it a good idea? It should be, as far I can think. In concrete, I need to serialize a window handle, which is typed IntPtr in .NET framework. Am I doing correct?

+2  A: 

The reason that an IntPtr is not serializable is that it generally doesn't make any sense at all when you remove it from it's environment.

If you serialize a window handle, it only makes sense if you deserialize it in the same spot, while the window still exists. If you deserialize it on a different computer, in a different application, or after the window is removed, the handle has no meaning.

So, you can cast it to a type that is serializable, but it's up to you to make sure that it still makes sense when you deserialize it.

Guffa
This argument could be applicable to every information, even a string. For example, a string could specify a shared memory name, and it could be meaningless after serialization. The serialization is able to restore the bit configuration of any object, and it is obvious that an IntPtr has a sequence of bit, that could be serialized as well...
Luca
@Luca: It's of course based on what the data types are intended for, not what they might possibly be (mis)used for.
Guffa
A: 

Think of IntPtr as void*. If you want to do anything useful with it, you have no choice but to cast it to something else.

So yes, casting it to int64 in order to serialize it is perfectly reasonable.

Tergiver