Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

A question about classes

Status
Not open for further replies.

Zoomy

Programmer
Aug 28, 2002
6
US
I have a class, it looks like this(ill keep it simple):



Code:
Public Class Person
     Private m_Name as String

     Public Property Name() As String
          Get
               Name = m_Name
          End Get
          Set(ByVal Value As String)
               m_Name = Value
          End Set
     End Property
End Class


now i create instance of this like so:


Code:
     Dim OldMan As New Person


But what i want to do is set his name right away when i create the instance like this:


Code:
     Dim OldMan As New Person("Mr. Smith")


What do i have to add to my class to make this possible? I thought i could add a Sub New to my class like this to make it possible but it does not seem to work:


Code:
     Sub New(ByVal n as String)
          m_Name = n
     End Sub


but i just get an error saying "Argument not specified for parameter n"

Can someone help me out please, i just need to know how to set a property of a class right when i instance it
 
I tried the same code and it works ok, so I don't see anything wrong with how you are coding it. However, you might want to explicitly specify Public in front of New, but I'm not sure if this makes a difference.

Paul
 
I tried the code too, it gives an error on the first syntax, probably the new constructor has replaced the default. I added a default constructor with no arguments and it worked OK, as below.
The button1 routine was for testing.

Public Class Person
Private m_Name As String
Public Property Name() As String
Get
Name = m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

Sub New() 'default constructor
End Sub

Sub New(ByVal n As String) 'user defined constructor
m_Name = n
End Sub

End Class

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim OldMan As New Person() ' uses default constr.
OldMan.Name = "Mr. Smith"
Label1.Text = OldMan.Name
Dim OldMan1 As Person = New Person("Mr. Smith1")
label2.text = oldman1.name
End Sub
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top