VB.NET


Introduction

Visual Basic .NET is an Object-Oriented programming language designed by Microsoft. With the word “Basic” being in the name of the language, you can already see that this is a language for beginners. Although the language is aimed at noobs and novices, you should not underestimate the power of the language itself. There are people who criticize VB.NET because of the simplicity of the syntax, but VB.NET has the ability to create very powerful and sophisticated applications. VB.NET is a great place to start because of how easy and straight forward it is. The syntax is easy and you will not find yourself writing hundreds of lines of code as there are many shortcuts that make coding so much easier in this language.
If you have had any experience in computer programming, you should understand what a syntax is and the purpose of it. If not, let’s take a look at the VB.NET syntax. The purpose of typing code is to instruct the application what to do. It’s not as easy as typing “Hey application, multiply 5 by 8″ but it’s pretty darn close! If you wanted to tell your application to show a Message Box telling you that HowToStartProgramming.com is awesome, this would be the code you would use:
MessageBox.Show("HowToStartProgramming.com is awesome")
Wow pretty easy right? I bet you thought that you would be typing 0′s and 1′s like in binary! Well now that you have looked at the syntax for VB.NET, you are ready to start your first tutorial. Please select the first tutorial from the list below and begin watching.

Complete Comparison for VB.NET and C#

Some people like VB.NET's natural language, case-insensitive approach, others like C#'s terse syntax. But both have access to the same framework libraries.

