Delimiter Switcher

Concatenating a list of error messages and you need a line break after each message but not the last? Instead think of it as preprending a line break before each line except the first.

Hear is a class that helps out with this

    /// <summary>
    /// Used for delimiting between string tokens and or lines.  Emits a delimiter for the first line and a different for all of the rest.  
    /// </summary>
    /// <remarks>
    /// Useful for comma/tab delimited values etc, where the delimiter must be before each token except for the first.  Great for lazy developers
    /// who do not want to write code checking whether or not they are on the first iteration of a loop appending to a delimited list.
    /// </remarks>
    public class ListDelimiter
    {
    // first 
    string _first;
    string _second;
    Func<string> _getDelimiter;

    /// <summary>
    /// Constructor, initialize delimiters.
    /// </summary>
    /// <param name="first">Value used for the first delimiter.</param>
    /// <param name="rest">Value used for the rest.</param>
    public ListDelimiter(string first, string rest)
    {
        _first = first;
        _second = rest;
        Reset();
    }

    /// <summary>
    /// Return first delimiter.
    /// </summary>
    private string _getFirst()
    {
        _getDelimiter = _getSecond;
        return _first;
    }

    /// <summary>
    /// Return second delimeter.
    /// </summary>
    private string _getSecond()
    {
        return _second;
    }

    /// <summary>
    /// Resets.  After calling this method, accessing the <see cref="Delimiter"/> property will return the first delimter.
    /// </summary>
    public void Reset()
    {
        _getDelimiter = _getFirst;
    }

    /// <summary>
    /// Access current delimeter.
    /// </summary>
    public string Delimiter
    {
        get { return _getDelimiter(); }
    }
}

Download PDF

Leave a Reply

Your email address will not be published. Required fields are marked *