Monday, April 30, 2012

Data Saving with stored procedure in VB.NET


Dim cmm = New SqlCommand
            cmm.CommandType = CommandType.StoredProcedure
            cmm.CommandText = "sp_facility_addupdate"
            cmm.Parameters.Add("@facility_id", SqlDbType.BigInt, 0).Value = Convert.ToInt64(hdnFac_ID.Value)
            cmm.Parameters("@facility_id").Direction = ParameterDirection.InputOutput

            cmm.Parameters.Add("@location_id", SqlDbType.BigInt, 0).Value = Convert.ToInt64(Session("Location_ID"))

            cmm.Parameters.Add("@facility_name", SqlDbType.VarChar, 50).Value = txtFacNm.Text
            If ddl_FacilityType.SelectedValue = 1 Then
                cmm.Parameters.Add("@facility_type", SqlDbType.VarChar, 50).Value = "Production Facility"
            ElseIf ddl_FacilityType.SelectedValue = 2 Then
                cmm.Parameters.Add("@facility_type", SqlDbType.VarChar, 50).Value = "Repair Facility"
            ElseIf ddl_FacilityType.SelectedValue = 3 Then
                cmm.Parameters.Add("@facility_type", SqlDbType.VarChar, 50).Value = "Warehouse"
            ElseIf ddl_FacilityType.SelectedValue = 4 Then
                cmm.Parameters.Add("@facility_type", SqlDbType.VarChar, 50).Value = "Consolidation Center"
            End If
            cmm.Parameters.Add("@address_1", SqlDbType.VarChar, 50).Value = txtAddr1.Text
            cmm.Parameters.Add("@address_2", SqlDbType.VarChar, 50).Value = txtAddr2.Text
            cmm.Parameters.Add("@city", SqlDbType.VarChar, 50).Value = txtCity.Text
            cmm.Parameters.Add("@state", SqlDbType.VarChar, 50).Value = txtState.Text
            cmm.Parameters.Add("@country", SqlDbType.VarChar, 50).Value = ddl_country.SelectedValue
            cmm.Parameters.Add("@zip", SqlDbType.VarChar, 50).Value = txtZip.Text
            cmm.Parameters.Add("@phone", SqlDbType.VarChar, 50).Value = txtPhone.Text
            cmm.Parameters.Add("@isdcode", SqlDbType.VarChar, 20).Value = txtisdcode.Text
            cmm.Parameters.Add("@created_id", SqlDbType.BigInt, 0).Value = Convert.ToInt64(lblCreator_ID_Fac.Text)
            cmm.Parameters.Add("@last_update_id", SqlDbType.BigInt, 0).Value = Convert.ToInt64(dt.Rows(0)("user_id").ToString())

            DataConnect.GetInstance.ExecuteNonQuery(cmm)

Structures


Structures are used to create a variable set of different datatypes in VB.NET (In
earlier versions of VB we use TYPE and END TYPE to define it). Here it is
defined with STRUCTURE and END STRUCTURE keyword.
It supports allmost all the features of OOPS, like
• Implementing interfaces
• Constructors, methods, properties, fields, constants and events
• Shared constructors
Ex: -
Defining the structure:-
VB.NET
Structure Person
Public FirstName As String
Public LastName As String
Public Address As String
Public Pincode As String
Public DateOFBirth As DateTime
Public Sub DisplayInfo()
Dim msg As String
msg = FirstName & " " & LastName & vbCrLf
msg = msg & Address & vbCrLf
msg = msg & "PIN – " & Pincode
msg = msg & "Date of Birth : " & DateOFBirth.ToString
End Sub
End Structure
C#
struct Person
{
Public String FirstName;
Public String LastName ;
Public String Address ;
Public String Pincode ;
Public DateTime DateOFBirth;
Public void DisplayInfo()
{
String msg=new String();
msg = FirstName + " " + LastName ;
msg = msg + Address ;
msg = msg + "PIN – " + Pincode;
msg = msg + "Date of Birth : " + DateOFBirth.ToString;
}
}
In the example a Person structure is declared to hold the a person’s details like
name, address, pincode etc., we have already seen this person details in terms
of a class object. Basically the structures are used to hold the set of values like
array. Theoritically arrays holds a set of single datatype values, but structures
holds a set of different datatype values. Due to the OOPS feature of .NET we can
implement the methods and properties in the structures too. This is shown in the
person structure. Here the Firstname,Lastname,Address,Pincode,Dateofbirth are
all the variables of person structure with different datatype declarations, where
DisplayInfo is a method to disputably the information.
Variables holds the data and methods operates on the data stored in it as in the
normal class object.
Usage of the structure:-
VB.Net
'Creating an instance of the structure like a normal class variable
Dim varPerson As Person = New Person()
'Setting the structure variables with the values
varPerson.firstname = “Rama”
varPerson.lastname = “Lakan”
varPerson.address = “Mysore”
varPerson.pincode = “570002”
varPerson.dateofbirth = “25/06/1977”
'Calling the strcuture method to manipulate and display the person address
varPerson.displayinfo()
C#
Person varPerson =New Person();
'Setting the structure variables with the values
varPerson.firstname = “Rama”;
varPerson.lastname = “Lakan”;
varPerson.address = “Mysore”;
varPerson.pincode = “570002”;
varPerson.dateofbirth = “25/06/1977”;
'Calling the strcuture method to manipulate and display the person address
varPerson.displayinfo();

Events


defined in button class and will be raised when the
user clicks the button. The following example shows how the event can be
defined, raised in the class and used by the object user.
Declaration:- The event member will be declared with Event keyword. Basically
the event member should always be public. Because these are the members will
be used by the external users.
'Declare a class which operates on the Employee collection database
'This class is used to find some summarised operation on the Employee
'collction database, which means finding the relavent employee ‘information, 'getting the
total no. of employees in the collection and ‘others - Its just 'an example to explain how
event works
Public Class EmployeeCollection
'Declare an event which will be raised after finding the data
'Keyword ‘Event’ is used the declare the events
Public Event FindResult(ByVal blnFound As Boolean)
'This method is to find the data from employee colletion database and 'raise the findresult
event to return the result
Public Sub FindData(ByVal Name As String)
'find the Employee with name and return the result as boolean, if
'the data is found then raise FindResult with True else with
'False
Dim found As Boolean
found = FineEmployee(Name)
If found Then
'Raise the event with parameter
RaiseEvent FindResult(True)
Else
'Raise the event with parameter
RaiseEvent FindResult(False)
End If
End Sub
End Class
Usage:- In order to access the events of the objects, the object should be
declared with withevents clause. This is shown in the following example with form
load event.
'Declare the object with WithEvents clause to create an instance
Dim WithEvents objEmpColl As EmployeeCollection = New EmployeeCollection()
Public Sub load()
'Find the Employee with name Rama in the Employee collection
objEmpColl.FindData("Rama")
End Sub
'The following event will be raised after the search operation
Private Sub objObject_FindResult(ByValue blnFound as Boolean) Handles
objObject.FindResult
If blnFound Then
MsgBox("The given Employee is Found in the collection")
Else
MsgBox("The given Employee is not Found")
End If
End Sub

Delegates


