I am trying to find the best practices or some accepted design patterns for serializing classes that aren't built for serialization. Below is the method I've currently implemented:
For example, consider some simple class where I want a constructor:
public class Coord
{
public int x { get; private set;}
public int y { get; private set;}
public Coord(int x, int y)
{
this.x = x;
this.y = y;
}
}
If I want to serialize this, I can't without exposing the fields as fully public, and providing a parameterless constructor.
Is it acceptable practice to create some other class just to hold the values I want serialized:
public class DataItem
{
public int x;
public int y;
}
Then perhaps have methods that build and load between these classes
public static DataItem saveCoord (Coord c)
{
DataItem result = new DataItem ();
result.x = c.x;
result.y = c.y;
return result;
}
public static Coord loadCoord (DataItem di)
{
Coord result = new Coord (di.x, di.y);
return result;
}
Then I can perform any serialization actions on my DataItem class.
What might be criticisms of this method? Are there better, established patterns?
Sorry if my question is poor, I'm a fresh learner!