Mark A. Durham
Mark A. Durham

Reputation: 864

Is there a difference between the Visual Basic Strings.Trim(String) method and the .NET String.Trim method?

Is there a difference between using the Visual Basic (VB.NET) Strings.Trim(String) method:

Dim myString As String = "    myString    "
myString = Trim(myString)

and the .NET String.Trim method:

Dim myString As String = "    myString    "
myString = myString.Trim()

Upvotes: 2

Views: 2205

Answers (3)

Blastboy
Blastboy

Reputation: 1

A variable of type String can be Nothing, and in that case they behave differently:

Trim(myString) returns "" (an empty string)

myString.Trim() gives a runtime error

myString?.Trim() returns Nothing

Upvotes: 0

dbasnett
dbasnett

Reputation: 11773

The differences can be gleaned from the documentation,

Trim - VisualBasic namespace

https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.strings.trim?view=net-5.0

Trim - System namespace

https://learn.microsoft.com/en-us/dotnet/api/system.string.trim?view=net-5.0

Upvotes: 1

Mark A. Durham
Mark A. Durham

Reputation: 864

Yes, the results of these two methods can be different. The first Strings.Trim(String) method -- Trim(myString) -- trims only spaces off the leading and trailing parts of the string, not tabs or other whitespace characters. The second String.Trim method -- myString.Trim() -- trims all whitespace (including tabs, carriage returns, linefeeds ... any character for which IsWhiteSpace(char) returns true) off the leading and trailing parts of the string.

Upvotes: 5

Related Questions