HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMajor

Get string truncated to max length

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
truncatedlengthgetmaxstring

Problem

This is an extension method to get a string that is truncated to a maximum length.

Any comments?

public static class StringExtensions
{
    public static string WithMaxLength(this string value, int maxLength)
    {
        if (value == null)
        {
            return null;
        }

        return value.Substring(0, Math.Min(value.Length, maxLength));
    }
}

Solution

If you're using C# 6.0, I believe you can drop the null-check:

public static string WithMaxLength(this string value, int maxLength)
{
    return value?.Substring(0, Math.Min(value.Length, maxLength));
}


Other than that, it's like Jeroen said: that's pretty much as good as it gets.

The class and parameter naming is exactly as I'd have it, and the name of the extension method is decent, although I'd try to find a name that better indicates that truncation will occur when value is longer than maxLength... but WithMaxLength isn't a bad name.

Code Snippets

public static string WithMaxLength(this string value, int maxLength)
{
    return value?.Substring(0, Math.Min(value.Length, maxLength));
}

Context

StackExchange Code Review Q#101017, answer score: 45

Revisions (0)

No revisions yet.