Could someone explain to me the concept of Get and Set property? It's just not sinking in for me.
This is not a concept native to vb.net. It is part of the .net framework and oop. To make a long story short it is just the way a client uses/interacts with the object in order to force him/her to follow a particular pattern of usage. It is a way of reading/setting values of the private members/variables after a layer where some logic can be implemented. For e.g. in the setter implementation of a class called Account. Lets say it has a property called Balance which is of string datatype (for example sake), but has only numeric values.
Dim acc as New Account("CustID-1234")
acc.Balance = "1234" 'This is valid
acc.Balance = "Ten thousand" 'this is wrong
Hence inorder to provide consistency in the data of an object (while either reading/setting) we have getters and setters resp.
Now the setter for the above class can be written like this:
Public Class Account
'...Var dec
Public Property Balance() As String
Get
Return m_iBal.ToString()
Set (value As String)
Dim i As Integer
If Integer.TryParse(value, i) Then
m_Bal = i
Else
'You can throw a nasty error
End If
End Property
End Class
I don't use Visual Basic, but the principle works like this:
You have a private variable in your class, let's call it myNumber (which would be some numeric type). You don't want to allow public access to this variable for whatever reason.
You'd create a get and a set method for this variable (also called accessor and mutator methods) which would have an access level of public. This will allow you more control over how the value is set or retrieved. Here's some pseudocode:
getMyNumber(){
return myNumber;
}
setMyNumber(value){
if(value > 0){
myNumber = value;
}
}
With this setter method, you can make sure that myNumber can never be set to 0 or a negative value (for example).
Make sense?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With