The Delegate class is one of the most important classes to know how to use
when programming .NET. Delegates are often described as the 'backbone of the
event model' in VB.NET. In this we are going to introduce you to delegates
(Sytem.Delegate class) and show you how powerful of an event mechanism
through delegates.
Delegates are implemented using the delegate class found in the System
namespace. A delegate is nothing more than a class that derives from
System.MulticastDelegate. A delegate is defined as a data structure that refers to
a static method or to a class instance and an instance method of that class. In
other words, a delegate can be used like a type safe pointer. You can use a
delegate to point to a method, much like a callback or the 'AddressOf' operator in
VB.NET. Delegates are often used for asynchronous programming and are the
ideal method for generically defining events.
Before you get into the actual delegate class let us see some code which
simulates the delegate functionality through simple class code for the sake of
understanding. We have a simple class called 'VBDelegate' with two static
methods named 'CallDelegate' and 'DisplayMessage' as shown below. When the
CallDelegate method is called,(when the program is run) to display the message.
Now normally, if we had a class called 'VBDelegate' with a method named
'DisplayMessage'
VB.NET
Public Class VBDelegate
'Static method to call displaymessage function
Public Shared Sub CallDelegate()
DisplayMessage("Some Text")
End Sub
'Static Function to display the message
Private Shared Function DisplayMessage(ByVal strTextOutput As String)
MsgBox(strTextOutput)
End Function
End Class
C#
Public Class CSDelegate
{
'Static method to call displaymessage function
Public static void CallDelegate()
{
DisplayMessage("Some Text")
}
'Static Function to display the message
Private static void DisplayMessage(String strTextOutput)
{
MessageBox.Show(strTextOutput)
}
}
There is nothing wrong with this approach at all. In fact, it is probably more
commonly used than delegates. However, it does not provide much in terms of
flexibility or a dynamic event model. With delegates, you can pass a method
along to something else, and let it execute the method instead. Perhaps you do
not know which method you want to call until runtime, in which case, delegates
also come in handy.
Now we will implement the same functionality as before, using a actual delegate
class of .NET.
Delegates in VB.NET are declared like:
Delegate [Function/Sub] methodname(arg1,arg2..argN)
The declared delegate methodname will have the same method signature as the
methods they want to be a delegate for. This example is calling a shared
method..
VB.NET
Class VBDelegate
'Declaration of delegate variable with arguments
Delegate Function MyDelegate(ByVal strOutput As String)
'Function to call the delegates
Public Shared Sub CallDelegates()
'Declare variables of type Mydelegate points to the
'function MessageDisplay with AddressOf operator
Dim d1 As New MyDelegate(AddressOf MesssageDisplay)
Dim d2 As New MyDelegate(AddressOf MesssageDisplay)
'Pass the arguments to the function through delegates
d1("First Delegation ")
d2("Second Delegation ")
End Sub
'Function to display the message
Private Shared Function MesssageDisplay(ByVal strTextOutput As String)
MsgBox(strTextOutput)
End Function
End Class
C#
Class CSDelegate
{
'Declaration of delegate variable with arguments
delegate void MyDelegate(String strOutput);
'Function to call the delegates
Public static void CallDelegates()
{
'Declare variables of type Mydelegate points to the
'function MessageDisplay
MyDelegate d1 = New MyDelegate(MesssageDisplay);
MyDelegate d2 = New MyDelegate(MesssageDisplay);
'Pass the arguments to the function through delegates
d1("First Delegation ");
d2("Second Delegation ");
}
'Function to display the message
Private static void MesssageDisplay(String strTextOutput)
{
MessgeBox.Show(strTextOutput);
}
}
The Output to the display window is:
First Delegation in one message window
And
Second Delegation in the second message window
What has happened in the above code? Let's take a look
First, we defined a delegate. Remember, when defining a delegate it is very
similar to stating the signature of a method. We have said we want a delegate
that can accept a string as an argument so basically, this delegate can work with
any method that takes the same argument(s).
In our CallDelagates method, we create two instances of our 'MyDelegate'. Then,
we pass into MyDelegate's constructor the address of our 'DisplayMessage'
method. This means that the method we pass into the delegate's constructor (in
this case it's 'DisplayMessage' method) must have a method signature that
accepts a string object as an input argument, just like our delegate does. Now,
you might be thinking, "why are we passing in the address of a method when we
defined our delegate to accept a string object as it's input argument?" In the code
above, we are telling the delegate which method to call, not which string we're
passing in. Carefully understand this concept.
Then finally we have our 'DisplayMessage' method, which takes the string
passed in by the delegate and tells it what string is to be displayed.
The same approach is used while handling the events in the .NET. This topic is
just to understand how delegates works in .NET.

Interfaces


An interface is like an abstract class which allows the derived class to inherit
more than one interfaces into it.
We have already seen an abstract class can have methods with or without
implementation. But an interface can only have members without
implementation. So it provides only structure of the objects like abstract class.
To implement an interface in VB.NET, we use the keyword Implements and we
must provide implementations for all the methods of the interface we implements.
Defining an Interface:- Interfaces are declared with the following structure
Public Interface <Name of the interface>
:
<decleration of memebrs of the interface, means methods and properties
structure>
:
End Interface
Let us take up a example and see how the declaration been done
Interface IShape
Sub Draw(ByVal coord() As ArrayList)
End Interface
interface IShape
{
void Draw(ArrayList coord);
}
Implementation of Interface:- Interfaces are implemented using Implements keyword. All the
members of the interface are implemented with Implements keyword.
“To implement a interface, we must implement all the methods and properties defined by the
interface”
If more than one interface is to be implemented, then interfaces names should separated by
commas with the implements keyword while defining a class.
Lets us take an example of implementation:-
Public Class Drawing
Implements Ishape
Public Sub Draw(ByVal parCoord() As ArrayList) Console.Write("Draw a Circle")
End Sub
End Class
Public Class Drawing: Ishape
{
Public void Draw (ArrayList parCoord)
{
Console.Write("Draw a Circle");
}
}
In the example, we are implementing Isahpe interface, which contains Draw method into the
Drawing Class.

Abstract Classes (Virtual Class)


So far, we have seen how to inherit the class, how to overload and override
methods. In the examples shown in inheritance topic, parent class has been
useful in both inheritance and create an instance also.
Actually in some situation the classes are required only for inheritance, such type
of classes are called Abstract classes. This concept is very useful when
creating a framework for the applications where there will not be any
implementation for the methods and properties in the abstract class. It just
defines the structure.
Abstract classes are declared using MustInherit and MustOverride keyword.
Syntax:-
Public MustInherit Class AbstractBaseClass
Public MustOverride Sub DoSomething()
Public MustOverride Sub DoOtherStuff()
End Class
public abstract class AbstractBaseClass
{
public abstract void DoSomething();
public abstract void DoOtherStuff();
}
MustInherit keyword is used with the class name, where as MustOverride
keyword is used with the members of the class.
Implementaion:-

Public Class DerivedClass
Inherits AbstractBaseClass
Public Overrides Sub DoSomething()
MsgBox("This method is overrides the Base class DoSomething to implement the
method functionality”)
End Sub
Public Overrides Sub DoOtherStuff()
MsgBox(“This method is overrides the Base class DoOtherStuff to implement the
method functionality”)
End Sub
End Class


public class DerivedClass : AbstractBaseClass
{
public Override void DoSomething()
{
MessagegBox.Show("This method is overrides the Base class DoSomething to
implement the method functionality”);
}
public Override void DoOtherStuff()
{
MessaggeBox.Show(“This method is overrides the Base class DoOtherStuff to
implement the method functionality”);
}
}
MustInherit forces the classes to be inherited from the derived class and write
an implementation code for the methods and properties in the derived class
before using it.
As in the above example, any class that inherits AbstractBaseClass must
implement the Dosomething and DoOtherStuff methods.
We cannot create an instance of the AbstractBaseClass as shown below.
Dim obj as New AbstractBaseClass()
‘Error in Decleration
AbstractBaseClass obj = new AbstractBaseClass()
‘Error in Decleration
Restricting Inheritence
If we want to prevent a class being used as a Base class we can use
NotInheritable keyword with the class declaration.
Public NotInheritable Class NormalClass
'Decleration of Class members
End Class
public sealed class NormalClass
{
'Decleration of Class members
}
For example when we want an employee class need not to be used as a Base
class, we can declare the employee class structure with NotInheritable keyword.
So that it can be used only for instantiation.

