Substring is not working as expected if length is greater than length of String

A quick one line would be:

  B = A?.Length > 40 ? A.Substring(0, 40) : A;

which only implements the substring when the length is more than 40.
For the sake of redundancy, 40 would preferably be a variable of course. The use of ‘?.’ prevents errors when ‘A’ is null.
As ean5533 mentioned A.Substring(0, Math.Min(40, A.Length)) can also be used. Same outcome, prevents the use of ’40’ twice, but will always invoke the substring function (not that that matters in this day of age)

For ease of use, an extension method can be created

public static string Truncate(this string value, int MaxLength) => value?.Length > MaxLength? value.Substring(0, MaxLength) : value;

Leave a Comment