Not a duplicate of this.
I want to make a string have a max length. It should never pass this length. Lets say a 20 char length. If the provided string is > 20, take the first 20 string and discard the rest.
The answers on that question shows how to cap a string with a function but I want to do it directly without a function. I want the string length check to happen each time the string is written to.
Below is what I don't want to do:
string myString = "my long string";
myString = capString(myString, 20); //<-- Don't want to call a function each time
string capString(string strToCap, int strLen)
{
...
}
I was able to accomplish this with a property:
const int Max_Length = 20;
private string _userName;
public string userName
{
get { return _userName; }
set
{
_userName = string.IsNullOrEmpty(value) ? "" : value.Substring(0, Max_Length);
}
}
Then I can easily use it whout calling a function to cap it:
userName = "Programmer";
The problem with this is that every string
I want to cap must have multiple variables defined for them. In this case, the _userName
and the userName
(property) variables.
Any clever way of doing this without creating multiple variables for each string and at the-same time, not having to call a function each time I want to modify the string
?