1

I'm using RestSharp to deserialize some data. This works fine and all the data loads correctly, however one of my fields is in csv format (I can't change this unfortunately) and I need to parse out that data and load it into my object.

What is a good way to structure my class so that the code inside loadData() is run when the "data" object receives a value? I basically want to avoid running loadData on its own before I can use every object, as my SkaterData object is created 20+ times.

This is what my class structure looks like:

public class SkaterData
{
    public int id { get; set; }
    public string data { get; set; }
    public PlayerData PlayerData { get; set; }

    public void loadData()
    {
        var dataRows = data.Split(',');
        PlayerData = new PlayerData(Int32.Parse(dataRows[0]), dataRows[1], dataRows[2]);
    }
}

public class PlayerData
{
    public int Number { get; set; }
    public string Position { get; set; }
    public string Name { get; set; }

    public PlayerData(int number, string position, string name)
    {
        this.Name = name;
        this.Position = position;
        this.Number = number;
    }
}
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Red 5
  • 318
  • 3
  • 13

2 Answers2

2

Both getters and setters are functions which means that you can write something like this:

private string _data;
public int id { get; set; }

public string data
{
    get { return _data; }
    set
    {
        _data = value;
        loadData();
    }
}

public PlayerData PlayerData { get; set; }

public void loadData()
{
    var dataRows = data.Split(',');
    PlayerData = new PlayerData(Int32.Parse(dataRows[0]), dataRows[1], dataRows[2]);
}

In the above code sample, I explicitly defined the data property (which the syntax you were using is just sytantic sugar for). I then added calling loadData to the setter of this property.

Since that setter will get called on deserialization (probably) you may need a slightly different variant of what I have, but its hard to say what it would be based on your problem statement.

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
1

I am pretty sure this is what OnDeserializedAttribute is for, but I have not been able to get it to work using an XmlSerializer (edit: that's because it doesn't implement it I guess).

[OnDeserialized()]
internal void OnDeserializedMethod(StreamingContext context)
{

}
Chris
  • 3,400
  • 1
  • 27
  • 41