This question already has an answer here:
- How do I truncate a .NET string? 28 answers
I was just simply wondering how I could limit the length of a string in C#.
string foo = "1234567890";
Say we have that. How can I limit foo to say, 5 characters?
Use Remove()...
If this is in a class property you could do it in the setter:
Strings in C# are immutable and in some sense it means that they are fixed-size.
However you cannot constrain a string variable to only accept n-character strings. If you define a string variable, it can be assigned any string. If truncating strings (or throwing errors) is essential part of your business logic, consider doing so in your specific class' property setters (that's what Jon suggested, and it's the most natural way of creating constraints on values in .NET).
If you just want to make sure isn't too long (e.g. when passing it as a parameter to some legacy code), truncate it manually:
string shortFoo = foo.Length > 5 ? foo.Substring(0, 5) : foo;
Note that you can't just use foo.Substring(0, 5) by itself because it will throw an error when foo is less than 5 characters.
You can avoid the if statement if you pad it out to the length you want to limit it to.
name1 will have Chris
name2 will have Jay
No if statement needed to check the length before you use substring
You can try like this: