Vous êtes sur la page 1sur 13

Advantages of both languages

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

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

Take the AddressOf (For class members, this operator returns delegate
address of a a reference to a function in the form of a delegate
function instance)
Declare that n/a volatile
an object can
be modified
asynchronousl
y
Force explicit Option Explicit n/a. (All variables must be
declaration of declared prior to use)
variables
Test for an obj = Nothing obj == null
object variable
that does not
refer to an
object
Value of an Nothing null
object variable
that does not
refer to an
object
Test for a IsDbNull n/a
database null
expression
Test whether an/a n/a
Variant
variable has
been
initialized
Define a Default by using indexers
default
property
Refer to a MyBase base
base class
Declare an Interface interface
interface
Specify an Implements (statement) class C1 : I1
interface to be
implemented
Declare a classClass <implementation> class
Specify that a MustInherit abstract
class can only
be inherited.
An instance of
the class
cannot be
created.
Specify that a NotInheritable sealed
class cannot
be inherited
Declare an Enum <members> End Enum enum
enumerated
type
Declare a classConst const (Applied to a field
constant declaration)
Derive a class Inherits C2 class C1 : C2
from a base
class
Override a Overrides override
method
Declare a MustOverride abstract
method that
must be
implemented
in a deriving
class
Declare a NotOverridable (Methods are sealed
method that not overridable by default.)
can't be
overridden
Declare a Overridable virtual
virtual
method,
property
(Visual Basic),
or property
accessor (C#,
C++)
Hide a base Shadowing n/a
class member
in a derived
class
Declare a Delegate delegate
typesafe
reference to a
class method
Specify that a WithEvents (Write code - no specific
variable can keyword)
contain an
object whose
events you
wish to handle
Specify the Handles (Event procedures can still be associated n/a
events for with a WithEventsvariable by naming pattern.)
which an
event
procedure will
be called
Evaluate an Hide Copy Coden/a
object With objExpr
expression <.member>
<.member>
once, in order End With
to access
multiple
members
Structured Hide Copy Codetry, catch, finally, throw
exception Try <attempt>
handling Catch
<handle errors>
Finally
<always execute>
End Try

Decision Select Case ..., Case, Case Else, End Select switch, case, default, goto,
structure break
(selection)
Decision If ... Then, ElseIf ... Then, Else, End If if, else
structure (if ...
then)
Loop structureWhile, Do [While, Until] ..., Loop [While, do, while, continue
(conditional) Until]
Loop structureFor ..., [Exit For], Next<BR>For Each ..., for, foreach
(iteration) [Exit For,] Next
Declare an Hide Copy Code Hide Copy Code
array Dim a() As Long int[] x = new int[5];

Initialize an Hide Copy Code Hide Copy Code


array Dim a() As Long = {3, 4, 5} int[] x = new int[5] {
1, 2, 3, 4, 5};

Reallocate Redim n/a


array
Visible outsidePublic public
the project or
assembly
Invisible Friend internal
outside the
assembly
(C#/Visual
Basic) or
within the
package
(Visual J#,
JScript)
Visible only Private private
within the
project (for
nested
classes, within
the enclosing
class)
Accessible Public public
outside class
and project or
module
Accessible Friend internal
outside the
class, but
within the
project
Only Private private
accessible
within class or
module
Only Protected protected
accessible to
current and
derived
classes
Preserve Static n/a
procedure's
local variables
Shared by all Shared static
instances of a
class
Comment ' //, /* */ for multi-line
code Rem comments
/// for XML comments
Case- No Yes
sensitive?
Call Windows Declare <API> use Platform Invoke
API
Declare and Event, RaiseEvent event
raise an event
Threading SyncLock lock
primitives
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 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 Is ==
reference variables
Compare object reference TypeOf x Is Class1 x is Class1
type
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 Hide Copy Code Hide Copy Code
Variables Dim x As Integer int x;
Public x As Integer = 10 int x = 10;

Comments Hide Copy Code Hide Copy Code


' comment // comment
x = 1 ' comment /* multiline
Rem comment comment */

Assignment Hide Copy Code Hide Copy Code


