Tiny way to get the first 25 characters

后端 未结 12 1565
感动是毒
感动是毒 2020-12-29 13:12

Can anyone think of a nicer way to do the following:

public string ShortDescription
{
    get { return this.Description.Length <= 25 ? this.Description :          


        
12条回答
  •  旧时难觅i
    2020-12-29 14:10

    I think the approach is sound, though I'd recommend a few adjustments

    • Move the magic number to a const or configuration value
    • Use a regular if conditional rather than the ternary operator
    • Use a string.Format("{0}...") rather than + "..."
    • Have just one return point from the function

    So:

    public string ShortDescription
    {
        get
        {
            const int SHORT_DESCRIPTION_LENGTH = 25;
    
            string _shortDescription = Description;
    
            if (Description.Length > SHORT_DESCRIPTION_LENGTH)
            {
                _shortDescription = string.Format("{0}...", Description.Substring(0, SHORT_DESCRIPTION_LENGTH));
            }
    
            return _shortDescription;
        }
    }
    

    For a more general approach, you might like to move the logic to an extension method:

    public static string ToTruncated(this string s, int truncateAt)
    {
        string truncated = s;
    
        if (s.Length > truncateAt)
        {
            truncated = string.Format("{0}...", s.Substring(0, truncateAt));
        }
    
        return truncated;
    }
    

    Edit

    I use the ternary operator extensively, but prefer to avoid it if the code becomes sufficiently verbose that it starts to extend past 120 characters or so. In that case I'd like to wrap it onto multiple lines, so find that a regular if conditional is more readable.

    Edit2

    For typographical correctness you could also consider using the ellipsis character (…) as opposed to three dots/periods/full stops (...).

提交回复
热议问题