Make sure that length won't exceed LongTitle
(null
checking skipped):
int maxLength = Math.Min(LongTitle.Length, 20);
string title = LongTitle.Substring(0, maxLength);
This can be turned into extension method:
public static class StringExtensions
{
/// <summary>
/// Truncates string so that it is no longer than the specified number of characters.
/// </summary>
/// <param name="str">String to truncate.</param>
/// <param name="length">Maximum string length.</param>
/// <returns>Original string or a truncated one if the original was too long.</returns>
public static string Truncate(this string str, int length)
{
if(length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), "Length must be >= 0");
}
if (str == null)
{
return null;
}
int maxLength = Math.Min(str.Length, length);
return str.Substring(0, maxLength);
}
}
Which can be used as:
string title = LongTitle.Truncate(20);