Statements nVal = 7 nVal = 7;

Conditional Hide Copy Code Hide Copy Code


Statements If nCnt <= nMax Then if (nCnt <= nMax)
' Same as nTotal = {
' nTotal + nCnt. nTotal += nCnt;
nTotal += nCnt nCnt++;
' Same as nCnt = nCnt + 1. }
nCnt += 1 else
Else {
nTotal += nCnt nTotal +=nCnt;
nCnt -= 1 nCnt--;
End If }

Selection Hide Copy Code Hide Copy Code


Statements Select Case n switch(n)
Case 0 {
MsgBox ("Zero") case 0:
' Visual Basic .NET exits Console.WriteLine("Zero");
' the Select at break;
' the end of a Case. case 1:
Case 1 Console.WriteLine("One");
MsgBox ("One") break;
Case 2 case 2:
MsgBox ("Two") Console.WriteLine("Two");
Case Else break;
MsgBox ("Default") default:
End Select Console.WriteLine("?");
break;
}

FOR Loops Hide Copy Code Hide Copy Code


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 Hide Shrink Copy Code Hide Shrink Copy Code
Class Public Class BaseCls public class BaseCls
Members ' The element to be shadowed {
Public Z As Integer = 100 // The element to be hidden
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 = "*" {
public Shadows Sub Test() // The hiding element
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 =
New DervCls() public class UseClasses
' Access through derived {
' class. // DervCls widens to BaseCls
Dim DObj As DervCls = BaseCls BObj = new DervCls();
New DervCls() // Access through derived
//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 Hide Copy Code Hide Copy Code


Loops ' Test at start of loop while (n < 100)
While n < 100 . n++;
' Same as n = n + 1.
n += 1
End While '

Parameter Hide Copy Code Hide Copy Code


Passing by ' The argument Y is /* Note that there is
Value 'passed by value. no way to pass reference
Public Sub ABC( _ types (objects) strictly
ByVal y As Long) by value. You can choose
'If ABC changes y, the to either pass the reference
' changes do not affect x. (essentially a pointer), or
End Sub a reference to the reference
(a pointer to a pointer).*/
ABC(x) ' Call the procedure. // The method:
' You can force parameters to void ABC(int x)
' be passed by value, {
' regardless of how ...
' they are declared, }
' by enclosing // Calling the method:
' the parameters in ABC(i);
' extra parentheses.
ABC((x))

Parameter Hide Copy Code Hide Copy Code


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
'by referece: (objects) strictly by value.
' If ABC changes y, the changes are You can choose to either
' made to the value of x. pass the reference
End Sub (essentially a pointer),
or a reference to the
ABC(x) ' Call the procedure. 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 Hide Copy Code Hide Copy Code


Exception Try // try-catch-finally
Handling If x = 0 Then try
Throw New Exception( _ {
"x equals zero") if (x == 0)
Else throw new System.Exception(
Throw New Exception( _ "x equals zero");
"x does not equal zero") else
End If throw new System.Exception(
Catch err As System.Exception "x does not equal zero");
MsgBox( _ }
"Error: " & Err.Description) catch (System.Exception err)
Finally {
MsgBox( _ System.Console.WriteLine(
"Executing finally block.") err.Message);
End Try }
finally
{
System.Console.WriteLine(
"executing finally block");
}

Set an Hide Copy Code Hide Copy Code


Object o = Nothing o = null;
Reference to
Nothing
Initializing Hide Copy Code Hide Copy Code
Value Types Dim 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);

New Features of both languages in 2005 version


