I want to serialize my enum-value as an int, but i only get the name.
Here is my (sample) class and enum:
public class Request {
public RequestTy
Please see the full example Console Application program below for an interesting way to achieve what you're looking for using the DataContractSerializer:
using System;
using System.IO;
using System.Runtime.Serialization;
namespace ConsoleApplication1
{
[DataContract(Namespace="petermcg.wordpress.com")]
public class Request
{
[DataMember(EmitDefaultValue = false)]
public RequestType request;
}
[DataContract(Namespace = "petermcg.wordpress.com")]
public enum RequestType
{
[EnumMember(Value = "1")]
Booking = 1,
[EnumMember(Value = "2")]
Confirmation = 2,
[EnumMember(Value = "4")]
PreBooking = 4,
[EnumMember(Value = "5")]
PreBookingConfirmation = 5,
[EnumMember(Value = "6")]
BookingStatus = 6
}
class Program
{
static void Main(string[] args)
{
DataContractSerializer serializer = new DataContractSerializer(typeof(Request));
// Create Request object
Request req = new Request();
req.request = RequestType.Confirmation;
// Serialize to File
using (FileStream fileStream = new FileStream("request.txt", FileMode.Create))
{
serializer.WriteObject(fileStream, req);
}
// Reset for testing
req = null;
// Deserialize from File
using (FileStream fileStream = new FileStream("request.txt", FileMode.Open))
{
req = serializer.ReadObject(fileStream) as Request;
}
// Writes True
Console.WriteLine(req.request == RequestType.Confirmation);
}
}
}
The contents of request.txt are as follows after the call to WriteObject:
2
You'll need a reference to the System.Runtime.Serialization.dll assembly for DataContractSerializer.