Fixed Length Strings

How do I declare a fixed length string
In VB6 it was 

Dim myString as String * 80


Answer this question

Fixed Length Strings

  • Eli Gazit

    the only way that comes to my mind to make a string of fixed length with .NET built-in types is to make a const/readonly string:

    const string s1 = "blah";
    readonly string s2 = "blah";

    but maybe this is not exactly what you want ;-)

    if you want to stick strings together and don't want to allow the size to exceed a certain limit,
    you could initialize a stringbuilder like this:

    using System.Text;
    ....
    ....
    StringBuilder sb = new StringBuilder(initialCapacity, maxCapacity);

    and work with this thing instead of the string.

    other than that, I'd say you can't declare a fixed size string in .NET, unless you make your own string class ;-)

  • Kmc85

    uh, sorry btw., saying you knew how it was in VB6 could mean you want to know it for VB.NET, not C#. the syntax would be different, but the string builder should be there in VB too, since it's part of the .NET library. well if this is useful to you is another question ;)

  • waddies

    Visual Basic 6.0
    In Visual Basic 6.0, you can specify the length of a string in its declaration. This causes the string to have a fixed length, as in the following example: 
    Dim Name As String * 30 

    Visual Basic .NET
    In Visual Basic .NET, you cannot declare a string to have a fixed length unless you use the VBFixedStringAttribute Class attribute in the declaration. The code in the preceding example causes an error. 
    You declare a string without a length. When your code assigns a value to the string, the length of the value determines the length of the string, as in the following example: 
    Dim Name As String 
    ' ... 
    Name = "Name is now 30 characters long" ' Length can be changed later.



    Structure Person
       Public ID As Integer
       Public MonthlySalary As Decimal
       Public LastReviewDate As Long
       <VBFixedString(15)> Public FirstName As String
       <VBFixedString(15)> Public LastName As String
       <VBFixedString(15)> Public Title As String
       <VBFixedString(150)> Public ReviewComments As String
    End Structure
    Note   The VBFixedStringAttribute is informational and cannot be used to convert a variable length string to a fixed string. The purpose of this attribute is to modify how strings in structures and non-local variables are used by methods or API calls that recognize the VBFixedStringAttribute. Keep in mind that this attribute does not change the actual length of the string itself.

  • Fixed Length Strings