Tips in VB.NET - Tip #8
How to restrict a user some passing illegal or invalid input to a function, sub routine or a property.
Sometimes we may be in position where we need to pass only certain inputs for a function or a property. Usually most of us will be doing validation inside the code, in order to restrict the user from entering the invalid inputs. For example, I want to define a function which is going to take the gender of an employee as the input. Ie., it should take either Male or Female. Lets see how this can be achieved.
Public Sub GetGender(ByVal gen As String) If gen = "Male" Then MsgBox("Male") ElseIf gen = "Female" Then MsgBox("Female") Else MsgBox("Invalid input") End If End Sub
Where this is not the best practice. In this example it is very simple, I need to check only three conditions. Where I may be required to check for multiple data values. Which becomes big process. Where I need to put lot of IF blocks to check. And also it is time consuming.
The best practice is to use Enumeration in this case.
Enum Gender Male Female End Enum Public Sub GetGender(ByVal gen As Gender) ................................. ................................. End Sub
Let me give my an example, how I have used this Enum in my project. I was developing a Cricketer Application which is a cricket score tracker. In that I will be continuously requesting to my Remote Server for the latest update, and I need to show them to the user. Say, when a 4 is hit, I need to tell him that such a person as a hit a four and similarly the other happening.
Where I receive this enumeration from the server. I check for the enumeration value and decide what has happened.
Note This hold good for both C#, VB.Net
Please send me your suggestion and feedback to sadhasivam1981@yahoo.com.
Please vist http://sadhasivam.t35.com to know more about me.
Every Features has a purpose
Finding it leads to great benefits
|
No responses found. Be the first to respond and make money from revenue sharing program.
|