Trim a String to a Particular Length

One piece of code that is very popular, besides checking for null, is being able to trim a string to a particular length, making sure a string is not too long to save in the database or display on your page or MVC View. In the olden days, we had lots of code like this:

if (myString.Length > 10)
{
	dbTable.Property = myString.Substring(0,10);
}
else
{
	dbTable.Property = myString;
}

In one form or another. Now, with extension methods, we can add this into our bag of tricks to have available everywhere:

public static class StringExtensions
{
	public static string Trim(this string value, int MaxLength)
	{
		return value.Substring(0, Math.Min(MaxLength, value.Length));
	}
}

Notice that I’m using the Math.Min function to tell the Substring whether to return the string as it is, or use the MaxLength argument. Now the code above will look like this:

dbTable.Property = myString.Trim(10);

And it will save the value of myString as it’s current value, unless it’s longer than 10, which will cause it to be trimmed.

One of the big advantages of using String Extension Methods like this is that they can be used in Linq queries very easily. If you want to see more about extension methods, check out my other posts below: