Search code examples
c#arraysstringlimit

C#: Limit the length of a string?


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?


Solution

  • 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:

    const int MaxLength = 5;
    
    
    var name = "Christopher";
    if (name.Length > MaxLength)
        name = name.Substring(0, MaxLength); // name = "Chris"