Rajanikant Hawaldar
How to serialize hashtables?

How to serialize hashtables?

By Rajanikant Hawaldar in C# on Sep 27 2020
  • Er.Parikshit Singh
    Oct, 2020 2

    Use custom serialization using ICollection interface implementation, and mark Hashtable as [NonSerialized], instead, use custom collection instead of Hashtable or use it internally, for collection of elements, as in this example:
    using System;
    using System.IO;
    using System.Collections;
    using System.Xml.Serialization;

    public class Test{
    static void Main(){
    Test t = new Test();
    t.SerializeCollection(“coll.xml”);
    }

    1. private void SerializeCollection(string filename){
    2. Employees Emps = new Employees();
    3. // Note that only the collection is serialized -- not the
    4. // CollectionName or any other public property of the class.
    5. Emps.CollectionName = "Employees";
    6. Employee John100 = new Employee("John", "100xxx");
    7. Emps.Add(John100);
    8. XmlSerializer x = new XmlSerializer(typeof(Employees));
    9. TextWriter writer = new StreamWriter(filename);
    10. x.Serialize(writer, Emps);
    11. }

    }
    public class Employees:ICollection{
    public string CollectionName;
    private ArrayList empArray = new ArrayList();

    1. public Employee this[int index]{
    2. get{return (Employee) empArray[index];}
    3. }
    4. public void CopyTo(Array a, int index){
    5. empArray.CopyTo(a, index);
    6. }
    7. public int Count{
    8. get{return empArray.Count;}
    9. }
    10. public object SyncRoot{
    11. get{return this;}
    12. }
    13. public bool IsSynchronized{
    14. get{return false;}
    15. }
    16. public IEnumerator GetEnumerator(){
    17. return empArray.GetEnumerator();
    18. }
    19. public void Add(Employee newEmployee){
    20. empArray.Add(newEmployee);
    21. }

    }

    public class Employee{
    public string EmpName;
    public string EmpID;
    public Employee(){}
    public Employee(string empName, string empID){
    EmpName = empName;
    EmpID = empID;
    }
    }

    • 0
  • Er.Parikshit Singh
    Oct, 2020 2


Most Popular Job Functions


MOST LIKED QUESTIONS