I tried the following:
var Title = LongTitle.Substring(0,20) This works but not if LongTitle has a length of less than 20. How can I limit strings to a maximum of 20 characters but not get an error if they are just for example 5 characters long?
I tried the following:
var Title = LongTitle.Substring(0,20) This works but not if LongTitle has a length of less than 20. How can I limit strings to a maximum of 20 characters but not get an error if they are just for example 5 characters long?
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); null in the extension method?length could be optional, but what value would it take? 0? Does it even makes sanse to truncate string to empty string?Shortest, the:
var title = longTitle.Substring(0, Math.Min(20, longTitle.Length)) Ok since some new C# version this suggested variant became the shortest:
var title = longTitle[..Math.Min(20, longTitle.Length)] If the string Length is bigger than 20, use 20, else use the Length.
string title = LongTitle.Substring(0, (LongTitle.Length > 20 ? 20 : LongTitle.Length)); You can use the StringLength attribute. That way no string can be stored that is longer (or shorter) than a specified length.
[StringLength(20, ErrorMessage = "Your Message")] public string LongTitle;