VB.NET C#
Visual Basic 2005 has many new and improved With the release of Visual Studio 2005, the C#
language features -- such as inheritance, interfaces, language has been updated to version 2.0.
overriding, shared members, and overloading -- that This language has following new features:
make it a powerful object-oriented programming
language. As a Visual Basic developer, you can now1.
Generics types are added to the language to
create multithreaded, scalable applications using enable programmers to achieve a high level of
explicit multithreading. This language has following
code reuse and enhanced performance for
new features, collection classes. Generic types can differ only
by arity. Parameters can also be forced to be
1. Continue Statement, which immediately skips to the specific types.
next iteration of a Do, For, or While loop. 2. Iterators make it easier to dictate how a for
2. IsNot operator, which you can avoid using each loop will iterate over a collection's
the Notand Is operators in an awkward order. contents.
3. 3. Using...End. Using statement block ensures Hide Copy Code
disposal of a system resource when your code leaves // Iterator Example
the block for any reason. public class NumChar
{
Hide Copy Code
string[] saNum = {
Public Sub setbigbold( _ "One", "Two", "Three",
ByVal c As Control) "Four", "Five", "Six",
Using nf As New _ "Seven", "Eight", "Nine",
System.Drawing.Font("Arial",_ "Zero"};
12.0F, FontStyle.Bold) public
c.Font = nf System.Collections.IEnumerator
c.Text = "This is" &_ GetEnumerator()
"12-point Arial bold" {
End Using foreach (string num in saNum)
End Sub yield return num;
}
4. Explicit Zero Lower Bound on an Array, Visual Basic }
now permits an array declaration to specify the lower // Create an instance of
// the collection class
bound (0) of each dimension along with the upper NumChar oNumChar = new NumChar();
bound. // Iterate through it with foreach
5. Unsigned Types, Visual Basic now supports unsigned foreach (string num in oNumChar)
Console.WriteLine(num);
integer data types (UShort, UInteger, and ULong)
as well as the signed type SByte. 3. Partial type definitions allow a single type,
6. Operator Overloading, Visual Basic now allows you such as a class, to be split into multiple files.
to define a standard operator (such as +, &, Not, The Visual Studio designer uses this feature to
or Mod) on a class or structure you have defined. separate its generated code from user code.
7. Partial Types, to separate generated code from your 4. Nullable types allow a variable to contain a
authored code into separate source files. value that is undefined.
8. Visual Basic now supports type parameters on generic 5. Anonymous Method is now possible to pass a
classes, structures, interfaces, procedures, and block of code as a parameter. Anywhere a
delegates. A corresponding type argument specifies delegate is expected, a code block can be used
at compilation time the data type of one of the instead: There is no need to define a new
elements in the generic type. method.
9. Custom Events. You can declare custom events by Hide Copy Code

using the Custom keyword as a modifier for button1.Click +=


the Event statement. In a custom event, you specify delegate { MessageBox.Show(
"Click!") };
exactly what happens when code adds or removes an
event handler to or from the event, or when code 6. . The namespace alias qualifier (::) provides
raises the event. more control over accessing namespace
10. Compiler Checking Options, The /nowarn and members. The global :: alias allows to access
/warnaserror options provide more control over how the root namespace that may be hidden by an
warnings are handled. Each one of these compiler entity in your code.
options now takes a list of warning IDs as an optional Static classes are a safe and convenient way
7.
parameter, to specify to which warnings the option of declaring a class containing static methods
applies. that cannot be instantiated. In C# v1.2 you
11. There are eight new command-line compiler would have defined the class constructor as
options: private to prevent the class being instantiated.
a. The /codepage option specifies which codepage to 8. 8. There are eight new compiler options:
use when opening source files. a. /langversion option: Can be used to specify
b. The /doc option generates an XML documentation compatibility with a specific version of the
file based on comments within your code. language.
c. The /errorreport option provides a convenient way b. /platform option: Enables you to target IPF
to report a Visual Basic internal compiler error to (IA64 or Itanium) and AMD64 architectures.
Microsoft. c. #pragma warning: Used to disable and enable
d. The /filealign option specifies the size of sections in individual warnings in code.
your output file. d. /linkresource option: Contains additional
e. The /noconfig option causes the compiler to ignore options.
the Vbc.rsp file. e. /errorreport option: Can be used to report
f. The /nostdlib option prevents the import internal compiler errors to Microsoft over the
of mscorlib.dll, which defines the entire System Internet.
namespace. f. /keycontainer and /keyfile: Support
g. The /platform option specifies the processor to be specifying cryptographic keys.
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.

Vous aimerez peut-être aussi