1

I have a class with multiple properties, some of property type in class is datatable

I am using BinaryFormatter to create a clone copy of class, it works fine but datatable.defaultview.sort that was set with some value does not coping as is in cloned object. This is a sample code

   public static void Main(string[] args)
    {
        TestCloneDatatable();
    }


    private static void TestCloneDatatable()
    {
        DataTable datatatable = new DataTable();
        datatatable.Columns.Add("ID", typeof(int));
        datatatable.Columns.Add("AddressLine1", typeof(string));

        for (int i = 0; i < 10; i++)
        {
            datatatable.Rows.Add(i, string.Concat("test ", i));
        }

        datatatable.DefaultView.Sort = "AddressLine1 ASC";

        Test test = new Test();
        test.ID = 1;
        test.Name = "my Name";
        test.Addresss = datatatable;


        Test testClone = test.Clone();

        string sort = testClone.Addresss.DefaultView.Sort; //here it is empty, I need "AddressLine1 ASC" should be there 

    }

    [SerializableAttribute]
    public class Test
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public DataTable Addresss { get; set; }


        public Test Clone()
        {

            Test result = DeepCopy<Test>(this);
            return result;
        }

        protected T DeepCopy<T>(T item)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new System.IO.MemoryStream();
            formatter.Serialize(stream, item);
            stream.Seek(0, SeekOrigin.Begin);
            T result = (T)formatter.Deserialize(stream);
            stream.Close();
            return result;
        }

    } 
Neeraj Kumar Gupta
  • 2,157
  • 7
  • 30
  • 58
  • DefaultView is a read-only property. The serializer can't deal with that. You will probably have to set a custom View. – bommelding Jul 24 '18 at 12:00
  • thanks @bommelding, I am using BinaryFormatter should it work? .. some of link says that using BinaryFormatter we can serialize it .. https://bytes.com/topic/net/answers/171953-possible-serialize-read-only-property – Neeraj Kumar Gupta Jul 24 '18 at 12:34
  • I don't know, you have a pretty good mcve here that says No. – bommelding Jul 24 '18 at 12:53

0 Answers0