VB.NET
Class NotInheritable Employee
Inherits Person
Public EmpId As Integer
Private Sal As Double = 0
Public Basic As Double
Public Allowance As Double
Public Deductions As Double
Public Shadows Sub DisplayInfo()
Dim msg As String
msg = MyBase.DisplayInfo("")
msg = msg & "ID : " & EmpId.ToString & vbCrLf
msg = msg & "Basic : " & Basic.ToString & vbCrLf
msg = msg & "Allowances : " & Allowance.ToString & vbCrLf
msg = msg & "Deductions : " & Deductions.ToString & vbCrLf
msg = msg & "Net Salary : " & Basic.ToString & vbCrLf
MsgBox(msg)
End Sub
Public ReadOnly Property Salary() As Double
Get
Return Sal
End Get
End Property
Public Sub ProcessSalary()
Sal = Basic + Allowance - Deductions
End Sub
End Class
Following decleration is not posssible, .NET generates error!!!!
Public Class Staff
Inherits Employee
End Class

C#

class sealed Employee: Person
{
public int EmpId ;
private double Sal = 0;
public double Basic;
public double Allowance;
public double Deductions;
public new void DisplayInfo
{
string msg;
msg = Base.DisplayInfo("");
msg = msg + "ID : " + EmpId.ToString;
msg = msg + "Basic : " + Basic.ToString;
msg = msg + "Allowances : " + Allowance.ToString;
msg = msg + "Deductions : " + Deductions.ToString;
msg = msg + "Net Salary : " + Basic.ToString;
MessageBox.Show(msg);
}
public double Salary
{
get
{
return Sal;
}
}
public void ProcessSalary()
{
Sal = Basic + Allowance – Deductions;
}
}
Following decleration is not posssible, .NET generates error!!!!
Public Class Staff: Employee
{
----
}

Polymorphism


It is the capability to have methods and properties in multiple classes that have
the same name can be used interchangeably, even though each class
implements the same properties or methods in different ways.
Let us understand what is polymorphism with the following example.
Now we will consider the maintenance of company information which includes
employee and customer details. A person (base class) is defined to hold the
common information of the individual. The base class maintains contact
information of the person and manipulates the data. It contains save method to
update the contact information of the person.
Two derived classes, Employee and Customer are used to process the employee
and customer details. These two derived classes inherits person class to
manipulate identity of the person instead of rewriting the same code again in the
derived classes. Since each derived class needs to use the displayinfo method to
display the additional information with the contact details, the displayinfo method
of the base class will be overwritten in the respective derived class using
overrides keyword. The overriding member signature in the derived class must
be as the base class signature.
Signature includes the member type, member name, parameters datatype and
return datatype.
Look into the following example and see the implementation of base class
(Person) and the derived class (Employee), observe the changes in the
displayInfo method in both the classes.

Ex:-
Class Person
Private Name As String
Private Address As String
Public ReadOnly Property PName() As String
Get
Return Name
End Get
End Property
Public ReadOnly Property PAddress() As String
Get
Return Address
End Get
End Property
Public Overridable Function DisplayInfo() As String
Dim msg As String
msg = "Name : " & Name & vbCrLf
msg = msg & "Address : " & Address & vbCrLf
Return msg
End Function
Public Sub Save(ByVal parName As String, ByVal parAddress As String)
Name = parName
Address = parAddress
End Sub
End Class




class Person
{
private string Name;
pPrivate string Address;
public string PName()
{
get
{
return Name;
}
}
public string Paddress
{
get
{
return Address;
}
}
public virtual string DisplayInfo()
{
string msg;
msg = "Name : " + Name;
msg = msg + "Address : " + Address;
return msg;
}
public void Save(string parName, string parAddress)
{
Name = parName;
Address = parAddress;
}
}


Derived Class:-


Class Employee
Inherits Person
Public EmpId As Integer
Private Sal As Double = 0
Public Basic As Double
Public Allowance As Double
Public Deductions As Double
Public Overrides Function DisplayInfo() As String
Dim msg As String
msg = MyBase.DispalyInfo()
msg = msg & "ID : " & EmpId.ToString & vbCrLf
msg = msg & "Basic : " & Basic.ToString & vbCrLf
msg = msg & "Allowances : " & Allowance.ToString & vbCrLf
msg = msg & "Deductions : " & Deductions.ToString & vbCrLf
msg = msg & "Net Salary : " & Sal.ToString & vbCrLf
return(msg)
End Function
Public ReadOnly Property Salary() As Double
Get
Return Sal
End Get
End Property
Public Sub ProcessSalary()
Sal = Basic + Allowance - Deductions
End Sub
End Class


class Employee: Person
{
public int EmpId;
private double Sal = 0;
public double Basic;
public double Allowance;
public double Deductions;
public override string DisplayInfo()
{
string msg ;
msg = base.DispalyInfo();
msg = msg + "ID : " + EmpId.ToString;
msg = msg + "Basic : " + Basic.ToString;
msg = msg + "Allowances : " + Allowance.ToString;
msg = msg + "Deductions : " + Deductions.ToString;
msg = msg + "Net Salary : " + Sal.ToString ;
return(msg)
}
public double Salary
{
get
{
return Sal;
}
}
public void ProcessSalary()
{
Sal = Basic + Allowance – Deductions;
}
}


The following keywords are used in achieving polymorphism.
• Overridable:- A method or property defined in the base class can be
overwritten in the derived class.
• Overrides:- Indicates the method or property is being overwritten in the
derived class.
• Mustoverrides:- A method or property defined in the base class must be
overwritten in the derived class
• Notoverridable:- A method or property defined in the base class must not
be overwritten in the derived class.

Virtual Members :-Virtual members are those that can be overridden and
replaced by the derived classes. They are declared with Overridable keyword.
The methods or properties which doesn’t contain overridable keyword are called
Non-Virtual members.
For ex:- DisplayInfo method is an virtual method of Person base class, because it
has been overwritten in the Employee derived class with new DisplayInfo method
with same signature.

Restricting Polymorphism :-
We have already seen polymorphism is implemented with Overridable and
Overrides keyword. Some situation arises where we need to break the
polymorphism effect of the base class method. It means changing the signature
of the base class member while overriding it in the derived class violates the
polymorhism rule “signatures must be same”. Restriction is required to
completely change the implementation of the member in the derived class. So it
restricts the polymorphism of the base class member with new implementation in
the derived class. The Shadow keyword used to implement this concept.
Take an example shown below which contains two classes 1) Person Class 2)
Employee class.
Person class is a base class contains method to be overwritten from the derived
class. The signature of the overridable method is
Public Overridable Function DisplayInfo() as String
Employee class is a derived class which inherits person class and restricts the
implementation of the polymorphism method displayinfo of the base class with
shadows keyword.
From the above explanation, we can observe that the signature of the DisplayInfo
member is changed from function in the base class to the subroutine in the
derived class with complete change in the implementation.

Ex:-
Base Class:-
Public Shadows Sub DisplayInfo()
Class Person
Public Name As String
Public Address As String
Public Overridable Function DisplayInfo() As String
Dim msg As String
msg = Name & vbCrLf
msg = msg & Address & vbCrLf
Return msg
End Function
Public Sub Save(ByVal parName As String, ByVal parAddress As String)
name = parName
address = parAddress
End Sub
End Class


class Person
{
public string Name;
public string Address ;
public virtual string DisplayInfo()
{
string msg;
msg = Name ;
msg = msg + Address;
return msg;
}
public void Save(string parName, string parAddress)
{
name = parName;
address = parAddress;
}
}


Derived Class:-


Class Employee
Inherits Person
Public EmpId As Integer
Private Sal As Double = 0
Public Basic As Double
Public Allowance As Double
Public Deductions As Double
Public Shadows Sub DisplayInfo()
Dim msg As String
msg = MyBase.DisplayInfo("")
msg = msg & "ID : " & EmpId.ToString & vbCrLf
msg = msg & "Basic : " & Basic.ToString & vbCrLf
msg = msg & "Allowances : " & Allowance.ToString & vbCrLf
msg = msg & "Deductions : " & Deductions.ToString & vbCrLf
msg = msg & "Net Salary : " & Basic.ToString & vbCrLf
MsgBox(msg)
End Sub
Public ReadOnly Property Salary() As Double
Get
Return Sal
End Get
End Property
Public Sub ProcessSalary()
Sal = Basic + Allowance - Deductions
End Sub
End Class


