In this article I am going to present you a brief comparison between C#.NET and VB.NET in A-Z technical words.
Summary :
In this article I am going to present you a brief comparison between C#.NET and
VB.NET in A-Z technical words.
Concepts Covered :
- Introduction to VB.NET and C#.Net
- Individual advantages of both the languages
- A - Z(Technical words) Comparison with examples.
Introduction to VB.NET and C#.Net
Before directly going into the comparisons let us see
the brief description of both VB.NET and C#.NET
What
is VB.NET :
It is an Event oriented programming language on the Object Oriented Programming
(OOP) language platform which fully implements the features like encapsulation,
inheritance, and polymorphism. Which is unlike in its previous version which is
Visual Basic , VB.NET does not compile to native machine code but instead it
compiles to MSIL(Microsoft Intermediate Language), after that this is further
compiled to machine code for the processor where the code is executed . This
can be done in real time using the JIT(Just In Time) compiler ,or it can be
compiled in to machine language before execution through ngen.exe tool which is available with the MS.NetFramework SDK .
What
is C#.NET : It
is an object oriented programming language which is used to add the complex
computing power of C++ with the relatively easy use of programming with Visual
Basic. Microsoft’s primary goal is to distribute the data and services through
web and which in turn allows to develop relatively high portable applications.
It simplifies its use of XML(Extensible Markup Language) and SOAP(Simple Object
Access Protocol).This language is expected to build the applications faster and
less expensive so that it will draw new products and services to the IT
industry.
Individual advantages of both the languages Each language has got its own importance and advantages , here i am listing some of those ....

