Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.net Mid as left operator special (strange?) behaviour

Tags:

.net

vb.net

Today, while talking with my colleague, something odd came out of his mind.

A "secret" way to handle string coming from vb6, which was like:

 Dim strSomeString as String
 strSomeString = "i am phat" 
 Mid$(strSomeString, 6,4) = "hack"

This would put i am hack inside strSomeString.

While being surprised of such oddity being supported in vb6, I was totally blown when I read that it is supported in VB.Net too (probably for compatibility with old code).

Dim TestString As String
' Initializes string.
TestString = "The dog jumps"
' Returns "The fox jumps".
Mid(TestString, 5, 3) = "fox"
' Returns "The cow jumps".
Mid(TestString, 5) = "cow"
' Returns "The cow jumpe".
Mid(TestString, 5) = "cow jumped over"
' Returns "The duc jumpe".
Mid(TestString, 5, 3) = "duck"

My question is: how is it technically working? What is Mid acting like in that particular situation? (method? function? extension method?)

like image 337
Alex Bagnolini Avatar asked Dec 04 '09 16:12

Alex Bagnolini


1 Answers

It gets translated to an MSIL call to this function in Microsoft.VisualBasic.CompilerServices.StringType

Public Shared Sub MidStmtStr ( _
    ByRef sDest As String, _
    StartPosition As Integer, _
    MaxInsertLength As Integer, _
    sInsert As String _
)

This compiler trick is purely for backwards compatibility. It's built into the compiler, so isn't the kind of trick you can implement yourself on your own types.

So

Mid(TestString, 5, 3) = "fox"

becomes

MidStmtStr(TestString, 5, 3, "fox")

Hope this helps,

like image 112
Binary Worrier Avatar answered Nov 15 '22 05:11

Binary Worrier