class Employee: Person
{
public int EmpId ;
private double Sal = 0;
public double Basic;
public double Allowance;
public double Deductions;
public new void DisplayInfo
{
string msg;
msg = Base.DisplayInfo("");
msg = msg + "ID : " + EmpId.ToString;
msg = msg + "Basic : " + Basic.ToString;
msg = msg + "Allowances : " + Allowance.ToString;
msg = msg + "Deductions : " + Deductions.ToString;
msg = msg + "Net Salary : " + Basic.ToString;
MessageBox.Show(msg);
}
public double Salary
{
get
{
return Sal;
}
}
public void ProcessSalary()
{
Sal = Basic + Allowance – Deductions;
}
}

Derived Class

VB.NET



Class Customer
Inherits Person
Public CustId As Integer
Public DebitBalance As Double
Public ReadOnly Property Debit() As Double
Get
Return DebitBalance
End Get
End Property
End Class





Class Employee
Inherits Person
Public EmpId As Integer
Private Sal As Double = 0
Public Basic As Double
Public Allowance As Double
Public Deductions As Double
Public ReadOnly Property Salary() As Double
Get
Return Sal
End Get
End Property
Public Sub ProcessSalary()
Sal = Basic + Allowance - Deductions
End Sub
End Class



C#



class Customer:Person
{
public int CustId ;
public double DebitBalance;
public double Debit()
{
get
{
return DebitBalance;
}
}
}







class Employee: Person
{
public int EmpId ;
private double Sal = 0;
public double Basic ;
public double Allowance;
public double Deductions;
public double Salary
{
get
{
return Sal;
}
}
public void ProcessSalary()
{
Sal = Basic + Allowance – Deductions;
}
}


Base Class

VB.NET



Class Person
Public FirstName As String
Public LastName As String
Public Address As String
Public Pincode As String
Public Sub DisplayInfo()
Dim msg As String
msg = FirstName & " " & LastName & vbCrLf
msg = msg & Address & vbCrLf
msg = msg & "PIN – " & Pincode
Msgbox(msg)
End Sub
End Class


C#



class Person
{
public string FirstName;
public string LastName;
public string Address;
public string Pincode;
public void DisplayInfo()
{
string msg;
msg = FirstName + " " + LastName;
msg = msg + Address ;
msg = msg + "PIN – " + Pincode;
MessageBox.Show(msg);
}
}

Inheritence

VB.NET

Class Employee
Public EmpId As Integer
Private Sal As Double = 0
Public Basic As Double
Public Allowance As Double
Public Deducions As Double
Public FirstName As String
Public LastName As String
Public Address As String
Public Pincode As String
Public Sub DisplayInfo()
Dim msg As String
msg = FirstName & " " & LastName & vbCrLf
msg = msg & Address & vbCrLf
msg = msg & "PIN – " & Pincode
Msgbox(msg)
End Sub
Public ReadOnly Property Salary() As Double
Get
Return Sal
End Get
End Property
Public Sub ProcessSalary()
Sal = Basic + Allowance - Deductions
End Sub
End Class


C#

class Employee
{
public int EmpId;
private double Sal = 0;
public double Basic;
public double Allowance;
public double Deducions;
public string FirstName;
public string LastName;
public string Address;
public string Pincode;
public void DisplayInfo()
{
string msg;
msg = FirstName + " " + LastName + vbCrLf;
msg = msg + Address + vbCrLf;
msg = msg + "PIN – " + Pincode;
MesssgeBox.Show(msg);
}
public double Salary
{
get
{
return Sal;
}
}
public void ProcessSalary()
{
Sal = Basic + Allowance – Deductions;
}
}

Constructors


Constructors are special member functions, which are used for initializing the
class data members. In the earlier object oriented programming languages
constructors were quite important since initialization of the data members was
not allowed at the time of declaration. C# however allows us to have the member
variables to be initialized along with declarations. Then why are constructors
required? Well, the variables may not always be initialized to some constants but
can also be initialized with the values specified by the user. There can also be
certain kind of processing to be done while a class is instantiated. So a
constructor happens to be quite important member function in the class as far as
initialization is concerned.
C# supports following types of constructors
• Default Constructors
• Parameterized constructors
• Private constructors
• Static constructors

C# Class Example


public class Employee
{
int Empid;
string EmpName;
string EmpAddress;
double Basic;
public void AddDetails ()
{
---------
---------
}
public void PrintDetails ()
{
---------
---------
}
public void CalcSalary ()
{
---------
---------
}
}

VB.Net Class Example


Public Class Employee
Dim Empid As Integer
Dim EmpName As String
Dim EmpAddress As String
Dim Basic As Double
Public Sub AddDetails ()
---------
---------
End Sub
Public Sub PrintDetails ()
---------
---------
End Sub
Public Sub CalcSalary ()
---------
---------
End Sub
End Class

Polymorphism


The word “polymorphism” means “different forms”. Applied in object-oriented
paradigm it means the ability of an entity to exhibit different forms at runtime.
However, why would such a kind of feature be required? One major reason to
have this is to eliminate the type inspection. As we can see in the earlier case
study that we discussed there would also be a type inspection checking at the
client application level where in the employee entities would be used. So just as
in every functionality, we had checked for the type of employee we will also have
to check in the main function about the type of employee we are handling. With
polymorphism, we can have this level of type inspection also being eradicated
totally.

Inheritance


What is common between a father and a son? At least one thing would be
common – their assets!
In real life, inheritance allows us to reuse things that belong to a particular entity.
Also, in object oriented world a class can inherit the properties and functionalities
defined in some another class so that they can be reused. Then we have to be a
bit careful in designing these classes because reusability cannot be done unless
the classes are of the same type. So the class which would be reusing the
functionalities of the other class in object oriented terms we would say that the
class is “deriving” from the former class and is termed as the derived class. The
class that is being “derived from” is termed as the base class. Inheritance
directly results in the following benefits: --

Reusability: -- Inheritance results in functionalities defined in one class being
reused in the derived classes. So the efforts of rewriting the same functionality
for every derived class is being saved. This definitely saves a lot of development
time.

Enhancement and Specification: -- Due to the characteristic of inheritance, we
can club the common functionalities in the base class and have the specific
functionalities in the derived class. This feature can be used to have a
functionality defined in the base class to be further modified for betterment or
specification by the derived class. This mechanism of redefining the functionality
of the base class in the derived class is termed as “overriding”

Avoiding type inspection:-- In the case study that we discussed to understand
procedural approach we had a strict type inspection routine at the library end
wherein in every function in the library we had to check for the type of the
employee for whom the work has to be done. With inheritance, we would have a
common base class called as “Employee” which would have all the common
functionalities defined where as the specific routines do be done for various types
of employees would go in the respective derived classes. So there would be
class defined for every type of employee and the class would all the
specifications for that type of employee and would be derived from the base
class Employee to inherit the common functionalities. Therefore, in the functions
now we wont have to check for the type of employee every time because every
employee type has its own specific routines defined within it.

Encapsulation


Many a times when we use certain tools, we hardly pay attention to the details
about the functionality of the tool. We hardly pay attention to the various other
units, which make up the tool. This behavior to ignore unwanted details of an
entity is termed as abstraction.
Now if the details are unwanted why show them to the user? Therefore, the
creator might attempt to hide these unwanted details. This behavior is termed as
encapsulation. So we can say that encapsulation is an implementation of
abstraction. Encapsulation directly leads to two main advantages:

Data Hiding: -- The user of the class does not come to know about the internals
of the class. Hence, the user never comes to know about the exact data
members in the class. The user interacts with the data members only through the
various member functions provided by the class.