VB.NET
| C#.NET
|
1. It has the ability to implement interfaces with methods of different names, of course which makes harder to find the implementation of interfaces.
2. VB.NET is not case sensitive.
3. It has the support of named indexers
4. Option Strict, this is one of the good advantage because of this we cannot accidentally assign an integer to a string , but an integer value can be placed in a long though.
5.It Cannot handle UnManaged Code. Wondering how this become an advantage ? because of this more stable and secure production of code is obtained.
6.It has the support for optional parameters.It is very handy for some COM interoperability.
| 1.The use of Using statement which makes unmanaged resource disposal easy.
2.It supports Explicit interface implementation.Suppose if an interface is already implemented in a base class can be re -implemented separately in derived class.
3.It has the language support for the Unsigned types
|
Now lets start with the comparisons of both VB.NET and C#.NET
A - Z(Technical words) Comparison with examples
A
Arrays
: An
Array is a continuous series of elements of same data type which is placed in a
sequential memory locations that can be individually identified by adding an
index to an unique identifier.
Let’s see how the implementation changes between these
two languages.
VB.NET
| C#.NET
|
Dim numbers() As Integer = {1, 2, 3,4,5} For i As Integer = 0 To numbers.Length - 1 Console.WriteLine(numbers(i)) Next
| int[] numbers = {1, 2, 3,4,5}; for (int i = 0; i < numbers.Length; i++) Console.WriteLine(numbers [i]);
|
B
Base Class : In Object Oriented Programming a Class which provides characteristics such as Properties and methods to the Derived Class(Child Class) is said to be Base Class(Parent Class)
Here Person Class is the base class where it is being inherited by Employee class which is Derived class
VB.NET
| C#.NET
|
Class Person Public Name As String Public Address As String End Class
Class Employee Public Name As String Public Address As String Public Salary As Integer End Class
Class Employee Inherits Person Public Salary As Integer End Class
|
class Person
{
public void BaseDisplay() { System.Console.WriteLine("This is Base Class");
} } Class Employee : Person { public void DerivedDisplay() { System.Console.WriteLine("This is Derived Class"); } }
Class Execute { Employee objDerived=new Employee(); objDerived.BaseDisplay(); objDerived.DerivedDisplay(); }
|
C
Constants : Constants stores values , as the name suggests it remains unchanged through out the execution of the program.We must use constants only when we frequently use them and also to make our code more readable.
VB.NET
| C#.NET
|
Const Tot_Students As Integer = 25 | const int Tot_Students= 25; |
Classes/Interfaces : Classes are nothing but a collection functions/mehods.These methods are used to perform certain operations.All the sheilding to these methods are given by Classes.Interfaces are nothing but , it is a group of related methods with empty structure.
VB.NET | C#.NET |
Public
Private
Friend
Protected
Protected Friend
'List of
MustInherit NotInheritable 'List of
MustOverride NotInheritable Shared Overridable
'Defining A Class
Class Person Public Name As String Public Address As String
End Class
'Defining An InterfacInterface IAdd Sub Add() Property Addition() As Integer End Interface
|
public
private internal protected protected internal
'List of
abstract
sealed static
'List of
abstract
sealed static virtual 'Defining A Class Class Person { String Name; String Address; }
'Defining An Interface
interface IAdd
{
void Add();
Integer Addition{ get; set; }
}
|
Constructors/Destructors : Constructor is a class member function which has a same name as that of Class Name. The main purpose of this constructor is to initialize all the member variables when ever a object of this class is created.It just resembles a instance method.If there are any resources allocated such as Memory or Files are typically handled by Destrucotrs.These are used to free the memory.
VB.NET
| C#.NET
|
Class DemoConst
Private GlobalLevel As Integer Public Sub Old() GlobalLevel = 0 End Sub Public Sub Old(ByVal GlobalLevel As Integer) Me.GlobalLevel = GlobalLevel End Sub
Shared Sub Old()
End Sub
Protected Overrides Sub Finalize() frees unused resources. MyBase.Finalize() End Sub End Class | Class DemoConst { private int GlobalLevel;
public DemoConst() { GlobalLevel= 0; }
public DemoConst(int GlobalLevel) { this.GlobalLevel = GlobalLevel; }
static DemoConst() {
}
~DemoConst() { frees unused resources. } }
|
Comments : These are nothing but disabling the code part, So that the execution is not followed to that part. Both VB.NET and C#.NET has different styles of commenting.
VB.NET | C#.NET |
| String Demo1; String Demo2;
|
D
Data types : It is nothing but a Data Storage format which contains a Specific type or a different range of values.All the variables which are used must be defined with a Data type.Almost all the Data types are similar in both but with small differences.
VB.NET | C#.NET |
The Different value types available here are :
Boolean
Byte, SByte
Char
Short, UShort, Integer, UInteger, Long, ULong
Single, Double
Decimal
Date
The Different Reference types available here are :
Object
String
| The Different value types available here are :
bool
byte, sbyte
char
short, ushort, int, uint, long, ulong
float, double
decimal
DateTime
The Different Reference types available here are:
object
string |
Delegates/Events : Delegate is just as same as a pointer in C or C++. Just like passing a method as a parameter to our delegate. So with this we cannot know which method is invoked in compile time. Event is just an action performed by an object. These Events are implemented using Delegates.
VB.NET | C#.NET |
'Declaring a Delegate and Event Delegate Sub MsgArrivedEventHandler(ByVal myMessage As String) Event MyMsgArrivedEvent As MsgArrivedEventHandler
| 'Declaring a Delegate and Event delegate void MsgArrivedEventHandler(string message);
event MsgArrivedEventHandler MsgArrivedEvent;
|
E
Enumerations : This provides an efficient way to define a set of user defined name values which can be assigned to a variable.
VB.NET | C#.NET |
Enum MyAction Run
[Stop]
Jump Forward End Enum Dim a As MyAction = MyAction.Stop If a <> MyAction.Run Then _ Console.WriteLine(a.ToString & " is " & a)
| enum MyAction {Run, Stop, Jump, Forward}; MyAction a = MyAction .Stop;
if (a != MyAction.Run) Console.WriteLine(a + " is " + (int) a);
|
F
Functions : These are a set of operations which are grouped together to form a desired functionality.
VB.NET | C#.NET |
Sub AddFunction(ByVal a As Integer, ByRef b As Integer) Dim a=5,b=6,C as Integer
C = a + b Return C End Sub
AddFunction()
| void AddFunction(int x,int y) { int z; z = x + y; return z; } AddFunction(5,6);
|
G
Generics : Generics are one of the most important feature introduced in 2.0 Framework. This allows to create a type safe data structures without the use of committing to actual data types.This results in highly efficient performance because here we get to reuse the data processing algorithms.Let's see how it is implemented in both the languages.
VB.NET | C#.NET |
Dim numbers As New List(Of Integer)
numbers.Add(8) numbers.Add(10) ShowList(Of Integer)(numbers)
'Method to Display any kind of list Sub ShowList(Of T)(ByVal list As List(Of T))
For Each myItem As T In list
Console.WriteLine(myItem)
Next
End Sub | List<int> numbers = new List<int>();
numbers.Add(8);
numbers.Add(10);
ShowList<int>(numbers); 'Method to Display any kind of list void DisplayList<T>(List<T> list) {
foreach (T item in list)
Console.WriteLine(item);
} |
H
Handling
Structured exception : .NET offers more powerful and readable way to handle errors. This error handling enables us to nest error handlers inside other error handlers which are in the same procedure. VB.NET also allows backward compatibility by also providing the unstructured exception handling by using On Error GoTo Statement and Err. Object.
VB.NET | C#.NET |
Try 'Perform Actions Catch ex As System.Exception MessageBox.Show("Error: " + ex.Message) Finally ' Perform any tidy up code. End Try
| try { 'Perform Actions } catch (System.Exception ex) { MessageBox.Show("Error: " + ex.Message); } finally { // Perform any tidy up code. }
|
I
I/O( Console) : Console I/O is the standard input,output and error streams for console applications.To perform this we have a class called Console. This class cannot be inherited.
VB.NET | C#.NET |
Console.Write("This is DotNetFunda !!!") Dim yourName As String = Console.ReadLine() Console.Write("Best Place for .NET community !!!") Dim yourAge As Integer = Val(Console.ReadLine()) Console.WriteLine("{0} is {1} years old.", youName, yourAge) | Console.Write("This is DotNetFunda !!!"); string yourName= Console.ReadLine(); Console.Write("Best Place for .NET community !!!"); int yourAge = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("{0} is {1} years old.", yourName, yourAge) |
J
Just In Time Compiler : Just In Time compiler is also known as Dynamic Translation.This compiler would translate the Byte code(A program which contains instructions and which are to be interpreted) into the instructions that can be directly sent to the processor.
K
Keyword Differences : The basic keyword syntax differs from other.The purpose of achieving the functionality is same.Let us see how it differs.
Action
| VB.NET
| C#.NET
|
Creating a New Object
| New , CreateObject()
| new
|
Method Called by the System before garbage collection
| Finalize
| desturctor
|
Testing Database Null Exception
| IsDbNull | N/A
|
Defining Default property
| Default
| By using Indexers
|
Declaring a method which cannot be overridden
| NotOverridable | sealed
|
Hiding a base class member in a derived class
| Shadowing | N/A
|
Case Sensitive ?
| NO
| YES
|
L
Loops :
A loop is a way of repeating a statement a number of times until it is stopped using a condition.
VB.NET | C#.NET |
'While Loop While demo < 100 demo += 1 End While 'Do While Do While demo < 100 demo += 1 Loop 'For Each Dim names As String() = {"Name 1", "Name 2", "Name 3"} For Each s As String In names Console.WriteLine(s) Next 'For & If Loop For i = 0 To 9
If i < = 9 Then Continue For Console.WriteLine(i) Next
| 'While Loop while (c < 100) c++; 'Do While do c++; while (c < 100); 'For Each string[] names = {"Name 1", "Name 2", "Name 3"};
foreach (string s in names)
Console.WriteLine(s); 'For & If Loop for (i = 0; i <= 9; i++) {
if (i < 9)
continue;
Console.WriteLine(i);
} |
M
Multi-line XML comments : The format used to comment multi-line XML comments are :
VB.NET | C#.NET |
''' <MyData> XML Comments </MyDAata>
| |
N
Name Spaces : Name Space is a collection of programming elements which are organized for grouping operations and easy access. It includes Classes,Structures,Modules,Interfaces,Delegates,Enumerations.
VB.NET | C#.NET |
Namespace Cricket.Allow.Graphics ... End Namespace
| Namespace Cricket.Allow.Graphics { ... } |
O
Operators : These are the special characters which are used to perform operations arguments to return a specific result.
VB.NET | C#.NET |
Operators
= < > <= >= <>
+ - * /
Mod
\
^
= += -= *= /= \= ^= <<=
>>= &=
And Or Xor Not << >>
AndAlso OrElse And Or Xor Not
&
|
== < > <= >= !=
+ - * /
%
/
Math.Pow(x, y)
= += -= *= /= %= &= |=
^= <<= >>= ++ --
& | ^ ~ << >>
Operators
&& || & | ^ !
+
|
P
Programming Structure : The Basic Structure of flow of code is different from each other.Differences shown below.
VB.NET | C#.NET |
Imports System Namespace Demo Class DemoWorld Overloads Shared Sub Main(ByVal args() As String) Dim name As String = "DOT NET FUNDA"
If args.Length = 1 Then name = args(0) Console.WriteLine("Hello, " & name & "!") End Sub End Class End Namespace | using System; namespace Demo {
public class DemoWorld {
public static void Main(string[] args) {
string name = "DOT NET FUNDA";
if (args.Length == 1) name = args[0]; Console.WriteLine("Hello, " + name + "!"); } }
} |
Q
Querying Through Records (D/B Connection): Accessing a Database in both the languages can be done in many ways.The Procedure to obtain this same in case of both the languages but syntax differs.
VB.NET | C#.NET |
Imports System.Data.SqlClient Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load If Not IsPostBack Then BindDataToGrid() End If End Sub Function BindDataToGrid() As DataTable Try myConnection = New SqlConnection("server=Server Name;user id=UserName;password=Password;database=DatabaseName") myConnection.Open() Dim query As String = "Select * from BonusForm" Dim myDataAdapter As SqlDataAdapter myDataAdapter = New SqlDataAdapter(query, myConnection) Dim myDataSet As DataSet = New DataSet myDataAdapter.Fill(myDataSet) gridExceptionBonus.DataSource = myDataSet gridExceptionBonus.DataBind() Return myDataSet.Tables(0) Catch ex As Exception Response.Write("Error Occured ::" + ex.Message) Finally myConnection.Close() End Try End Function
| SqlConnection con; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { con = new SqlConnection("server=Server Name;user id=UserName;password=Password;database=DatabaseName"); con.Open(); SqlCommand newCmd = new SqlCommand("Select * from GuidelinesDetails", con); SqlDataReader rdr; rdr = newCmd.ExecuteReader(); repeaterGuidelines.DataSource = rdr; repeaterGuidelines.DataBind(); rdr.Close();
BindGuidelinesData(); } }
|
R
Regular Expressions : These are the expressions which are useful for efficient validation purposes. There are many examples to explain this scenario. I take how to remember multiple parts of a matched pattern.
VB.NET | C#.NET |
Dim r As New Regex("(\d\d):(\d\d) (am|pm)")
Dim m As Match = r.Match("The Time is 09:45 pm.")
If m.Success Then
Console.WriteLine("Hour: " & m.Groups(1).ToString)
Console.WriteLine("Min: " & m.Groups(2).ToString) Console.WriteLine("Ending: " & m.Groups(3).ToString) End If | Regex r = new Regex("@(\d\d):(\d\d) (am|pm)");
Match m = r.Match("The Time is 09:45 pm.");
if (m.Success) {
Console.WriteLine("Hour: " + m.Groups[1]);
Console.WriteLine("Min: " + m.Groups[2]);
Console.WriteLine("Ending: " + m.Groups[3]);
} |
S
Strings : String is a contiguous sequence of symbols or values.Used to store text elements.
VB.NET | C#.NET |
Dim name As String = "Dot Net Funda" name= "This is " & name
|
String name= "Dot Net Funda"; name= "This is " & name; |
Structs : Struct is a type which can hold a group of variables in one variable. Typically collection data related to different data types.
VB.NET | C#.NET |
Structure EmployeeRecord public name as String public age as Integer
public Sub New(ByVal name As String, ByVal age As Integer) Me.name = name Me.age = age End Sub End Structure | Struct EmployeeRecord { public string name; public int age;
public EmployeeRecord(string name, int age) { this.name = name; this.age = age; }
}
|
T
Type checking : It is the process of identifying errors in a program basing on explicitly or implicitly stated type information.It is generally divided into two parts namely Strongly Typed and Weakly Typed.
VB.NET | C#.NET |
Sub Type_Check_Variable_Types() Dim varByte As Sbyte Dim varInt As Integer Dim varString As String Dim varExp As Exception varString = "DotNetFunda"
varExp = New System.Exception("DemoSample Exception")
Dim varArr As Object() = {varByte, varInt, varString, varExp} MsgBox(varArr.GetType.ToString())
For Each obj As Object In varArr
MsgBox(obj.GetType.IsValueType) MsgBox(obj.GetType().ToString)
Next
End Sub
| public void Type_Check_Variable_Types() { sbyte varByte = 0; int varInt = 0; string varString = null; Exception varExp = null;
varString = "DotNetFudna";
varExp = new System.Exception("DemoSample Exception");
object[] varArr = { varByte, varInt, varString, varExp }; Interaction.MsgBox(varArr.GetType().ToString());
foreach (object obj in varArr) { Interaction.MsgBox(obj.GetType().IsValueType); Interaction.MsgBox(obj.GetType().ToString());
}
}
|
U
Using Objects : Creating Objects in order to find the relationship between different methods.
VB.NET
| C#.NET
|
Dim hero As DemoSample= New DemoSample With hero .Name = "Good Boy" .PowerLevel = 3 End With
hero.Defend("DotNetFunda") hero.Rest() DemoSample.Rest()
Dim hero2 As DemoSample = hero hero2.Name = "Good Girl" Console.WriteLine(hero.Name) hero = Nothing If hero Is Nothing Then _ hero = New DemoSample
Dim obj As Object = New DemoSample If TypeOf obj Is DemoSample Then _ Console.WriteLine("Is a DemoSample object.")
' Mark object for quick disposal Using reader As StreamReader = File.OpenText("test.txt") Dim line As String = reader.ReadLine() While Not line Is Nothing Console.WriteLine(line) line = reader.ReadLine() End While End Using
| DemoSample hero = new DemoSample();
hero.Defend("DotNetFunda"); hero.Rest(); DemoSample.Rest(); DemoSample hero2 = hero; hero2.Name = "Good Girl"; Console.WriteLine(hero.Name); hero = null; if ((hero == null)) { hero = new DemoSample(); } object obj = new DemoSample(); if ((obj.GetType() == DemoSample)) { Console.WriteLine("Is a DemoSample object."); } // Mark object for quick disposal Using{ StreamReader reader = File.OpenText("test.txt"); string line = reader.ReadLine(); while (!(line == null)) { Console.WriteLine(line); hero.Name = 3; line = reader.ReadLine(); } }
|
V
Val
: Using Val we can represent a char value in integer representation or its equivalent numeric representation.
VB.NET | C#.NET |
Module Module1 Sub Main()
Dim myNumber As Char = "a"c Dim i As Integer = Val(myNumber) Dim a As Integer = Asc(myNumber) Console.WriteLine(myNumber) Console.WriteLine(i) Console.WriteLine(a)
End Sub End Module 'Output : a 0 97
| class Module1 { static void Main() { char myNumber = "a"; c; int i = double.Parse(myNumber); int a = Asc(myNumber); Console.WriteLine(myNumber); Console.WriteLine(i); Console.WriteLine(a); } } // Output : a 0 97
|
W
Web Services : It is an application programming interface that can be accessed over a network.It is just a method between two electronic devices over a network.VB.NET | C#.NET |
<WebMethod()> Public Function GetIPAddress() As String
Dim strHostName As String = "" Dim strIPAddress As String = "" Dim host As System.Net.IPHostEntry
strHostName = System.Net.Dns.GetHostName() strIPAddress = System.Net.Dns.GetHostEntry(strHostName).HostName.ToString()
host = System.Net.Dns.GetHostEntry(strHostName) Dim ip As System.Net.IPAddress For Each ip In host.AddressList Return ip.ToString() Next
Return ""
End Function
| [WebMethod()]
public string GetIPAddress() {
string strHostName = "";
string strIPAddress = "";
System.Net.IPHostEntry host;
strHostName = System.Net.Dns.GetHostName();
strIPAddress = System.Net.Dns.GetHostEntry(strHostName).HostName.ToString();
host = System.Net.Dns.GetHostEntry(strHostName);
System.Net.IPAddress ip;
foreach (ip in host.AddressList) {
return ip.ToString();
}
return "";
}
|
X
eXplict Vs Implicit : Implicit conversions are handled by the .NET compiler.An explicit conversion uses a type conversion keyword with these conversion key words we can perform explicit conversions.
VB.NET | C#.NET |
Public Class MyClass Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim dblNumber As Double Dim intNumber As Integer dblNumber = 9.63 MsgBox("The value of dblNumber is " & dblNumber) intNumber = dblNumber 'after conversion MsgBox("The value of intNumber is " & intNumber) End Sub End Class
| public class MyClass { private void Button1_Click(object sender, System.EventArgs e) { double dblNumber; int intNumber; dblNumber = 9.63; MsgBox(("The value of dblNumber is " + dblNumber)); intNumber = dblNumber; // after conversion MsgBox(("The value of intNumber is " + intNumber)); } }
|
Y
Yield : It is used in an interator block to provide a value to the enumerator object or to signal the end of iteration.
VB.NET | C#.NET |
Private Shared Function GetItems() As IEnumerable(Of String) yield Return "DOTNETFUNDA" End Function
| private static IEnumerable<string> GetItems() { yield return "DOTNETFUNDA"; }
|
Z
Zones (Catalog) : These are used in web applications.The Container parts which holds all the controls can be placed in these zones. These can be also termed as specific space allocated for particular container in a web page.
VB.NET | C#.NET |
'Declaration Public Class CatalogZone _ Inherits CatalogZoneBase
| public class CatalogZone : CatalogZoneBase
|
Conclusion : Finally i would like to conclude, where each language has got its own pros and cons.It is difficult to predict which is good and which is bad. Both VB.NET and C#.NET are some of the most popular of those from Microsoft.
As suggested by one of our member,here are some of the conversion tools from both VB.NET to C#.NET and vice versa.
http://www.carlosag.net/Tools/CodeTranslator/
Final Word : I would like to thank DotNetFunda for allowing to publish articles with this beautiful interface,through this the presentation style looks very elegant.
Thanks and Regards,
SRIKANTH CH V R