Serializing Custom Exceptions

J

jehugaleahsa

Hello:

I am implementing a custom exception class and it exposes an interface
property. I want the property to be reinitialized when deserializing.

This is what my constructor and my GetObjectData look like:

protected CustomException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{
_custom = (ICustom)info.GetValue("Custom", typeof
(ICustom));
}

[SecurityPermission(SecurityAction.LinkDemand,
Flags=SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData(SerializationInfo info,
StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("Custom", _custom, typeof(ICustom));
}

ICustom is the interface I am exposing with a read-only property. The
concrete class is serializable:

public ICustom Custom
{
get
{
return _custom;
}
}

I want to make sure that no matter who is deserializing my exception
they will not lose this property. Can the deserializer detect the
actual type? can it create it? I see in the same process this works
fine. But what about across processes or a network?

First, will this work? Second, could someone explain to me how it
knows how to deserialize it into the correct type? Third, is there a
best practice for this kind of thing?

Thanks for any insight!
 
N

Nicholas Paldino [.NET/C# MVP]

It should work, but instead of passing typeof(ICustom) as the last
parameter to the AddValue method, pass:

_custom.GetType();

This way, the actual type will be stored in the stream, not the
interface type. When you get it back, it will be able to be cast to
ICustom.

As for it working cross-process, it should, assuming that the assembly
containing the type is loaded in the other app-domain (this is the boundary
you are concerned about btw, not the process boundary), it should work fine.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top