Data Security: - Since the data, members are not directly available to the user
directly but are available only through the member functions a validity check can
always be imposed to ensure that only valid data is been inserted into the class.
So a Date class, which contains individual data members for storing date, month
and year, will have it ensured the month is never 13 or the date is never
exceeding 31.

Classes


One of the major problems in the earlier approach was also the data and the
functions working upon the data being separate. This leads to the necessity of
checking the type of data before operating upon the data. The first rule of the
object-oriented paradigm says that if the data and the functions acting upon the
data can go together let them be together. We can define this unit, which
contains the data and its functions together as a class. A class can also be
defined as a programmatic representation of an entity and the behavior of that
entity can be represented by the functions in the class. In our earlier case study
the employee, can be represented as a class. A class will contain its data into
various variables, which would be termed as data members and the behavior of
the class, which will be encapsulated, as functions will be termed as member
functions.

Arrays in VB.NET


Till now we have been using variable to store values. We might come across a situation
when we might need to store multiple values of similar type. Such as names of 100
students in a school. One way to do it is to declare 100 variables and store all the names.
A much more simple and efficient way of storing these variable is using Arrays. An
Array is a memory location that is used to store multiple values.
All the values in an array are of the same type, such as Integer or String and are
referenced by their index or subscript number, which is the order in which these values
are stored in the array. These values are called the elements of the array.
The number of elements that an array contains is called the length of the array.
In VB.Net all arrays are inherited from the System.Array Class.
Arrays can be single or multidimensional. You can determine the dimensions of an array
by the number of subscripts that are used to identify the position of any array element.
A single dimensional array is identified by only a single subscript and an element in a
two-dimensional array is identified by two subscripts.
The dimension has to be declared before using them in a program. The array declaration
comprises the name of the array and the number of elements the array can contain.
The Syntax of single dimension array is as follows.

Dim ArrayName (number of elements) as Element Data type.


e.g.
Dim studentname(10) as string
Or
Dim studentname() as string = new string(10)
You can assign the values at runtime or even at the design time.
Design time declaration:
Studentname(0)=”Rohan”
Studentname(1)=”Mohan”
…..
Studentname(10)=”Nitin”
All arrays starts with the index of 0 i.e. All arrays are Zero Based and there is no
provision of an option Base Statement where in you can specify the Lower Bound . This
implies that above array can store 11 elements. Here 0, is the starting index or the lower
bound of the array. The lower bound is fixed for all the arrays.
Example 1.
We will create a VB.Net application that will accept the names of students in an single
dimension array and display it back.
Add a textbox and set the name property to txtnames. Set the multilane property of the
text box to true.
Put a button and write the following in the onclick event.
txtnames.Text = ""
Dim value, count As Integer
'Accept how many students names to enter
value = CInt(InputBox("Enter the number of students name to enter:"))
Dim arrnames(value) As String
Dim cnt As Integer
For cnt = 0 To value
arrnames(cnt) = InputBox("Enter the name of student " & cnt + 1 & ":",
"Student Name")
Next
'Display the entered value to the text box
For cnt = 0 To value
If txtnames.Text = "" Then
txtnames.Text = arrnames(cnt) & vbCrLf ' for carriage returns
Else
txtnames.Text = txtnames.Text & arrnames(cnt) & vbCrLf
End If
Next
Above example will accept number of names to be entered and will add the names in a
loop and then redisplay it in a text box.
The Syntax for multi-dimension arrays is as follows:
Previously we saw how we can store multiple names of students. But, if we want to store
related data of students like first name, middle name, last name. In such situations you
can use multi dimension arrays, such as two-or-three dimension arrays.
Dim ArrayName (number of 1st element, number of 2nd element,….) as element data
type.
Or
Simpler form would be
Dim ArrayName( number of rows, number of columns) as element data type of two
dimension.
e.g.
Dim studentdetails(10,2) as string
Index positions of array elements.
0,0 0,1
1,0 1,1
2,0 2,1
3,0 3,1

