What is the wrong in this sample code - Programmers Heaven

Howdy, Stranger!

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

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

What is the wrong in this sample code

Al_Mo3tasmAl_Mo3tasm Posts: 5Member
[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 Posts: 1,134Member
    [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 Posts: 39Member
    Define the type of variable in the following statement

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

Sign In or Register to comment.