Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

What is the wrong in this sample code

Al_Mo3tasmAl_Mo3tasm Member Posts: 5
[b][red]This message was edited by Al_Mo3tasm at 2005-11-29 4:31:13[/red][/b][hr]
Module Module1

Sub Main()

Dim ob1 As New xx
ob1.h = 20
Console.WriteLine(ob1.h)


End Sub

Public Class xx

Property h()
Get
Return h
End Get
Set(ByVal Value)
h = Value
End Set
End Property

End Class

End Module



The error is:
An unhandled exception of type 'systrm.StackOverflowException'occurred in unknown Module.

Comments

  • iwilld0itiwilld0it Member Posts: 1,134
    [b][red]This message was edited by iwilld0it at 2005-11-29 12:17:59[/red][/b][hr]
    [code]
    Public Class xx

    Property h()
    Get
    Return h
    End Get
    Set(ByVal Value)
    [b]h = Value[/b]
    End Set
    End Property

    End Class
    [/code]

    The part in bold is causing the stack overflow because you are recusively causing property h to be re-set. The mere assignment is causing the Set portion of the property statement to be re-executed (think about it.)

    The proper way to do it is this ...

    [code]
    Public Class xx
    Private mH

    Property h()
    Get
    Return mH
    End Get
    Set(ByVal Value)
    mH = Value
    End Set
    End Property

    End Class
    [/code]

    This is the typical pattern to assigning a property value to internal private variable (This is what encapsulation is.)

  • cucucucu Member Posts: 39
    Define the type of variable in the following statement

    : Set(ByVal Value)?
    Set(Byval Value as Long)

Sign In or Register to comment.