property assignment in vb.net

G

Guest

My first simple attempt at using a property. and I get an exception "An
unhandled exception of type 'System.StackOverflowException' occurred in
BalanceOmatic.exe" on line xxx. I have included the property code and the
button event used to set and call the property value. Any help greatly
appreciated.



What am I missing?

Thanks
Mike


Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnLogin.Click

User.MyProperty = "Property Set"

MsgBox(User.MyProperty & " User.MyProperty")

End Sub


Public Property MyProperty() As String
Get
MyProperty = MyProperty
End Get
Set(ByVal Value As String)
Line xxx MyProperty = Value
End Set
End Property
 
M

Marina

Your property is recursive. Instead of setting a private variable, you are
just assigning the value to the property itself - which just calls it over
and over again.

Your GET btw, could only return a boolean of whether or not the property is
equal to itself. Not only will this recursively call itself until you get a
StackOverflowException, but the return of that would actually be a Boolean
(if it was capable of ever ending), and not a string at all. Which means you
should turn Option Strict On.

You need to define your property like this:

private _myProp As String

Public Property MyProperty() As String
Get
Return _myProp
End Get
Set(ByVal Value As String)
_myProp = Value
End Set
End Property
 
G

Guest

I presume User is a class? although its not that relevant if it isnt.

have you dim'd a private variable to hold the properties value?

The 'Get' is coded incorrectly, it should return the private variables
contents!

Hope this helps. See below for code changes



PRIVATE _myProperty as string
 
G

Guest

Thanks for the reply. That was it of course. One more quick question. Why
the underscore in _myProp is that a property convention?

Thanks
Mike
 
M

Marina

The only reason I did that, is because VB is case insensitive. In C#, you
can have a private variable named 'someProperty' and a property named
'SomeProperty', and that all works.

In VB, those would be the same name, and you can't have that. So one
convention is to give private fields exposed as properties an underscore, so
you can have unique names.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top