0

Here is a case for which cloning of object fails:

[Serializable]
public class MasterClass
{
    public MasterClass(DataRow row)
    {
        EntityData = row;
    }

    public DataRow EntityData
    {
        get;
        set;
    }
}

for cloning I am using extention method(Clone()) from this SO question:

while cloning MasterClass object following error message thrown at runtime:

Type 'System.Data.DataRow' in Assembly 'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.

Any solution how to handle this?

Community
  • 1
  • 1
Ankush Madankar
  • 3,689
  • 4
  • 40
  • 74

3 Answers3

2

Try adding a parameterless constructor:

public MasterClass()
{
}

Converting DataRow

Assuming you DataRow has a Table:

[Serializable]
public class MyKeyValue {
    public string Key { get; set; }
    public string Value { get; set; }
}


[Serializable]
public class MasterClass
{
    public MasterClass() {}

    public MasterClass(DataRow row)
    {
        var list = new List<MyKeyValue>();
        foreach (DataColumn col in row.Table.Columns)
        {
            list.Add(new MyKeyValue{Key = col.ColumnName, Value = Convert.ToString(row[col.ColumnName])});
        }
        EntityData = list;
    }

    public IEnumerable<MyKeyValue> EntityData
    {
        get;
        set;
    }
}
Robert Fricke
  • 3,637
  • 21
  • 34
2

Depending on what you are using the DataRow for, you will likely have to parse the values into a custom class that is serializable.

Brian P
  • 1,569
  • 13
  • 23
  • Is there easy way to do this rather than converting `DataRow` into custom serializable class? – Ankush Madankar Jan 28 '14 at 12:56
  • I like Robert Fricke's answer (post-edit). It is the classiest with least amount of work. Just remember to convert your values when using them back to what they need to be. – Brian P Jan 29 '14 at 13:47
1

You must implement ISerializable interface - for serialization, and add constructor that takes (SerializationInfo info, StreamingContext context) - for deserialization.

Denis
  • 5,894
  • 3
  • 17
  • 23