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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How To: Restrict values passed to a function, procedure or a property.

How-to

How To: Restrict values passed to a function, procedure or a property.

by  PankajBanga  Posted    (Edited  )
Sometime we have to restrict the values passed into a function, procedure or a property. A common practice is to validate values inside the code. For instance the following procedure accepts marital status of a customer, checks for valid marital status and displays it in a message box.

Public Sub GetMaritalStatus(ByVal mStatus As String)
If mStatus = "Defacto" Then
MessageBox.Show("Defacto")
ElseIf mStatus = "Divorced" Then
MessageBox.Show("Divorced")
ElseIf mStatus = "Married" Then
MessageBox.Show("Married")
ElseIf mStatus = "Separated" Then
MessageBox.Show("Separated")
ElseIf mStatus = "Single" Then
MessageBox.Show("Single")
Else
MessageBox.Show("Invalid marital status.")
End If
End Sub

This is a simple example where I had to check only five conditions. Imagine having multiple data values, which becomes a sluggish, time consuming process involving heap of IF blocks. There is an alternative, which makes the process more efficient and regarded as a good programming practice, it is using Enumeration:

Enum MaritalStatus
Defacto
Divorced
Married
Separated
[Single]
End Enum

Now all you have to do is declare your argument as type MaritalStatus:

Public Sub GetMaritalStatus(ByVal mStatus As MaritalStatus)
.......

End Sub

Enumeration is basically a type which can hold a set of values. In .NET Framework Enumeration can be of any type except Char. If no underlying type is explicitly declared, Int32 is used.

For more information on Enumeration visit the following link:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemenumclasstopic.asp


Happy Programming!!!
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top