C# versus Visual Basic .Net

burgerraraSoftware and s/w Development

Nov 18, 2013 (3 years and 4 months ago)

115 views

C# versus Visual Basic .Net


C# and Visual Basic are both part of the Visual Studio .NET programming environment. Consequently, they share many
things in common. They also have some distinct differences. This document summaries the key syntax
differences
between C# and Visual Basic .NET code.



Data Type Comparison
1


Content and S
ize

Visual Basic

C#

JScript

Unknown data

n/a

n/a

Object


Decimal

Decimal


decimal


decimal


Date

Date


DateTime


DateTime


Date

object

SBCS character

(1 byte)

n/a

n/a

sbyte


Unicode character (2 bytes)

Char


char


char


Unicode character sequence

String


string


String


Boolean (platform dependent)

Boolean


bool


boolean


1 byte

SByte Data Type (Visual Basic)


sbyte


n/a

2 bytes

Short


short


short


4 bytes

Integer


int


int


8 bytes

Long


long


long


1 byte unsigned

Byte


byte


byte


2 bytes unsigned

UShort Data Type (Visual Basic)


ushort


n/a

4 bytes unsigned

UInteger Data Type


uint


n/a

8 bytes unsigned

ULong Data Type (Visual Basic)


ulong


n/a

4 bytes floating point

Single


float


float


8 bytes floating point

Double


double


Double



Java to C# Data Type Comparison
2


Java Type


Java
Default
Value


EMF Type


C# Type


C# Default
Value


java.math.BigDecimal

null


EBigDecima


not yet mapped to C#

? use System.Decimal or

J# java.math.BigDecimal
implementation?


-


java.math.BigInteger

null


EBigInteger


not yet mapped to C#

? use System.Decimal or

J# java.math.BigDecimal
implementation or

.NET 3.5 System.Numeric.BigInteger?


-




1

The data found in this table is taken from
http://msdn.microsoft.com/en
-
us/library/4xwz0t37(VS.80).aspx
.

2

The data found in this table is taken from
http://emf4net.org/emf4net/Translation/Types/tabid/60/Default.aspx
.


boolean

false


EBoolean


bool

false


java.lang.Boolean

null


EBooleanObject


System.Boolean

false


byte

0x00


EByte


sbyte


0x00


byte[]

null


EByteArray


sbyte[]


null


java.lang.Byte

null


EByteObject


System.SByte


0x00


char

\
u0000


EChar


char


\
u0000


java.lang.Character

null


ECharacterObject


System.Char


\
u0000


java.util.Date

?


EDate


System.DateTime


01.01.0001
00:00:00


double

0.0D


EDouble


double


0.0D


java.lang.Double

null


EDoubleObject


System.Double


0.0D


java.util.List

null


-


System.Collections.Generic.IList


null


float

0.0F


EFloat


float


0.0F


java.lang.Float

null


EFloatObject


System.Single


0.0F


int


0


EInt


int


0


java.lang.Integer

null


EIntegerObject


System.Int32


0


java.lang.Class

null


EJavaClass


System.Type


?


java.lang.Object

null


EJavaObject


System.Object


null


long

0L


ELong


long


0L


java.lang.Long

null


ELongObject


System.Int64


0L


java.util.Map

null


EMap


System.Collections.Generic.IDictionary


null


short

0


EShort


short


0


java.lang.Short

null


EShortObject


System.Int16


0


java.lang.String

null


EString


System.String


null



C#
Integer
Data Type Ranges
3


Type Range Size

Type Range Size

Type Range Size

sbyte

-
128 to 127

Signed 8
-
bit integer

byte

0 to 255

Unsigned 8
-
bit intege

char

U+0000 to U+ffff

Unicode 16
-
bit character

short

-
32,768 to 32,767

Signed 16
-
bit integer

ushort

0 to 65,535

Unsigned 16
-
bit integer

int

-
2,147,483,648 to 2,147,483,647

Signed 32
-
bit integer

uint

0 to 4,294,967,295

Unsigned 32
-
bit
integer

long

-
9,223,372,036,854,775,808 to
9,223,372,036,854,775,807

Signed 64
-
bit integer

ulong

0 to 18,446,744,073,709,551,615

Unsigned 64
-
bit integer





3

