Richard Edwards
Richard Edwards

Reputation: 1399

Creating objects that initialize themselves based on a configuration string

I am coding a bunch of the following type of classes and it just seems a bit smelly to me. Basically I want to deserialze based on some json configuration of properties as well as serialize it for storage. I thought the following method would work well since I don't want to stipulate that the serialization/deserialization has to be json etc.

The code looks like this for a simple object:

public class IntegerDatasourceInstanceOptions
{
    public int Start { get; set; }
    public int Count { get; set; }

    public IntegerDatasourceInstanceOptions()
    {

    }

    public IntegerDatasourceInstanceOptions(string config)
    {
        var options = JsonConvert.DeserializeObject<IntegerDatasourceInstanceOptions>(config);
        if (options != null)
        {
            Start = options.Start;
            Count = options.Count;
        }
    }

    public override string ToString()
    {
        return JsonConvert.SerializeObject(this);
    }
}
  1. Is this the correct way to go about this or should I use ISerializable instead?
  2. I want to eliminate having to update all of the properties in the constructor. It's fine for a couple of properties in this case but if I have one with 30 properties it becomes a bit of a nightmare

I guess I'm just looking for some feedback as to whether this is the best way to go or not.

Upvotes: 0

Views: 60

Answers (1)

Lloyd
Lloyd

Reputation: 29668

I tend to use a static method in instances like this, for example:

public class IntegerDatasourceInstanceOptions
{
    public int Start { get; set; }
    public int Count { get; set; }

    public IntegerDatasourceInstanceOptions()
    {

    }

    public override string ToString()
    {
        return JsonConvert.SerializeObject(this);
    }

    public static IntegerDatasourceInstanceOptions Create(string config)
    {
        return JsonConvert.DeserializeObject<IntegerDatasourceInstanceOptions>(config);
    }

}

You can then just do:

var options = IntegerDatasourceInstanceOptions.Create("{...}");

Upvotes: 2

Related Questions