Você está na página 1de 13

Introduction

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. We will discuss about
the differences in the following topics:

1. Advantages of both languages


2. Keyword Differences
3. Data types Differences
4. Operators Differences
5. Programming Difference

Advantages of both languages


VB.NET C#
• Support for optional parameters - very • XML documentation generated
handy for some COM interoperability. from source code comments. (This
• Support for late binding with Option is coming in VB.NET with
Strict off - type safety at compile time Whidbey (the code name for the
goes out of the window, but legacy next version of Visual Studio
libraries which don't have strongly typed and .NET), and there are tools
interfaces become easier to use. which will do it with existing
• Support for named indexers. VB.NET code already.)
• Various legacy VB functions (provided • Operator overloading - again,
in the Microsoft.VisualBasic coming to VB.NET in Whidbey.
namespace, and can be used by other • Language support for unsigned
languages with a reference to the types (you can use them from
Microsoft.VisualBasic.dll). Many of VB.NET, but they aren't in the
these can be harmful to performance if language itself). Again, support
used unwisely, however, and many for these is coming to VB.NET in
people believe they should be avoided Whidbey.
for the most part. • Explicit interface implementation,
• The with construct: it's a matter of where an interface which is
debate as to whether this is an advantage already implemented in a base
or not, but it's certainly a difference. class can be re-implemented
• Simpler (in expression - perhaps more separately in a derived class.
complicated in understanding) event Arguably this makes the class
handling, where a method can declare harder to understand, in the same
that it handles an event, rather than the way that member hiding normally
handler having to be set up in code. does.

• The VB.NET parts of Visual Studio • Unsafe code. This allows pointer
.NET compiles your code in the arithmetic etc, and can improve
background. While this is considered as performance in some situations.
an advantage for small projects, people However, it is not to be used
creating very large projects have found lightly, as a lot of the normal
that the IDE slows down considerably as safety of C# is lost (as the name
the project gets larger. 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, declarators (keywords include user-
Protected, Static1, defined types and built-in types)
Shared, Dim
Declare a named Const const
constant
Create a new object New, CreateObject() new
Function/method Sub void
does not return a
value
Overload a function Overloads (No language keyword required for
or method (Visual this purpose)
Basic: overload a
procedure or method)
Refer to the current Me this
object
Make a nonvirtual MyClass n/a
call to a virtual
method of the current
object
Retrieve character GetChar Function []
from 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 Dim x As Long = 5 // initialize to a value:
Dim c As New _ int x = 123;
where it is declared
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
declaration of prior to use)
variables
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 IsDbNull n/a
null expression
Test whether a n/a n/a
Variant 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 Implements (statement) class C1 : I1
to be implemented
Declare a class Class <implementation> class
Specify that a class MustInherit abstract
can only be inherited.
An instance of the
class cannot be
created.
Specify that a class NotInheritable sealed
cannot be inherited
Declare an Enum <members> End Enum enum
enumerated 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 sealed
can't be overridden are 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 WithEvents (Write code - no specific keyword)
variable can contain
an object whose
events you wish to
handle
Specify the events for Handles (Event procedures n/a
which an event can still be associated with a
procedure will be WithEvents variable by
called naming pattern.)
Evaluate an object With objExpr n/a
<.member>
expression once, in
<.member>
order to access End With
multiple members
Structured exception Try <attempt> try, catch, finally, throw
Catch
handling
<handle errors>
Finally
<always execute>
End Try
Decision structure Select Case ..., Case, switch, case, default, goto, break
(selection) Case Else, End Select
Decision structure If ... Then, ElseIf ... if, else
(if ... then) Then, Else, End If
Loop structure While, Do [While, Until] do, while, continue
(conditional) ..., Loop [While, Until]
Loop structure For ..., [Exit For], for, foreach
(iteration) Next
For Each ..., [Exit
For,] Next
Declare an array Dim a() As Long int[] x = new int[5];
Initialize an array Dim a() As Long = {3, int[] x = new int[5] {
4, 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 Private private
the project (for nested
classes, within the
enclosing class)
Accessible outside Public public
class and project or
module
Accessible outside Friend internal
the class, but within
the project
Only accessible Private private
within class or
module
Only accessible to Protected protected
current and derived
classes
Preserve procedure's Static n/a
local variables
Shared by all Shared static
instances 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 TypeOf x Is Class1 x is Class1
reference type
Concatenate strings & +
Shortcircuited Boolean AndAlso &&
AND
Shortcircuited Boolean OrElse ||
OR
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 Dim x As Integer int x;
Public x As Integer = 10 int x = 10;
Variables
Comments ' comment // comment
x = 1 ' comment /* multiline
Rem comment comment */
Assignment nVal = 7 nVal = 7;
Statements
Conditional If nCnt <= nMax Then if (nCnt <= nMax)
' Same as nTotal = {
Statements ' 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 Select Case n switch(n)
Case 0 {
Statements MsgBox ("Zero") case 0:
' Visual Basic .NET exits Console.WriteLine("Zero
' the Select at ");
' the end of a Case. break;
Case 1 case 1:
MsgBox ("One") Console.WriteLine("One"
Case 2 );
MsgBox ("Two") break;
Case Else case 2:
MsgBox ("Default") Console.WriteLine("Two"
End Select );
break;
default:
Console.WriteLine("?");
break;
}

FOR Loops 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);
For Each prop In obj foreach(prop current in obj)
prop = 42 {
Next prop current=42;
}
Hiding Public Class BaseCls public class BaseCls
' The element to be shadowed {
Base Class
Public Z As Integer = 100 // The element to be
Members public Sub Test() hidden
System.Console.WriteLine( _ public int Z = 100;
"Test in BaseCls") public void Test()
End Sub {
End Class System.Console.WriteLin
e(
Public Class DervCls "Test in BaseCls");
Inherits BaseCls }
' The shadowing element. }
Public Shadows Z As String =
"*" public class DervCls :
public Shadows Sub Test() BaseCls
System.Console.WriteLine( _ {
"Test in DervCls") // The hiding element
End Sub public new string Z = "*";
End Class public new void Test()
{
Public Class UseClasses System.Console.WriteLine(
' DervCls widens to BaseCls. "Test in DervCls");
Dim BObj As BaseCls = }
New DervCls() }
' Access through derived
' class. public class UseClasses
Dim DObj As DervCls = {
New DervCls() // DervCls widens to
BaseCls
Public Sub ShowZ() BaseCls BObj = new
System.Console.WriteLine( _ DervCls();
"Accessed through base "&_ // Access through derived
"class: " & BObj.Z) //class
System.Console.WriteLine(_ DervCls DObj = new
"Accessed through derived "&_ DervCls();
"class: " & DObj.Z) public void ShowZ()
BObj.Test() {
DObj.Test() System.Console.WriteLine(
End Sub "Accessed through " +
End Class "base class: {0}",
BObj.Z);
System.Console.WriteLine(
"Accessed through" +
" derived class:{0}",
DObj.Z);
BObj.Test();
DObj.Test();
}
}
WHILE ' Test at start of loop while (n < 100)
While n < 100 . n++;
Loops
' Same as n = n + 1.
n += 1
End While '
Parameter ' The argument Y is /* Note that there is
'passed by value. no way to pass reference
Passing by Public Sub ABC( _ types (objects) strictly
Value 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 Public Sub ABC(ByRef y As Long) /* Note that there is no
' The parameter y is declared way to pass reference types
Passing by
'by referece: (objects) strictly by
Reference ' If ABC changes y, the changes value.
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 Try // try-catch-finally
If x = 0 Then try
Exception
Throw New Exception( _ {
Handling "x equals zero") if (x == 0)
Else throw new
Throw New Exception( _ System.Exception(
"x does not equal zero") "x equals zero");
End If else
Catch err As System.Exception throw new
MsgBox( _ System.Exception(
"Error: " & Err.Description) "x does not equal
Finally zero");
MsgBox( _ }
"Executing finally block.") catch (System.Exception err)
End Try {
System.Console.WriteLine(
err.Message);
}
finally
{
System.Console.WriteLine(
"executing finally
block");
}

Set an o = Nothing o = null;


Object
Reference
to Nothing
Initializing Dim dt as New System.DateTime( _ System.DateTime dt =
2001, 4, 12, 22, 16, 49, 844) new System.DateTime(
Value 2001, 4, 12, 22, 16,
Types 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,
language features -- such as inheritance, the C# language has been updated to
interfaces, overriding, shared members, and version 2.0. This language has following
overloading -- that make it a powerful object- new features:
oriented programming language. As a Visual
Basic developer, you can now create 1. Generics types are added to the
multithreaded, scalable applications using language to enable programmers
explicit multithreading. This language has to achieve a high level of code
following new features, reuse and enhanced performance
for collection classes. Generic
1. Continue Statement, which types can differ only by arity.
immediately skips to the next iteration Parameters can also be forced to
of a Do, For, or While loop. be specific types.
2. IsNot operator, which you can avoid 2. Iterators make it easier to dictate
using the Not and Is operators in an how a for each loop will iterate
awkward order. over a collection's contents.
3. Using...End. Using statement block 3. // Iterator Example
4. public class NumChar
ensures disposal of a system resource 5. {
when your code leaves the block for any 6. string[] saNum = {
reason. 7. "One", "Two", "Three",
4. Public Sub setbigbold( _ 8. "Four", "Five", "Six",
5. ByVal c As Control) 9. "Seven", "Eight", "Nine",
6. Using nf As New _ 10. "Zero"};
7. System.Drawing.Font("Arial",_ 11. public
8. 12.0F, FontStyle.Bold) 12. System.Collections.IEnume
9. c.Font = nf rator
10. c.Text = "This is" &_ 13. GetEnumerator()
11. "12-point Arial bold" 14. {
12. End Using 15. foreach (string num in
End Sub saNum)
16. yield return num;
17. }
13. Explicit Zero Lower Bound on an 18. }
Array, Visual Basic now permits an 19. // Create an instance of
array declaration to specify the lower 20. // the collection class
bound (0) of each dimension along with 21. NumChar oNumChar = new
the upper bound. NumChar();
22. // Iterate through it with
14. Unsigned Types, Visual Basic now foreach
supports unsigned integer data types 23. foreach (string num in
(UShort, UInteger, and ULong) as well oNumChar)
as the signed type SByte. 24. Console.WriteLine(num);
15. Operator Overloading, Visual Basic 25. Partial type definitions allow a
now allows you to define a standard single type, such as a class, to be
operator (such as +, &, Not, or Mod) on a split into multiple files. The Visual
class or structure you have defined. Studio designer uses this feature to
16. Partial Types, to separate generated separate its generated code from
code from your authored code into user code.
separate source files. 26. Nullable types allow a variable to
17. Visual Basic now supports type contain a value that is undefined.
parameters on generic classes, 27. Anonymous Method is now
structures, interfaces, procedures, and possible to pass a block of code as
delegates. A corresponding type a parameter. Anywhere a delegate
argument specifies at compilation time is expected, a code block can be
the data type of one of the elements in used instead: There is no need to
the generic type. define a new method.
18. Custom Events. You can declare 28. button1.Click +=
29. delegate
custom events by using the Custom
{ MessageBox.Show(
keyword as a modifier for the Event "Click!") };
statement. In a custom event, you
specify exactly what happens when code 30. . The namespace alias qualifier
adds or removes an event handler to or (::) provides more control over
from the event, or when code raises the accessing namespace members.
event. The global :: alias allows to
19. Compiler Checking Options, The access the root namespace that
/nowarn and /warnaserror options may be hidden by an entity in your
provide more control over how code.
warnings are handled. Each one of these 31. Static classes are a safe and
compiler options now takes a list of convenient way of declaring a
warning IDs as an optional parameter, to class containing static methods
specify to which warnings the option that cannot be instantiated. In C#
applies. v1.2 you would have defined the
20. There are eight new command-line class constructor as private to
compiler options: prevent the class being
a. The /codepage option specifies instantiated.
which codepage to use when 32. 8. There are eight new compiler
opening source files. options:
b. The /doc option generates an a. /langversion option: Can
XML documentation file based be used to specify
on comments within your code. compatibility with a
c. The /errorreport option specific version of the
provides a convenient way to language.
report a Visual Basic internal b. /platform option: Enables
compiler error to Microsoft. you to target IPF (IA64 or
d. The /filealign option specifies Itanium) and AMD64
the size of sections in your architectures.
output file. c. #pragma warning: Used to
e. The /noconfig option causes the disable and enable
compiler to ignore the Vbc.rsp individual warnings in
file. code.
f. The /nostdlib option prevents d. /linkresource option:
the import of mscorlib.dll, which Contains additional
defines the entire System options.
namespace. e. /errorreport option: Can
g. The /platform option specifies be used to report internal
the processor to be targeted by compiler errors to
the output file, in those situations Microsoft over the
where it is necessary to Internet.
explicitly specify it.
f. /keycontainer and
h. The /unify option suppresses /keyfile: Support
warnings resulting from a specifying cryptographic
mismatch between the versions keys.
of directly and indirectly
referenced assemblies.

Você também pode gostar