Arcadian
Arcadian

Reputation: 4350

How to declare a fixed length string in vb.net without increasing the length during assignment

I have a fixed length string variable:

<VBFixedString(10)>
Public myVar As String

When I assign the var to a value that has 11 chars the var changes length.

This is what I get:

  myvar = "1234567890ABCD" ' result = myvar being "1234567890ABCD"

What I want is myvar to be: "1234567890"

and then if it is less than 10 I would like

myvar = "12345" to be "12345     "

I can do this with PadLeft PadRight but was wondering if I can declare it as a fixed length and it would handle all that for you.

Upvotes: 1

Views: 10161

Answers (2)

MotoSV
MotoSV

Reputation: 2368

From what I understand the VBFixedString attribute is only recognised by certain file based methods to help structure content written to/read from files. The compiler will not use that attribute for anything else, including to alter how a variable assignment is compiled.

Taken from MSDN:

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.

The last sentence is the important bit:

Keep in mind that this attribute does not change the actual length of the string itself.

http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.vbfixedstringattribute.aspx

EDIT 1:

A quick example on how to auto-padding a string based on a fixed length:

Function FixedLengthString(ByVal value As String, ByVal totalLength As Integer, ByVal padding As Char) As String
        Dim length = value.Length
        If (length > totalLength) Then Return value.Substring(0, totalLength)
        Return value.PadRight(totalLength, padding)
End Function

Here you can pass in a string and if the length of the string is greater than the specified total length you will get a string matching that length. Anything less and you'll get the string plus the padding character upto the specified total length.

This can be improved with error checking and maybe making the method an extension method so you don't have to pass "value".

Upvotes: 2

Al Jones
Al Jones

Reputation: 64

and from the old school, LSET will do exactly what you're asking.

 myvar = lset("1234567890ABCD",10)

results in "1234567890", while

 myvar = lset("12345",10)

results in "12345___" - sorry, the editor trimmed the spaces after the 12345 replaced with underscores

see MSDN entry for LSET

Upvotes: 3

Related Questions