Advantages of Both Languages: Microsoft - Visualbasic

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 11

Advantages of both languages

VB.NET C#
• Support for optional parameters - very • XML documentation generated from
handy for some COM interoperability. source code comments. (This is
• Support for late binding with Option Strict coming in VB.NET with Whidbey
off - type safety at compile time goes out of (the code name for the next version of
the window, but legacy libraries which don't Visual Studio and .NET), and there
have strongly typed interfaces become are tools which will do it with existing
easier to use. VB.NET code already.)
• Support for named indexers. • Operator overloading - again, coming
• Various legacy VB functions (provided in to VB.NET in Whidbey.
the Microsoft.VisualBasic namespace, • Language support for unsigned types
and can be used by other languages with a (you can use them from VB.NET, but
reference to the Microsoft.VisualBasic.dll). they aren't in the language itself).
Many of these can be harmful to Again, support for these is coming to
performance if used unwisely, however, and VB.NET in Whidbey.
many people believe they should be avoided • The using statement, which makes
for the most part. unmanaged resource disposal simple.
• The with construct: it's a matter of debate as • Explicit interface implementation,
to whether this is an advantage or not, but where an interface which is already
it's certainly a difference. implemented in a base class can be re-
• Simpler (in expression - perhaps more implemented separately in a derived
complicated in understanding) event class. Arguably this makes the class
handling, where a method can declare that it harder to understand, in the same way
handles an event, rather than the handler that member hiding normally does.
having to be set up in code.
• The ability to implement interfaces with • Unsafe code. This allows pointer
methods of different names. (Arguably this arithmetic etc, and can improve
makes it harder to find the implementation performance in some situations.
of an interface, however.) However, it is not to be used lightly,
• Catch ... When ... clauses, which allow as a lot of the normal safety of C# is
exceptions to be filtered based on runtime lost (as the name implies). Note that
expressions rather than just by type. unsafe code is still managed code, i.e.,
it is compiled to IL, JITted, and run
• The VB.NET parts of Visual Studio .NET within the CLR.
compiles your code in the background.
While this is considered as an advantage for
small projects, people creating very large
projects have found that the IDE slows
down considerably as the project gets larger.

Keyword Differences
Purpose VB.NET C#
Declare a variable Private, Public, Friend, declarators (keywords include user-
Protected, Static1, Shared, defined types and built-in types)
Dim
Declare a named Const const
constant
Create a new object New, CreateObject() new
Function/method does Sub void
not return a value
Overload a function or Overloads (No language keyword required for this
method (Visual Basic: purpose)
overload a procedure or
method)
Refer to the current Me this
object
Make a nonvirtual call MyClass n/a
to a virtual method of
the current object
Retrieve character from GetChar Function []
a string
Declare a compound Structure <members> End struct, class, interface
Structure
data type (Visual
Basic: Structure)
Initialize an object Sub New() Constructors, or system default type
(constructors) constructors
Terminate an object n/a n/a
directly
Method called by the Finalize destructor
system just before
garbage collection
reclaims an object7
Initialize a variable Collapse Collapse
where it is declared Dim x As Long = 5 // initialize to a value:
Collapse
Dim c As New _ int x = 123;
Car(FuelTypeEnum.Gas) // or use default

// constructor:

int x = new int();


Take the address of a AddressOf (For class delegate
function members, this operator returns
a reference to a function in the
form of a delegate instance)
Declare that an object n/a volatile
can be modified
asynchronously
Force explicit Option Explicit n/a. (All variables must be declared prior
declaration of variables to use)
Test for an object obj = Nothing obj == null
variable that does not
refer to an object
Value of an object Nothing null
variable that does not
refer to an object
Test for a database null IsDbNull n/a
expression
Test whether a Variant n/a n/a
variable has been
initialized
Define a default Default by using indexers
property
Refer to a base class MyBase base
Declare an interface Interface interface
Specify an interface to Implements (statement) class C1 : I1
be implemented
Declare a class Class <implementation> class
Specify that a class can MustInherit abstract
only be inherited. An
instance of the class
cannot be created.
Specify that a class NotInheritable sealed
cannot be inherited
Declare an enumerated Enum <members> End Enum enum
type
Declare a class Const const (Applied to a field declaration)
constant
Derive a class from a Inherits C2 class C1 : C2
base class
Override a method Overrides override
Declare a method that MustOverride abstract
must be implemented
in a deriving class
Declare a method that NotOverridable (Methods are sealed
can't be overridden not overridable by default.)
Declare a virtual Overridable virtual
method, property
(Visual Basic), or
property accessor (C#,
C++)
Hide a base class Shadowing n/a
member in a derived
class
Declare a typesafe Delegate delegate
reference to a class
method
Specify that a variable WithEvents (Write code - no specific keyword)
can contain an object
whose events you wish
to handle
Specify the events for Handles (Event procedures can n/a
which an event still be associated with a
procedure will be WithEvents variable by
called naming pattern.)
Evaluate an object Collapse n/a
expression once, in With objExpr
order to access multiple <.member>
<.member>
members End With
Structured exception Collapse try, catch, finally, throw
handling Try <attempt>
Catch
<handle errors>
Finally
<always execute>
End Try
Decision structure Select Case ..., Case, Case switch, case, default, goto, break
(selection) Else, End Select
Decision structure (if ... If ... Then, ElseIf ... if, else
then) Then, Else, End If
Loop structure While, Do [While, do, while, continue
(conditional) Until] ..., Loop [While,
Until]
Loop structure For ..., [Exit For], Next for, foreach
(iteration) For Each ..., [Exit For,]
Next
Declare an array Collapse Collapse
Dim a() As Long int[] x = new int[5];
Initialize an array Collapse Collapse
Dim a() As Long = {3, 4, int[] x = new int[5] {
5} 1, 2, 3, 4, 5};

Reallocate array Redim n/a


Visible outside the Public public
project or assembly
Invisible outside the Friend internal
assembly (C#/Visual
Basic) or within the
package (Visual J#,
JScript)
Visible only within the Private private
project (for nested
classes, within the
enclosing class)
Accessible outside Public public
class and project or
module
Accessible outside the Friend internal
class, but within the
project
Only accessible within Private private
class or module
Only accessible to Protected protected
current and derived
classes
Preserve procedure's Static n/a
local variables
Shared by all instances Shared static
of a class
Comment code ' //, /* */ for multi-line comments
Rem
/// for XML comments
Case-sensitive? No Yes
Call Windows API Declare <API> use Platform Invoke
Declare and raise an Event, RaiseEvent event
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 short, char (Unicode character)
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 \ /
Modulus (division Mod %
returning 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 Is ==
reference variables
Compare object reference TypeOf x Is Class1 x is Class1
type
Concatenate strings & +
Shortcircuited Boolean AndAlso &&
AND
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 Collapse Collapse
Variables Dim x As Integer int x;
Public x As Integer = 10 int x = 10;
Comments Collapse Collapse
' comment // comment

x = 1 ' comment /* multiline


comment */
Rem comment
Assignment Collapse Collapse
Statements nVal = 7 nVal = 7;
Conditional Collapse Collapse
Statements If nCnt <= nMax Then if (nCnt <= nMax)
' Same as nTotal = {
nTotal += nCnt;
' nTotal + nCnt. nCnt++;
}
nTotal += nCnt else
' Same as nCnt = nCnt + 1. {
nTotal +=nCnt;
nCnt += 1 nCnt--;
Else }
nTotal += nCnt
nCnt -= 1
End If
Selection Collapse Collapse
Statements Select Case n switch(n)
Case 0 {
MsgBox ("Zero") case 0:
' Visual Basic .NET exits Console.WriteLine("Zero")
;
' the Select at break;
case 1:
' the end of a Case. Console.WriteLine("One");
break;
Case 1 case 2:
MsgBox ("One") Console.WriteLine("Two");
Case 2 break;
MsgBox ("Two") default:
Case Else Console.WriteLine("?");
MsgBox ("Default") break;
End Select }

FOR Loops Collapse Collapse


For n = 1 To 10 for (int i = 1; i <= 10; i++)
MsgBox("The number is " & n) Console.WriteLine(
Next "The number is {0}", i);
foreach(prop current in obj)
For Each prop In obj {
prop = 42 current=42;
Next prop }
Hiding Base Collapse Collapse
Class Public Class BaseCls public class BaseCls
' The element to be shadowed {
Members // The element to be hidden
Public Z As Integer = 100
public Sub Test() public int Z = 100;
System.Console.WriteLine( _ public void Test()
"Test in BaseCls") {
End Sub System.Console.WriteLine(
End Class "Test in BaseCls");
}
Public Class DervCls }
Inherits BaseCls
' The shadowing element. public class DervCls : BaseCls
{
Public Shadows Z As String = "*" // The hiding element
public Shadows Sub Test()
System.Console.WriteLine( _ public new string Z = "*";
"Test in DervCls") public new void Test()
End Sub {
End Class System.Console.WriteLine(
"Test in DervCls");
Public Class UseClasses }
' DervCls widens to BaseCls. }

Dim BObj As BaseCls = public class UseClasses


New DervCls() {
' Access through derived // DervCls widens to BaseCls

' class. BaseCls BObj = new DervCls();


// Access through derived
Dim DObj As DervCls =
New DervCls() //class
Public Sub ShowZ() DervCls DObj = new DervCls();
System.Console.WriteLine( _ public void ShowZ()
"Accessed through base "&_ {
"class: " & BObj.Z) System.Console.WriteLine(
System.Console.WriteLine(_ "Accessed through " +
"Accessed through derived "&_ "base class: {0}",
"class: " & DObj.Z) BObj.Z);
BObj.Test() System.Console.WriteLine(
DObj.Test() "Accessed through" +
End Sub " derived class:{0}",
End Class DObj.Z);
BObj.Test();
DObj.Test();
}
}
WHILE Collapse Collapse
Loops ' Test at start of loop while (n < 100)
n++;
While n < 100 .
' Same as n = n + 1.

n += 1
End While '

Parameter Collapse Collapse


Passing by ' The argument Y is /* Note that there is
no way to pass reference
Value
'passed by value. types (objects) strictly
by value. You can choose
Public Sub ABC( _ to either pass the reference
ByVal y As Long) (essentially a pointer), or
'If ABC changes y, the a reference to the reference
(a pointer to a pointer).*/
' changes do not affect x. // The method:

End Sub void ABC(int x)


{
ABC(x) ' Call the procedure. ...
}
' You can force parameters to // Calling the method:

' be passed by value, ABC(i);

' regardless of how

' they are declared,

' by enclosing

' the parameters in

' extra parentheses.

ABC((x))
Parameter Collapse Collapse
Passing by Public Sub ABC(ByRef y As Long) /* Note that there is no
Reference ' The parameter y is declared way to pass reference types
(objects) strictly by value.
'by referece: You can choose to either
pass the reference
' If ABC changes y, the changes are (essentially a pointer),
or a reference to the
' made to the value of x. reference (a pointer to a
pointer).*/
End Sub // Note also that unsafe C#

ABC(x) ' Call the procedure. //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 Collapse Collapse
Exception Try // try-catch-finally
If x = 0 Then
Handling
Throw New Exception( _ try
"x equals zero") {
Else if (x == 0)
Throw New Exception( _ throw new System.Exception(
"x does not equal zero") "x equals zero");
End If else
Catch err As System.Exception throw new System.Exception(
MsgBox( _ "x does not equal zero");
"Error: " & Err.Description) }
Finally catch (System.Exception err)
MsgBox( _ {
"Executing finally block.") System.Console.WriteLine(
End Try err.Message);
}
finally
{
System.Console.WriteLine(
"executing finally block");
}

Set an Collapse Collapse


Object o = Nothing o = null;
Reference to
Nothing
Initializing Collapse Collapse
Value TypesDim dt as New System.DateTime( _ System.DateTime dt =
2001, 4, 12, 22, 16, 49, 844) new System.DateTime(
2001, 4, 12, 22, 16,
49, 844);

You might also like