The data in this table is taken from
http://msdn.microsoft.com/en
-
us/library/exx3b86w(VS.80).aspx
.

Advantages of both languages
4

VB.NET

C#



Support for optional parameters
-

very handy for
some COM interoperability.



Support for late binding with Option Strict off
-

type
safety at compile time goes out of the window, but
legacy libraries which don't have strongly typed
interfaces become easier to use.



Support for named indexers.



Various legacy VB functions (provided
in the
Microsoft.VisualBasic

namespace, and can be
used by other languages with a reference to the
Microsoft.VisualBasic.dll
). Many of these can be
harmful to performance if used unwisely, however,
and many people believe they should be avoided for
the mos
t part.



The
with

construct: it's a matter of debate as to
whether this is an advantage or not, but it's certainly
a difference.



Simpler (in expression
-

perhaps more complicated
in understanding) event handling, where a method
can declare that it handles

an event, rather than the
handler having to be set up in code.



The ability to implement interfaces with methods of
different names. (Arguably this makes it harder to
find the implementation of an interface, however.)



Catch

...
When

... clauses, which al
low exceptions to
be filtered based on runtime expressions rather than
just by type.



The VB.NET parts of Visual Studio .NET compiles
your code in the background. While this is
considered as an advantage for small projects,
people creating very large proje
cts have found that
the IDE slows down considerably as the project gets
larger.



XML documentation generated from source
code comments. (This is coming in
VB.NET with Whidbey (the code name for
the next version of Visual Studio and
.NET), and there are tool
s which will do it
with existing VB.NET code already.)



Operator overloading
-

again, coming to
VB.NET in Whidbey.



Language support for unsigned types (you
can use them from VB.NET, but they aren't
in the language itself). Again, support for
these is comi
ng to VB.NET in Whidbey.



The
using

statement, which makes
unmanaged resource disposal simple.



Explicit interface implementation, where an
interface which is already implemented in a
base class can be re
-
implemented separately
in a derived class. Arguably this makes the
class harder to understand, in the same way
that member hiding normally does.



U
nsafe code. This allows pointer arithmetic
etc, and can improve performance in some
situations. However, it is not to be used
lightly, as a lot of the normal safety of C# is
lost (as the name implies). Note that unsafe
code is still managed code, i.e., it
is
compiled to IL, JITted, and run within the
CLR.

Keyword Differences

Purpose

VB.NET

C#

Declare a variable

Private
,
Public
,
Friend
,
Protected
,
Static1
,
Shared
,
Dim

declarators

(keywords include user
-
defined types and built
-
in types)

Declare a named
constant

Const

const

Create a new object

New
,
CreateObject()

new

Function/method does not
Sub

void




4

The following
six
table is taken from “The Code Project” webpage found at
http://www.codeproject.com/KB/dotnet/vbnet_c__difference.aspx
. Another excellent comparison between the syntax of the two
languages can be found at
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html
.

return a value


Overload a function or
method (Visual Basic:
overload a procedure or
method)

Overloads

(No language keyword required for this
purpose)

Refer to the current object

Me

this

Make a nonvirtual call to a
virtual method of the current
object

MyClass

n/a

Retrieve character from a
string

GetChar Function

[]

Declare a compound data
type (Visual Basic: Structure)

Structure <members> End
Structure

struct
,
class
,
interface

Initialize an object
(constructors)

Sub New()

Constructors, or system default type
constructors

Terminate an object directly

n/a

n/a

Method called by the system
just before garbage collection
reclaims an object7

Finali
ze

destructor

Initialize a variable where it
is declared

Dim x As Long = 5

Dim c As New _


Car(FuelTypeEnum.Gas)

// initialize to a value:


int x = 123;

// or use default


// constructor:


int x = new int();

Take the address of a
function

AddressOf

(For class members, this
operator returns a reference to a
function in the form of a delegate
instance)

delegate

Declare that an object can be
modified asynchronously

n/a

volatile

Force explicit declaration of
variables

Option Explicit

n/a. (All
variables must be declared prior
to use)

Test for an object variable
that does not refer to an
object

obj = Nothing

obj == null

Value of an object variable
that does not refer to an
object

Nothing

null

Test for a database null
expression

IsDbNull

n/a

D
efine a default property

Default

by using indexers

