Friday, December 16, 2016

Custom cast support for objects


We are working with Hashtables a lot in a project, where we need to convert objects into hashtable and from hashtables

A way to do this is by adding custom casting in the class to the class type, and to add a method to convert to hashtable.

Example

   public class MyClass
    {
        public string Name;
        public int Id;
        public string Description;

        public static explicit operator MyClass(Hashtable hashtable)
        {
            MyClass mt = new MyClass();
            mt.Description = hashtable["Description"].ToString();
            mt.Id = int.Parse(hashtable["Id"].ToString());
            mt.Name = hashtable["Name"].ToString();
            return mt;
        }

        public Hashtable ToHashtable()
        {
            var hashtable = new Hashtable();
            hashtable["Name"] = "name";
            hashtable["Id"] = 1;
            hashtable["Description"] = "description";
            return hashtable;
        }
    }
Then simply we can do something like:
Hashtable hashtable = myClass.ToHashtable();

And 
MyClass casted = (MyClass) hashtable;
Example usage:
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass
            {
                Description = "description",
                Id = 1,
                Name = "name"
            };

            Hashtable hashtable = myClass.ToHashtable();
            Console.WriteLine("Hashtable: ");
            Console.WriteLine(hashtable["Name"]);
            Console.WriteLine(hashtable["Id"]);
            Console.WriteLine(hashtable["Description"]);


            MyClass casted = (MyClass) hashtable;
            Console.WriteLine("MyClass: ");
            Console.WriteLine(casted.Id);
            Console.WriteLine(casted.Description);
            Console.WriteLine(casted.Name);

            Console.ReadKey();
        }