serialization

C

csharpula csharp

Hello,

I was wondering how can I serialize/deserialize an enum? Is it like a
regular propery? How can I do it?

Thanks!
 
M

Marc Gravell

I was wondering how can I serialize/deserialize an enum? Is it like a
regular propery? How can I do it?

Absolutely, yes. If you use the inbiuilt serialization (either binary
or xml) it will work just fine. If you are doing things yourself, then
for strings TypeDescriptor.GetConverter is a good bet (or via the
PropertyDescriptor.Converter if you are looking at things on a per-
property basis).

At the simplest level (for doing things manually), how about:

static string Serialize<T>(T value)
{
return
TypeDescriptor.GetConverter(typeof(T)).ConvertToInvariantString(value);
}
static T Deserialize<T>(string value)
{
return
(T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(value);
}

Marc
 
C

csharpula csharp

Do I need any kind of attribute over the enum in order to serialize it
via xml? I did it and I can't see the enum in xml. Why?
thank u!
 
M

Marc Gravell

Do I need any kind of attribute over the enum in order to serialize it
via xml? I did it and I can't see the enum in xml. Why?

Nope; it should be fine as long as the property is public. Can you
perhaps post a short (but complete) example of something that doesn't
work? The only thing that occurs is a [Flags] enum without valid
combinations for all non-trivial values... a short (but complete)
example of it working for a random attribute is shown below...

Marc

using System;
using System.IO;
using System.Xml.Serialization;
[Serializable]
public sealed class Foo
{
public TypeCode Bar { get; set; }
}
static class Program
{
static void Main()
{

using (StringWriter sw = new StringWriter())
{
Foo foo = new Foo { Bar = TypeCode.DateTime };
new XmlSerializer(typeof(Foo)).Serialize(
sw, foo);
string xml = sw.ToString();
}
}
}
 

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