-
Aug 31st, 2012, 05:53 PM
#1
Thread Starter
Member
Confused about instantiating classes
There is something confusing to me about classes. Suppose I have a form with a textbox and a button on it and I define a class as follows:
Public Class Checktext
Private Shared m_Title As String = "TextBox Error"
Public Shared Property Title() As String
Get
Return m_Title
End Get
Set(ByVal value As String)
m_Title = value
End Set
End Property
Public Shared Function IsValid(ByVal control As Control) As Boolean
If control.GetType.ToString = "System.Windows.Forms.TextBox" Then
Dim textBox As TextBox = CType(control, TextBox)
If textBox.Text = "" Then
MessageBox.Show(textBox.Name.ToString & " cannot be empty.", Title)
textBox.Select()
Return False
Else
MessageBox.Show("That's better", Title)
Return True
End If
Else
MessageBox.Show("This is not a textbox", Title)
Return False
End If
End Function
End Class
The button click method looks like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If Not Checktext.IsValid(TextBox1) Then
TextBox1.Text = "Try again"
End If
End Sub
But I never make an instance of the class. That's the entire project. So why does this code work?
-
Aug 31st, 2012, 07:38 PM
#2
Re: Confused about instantiating classes
Shared members don't require an instance to use, more over you cannot use Shared members from an instance. e.g. the following code will cause a warning.
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim c As New Checktext
If Not c.IsValid(TextBox1) Then ' this cause a warning
TextBox1.Text = "Try again"
End If
End Sub
Last edited by 4x2y; Aug 31st, 2012 at 07:48 PM.
-
Aug 31st, 2012, 08:08 PM
#3
Thread Starter
Member
Re: Confused about instantiating classes
Ah, OK, then this is like static?
-
Sep 1st, 2012, 10:49 PM
#4
Re: Confused about instantiating classes
Originally Posted by franceint
Ah, OK, then this is like static?
It is static.
-
Sep 1st, 2012, 10:55 PM
#5
Re: Confused about instantiating classes
Originally Posted by franceint
Ah, OK, then this is like static?
Just note that there is a Static keyword in VB but it means something different. Shared in VB is equivalent to 'static' in C# or other C-based languages and Static in VB is used to make a local variable retain its value between method calls.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|