2

I have the simplest VB code:

Dim test As String = "DDN8057"
Console.WriteLine(test.TrimStart("DDN"))

gives me

N8057

Why? Converting this to C# (which I'm far more familiar with), made me realize that TrimStart actually expects a params char[], but running

Console.WriteLine("DDN8057".TrimStart("DDN".ToCharArray()));

gives me my expected

8057

So, I guess VB is capable of treating a string as a char array internally (is this true?), but why the discrepancy in my output?

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
  • Using either `{"D"c, "D"c, "N"c}` or `"DDN".ToCharArray` in VB gives your expected output. Passing a string when it expects a char array won't work as intended. It simply takes the first letter of the string and ignores the rest. Replace the second D with any other character to check this out – A Friend Jul 08 '16 at 15:17
  • 4
    If you switch Option Strict On (and you should always have it on) - then `test.TrimStart("DDN")` will not compile - for the reason you explained – Matt Wilko Jul 08 '16 at 15:18

1 Answers1

3

You do not have Option Strict switched On in your VB project.

I can tell because test.TrimStart("DDN") does not compile when this is on. This is because as you correctly pointed out TrimStart expects an explicit char array (or a single char)

What happens when you run this with Option Strict Off is the compiler coerces the String (DDN) into a single char (D) (this is an implicit narrowing conversion which Option Strict expressly forbids) which is why you get N8057 as your output.

You would think that as a string is just a char array it would convert it to an array but it doesn't - it effectively performs CChar("DDN")!

Conclusion

Option Strict On = Good. Here is how to switch it on by default: Option Strict on by default in VB.NET

Community
  • 1
  • 1
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
  • bah. I forgot about `option strict`. Even with it off though, it seems radical that VB lets that fly at runtime. – Jonesopolis Jul 08 '16 at 15:27
  • I thought `option strict off` was like using dynamic in C#. But based on the `option strict` docs, i guess string to char is a *narrowing conversion* – Jonesopolis Jul 08 '16 at 15:38
  • @Jonesopolis - there are subtle but important differences between dynamic and Option Strict. The error produced when Strict is On is `BC30512` - https://msdn.microsoft.com/en-us/library/4we5x2t7.aspx – Matt Wilko Jul 08 '16 at 15:44