0

Looking for suggestions for improvement.

Given a string, which could be null, limit the total length to no more than 20 characters

(Example, simplified for this question)

$"{value.Substring(0, Math.Min(value.Length, 20))}"

If value is "abcdefg" then the output would be "abcdefg". If value is "abcdefghijklmnopqrstuvwxyz" then output would be "abcdefghijklmnopqrstuv". Not talking about padding of a string in any way.

Is there a way to do this with a string formatter using string interpolation? For example, I've tried $"{value, 20}" and the like but that is for padding, not limiting.

Why do I need to use string interpolation? Because our code standard dictates it.

T H
  • 492
  • 5
  • 15
  • 2
    So you just want the full length of `value` or the first 20 characters, whichever is shorter? And to guard against a null value? Why interpolate this at all when there arent any other characters in the string? – maccettura Nov 30 '20 at 19:17
  • @maccettura Yes, that is correct. – T H Nov 30 '20 at 19:17
  • Did you see my comment edit? What is the point of interpolation here when you dont interpolate with anything? – maccettura Nov 30 '20 at 19:20
  • Just create an extension method on `string` that return `string.Empty` if its null, the string if the length us less than requested, and a substring otherwise. Extension methods surprisingly work when the variable is null. You can then use that within an interpolated string if you'd like – Flydog57 Nov 30 '20 at 19:26
  • @Flydog57 Like maccettura mentioned there is no point in doing interpolation if the value is null. It should outright be skipped over. – Franck Nov 30 '20 at 19:28
  • @Franck: If you have an expression like `$"Address: {person.Address1} {person.Address2}"` and you want to make sure that neither address goes over 20 char, then having a string extension method like I describe (that handles null) called `MaxLen(int)` would work well: `$"Address: {person.Address1.MaxLen(20)} {person.Address2.MaxLen(20)}"`. It depends on what the OP really wants to do – Flydog57 Nov 30 '20 at 19:41
  • 1
    @maccettura The sample string I gave was just an example for simplification. In my "real code" there are other static text in the string as well as other variables. – T H Nov 30 '20 at 20:36
  • This works as an extension method (with some formatting): `public static string MaxLen(this string thisString, int maxLen) { if (thisString == null) { return string.Empty; } if (thisString.Length <= maxLen) { return thisString; } return thisString.Substring(0, maxLen); }` – Flydog57 Nov 30 '20 at 22:14

0 Answers0