tags:

views:

69

answers:

1

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?)

+7  A: 

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,

Binary Worrier
Wonderful answer, thank you.
Alex Bagnolini
@Alex: Glad to be of help mate.
Binary Worrier