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
{
///
/// Truncates string so that it is no longer than the specified number of characters.
///
/// String to truncate.
/// Maximum string length.
/// Original string or a truncated one if the original was too long.
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);