Thursday, January 30, 2014

Encapsulate a string to act as an array of strings


Here is a quick snippet for expose in a class a string that contains values comma-separated (eg: value1,value2,value3) as an array.

    string myString;

    public string[] MyArray
    {
      get
      {
        if (string.IsNullOrEmpty(myString))
          return new string[0];
        return myString.Split(',');
      }

      set
      {
        myString = String.Join(",", value);
      }
    }

Sample input

 myString = "value1,value2,value3";

Result

myArray = string[]{ "value1", "value2", "value3" };

Tips

Be sure that string does not contains extra ',' in order to avoid unwanted splitting.

Submit this story to DotNetKicks