Universal conversion of types

Assuming I have a table Entities with the columns Value and Type as varchar(strings) in a database, how would I go around to loading these values in C# and converting to the type specified in the table? I was intending to save the getType result for the Type value.

Upvotes: 1

Views: 222

Answers (4)

Thorsten Hans
Thorsten Hans

Reputation: 2683

When you're not using any OR mapper, I would prefer to build a simple class and serialize the instance of that type into xml and store in in a xml column within the databse.

    using System.Xml.Serialization;

    public class MySettings
    {
    public String Setting1 { get; set; }
    public int Setting2 { get; set; }

    public String ToXml()
    {
        string settingsXml;
        var xmlSerializer = new XmlSerializer(typeof(MySettings));
        using (var stream = new MemoryStream())
        {
            xmlSerializer.Serialize(stream, this);
            stream.Position = 0;
            using(var reader = new StreamReader(stream))
            {
                settingsXml = reader.ReadToEnd();
            }
        }
        return settingsXml;
    }

    public static MySettings FromXml(string xml)
    {
        MySettings settings = null;
        using(MemoryStream stream  = new MemoryStream(System.Text.Encoding.Default.GetBytes(xml)))
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof (MySettings));
            settings = (MySettings) xmlSerializer.Deserialize(stream);
        }
        return settings;
    }
}

Upvotes: 0

Saeed Amiri
Saeed Amiri

Reputation: 22565

You can do this by Activator.CreateInstance Method for sample code (which is very similar to ur case) see MSDN Sample linked above.

Upvotes: 1

Thorsten Hans
Thorsten Hans

Reputation: 2683

How do you read from your database? Are you using ADO.NET, or are you using any kind of OR Mapper such as EF or NHibernate? In the case of OR Mapping you could build a strongly typed object which could define the types... the OR mapper itself is responsible for the casting.

Upvotes: 1

jgauffin
jgauffin

Reputation: 101150

Save the value.GetType().AssemblyQualifiedName in the Type column and then use Type.GetType(asmQualfName) to get the type back when loading from the db. After that you can just use Activator.CreateInstance to get an object of the correct type.

Upvotes: 1

Related Questions