10,0 10,1
studentdetails(0,0) = “Manoj”
studentdetails(0,1) = “Malik”
To display “Malik” we need to use the index position of the array and say ,
Studentdetails(0,1).
Example 2.
We will create a VB.Net application, which will accept Student Name, Address and city
name and display it in the text box in a formatted way.
As in the earlier example we will create a text box , change its name and its multi line
property to true.
Change the text box to txtsummary.
Add a button and write the below code in that.
Dim arrsummary(3, 3) As String
Dim i, j As Integer
'As we wanted just 3 columns we have set it to 2, else if u want to be
two only then while declaring the array make it (2,2) as the lower
index is 0.
For i = 0 To 2
For j = 0 To 2
arrsummary(i, j) = InputBox("Enter the value for " & i & " row _
and " & j & " column ", "Summary")
Next
Next
'Display the values in the summary array.
For i = 0 To 2
For j = 0 To 2
If txtsummary.Text = "" Then
txtsummary.Text = arrsummary(i, j)
Else
txtsummary.Text = txtsummary.Text & "-" & arrsummary(i, j)
End If
Next
txtsummary.Text = txtsummary.Text & vbCrLf
Next
Mohan #2/b,4th lane Kanpur
Mike 8th block csd NY
Lim Chou Lane Hong Kong

Dynamic Arrays.
Till now what we read were about fixed arrays. Let us see how we can manipulate the
size of an array at run time.
Many times we feel that the size of array in not enough or too much then required. As we
know that array will allocate memory location when its declared, so to release or add
more we need to change the dimension of the array which has been pre-declared.
We can create a dynamic array by not specifying the size of the array at the time of array
declaration.
Syntax:
Dim student_names() as string
In the above syntax you will see that number of elements are not mentioned. Now to redeclare
the elements we make use of ReDim for an array to change its dimension.
e.g.
Dim student_names() as string
ReDim student_names(10)
ReDim can also change the size of multi-dimensional arrays.
You can change the number of dimensions in an array, but you cannot make a multidimensional
array to a single dimension or lesser than the original dimension.
e.g.
Dim student_details(10,15) as string 'Declaring the array
ReDim student_details(10,25) 'Resizing the array
This statement does not change the data type of the array element or initialize the new
values for the array elements.
This statement can be used at the procedure level only not at the class level or module
level.
ReDim statements reinitializes the value of arrays with the respective data type declared
by the array.
If u have initialized the array to a some values it will be lost during the time of resizing
and the default values will be restored in those elements.
E.g.
'Declaring the array and initializing the value for the array
dim students_names() as string = {“Rahul”}
'This will display the value Rahul
msgbox(students_names(0))
Now resizing the array.
ReDim students_names(10)
'This will give a fixed size to 10 elements
msgbox(students_names(0))
This will display a blank value, as during the resizing the values of the array are
reinitialized to default value of string which is blank.
Now to avoid such problems we will make use of a keyword called Preserve while
resizing the array to new value.
Using the above example , we will make changes in the declaration.

ReDim students_names(10) 'The old declaration
ReDim Preserve students_names(10)
Students_names(1) = “Alex”
Students_names(2) = “Michael”
Msgbox(students_names(0))


This will display the value as ‘Rahul’ which we had initialized before resizing it. So
Preserve will restore all the initialized value of elements declared in an array.
If the array is an two or more dimensional array , you can only change the size of the last
dimension by using preserve keyword.
Dim student_details(10,20) as string
ReDim preserve student_details(15,25)
This will raise error because we are trying to change the first dimension also. So u can
only change the last dimension in case of multi-dimensional array.
Few Important methods in arrays.
Ubound() and Lbound().
Ubound is to get the upper limit of an array.
Lbound is to get the lower limit of an array by default lower limit is 0.
e.g.

Dim weeks() As String = {"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"}
Dim upper As Integer
Dim lower As Integer
upper = UBound(weeks)
lower = LBound(weeks)
MsgBox(upper.ToString & " - " & lower.ToString)
You will get 6 – 0 as the answer.


If you count the number of elements initialized elements its seven, but all arrays starts
with lower bound as 0. So from 0 – 6 is equal to 7 elements.
This works for single dimension , but for multi-dimensions,
We make use of the following:
Getupperbound(), getlowerbound() these functions are methods of the array class.
You can use it with single dimension also but best for multi-dimensional arrays.
Syntax : arrayname.getupperbound/getlowerbound(dimension)
Dimension refers to the which upper/lower bound should be found, 0 for first, 1 for
second and so on.
example.
Dim student_details(10,20,15)
Dim upperlimit as integer
upperlimit = student_details.getupperbound(0)
' This will return 10 for the 1st row element
upperlimit = student_details.getupperbound(1)
' This will return 20 for the 2nd row of element
For all getlowerbound(dimension) it will return 0 as the base lower bound is zero in .NET

Control Statements in VB.NET


VB.Net has statements such as If .. Then ..else and Select …. Case, which help you to
conditionally execute program.
VB.Net provides you with various looping statements, such as Do… Loop, While…. End
While, and For… Next.

1. The If….Then….Else…End if Statement
Consider a student marks and grade evaluation. For Marks above 75 the grade is ‘A’ and
for below 75 is ‘B’. In this situation when you need to execute some code based on some
condition, you can make use of, If…then…else…end if.
The Cultural syntax normally used is as follows:
If condition Then
Executable statements when the condition is True
Else
Executable statements when the Condition is False
End If
OR using Elseif for Advanced Decision making
If condition Then
Executable statements
ElseIf condition Then
Executable statements
End If
Single if can have multiple else with conditions, as mentioned above in elseif format and
finally a single End If for the main If condition.
Nesting IF…Then Constructs
If condition Then
If condition2 Then
Executable statements when the condition2 is TRUE
Else
Executable Statements
End if
Else
Executable statements
End If
One important thing to keep in mind when nesting IF…Then constructs is that you must have corresponding End If statement for
every IF ..Then statement, unless the If then statement executes only one statement and that statement appears on the same line as
If…Then

2. The Select…Case Statement(Evaluating an Expression for Multiple Values)
The Select…Case Statement is similar to If…Else…End if. The only difference between
two is that If and elseif can evaluate different expressions in each statement, but the
Select statement can evaluate only one expression.
The drawback of IF...Then construct is that it isn’t capable of handling a decision
situation without a lot of extra work. One such situation is when you have to perform
different actions based on numerous possible values of an expression, not just True or
False. For instance performing actions based on Students Marks.
If intmarks >35 Then
…….
Elseif intmarks >50 then
……
Elseif intmarks>65 then
…..
Elseif intmarks>75 then

Else
….
End If
As you see the structure can be a bit hard to read and if the conditions increase you may
end up writing a confusing and an unreadable piece of Code
The Select uses the result of an expression to execute different set of statements.
The syntax for the Select…Case Statement is as follows:

Select Case [expression]
Case [expression list]
Executable statements.
Case Else
Executable statements.
Exit Select - to exit from the select
End Select


Note: Case Else is used to define the code that executes only when the expression doesn’t
evaluate to any of the values in Case Statements .Use of Case Else is optional
Lets see the same example as above but this time with Select Case

Select Case intmarks
Case Is >35
Executable statements
Case Is >50
Executable statements
Case Is>65
Executable statements
Case Is >75
Executable statements
Case Else
Executable statements
End Select


Evaluating More than one possible Value in a Case Statement
Select Case helps you to use some more advanced expression comparisons. Like,you can
specify multiple comparisons in a Single Case statement by just using comma. Lets see
how it does

Select Case strColor
Case Is=”Red”,”Blue”,”Magenta”
‘Color is a Dark Shade
Case Is =”Cream”,”white”
‘Color is a Cool Shade
End Select


Another comparison expression used is keyword To, Visual Basic.NET evaluates the
expression and finds out whether it is in the range mentioned and if yes the Statement is
executed. Please note that when using To, you can’t include Is = as you can with the
simple expression

Select Case intmarks
Case 1 to 35
‘Executable statements
Case 36 to 50
‘Executable Statements
End Select

3. For…Next Statement
The For…Next Statements are used repeat a set of statements for specific number of
times.
The syntax for the For…Next Statements is as follows:

For counter = <start value> to <end value> [Step Value]
Executable Statements
Exit For
Next [counter]


Counter is any numeric value.
Start value is the initial value of the counter.
End value is the final value of the counter.
Step Value is the value by which the counter is incremented. It can be positive or
negative. The default value is 1.
Exit For is used to exit the For…Next loop at any time. When Exit for is encountered
,the execution jumps to the statement following Next
Next is the statement the marks the end of the For statement. As soon as the program
encounters the Next statement, the step value is added to the counter and the next
iteration of the loop takes place.

Dim intctr as Integer
For intctr=1 to 100
Debug.WriteLine(intctr)
Next intctr


This routine starts a loop with a For statement after a variable intctr is declared. This loop
initializes intctr to 1 and then prints 1 through 100 to the output window. It prints in steps
of 1 as Step has been omitted here, so the default is 1
Example of use of STEP in For....Loop.
Let us write a table of 2 using step in for loop.
Add a label with name it as lbtables and make it bit bigger on the screen.

Dim j = 1
For i = 2 To 20 Step 2
Me.lbtables.Text = Me.lbtables.Text & "2 X " & j.ToString & " = " &
i.ToString & vbCrLf
j = j + 1
Next
Output:
2 X 1 = 2
..
..
..
..
..

2 X 10 = 20


An Example of Nested For loop.
Let us write a small code to display a structure of stars ‘*’ in triangle format.
*
* *
* * *
* * * *
* * * * *
* * * * * *
Let us have a label with name stars. Increase the height of the label to get a clear view of
the image.

Dim star As String
Dim i, j As Integer
For i = 0 To 5 ' First loop to count the rows
For j = 0 To i ' Second loop to count the columns
star = star & " * "
Next
Me.stars.Text = Me.stars.Text & star & vbCrLf ' To print *
star = ""
Next


4. For Each…Next Statement
The For Each…Next Statement is used to repeat a set of statements for each element in
an array or collection.
The For Each…Next statement is executed if there is at least one item in an array of
collection.
The Loop repeats of each element in an array or collection.
The syntax for the For Each…Next statement as follows:

For Each Component In Set
Executable statements
Next


Component is the variable used to refer to the elements of an array or a collection.
Set refers to an array or any collection object. e.g.

Dim weeks() As String = {"Monday", "Tuesday", "Wednesday", "Thursday",_
"Friday", "Saturday", "Sunday"}
Dim eachday As String
For Each eachday In weeks
MsgBox(eachday)
Next


An example for using for each element in a collection of string into a single string
element.
Each element of array which is of type string is read from the collection and stored into
the single string type object.

5. While…End Statement
The While…End Statement is used to repeat set of executable statements as long as the
condition is true.
The syntax for the While…End statement is as follows:

While Condition
Executable Statements
End While


In this if the condition is satisfied then the statements are executed. Else it will not
enter the While condition at all.

6. Do...Loop Statement
The Do…Loop Statement is similar to While…End. Here we have two types of
formatting the loop.
a) Do While / Until Condition Executable Statements Loop
b) Do Executable Statements Loop While/Until Condition
The Difference is in a) The loop will be executed if the condition is satisfied, but in b)
The Loop will be executed at least once even if the condition does not satisfy.

Do While Expression
[Statements]
Loop
Do Until Expression
[Statements]
Loop


Note: For VB programmers While Wend is not supported it is While… End now

A Complete Example with set of control statements.

We will create a VB.Net application, which will accept students name and its grade.
Depending up the type of grade it will add remarks.

