How to use a Byref variable in Property

I want to do soemthing like 
Str = "ABCD"
     ItemVal(2,Str) = "X"
         which replaces the 2nd character in Str to X
so that after this value of STR would be "AXCD"

in VB 6 I could do this by  passing ByRef variable to a Property

Property ItemVal(byval Index as integer, byref Str as string)
Set(Value as string)

End Set..........

Any ideas how can we do it in .net now that we can't have byref varaibles in property.



Answer this question

How to use a Byref variable in Property

  • sj2509

    Why not try simply using a function for this...

    You have two versions one that persists the change to the local variable on the object and one that doesn't.  The functions allow byref or byval

    Public Class Fred
        Dim strStore As String = "ABCD"

        Public Function ItemVal1(ByVal index As Integer, ByVal str As String) As String
            '//Return and leave Original Intact
            Dim strReturn As String = strStore
            Mid$(strReturn, index, 1) = str
            Return strReturn
        End Function

        Public Function ItemVal2(ByVal index As Integer, ByVal str As String) As String
            '//Chnage Original and Return
            Dim strReturn As String = strStore
            Mid$(strStore, index, 1) = str
            Return strStore
        End Function

        Public ReadOnly Property ItemVal()
            Get
                Return strStore
            End Get
        End Property
    End Class

    Module Module1

        Sub Main()
            Dim x As New Fred
            Console.WriteLine(x.ItemVal())

            Console.WriteLine(x.ItemVal1(2, "X"))
            Console.WriteLine(x.ItemVal())

            Console.WriteLine(x.ItemVal2(2, "Y"))
            Console.WriteLine(x.ItemVal())
        End Sub

    End Module

     


  • Mary Lindholm

    Thanks Dustin. I know that one.

    But I want to do something like 

       ItemVal(1,SrcArray) = "A".


  • LostGamer

    I would turn it into a sub.

    Example...



    Public Class Form1

        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim str As String = "Hello"
            ItemVal("a", 1, str)
            MsgBox(str)
        End Sub

        Public Sub ItemVal(ByVal NewVal As Char, ByVal Pos As Integer, ByRef Source As String)
            Dim Str As Char()
            str = Source.ToCharArray()
            str(Pos) = NewVal
            Source = str
        End Sub
    End Class

     



    Hope it helps!

    Dustin.


  • How to use a Byref variable in Property