Refer to a base class

MyBase


base

Declare an interface

Interface

interface

Specify an interface to be
implemented

Implements (statement)

class C1 : I1

Declare a class

Class <implementation>

class

Specify that a class can only
be inherited. An instance of
the class cannot be created.

MustInherit


abstract

Specify that a class cannot be
inherited

NotInheritable


sealed

Declare an enumerated type

Enum <members> End Enum

enum

Declare a class constan
t

Const

const

(Applied to a field declaration)

Derive a class from a base
class

Inherits C2


class C1 : C2

Override a method

Overrides

override

Declare a method that must
be implemented in a deriving
class

MustOverride

abstract

Declare a method that
can't
be overridden

NotOverridable

(Methods are not
overridable

by default.)

sealed

Declare a virtual method,
property (Visual Basic), or
property accessor (C#, C++)

Overridable

virtual

Hide a base class member in
a derived class

Shadowing

n/a

Declare a

typesafe reference
to a class method

Delegate

delegate

Specify that a variable can
contain an object whose
events you wish to handle

WithEvents

(Write code
-

no specific keyword)

Specify the events for which
an event procedure will be
called

Handles

(Event procedures can still
be associated with a
WithEvents

variable by naming pattern.)

n/a

Evaluate an object expression
once, in order to access
multiple members

With objExpr


<.member>


<.member>

End With

n/a

Structured exception
handling

Try <
attempt>

Catch

<handle errors>

Finally

<always execute>

End Try

try
,
catch
,
finally
,

throw

Decision structure (selection)

Select Case ...
,
Case
,
Case Else
,
End Select

switch
,
case
,
default
,
goto
,
break

Decision structure (if ... then)

If ... Then
,
ElseIf

... Then
,
Else
,
End If

if
,
else

Loop structure (conditional)

While, Do [While
,
Until] ...
,
Loop [While, Until]

do
,
while
,
continue

Loop structure (iteration)

For ...
,
[Exit For], Next

For Each ..., [Exit For,] Next

for
,
foreach

Declare an array

Dim a()

As Long

int[] x = new int[5];

Initialize an array

Dim a() As Long = {3, 4, 5}


int[] x = new int[5] {


1, 2, 3, 4, 5};

Reallocate array

Redim

n/a

Visible outside the project or
Public

public

assembly

Invisible outside the
assembly (C#/Visual
Basic)
or within the package (Visual
J#, JScript)

Friend

internal

Visible only within the
project (for nested classes,
within the enclosing class)

Private

private

Accessible outside class and
project or module

Public

public

Accessible outside the class,

but within the project

Friend

internal

Only accessible within class
or module

Private

private

Only accessible to current
and derived classes

Protected


protected

Preserve procedure's local
variables

Static

n/a

Shared by all instances of a
class

Shared


static

Comment code

'

Rem

//, /* */

for multi
-
line comments

///

for XML comments

Case
-
sensitive?

No

Yes

Call Windows API

Declare <API>

use Platform Invoke

Declare and raise an event

Event
,
RaiseEvent

event

Threading primitives

SyncLock

lock

Go to

Goto

goto

Data types Differences

Purpose/Size

VB.NET

C#

Decimal

Decimal


decimal

Date

Date

DateTime

(varies)

String


string

1 byte

Byte

byte

2 bytes

Boolean

bool

2 bytes

Short
,
Char (Unicode
character)

short
,
char (Unicode character)

4 bytes

Integer

int

8 bytes

Long

long

4 bytes

Single

float

8 bytes

Double

double

Operators Differences

Purpose

VB.NET

C#

Integer division

(truncates)

\

/

Modulus (division returning
Mod

%

only the remainder)

Exponentiation

^

n/a

Integer division
Assignment

\
=

/=

Concatenate

&= NEW

+=

Modulus

n/a

%=

Bitwise
-
AND

n/a

&=

Bitwise
-
exclusive
-
OR

n/a

^=

Bitwise
-
inclusive
-
OR

n/a

|=

Equal

=

==

Not equal

<>


!=

Compare two object reference
variables

Is

==

Compare object reference type

TypeOf x Is
Class1

x is Class1


Concatenate strings

&

+

Shortcircuited Boolean AND

AndAlso

&&

Shortcircuited Boolean OR

OrElse

||

Scope resolution

.

.

and
base

Array element

()

[ ]

Type cast

Cint
,
CDbl
, ...,
CType

(type)

Postfix increment

n/a

++

Postfix
decrement

n/a

--

Indirection

n/a

*

(unsafe mode only)

Address of

AddressOf

&

(unsafe mode only; also see fixed)

Logical
-
NOT

Not

!

One's complement

Not

~

Prefix increment

n/a

++

Prefix decrement

n/a

--

Size of type

n/a

sizeof

Bitwise
-
AND

And

&

Bitwise
-
exclusive
-
OR

Xor

^

Bitwise
-
inclusive
-
OR

Or

|

Logical
-
AND

And

&&

Logical
-
OR

Or

||

Conditional

If Function ()

?:

Pointer to member

n/a

.

(Unsafe mode only)

Programming Difference

Purpose

VB.NET

C#

Declaring Variables

Dim x As Integer

Public x

As Integer = 10

int x;

int x = 10;

Comments

' comment


x = 1 ' comment


Rem comment

// comment


/* multiline


comment */

Assignment
Statements

nVal = 7

nVal = 7;

Conditional
Statements

If nCnt <= nMax Then


' Same as nTotal =



' nTotal + nCnt.



nTotal += nCnt


' Same as nCnt = nCnt + 1.



nCnt += 1

Else


nTotal += nCnt


nCnt
-
= 1

End If

if (nCnt <= nMax)

{


nTotal += nCnt;


nCnt++;

}

else

{


nTotal +=nCnt;


nCnt
--
;

}

Selection
Statements

Select Case n


Case 0


MsgBox ("Zero")


' Visual Basic .NET exits



' the Select at



' the end of a Case.



Case 1


MsgBox ("One")


Case 2


MsgBox ("Two")


Case Else


MsgBox ("Default")

End Select


switch(n)

{


case 0:


Console.WriteLine("Zero");


break;


case 1:


Console.WriteLine("One");


break;


case 2:


Console.WriteLine("Two");


break;


default:


Console.WriteLine("?");


break;

}


FOR Loops

For n = 1 To 10


MsgBox("The number is " & n)

Next


For Each prop In obj


prop = 42

Next prop

for (int i = 1; i <= 10; i++)


Console.WriteLine(


"The number is {0}", i);

foreach(prop current in obj)

{


current=42;

}

Hiding Base Class
Members

Public Class
BaseCls


' The element to be shadowed



Public Z As Integer = 100


public Sub Test()


System.Console.WriteLine( _


"Test in BaseCls")


End Sub

End Class


Public Class DervCls


Inherits BaseCls


' The shadowing element.



Public Shadows Z As String = "*"


public Shadows Sub Test()


System.Console.WriteLine( _


"Test in DervCls")


End Sub

End Class


Public Class UseClasses


' DervCls widens to BaseCls.



Dim BObj As BaseCls =

public class BaseCls

{


// The element to be hidden



public int Z = 100;


public void Test()


{


System.Console.WriteLine(


"Test in BaseCls");


}

}


public class DervCls : BaseCls

{


// The hiding element



public new string Z = "*";


public new void Test()


{


System.Console.WriteLine(


"Test in DervCls");


}

}


public class UseClasses


New DervCls()


' Access through derived



' class.



Dim DObj As DervCls =


New DervCls()



Public Sub ShowZ()


System.Console.WriteLine( _


"Accessed through base "&_


"class: " & BObj.Z)


System.Console.WriteLine(_


"Accessed through derived "&_


"class: " & DObj.Z)


BObj.Test()


DObj.Test()


End Sub

End Class





{


// DervCls

widens to BaseCls



BaseCls BObj = new DervCls();


// Access through derived



//class



DervCls DObj = new DervCls();


public void ShowZ()


{


System.Console.WriteLine(


"Accessed through " +


"base class: {0}",


BObj.Z);


System.Console.WriteLine(


"Accessed through" +


" derived class:{0}",


DObj.Z);


BObj.Test();


DObj.Test();


}

}

WHILE Loops

' Test at start of loop


While n < 100 .


' Same as n = n + 1.



n += 1

End While '


while (n <

100)


n++;






Parameter Passing
by Value

' The argument Y is


'passed by value.


Public Sub ABC( _


ByVal y As Long)

'If ABC changes y, the


' changes do not affect x.


End Sub



ABC(x) ' Call the procedure.


' You can force parameters to


' be passed by value,


' regardless of how


' they are declared,


' by enclosing


' the parameters in


' extra parentheses.


ABC((x))



/* Note that there is

no way to pass reference

types (objects) strictly

by value. You can choose

to either pass the reference

(essentially a pointer), or

a reference to the reference

(a pointer to a pointer).*/

// The method:


void ABC(int x)

{


...

}

// Calling the method:


ABC(i);

Parameter Passing
by Reference

Public Sub ABC(ByRef y As Long)

' The parameter y is declared


'by referece:


' If ABC changes y, the changes are


' made to the value of x.


End Sub


ABC(x) ' Call the procedure.














/* Note that there is no


way to pass reference types


(objects) strictly by value.


You can choose to either


pass the reference


(essentially a pointer),


or a reference to the


reference (a pointer to a


pointer).*/

// Note also that unsafe C#


//methods can take pointers


//just like C++ methods. For


//details, see unsafe.


// The method:


void ABC(ref int x)

{


...

}

// Calling the method:


ABC(ref i);

Structured
Exception Handling

Try


If x = 0 Then


Throw New Exception( _


"x equals zero")


Else


Throw New Exception( _


"x does not equal zero")


End If

Catch err As System.Exception


MsgBox( _


"Error: " & Err.Description)

Finally


MsgBox( _


"Executing finally block.")

End Try









// try
-
catch
-
finally


try

{


if (x == 0)


throw new System.Exception(


"x equals zero");


else


throw new System.Exception(


"x does not equal zero");

}

catch (System.Exception err)

{


System.Console.WriteLine(


err.Message);

}

finally

{


System.Console.WriteLine(


"executing finally block");

}




Set an Object
Reference to
Nothing

o = Nothing

o = null;

Initializing Value
Types

Dim dt as New System.DateTime( _


2001, 4, 12, 22, 16, 49, 844)



System.DateTime dt =


new System.DateTime(


2001, 4, 12, 22, 16,


49, 844);



New Features of both languages in 2005 version

VB.NET

C#

Visual Basic 2005 has many new and improved language
features
--

such as inheritance, interfaces, overriding,
shared members, and overloading
--

that make it a powerful
object
-
oriented programming language. As a Visual Basic
developer, you can now create multithreaded, scalable
applications using explicit multithreading. This language
has following new features,

1.

Continue

Statement, which immediately skips to
the next iteration of a
Do
,
For
, or
While

loop.

2.

IsNot

operator, which you can avoid using the
Not

and
Is

operators in an awkward order.

3.

3.
Using...End
.
Using

statement block ensures
disposal of a system resource whe
n your code
leaves the block for any reason.

4.

Public Sub setbigbold( _

5.


ByVal c As Control)

6.

Using nf As New _

7.


System.Drawing.Font("Arial",_

8.


12.0F, FontStyle.Bold)

9.


c.Font = nf

10.


c.Text = "This is" &_

11.


"12
-
point Arial bold"

12.

End Using

End Sub

13.

Explicit Zero Lower Bound on an Array
, Visual
Basic now permits an array declaration to specify
the lower bound (0) of each dimension along with
the upper bound.

14.

Unsigned Types
, Visual Basic now supports
unsigned integer data types (
UShort
,
UInteger
, and
ULong
) as well as the signed type
SByte
.

15.

Operator Overloading
, Visual Basic now allows
you to define a standard operator (such as
+
,
&
,
Not
,
or
Mod
) on a class or structure you have defined.

16.

Partial Types
, to separate generated code from
your authored co
de into separate source files.

17.

Visual Basic now supports type parameters on
generic classes, structures, interfaces, procedures,
and delegates. A corresponding type argument
specifies at compilation time the data type of one of
the elements in the generic

type.

18.

Custom Events
. You can declare custom events by
using the Custom keyword as a modifier for the
Event

statement. In a custom event, you specify
exactly what happens when code adds or removes
an event handler to or from the event, or when code
raises

the event.

19.

Compiler Checking Options
, The /nowarn and
With the release of Visual Studio 2005, the C#
language has been updated to version 2.0. This
language has following new features:

1.

Generics

types

are added to the language to
enable programmers to achieve a high level
of code reuse and enhanced performance for
collection classes. Generic types can differ
only by arity. Parameters can also be forced
to be specific types.

2.

Iterators

make it eas
ier to dictate how a for
each loop will iterate over a collection's
contents.

3.

// Iterator Example

4.


5.

public class NumChar

6.

{

7.

string[] saNum = {

8.


"One", "Two", "Three",

9.


"Four", "Five", "Six",

10.


"Seven", "Eight", "Nine",

11.


"Zero"};

12.

public

13.


System.Collections.IEnumerator

14.


GetEnumerator()

15.

{

16.

foreach (string num in saNum)

17.

yield return num;

18.

}

19.

}

20.

// Create an instance of

21.


22.

// the collection class

23.


24.

NumChar oNumChar = new NumChar();

25.

// Iterate through it with foreach

26.


27.

foreach (string num in oNumCha
r)

28.

Console.WriteLine(num);

29.

Partial

type definitions allow a single
type, such as a class, to be split into
multiple files. The Visual Studio designer
uses this feature to separate its generated
code from user code.

30.

Nullable

types allow a variable to contain
a value that is undefined.

31.

Anonymous

Method

is now possible to pass
a block of code as a parameter. Anywhere a
delegate is expected, a code block can be
used instead: There is no need to define a
new method.

32.

button1.Cli
ck +=

33.


delegate { MessageBox.Show(

/warnaserror options provide more control over how
warnings are handled. Each one of these compiler
options now takes a list of warning IDs as an
optional parameter, to specify to which warnings
the o
ption applies.

20.

There are eight new command
-
line
compiler
options:


a.

The

/codepage

option specifies which
codepage to use when opening source files.

b.

The
/doc

option generates an XML
documentation file based on comments
within your code.

c.

The
/errorreport

option provides a
convenient way to report a Visual Basic
internal compiler error to Microsoft.

d.

The

/filealign

option specifies the size of
sections in your output file.

e.

The
/noconfig

option causes the compiler to
ignore the
Vbc.rsp

file.

f.

The
/nostdlib

option prevents the import of
mscorlib.dll
, which defines the entire
System namespace.

g.

The
/platform

option specifies the processor
to be targeted by the output file, in those
situations where it is necessary to explicitly
specify it.

h.

The
/unify

option
suppresses warnings
resulting from a mismatch between the
versions of directly and indirectly referenced
assemblies.


"Click!") };

34.

. The
namespace alias qualifier

(
::
)
provides more control over accessing
namespace members. The global
::

alias
allows to access the root namespace that
may be hidden by an entity in your code.

35.

Static

cl
asses

are a safe and convenient
way of declaring a class containing static
methods that cannot be instantiated. In C#
v1.2 you would have defined the class
constructor as private to prevent the class
being instantiated.

36.

8. There are eight new
compiler opt
ions
:

a.

/langversion
option: Can be used to
specify compatibility with a specific
version of the language.

b.

/platform

option: Enables you to
target IPF (IA64 or Itanium) and
AMD64 architectures.

c.

#pragma

warning: Used to disable
and enable individual warnin
gs in
code.

d.

/linkresource

option: Contains
additional options.

e.

/errorreport

option: Can be used to
report internal compiler errors to
Microsoft over the Internet.

f.

/keycontainer

and
/keyfile
: Support
specifying cryptographic keys.







Arrays


class

TestArraysClass

{


static

void

Main()


{


// Declare a single
-
dimensional array


int
[] array1 =
new

int
[5];



// Declare and set array element values


int
[] array2 =
new

int
[] { 1, 3, 5, 7, 9 };



// Alternative
syntax


int
[] array3 = { 1, 2, 3, 4, 5, 6 };



// Declare a two dimensional array


int
[,] multiDimensionalArray1 =
new

int
[2, 3];



// Declare and set array element values


int
[,] multiDimensionalArray2 = { { 1, 2, 3 }, {

4, 5, 6 } };



// Declare a jagged array


int
[][] jaggedArray =
new

int
[6][];



// Set the values of the first array in the jagged array structure


jaggedArray[0] =
new

int
[4] { 1, 2, 3, 4 };


}

}