Differences
  1. In C#, using keyword is used to release unmanaged resources. (Not available in VB.NET)
  2. Optional parameter is supported in VB.NET. (Not available in C#).
  3. Structure and unstructured error handling (On Error GoTo) is supported in VB.NET. (Unstructured error handling is not supported in C#).
  4. Event gets bind automatically in VB.Net.
  5. VB.NET is not case sensitive where C# is.
  6. Shadowing: – This is a VB.Net Concept by which you can provide a new implementation for the base class member without overriding the member. You can shadow a base class member in the derived class by using the keyword “Shadows”. The method signature, access level and return type of the shadowed member can be completely different than the base class member.

    Hiding
    : – This is a C# Concept by which you can provide a new implementation for the base class member without overriding the member. You can hide a base class member in the derived class by using the keyword “new”. The method signature, access level and return type of the hidden member has to be same as the base class member. Comparing the two:- 1) The access level, signature and the return type can only be changed when you are shadowing with VB.NET. Hiding and overriding demands these parameters as same.
    2) The difference lies when you call the derived class object with a base class variable. In class of overriding although you assign a derived class object to base class variable it will call the derived class function. In case of shadowing or hiding the base class function will be called.
  7. Visual Basic .NET can also force parameters to be passed by value, regardless of how they are declared, by enclosing the parameters in extra parentheses. There is no way to achieve this thing in C#.
    For Example:

    Dim y As Integer = 5
    Dim z As Integer
    z = Add(y) //This will set both Y and Z to 6.
    z = Add((y)) //This will set Z to 6 but Value of Y will not be change, as we have included extra parenthese while calling.

               
    The Add function:

    Public Function Add(ByRef x As Integer) As Integer
    x = x + 1
    Return x
    End Function

Comparison
VB.NETProgram StructureC#
Imports System

Namespace Hello
   Class HelloWorld
      Overloads Shared Sub Main(ByVal args() As String)
         Dim name As String = "VB.NET"

         'See if an argument was passed from the command line          If args.Length = 1 Then name = args(0)

          Console.WriteLine("Hello, " & name & "!")
      End Sub
   End Class
End Namespace
using System;

namespace Hello {
   public class HelloWorld {
      public static void Main(string[] args) {
         string name = "C#";

         // See if an argument was passed from the command line         if (args.Length == 1)
            name = args[0];

         Console.WriteLine("Hello, " + name + "!");
      }
   }
}

VB.NETCommentsC#
' Single line only
REM Single line only
''' <summary>XML comments</summary>
// Single line
/* Multiple
    line  */
/// <summary>XML comments on single line</summary>
/** <summary>XML comments on multiple lines</summary> */


VB.NETData TypesC#
Value TypesBoolean
Byte, SByte
Char
Short, UShort, Integer, UInteger, Long, ULong
Single, Double
Decimal
Date   (alias of System.DateTime)structures
enumerations
Reference TypesObject
String
arrays
delegates
InitializingDim correct As Boolean = True
Dim b As Byte = &H2A   'hex or &O52 for octalDim person As Object = Nothing
Dim name As String = "Dwight"
Dim grade As Char = "B"c
Dim today As Date = #12/31/2010 12:15:00 PM#
Dim amount As Decimal = 35.99@
Dim gpa As Single = 2.9!
Dim pi As Double = 3.14159265
Dim lTotal As Long = 123456L
Dim sTotal As Short = 123S
Dim usTotal As UShort = 123US
Dim uiTotal As UInteger = 123UI
Dim ulTotal As ULong = 123UL
Nullable TypesDim x? As Integer = Nothing
Anonymous TypesDim stu = New With {.Name = "Sue", .Gpa = 3.4}
Dim stu2 = New With {Key .Name = "Bob", .Gpa = 2.9}
Implicitly Typed Local VariablesDim s = "Hello!"
Dim nums = New Integer() {1, 2, 3}
Dim hero = New SuperHero With {.Name = "Batman"}
Type InformationDim x As Integer
Console.WriteLine(x.GetType())          ' Prints System.Int32
Console.WriteLine(GetType(Integer))   ' Prints System.Int32
Console.WriteLine(TypeName(x))        ' Prints Integer

Dim c as New Circle
isShape = TypeOf c Is Shape   ' True if c is a Shape

isSame = o1 Is o2   // True if o1 and o2 reference same object
Type Conversion / CastingDim d As Single = 3.5
Dim i As Integer = CType(d, Integer)   ' set to 4 (Banker's rounding)i = CInt(d)  ' same result as CTypei = Int(d)    ' set to 3 (Int function truncates the decimal)

Dim s As New Shape
Dim c As Circle = TryCast(s, Circle)   ' Returns Nothing if type cast failsc = DirectCast(s, Circle)   ' Throws InvalidCastException if type cast fails

Value Typesbool
byte, sbyte
char
short, ushort, int, uint, long, ulong
float, double
decimal
DateTime   (not a built-in C# type)structs
enumerations
Reference Typesobject
string
arrays
delegates
Initializingbool correct = true;
byte b = 0x2A;   // hexobject person = null;
string name = "Dwight";
char grade = 'B';
DateTime today = DateTime.Parse("12/31/2010 12:15:00 PM");
decimal amount = 35.99m;
float gpa = 2.9f;
double pi = 3.14159265;   // or 3.14159265Dlong lTotal = 123456L;
short sTotal = 123;
ushort usTotal = 123;
uint uiTotal = 123;   // or 123Uulong ulTotal = 123;   // or 123UL
Nullable Typesint? x = null;
Anonymous Typesvar stu = new {Name = "Sue", Gpa = 3.5};
var stu2 = new {Name = "Bob", Gpa = 2.9};   // no Key equivalent
Implicitly Typed Local Variablesvar s = "Hello!";
var nums = new int[] { 1, 2, 3 };
var hero = new SuperHero() { Name = "Batman" };
Type Informationint x;
Console.WriteLine(x.GetType());              // Prints System.Int32Console.WriteLine(typeof(int));               // Prints System.Int32
Console.WriteLine(x.GetType().Name);   // prints Int32

Circle c = new Circle();
isShape = c is Shape;   // true if c is a Shape

isSame = Object.ReferenceEquals(o1, o2)   // true if o1 and o2 reference same object
Type Conversion / Casting
float d = 3.5f;
i = Convert.ToInt32(d);     // Set to 4 (rounds)
int i = (int)d;     // set to 3 (truncates decimal)


Shape s = new Shape();
Circle c = s as Circle;   // Returns null if type cast failsc = (Circle)s;   // Throws InvalidCastException if type cast fails
VB.NETConstantsC#
Const MAX_STUDENTS As Integer = 25 ' Can set to a const or var; may be initialized in a constructorReadOnly MIN_DIAMETER As Single = 4.93 const int MAX_STUDENTS = 25; // Can set to a const or var; may be initialized in a constructor readonly float MIN_DIAMETER = 4.93f;

VB.NETEnumerationsC#
Enum Action
  Start
  [Stop]   ' Stop is a reserved word  Rewind
  Forward
End Enum

Enum Status
  Flunk = 50
  Pass = 70
  Excel = 90
End Enum
Dim a As Action = Action.Stop
If a <> Action.Start Then _
   Console.WriteLine(a.ToString & " is " & a)     ' Prints "Stop is 1"

Console.WriteLine(Status.Pass)     ' Prints 70
Console.WriteLine(Status.Pass.ToString())     ' Prints Pass

enum Action {Start, Stop, Rewind, Forward};
enum Status {Flunk = 50, Pass = 70, Excel = 90};

Action a = Action.Stop;
if (a != Action.Start)
  Console.WriteLine(a + " is " + (int) a);    // Prints "Stop is 1"Console.WriteLine((int) Status.Pass);    // Prints 70
Console.WriteLine(Status.Pass);      // Prints Pass
VB.NETOperatorsC#
Comparison=  <  >  <=  >=  <>
Arithmetic+  -  *  /
Mod
(integer division)(raise to a power)
Assignment=  +=  -=  *=  /=  \=  ^=  <<=  >>=  &=
BitwiseAnd   Or   Xor   Not   <<   >>
LogicalAndAlso   OrElse   And   Or   Xor   Not
Note: AndAlso and OrElse perform short-circuit logical evaluations
String Concatenation&
Comparison==  <  >  <=  >=  !=
Arithmetic+  -  *  /
(mod)(integer division if both operands are ints)Math.Pow(x, y)
Assignment=  +=  -=  *=  /=   %=  &=  |=  ^=  <<=  >>=  ++  --
Bitwise&   |   ^   ~   <<   >>
Logical&&   ||   &   |   ^   !
Note: && and || perform short-circuit logical evaluations
String Concatenation+

VB.NETChoicesC#
' Null-coalescing operator if called with 2 argumentsx = If(y, 5)   ' if y is not Nothing then x = y, else x = 5
' Ternary/Conditional operator (IIf evaluates 2nd and 3rd expressions)
greeting = If(age < 20, "What's up?", "Hello")
' One line doesn't require "End If"
If age < 20 Then greeting = "What's up?"
If age < 20 Then greeting = "What's up?" Else greeting = "Hello"
' Use : to put two commands on same line
If x <> 100 AndAlso y < 5 Then x *= 5 : y *= 2
' Preferred
If x <> 100 AndAlso y < 5 Then
  x *= 5
  y *= 2
End If
' Use _ to break up long single line or use implicit line break
If whenYouHaveAReally < longLine And
  itNeedsToBeBrokenInto2 > Lines Then _
  UseTheUnderscore(charToBreakItUp)
'If x > 5 Then
  x *= y
ElseIf x = 5 OrElse y Mod 2 = 0 Then
  x += y
ElseIf x < 10 Then
  x -= y
Else
  x /= y
End If
Select Case color   ' Must be a primitive data type
  Case "pink", "red"
    r += 1
  Case "blue"
    b += 1
  Case "green"
    g += 1
  Case Else
    other += 1
End Select


// Null-coalescing operatorx = y ?? 5;   // if y != null then x = y, else x = 5
// Ternary/Conditional operatorgreeting = age < 20 ? "What's up?" : "Hello";
if (age < 20)
  greeting = "What's up?";
else
  greeting = "Hello";
// Multiple statements must be enclosed in {}if (x != 100 && y < 5) {
  x *= 5;
  y *= 2;
}


No need for _ or : since ; is used to terminate each statement.


if
(x > 5)
  x *= y;
else if (x == 5 || y % 2 == 0)
  x += y;
else if (x < 10)
  x -= y;
else
  x /= y;


// Every case must end with break or goto case
switch (color) {                          // Must be integer or string
  case "pink":
  case "red":    r++;    break;
  case "blue":   b++;   break;  case "green": g++;   break;  default:    other++;   break;       // break necessary on default}

VB.NETLoopsC#
Pre-test Loops:
While c < 10
  c += 1
End While
Do Until c = 10
  c += 1
Loop
Do While c < 10
  c += 1
Loop
For c = 2 To 10 Step 2
  Console.WriteLine(c)
Next

Post-test Loops:
Do
  c += 1
Loop While c < 10
Do
  c += 1
Loop Until c = 10


Reference Books






No comments:

Post a Comment