Use of Optional Parameters in VB.Net

vishalneeraj-24503
Posted by vishalneeraj-24503 under VB.NET category on | Points: 40 | Views : 3899
Hi, today we will learn about working with Optional Parameters in VB.Net.
As the name supplies, Optional parameters are treated as optional,we need not pass values to optional parameters but sometimes it's required.

We always assign its value to anything or we have to provide a default values to it.

Note:- Optional Parameters always defined as the Last Parameters in Function or Method.

For example :-

Private Sub update_insert_records(ByVal employee_id As Integer, Optional ByVal is_update_flag_checked As Boolean = False)

Dim sql_query As String = String.Empty

Try
If (is_update_flag_checked = True) Then
sql_query = "update employee_master set employee_name='Vishal' where employee_id = "& employee_id &" and status = 'AA'"

'rest of the code
Else
sql_query = "insert into employee_master(employee_name,status) Values('Vishal','AA')"

'rest of the code
End If

Catch ex As Exception
Throw ex
End Try

End Sub

Protected Sub btn_save_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_submit.Click
Try
update_insert_records(0)
Catch ex As Exception
Throw ex
End Try
End Sub

Protected Sub btn_update_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_submit.Click
Try
update_insert_records(1,True)
Catch ex As Exception
Throw ex
End Try
End Sub

In the above example,

1). update_insert_records(0) -> will save employee record, because we haven't passed value to Optional Parameter so, default value will be false.

2). update_insert_records(1,True) -> will update employee record into DB,here we have passed value as True to optional parameter. So it will check is_update_flag_checked parameter then will update.

Comments or Responses

Login to post response