Serialization of enum with NetDataContractSerializer

400 Views Asked by At

I have the following:

[Serializable]
public class SimulationException : Exception
{
    public SimulationExceptionStatusCode StatusCode { get; set; }

    public SimulationException()
    { }

    public SimulationException(string msg) : base(msg)
    { }

    protected SimulationException(SerializationInfo info, StreamingContext context)
        : base(info, context)
    { }
}

[Serializable]
public enum SimulationExceptionStatusCode
{
    SimulationInstanceNotExist,
    LocationNotExist,
    InvalidOperation,
    GeneralError
}

and I am using the following to convert between fault and exceptions in client-server wcf: Converting Fault to exceptions

The thing is that when I am converting the exception to fault with this:

// converting to error to falut message Fault
MessageFault messageFault = MessageFault.CreateFault(
                new FaultCode("Sender"),
                new FaultReason(error.Message),
                error,
                new NetDataContractSerializer());
fault = Message.CreateMessage(version, messageFault, null);

the enum is not being serializied and when I am deserializing I get the default value for the enum.

What am I missing?

2

There are 2 best solutions below

1
Petar Vučetin On

Decorate it with EnumMemeber like so

[DataContract(Name = "SimulationExceptionStatusCode")]
public enum SimulationExceptionStatusCode
{
    [EnumMember]
    SimulationInstanceNotExist,
    [EnumMember]
    LocationNotExist,
    [EnumMember]
    InvalidOperation,
    [EnumMember]
    GeneralError
}
3
ilansch On

I had the same problem.
I did a simple work-around that might be good for you, when sending the enum, cast to int/string, send the int/string (in the data contract - i passed it in WCF), and then on service, cast the int/string to your enum.

When casting back to enum, use

Enum.Parse(..)