txtsummary.Text = ""
Dim value, ctr As Integer
'Accept a number from the user
value = CInt(InputBox("Enter the number of students"))
'Check if the validity of the number
If value <= 0 Then
MsgBox("Enter details of at least one student", "Error")
End If
Dim arrName(value) As String
Dim sGrade As String
Dim arrRemarks(value) As String
While ctr < value
'Accept the name of the students
arrName(ctr) = InputBox("Enter the name of the Student"_
& ctr + 1, "Enter Details")
'Accept the grade of the Student
sGrade = InputBox("Enter the grade of the student" &
"(_A/B/C/D/F)", "Grade Details")
' Assign remarks to students
Select Case UCase(sGrade)
Case "A"
arrRemarks(ctr) = "Excellent"
Case "B"
arrRemarks(ctr) = "Good"
Case "C"
arrRemarks(ctr) = "Fair"
Case "D"
arrRemarks(ctr) = "Poor"
Case "F"
arrRemarks(ctr) = "Fail"
Case Else
MsgBox("Incorrect value entered ", _
MsgBoxStyle.Critical)
Exit Sub ' To come out of the program
End Select
ctr = ctr + 1
End While
' Display the summary in the text box
For ctr = 0 To value - 1
If txtsummary.Text = "" Then
If LCase(arrRemarks(ctr)) = "fail" Then
txtsummary.Text = arrName(ctr) & " has failed _
in exams" & vbCrLf
Else
txtsummary.Text = arrName(ctr) & "'s performance is_
" & arrRemarks(ctr) & vbCrLf
End If
Else
If LCase(arrRemarks(ctr)) = "fail" Then
txtsummary.Text = txtsummary.Text & arrName(ctr) &_
" has failed in exams" & vbCrLf
Else
txtsummary.Text = txtsummary.Text & arrName(ctr) &_
"'s performance is " & arrRemarks(ctr) &_ vbCrLf
End If
End If
Next

Features of VB.NET


Option Explicit and Option Strict
Option Explicit and Option Strict are compiler options that can be globally assigned to a
project and are interpreted at compile time. Setting these options enables programmers to
resolve some of the errors (e.g. typological errors) at compile time and thus prevent
runtime errors.

Option Explicit
Option Explicit was a feature of VB 6.0 and it has been made a part of .NET environment
too. This option can be used only at the module level. When this option is turned on, it
forces explicit declaration of variables in that module. This option can be turned "On" or
"Off". When it is not specified, by default, it is set to "Off".
Syntax: Option Explicit [On / Off]
When it is set to "On", it checks for any undeclared variables in the module at compile
time. If any undeclared variable is found, it generates a compile time error since the
compiler would not recognize the type of the undeclared variable. When it is set to "On",
variables can be declared using Dim, Public, Private or ReDim statements. Setting this
option to "On" helps programmers do away with any typological errors in the code.
When it is set to "Off", all undeclared variables are considered to be of type Object.
It is preferable to set this option to "On".

Option Strict
Visual Basic language in general does not require explicit syntax to be used when
performing operations that might not be optimally efficient (e.g. late binding) or that
might fail at run time (e.g. narrowing conversions). This permissive semantics often
prevents detection of coding errors and also affects the performance of the application.
VB.NET enables a programmer to enforce strict semantics by setting this option to "On".
When used, this option should appear before any other code. This option can be set to
"On" or "Off". If this statement is not specified, by default, it is set to "Off".
Syntax: Option Strict [On / Off]

When it is set to "On", it disallows any narrowing conversions to occur without an
explicit cast operator, late binding and does not let the programmer omit "As" clause in
the declaration statement. Since setting it to "On" requires explicit conversion, it also
requires that the compiler be able to determine the type of each variable. Thus it is
implied that Option Strict also means Option Explicit.
Visual Basic .NET allows implicit conversions of any data type to any other data type.
However, data loss can occur if the value of one data type is converted to a data type with
less precision or a smaller capacity. Setting this option to "On" ensures compile-time
notification of these types of conversions so they may be avoided.
Explicit conversions happen faster than the implicit conversions performed by the
system. In case of implicit conversions, the system has to identify the types involved in
the conversion and then obtain the correct handler to perform the conversion. In case of
explicit conversions, processing time gets reduced since the type of conversion is
explicitly mentioned.
From programmer point of view, explicit conversion may seem to be a burden since it
slows the development of a program by forcing the programmer to explicitly define each
conversion that needs to occur.
It is always recommended that you set Option Strict to "On" and use explicit conversions.
ByVal is Default
When implementing functions/procedures we often need to pass information. This
information can be passed to the called function/procedure through parameters.
Parameters can be passed by value or by reference.
When ByVal keyword is used, it causes the parameter to be passed by value. In this case,
a copy of the original parameter is passed to the called module. Thus any changes made
to the copy of the parameter do not affect the original value of the parameter.
When ByRef keyword is used, it sends a reference (pointer) to the original value to the
called module rather than its copy. Thus any changes made to the parameter in the
function/procedure will cause the original value to be modified.
With ByRef you are exposing a variable to modification which can lead to an unexpected
behavior. If that procedure calls another procedure and passes the same parameter ByRef,
the chances of unintentionally changing the original variable are increased.
In VB.NET, every parameter, by default, is passed by value if nothing is explicitly
specified. Thus it protects arguments against modification.

Example:
Public Class SampleClass
Sub Proc(ByVal a As Integer, b As Integer, ByRef c As Integer)
a = a + 2
b = b + 3
c = c + 4
End Sub
End Class
Sub Main()
Dim num1, num2, num3 As Integer
Dim Obj As New SampleClass()
num1 = 2
num2 = 3
num3 = 4
Obj.Proc(num1, num2, num3)
System.Console.WriteLine(num1)
System.Console.WriteLine(num2)
System.Console.WriteLine(num3)
End Sub


Explanation:
In the class SampleClass, there is one procedure Proc that takes three integers as
arguments. In Main(), a variable of type SampleClass is defined and three other integer
variables num1,num2,num3 are declared and given some initial values. The procedure is
then called passing these three variables as arguments. First variable num1 is passed by
value, second variable num2 is also passed by value since nothing is specified explicitly
and the last variable num3 is passed by reference since it is explicitly mentioned.
After calling the procedure, when the values of the three variables are checked, you will
notice that num1 and num2 retain their original values since they are passed by value
whereas the value of num3 changes to 8 since it was passed by reference.
Sub and Functions with Parenthesis
In VB.NET, both functions and procedures require parentheses around the parameter list,
even if it is empty.

Example:
Consider the following code that contains two functions and one procedure. The first
function named "HelloWorld" accepts no argument and returns "Hello World". The
second function named "HelloName" accepts an argument and appends that argument to
the string "Hello World" and finally returns the appended string. The procedure named
"Hello" displays the string "Hello World" on the console.

Public Class SampleClass
Function HelloWorld( ) As String
Helloworld = "Hello World"
End Function
Function HelloName(ByVal name As String) As String
HelloName = "Hello " & name
End Function
Sub Hello()
System.Console.WriteLine("Hello World")
End Sub
End Class
Sub Main()
Dim Obj As New SampleClass()
Dim str1 As String
Dim str2 As String
str1 = Obj.HelloWorld()
str2 = Obj.HelloName(" Everybody")
Obj.Hello()
End Sub


Explanation:
As mentioned, while calling the procedure Hello, parentheses have to be used even
though it does not require any argument. Similar treatment has to done for functions.
Structures Replace User Defined Types
In VB.NET, structures can be defined using Structure keyword. Unlike user defined
types, structures share many features with classes. Explicit mention of access modifier for
each member is necessary in VB.NET. Access modifiers can be Public, Protected,
Friend, Protected Friend, or Private. You can also use the Dim statement, which
defaults to public access.
Let us take an example of a Person that will have some characteristics as Name, Address,
Tel, Age etc. Now if we were to use this number of times, it will be better to have a type
called Person. The example below shows how to handle this.

Structure Person
Structure Person
Dim Name as String
Private Address as String
Dim Tel as String
Public Age as Integer
End Structure
As shown in the above code, explicit mention of the access specifier for each member is a
must.
Structures, like classes, can contain data members as well as data methods. Structures are
value types and are hence allocated on the stack where as classes are reference types and
require heap allocation.
Block Level Scope
The scope of block level variables is restricted to the block in which they are defined.
This block can be a function, procedure, a loop structure etc. A block level variable is not
accessible anywhere, outside its block.

Example:
Consider the sample code segment.
Sub BlockScope()
Dim a As Integer = 1
Dim i As Integer = 1
While (i <= 2)
Dim j As Integer = 1
j = j + 1
i = i + 1
End While
a = a + j
End Sub


Explanation:
The above code segment will give a compile-time error, since the scope of the variable ‘j’
is restricted to the while block and hence it is not accessible outside the while block.
Though block level variables cannot be accessed outside their block, their lifetime is still
that of the procedure containing them.

Early Vs Late Binding
In case of early binding, the compiler knows the object's data type at compile time and
hence can directly compile code to invoke the methods on the object. This enables the
compiler to discover the appropriate method and ensure that the referenced method does
exist and the parameters provided are in sync with that of the referenced method.
Since object types are known ahead of time, the IDE aids the programmer by providing
support for IntelliSense. This helps the programmer do away with any typological and
syntactical errors. If the method being referenced is not found, the programmer is notified
at compile time thus letting him rectify it rather than making him wait till the application
is run.
In case of late binding, the compiler cannot determine the object's data type and thus the
code interacts with the object dynamically at runtime. To make an object late-bound, it is
defined as a variable of type Object. This variable can reference any type of object and
allows programmers to attempt arbitrary method calls against the object even though the
Object datatype does not implement those methods. Since type of the object is not
known until runtime, neither compile-time syntax checking nor IntelliSense is possible.
The typological errors also go undetected until the application is run. However, there is
an unprecedented flexibility, since code that makes use of late binding can talk to any
object from any class as long as those objects implement the methods we require.
The discovery of the referenced method is done dynamically done at runtime and is then
invoked. This discovery takes time and the mechanism used to invoke a method through
late binding is not as efficient as that used to call a method that is known at compile time.
Thus, though late binding is flexible, it is error-prone and slower as compared to early
binding.
When Option Strict is "On", it does not support late binding since the datatype of the
object should be known at compile time.

Example:
Consider the below given code segment
Public Class SampleClass
Public Sub Proc()
MessageBox("This method is discovered dynamically at runtime")
End Sub
End Class
Public Class MainClass
Shared Sub Main()
Dim Obj As Object
Obj = New SampleClass()
Obj.Proc()
End Sub
End Class


Explanation:
The above code segment implements late-binding. There are two classes viz.
SampleClass and MainClass. The class SampleClass contains a procedure named Proc
that takes no arguments. This procedure displays an appropriate message in a message
box. The class MainClass declares a variable Obj of type Object. Thus at compile-time,
the actual data type of the variable is not known. At runtime, the system finds that it is
referencing a variable of type Sampleclass. This reference to the class is achieved using
new operator. The referenced method Proc is discovered at runtime and is finally
invoked.
Ctype Function
Ctype is a general cast keyword that coerces an expression into any type. It returns the
result of explicitly converting an expression to a specified data type, object, structure,
class, or interface. If no conversion exists from the type of the expression to the specified
type, a compile-time error occurs. When Ctype is used to perform explicit conversion,
execution is faster since it is compiled inline and hence no call to a procedure is involved
to perform the conversion.
Syntax: Ctype (expression, type name)

Example:
Consider the below given code segment
Public Class TrialClass
Sub Proc (obj as Object)
Dim Obj1 As OtherClass( )
Obj1 = Ctype (obj, OtherClass)
Obj1.OtherProc( )
End Sub
End Class


Explanation:
The variable Obj1 is of type OtherClass. This class has a procedure named OtherProc.
In the above code segment, the procedure Proc takes one parameter of type Object. The
Ctype statement gains an early bound reference to the object of type OtherClass. Thus
performance benefits of early binding can be achieved.

Changes to Boolean Operators
In Visual Basic.NET, And, Or, Xor, and Not are the boolean operators and BitAnd,
BitOr, BitXor, and BitNot are used for bitwise operations.
VB.NET has introduced the concept of short-circuiting. According to this concept, if the
first operand of an And operator evaluates to False, the remainder of the logical
expression is not evaluated. Similarly, if the first operand of an Or operator evaluates to
True, the remainder of the logical expression is not evaluated.
To perform the above mentioned functionality, VB.NET has introduced two new
operators viz. AndAlso and OrElse. AndAlso performs short-circuiting logical
conjunction on two expressions whereas OrElse performs short-circuiting logical
disjunction on two expressions
Syntax : expression1 AndAlso expression2
expression1 OrElse expression2
Structured Error Handling
The whole idea behind error handling is to accurately trap the error. VB.NET has
introduced a structured approach for handling errors, in order to keep in sync with the
features offered by all Object Oriented languages viz. C#, Java etc. This structured
approach is implemented using a Try…Catch…Finally block structure and is known as
Exception Handling.
Try statement comes before the block of code that needs to tested for errors, Catch
statement handles specific errors and hence surrounds the block of code that handles
those errors and Finally block of code is always executed and contains cleanup routines
for exception situations. Since Catch block is specific to the type of error that needs to be
caught, a single Try statement can have multiple Catch blocks associated with it.

Example:
Consider the below given code segment
Dim num1 As Integer
Dim num2 As Integer
Dim num3 As Integer
Dim str As String
num1 = CType(System.Console.ReadLine( ), Integer)
num2 = CType(System.Console.ReadLine( ), Integer)
str = System.Console.ReadLine( )
Try
num3 = num1 / num2
num1 = CType(str, Integer)
Catch e1 As System.InvalidCastException
System.Console.WriteLine("There is a casting error")
Catch e2 As System.OverflowException
System.Console.WriteLine("There is an overflow error")
Finally
System.Console.Writeline("Please enter valid input")
End Try


Explanation:
The above code segment has been written with an intention of creating an error to explain
the structured way of trapping errors. As shown, it accepts two integers and one string
from the user and tries to divide first number by the second number and also tries to
convert the entered string to an integer. Since the statements that divide the numbers and
perform casting are critical, they are put in the Try…Catch…Finally block structure.
The code segment has two Catch statements viz. first statement handles the casting
(wrong format) error while the second one handles the overflow (division) error.
If the user will enter zero as the second number, then the code will throw an overflow
exception which will be handled by displaying the error message on the Console.
Similarly, if the user will enter a string say "Hello" as the third argument, the code will
throw an invalidcast exception which will be handled by displaying the error message on
the Console. In both the cases, the Finally block of code is always executed. Finally
block is even executed, when there is no error in the program. Thus it is the right place to
perform cleanup routines.
This structured approach provided by VB.NET lets the programmer track the precise
location of the error in the code.
Data Type Changes
Integer
Integer Type VB.NET CLR Type
8-bit Integer Byte System.Byte
16-bit Integer Short System.Int16
32-bit Integer Integer System.Int32
64-bit Integer Long System.Int64
Boolean
A Boolean variable can be assigned one of the two states viz. True or False.
In VB.NET, when numeric types are converted to Boolean values, 0 becomes False and
all other values become True.
When Boolean values are converted to Integer values, True maps to -1 and False maps
to 0.
String
To be inline with other .NET languages, VB.NET has updated string length declaration.
In VB.NET, you cannot declare a string to have a fixed length. You must declare the
string without a length. When a value gets assigned to the string, the length of the value
determines the length of the string.

Using Authorization with Swagger in ASP.NET Core

 Create Solution like below LoginModel.cs using System.ComponentModel.DataAnnotations; namespace UsingAuthorizationWithSwagger.Models {     ...