Sei sulla pagina 1di 14

Contents

1. 2. 3. 4. 5. 6. 7. 8. 9. Introduction Advantages of both languages Keyword Differences Data types Differences Operators Differences Programming Difference New Features of both languages in 2005 version Conclusion History

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. 2. 3. 4. 5. Advantages of both languages Keyword Differences Data types Differences Operators Differences Programming Difference

Advantages of both languages


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

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 allow 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 projects have found that the IDE slows down considerably as the project gets larger.

class. Arguably this makes the class harder to understand, in the same way that member hiding normally does. Unsafe 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 Declare a variable VB.NET C# Private, Public, Friend,Protected, Stati declarators (keywords c1, Shared, Dim include user-defined types and built-in types) Const const

Declare a named constant Create a new New, CreateObject() object Function/me Sub thod does not return a value Overload a Overloads function or method (Visual Basic: overload a procedure or method) Refer to the Me current object MyClass Make a nonvirtual call to a virtual method of the current object

new void

(No language keyword required for this purpose)

this

n/a

GetChar Function [] Retrieve character from a string Structure <members> EndStructure Declare a struct, class, interface compound data type (Visual Basic: Structure) Initialize an Sub New() Constructors, or system object default type constructors (constructors ) Terminate n/a n/a an object directly Finalize Method destructor called by the system just before garbage collection reclaims an object7 Collapse | Copy Code Collapse | Copy Code Initialize a variable // initialize to a value: Dim x As Long = 5 int x = 123; where it is Collapse | Copy Code// or use default declared // constructor:
Dim c As New _ Car(FuelTypeEnum.Gas) int x = new int();

Take the AddressOf (For class members, this operator address of a returns a reference to a function in the form of function a delegate instance) Declare that n/a an object can be modified asynchronou sly Option Explicit Force explicit declaration of variables Test for an obj = Nothing object variable that does not refer to an object Value of an Nothing object

delegate

volatile

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

obj == null

null

variable that does not refer to an object IsDbNull Test for a database null expression Test whether n/a a Variant variable has been initialized Default Define a default property Refer to a MyBase base class Declare an Interface interface Specify an Implements (statement) interface to be implemente d Class <implementation> Declare a class Specify that MustInherit a class can only be inherited. An instance of the class cannot be created. Specify that NotInheritable a class cannot be inherited Declare an Enum <members> End Enum enumerated type Const Declare a class constant Inherits C2 Derive a class from a base class Override a Overrides

n/a

n/a

by using indexers

base interface class C1 : I1

class abstract

sealed

enum

const (Applied to a field declaration) class C1 : C2

override

method MustOverride abstract Declare a method that must be implemente d in a deriving class sealed Declare a NotOverridable (Methods are method that notoverridable by default.) can't be overridden Overridable virtual Declare a virtual method, property (Visual Basic), or property accessor (C#, C++) Hide a base Shadowing n/a class member in a derived class Delegate delegate Declare a typesafe reference to a class method Specify that WithEvents (Write code - no specific a variable keyword) can contain an object whose events you wish to handle Specify the Handles (Event procedures can still be n/a events for associated with a WithEventsvariable by which an naming pattern.) event procedure will be called Collapse | Copy Coden/a Evaluate an object With objExpr <.member> expression <.member> once, in End With order to

access multiple members Structured exception handling

Collapse | Copy Codetry,

catch, finally, thro

Try <attempt> Catch <handle errors> Finally <always execute> End Try

Decision Select Case ..., Case, CaseElse, End Se switch, case, default, go lect structure to, break (selection) Decision If ... Then, ElseIf ... Then,Else, End if, else structure (if If ... then) Loop While, Do [While, Until] do, while, continue structure ...,Loop [While, Until] (conditional) Loop For ..., [Exit For], Next for, foreach For Each ..., [Exit For,]Next structure (iteration) Collapse | Copy Code Collapse | Copy Code Declare an array Dim a() As Long int[] x = new int[5];
Collapse | Copy Code Collapse | Copy Code Initialize an array Dim a() As Long = {3, 4, 5} int[] x = new int[5] {

1, 2, 3, 4, 5};

Reallocate array Visible outside the project or assembly Invisible outside the assembly (C#/Visual Basic) or within the package (Visual J#, JScript) Visible only within the project (for nested classes, within the enclosing class)

Redim Public

n/a

public

Friend

internal

Private

private

Accessible Public outside class and project or module Accessible Friend outside the class, but within the project Private Only accessible within class or module Protected Only accessible to current and derived classes Static Preserve procedure's local variables Shared by all Shared instances of a class Comment ' Rem code Casesensitive? Call Windows API Declare and raise an event Threading primitives Go to No

public

internal

private

protected

n/a

static

//, /* */ for multi-line comments /// for XML comments Yes


use Platform Invoke

Declare <API>

Event, RaiseEvent

event

SyncLock Goto

lock goto

Data types Differences


Purpose/Size Decimal Date (varies) 1 byte 2 bytes 2 bytes VB.NET C# Decimal decimal Date DateTime String string Byte byte Boolean bool Short, Char (Unicode character)short, char

4 bytes 8 bytes 4 bytes 8 bytes

Integer Long Single Double

(Unicode character) int long float double

Operators Differences
Purpose Integer division Modulus (division returning only the remainder) Exponentiation Integer division Assignment Concatenate Modulus Bitwise-AND Bitwise-exclusive-OR Bitwise-inclusive-OR Equal Not equal Compare two object reference variables Compare object reference type Concatenate strings Shortcircuited Boolean AND Shortcircuited Boolean OR Scope resolution Array element Type cast Postfix increment Postfix decrement Indirection Address of Logical-NOT One's complement Prefix increment Prefix decrement Size of type Bitwise-AND Bitwise-exclusive-OR Bitwise-inclusive-OR Logical-AND VB.NET \ Mod C# / %

^ \= &= NEW n/a n/a n/a n/a = <> Is TypeOf x Is Class1 & AndAlso OrElse . () Cint, CDbl, ..., CType n/a n/a n/a AddressOf Not Not n/a n/a n/a And Xor Or And

n/a /=

+= %= &= ^= |= == != == x is Class1 + && || . and base [ ] (type) ++ -* (unsafe mode only) & (unsafe mode only; also see fixed) ! ~ ++ -sizeof & ^ | &&

Logical-OR Conditional Pointer to member

Or If Function () n/a

|| ?: . (Unsafe mode only)

Programming Difference
Purpose VB.NET Declaring Variables Dim x As Integer Comments
' comment x = 1 ' comment Rem comment

C#
Collapse | Copy Code Collapse | Copy Code

Public x As Integer = 10

int x; int x = 10;


Collapse | Copy Code

Collapse | Copy Code

// comment /* multiline comment */


Collapse | Copy Code Collapse | Copy Code

Assignment Statements nVal = 7 Conditional Statements If nCnt <= nMax Then

nVal = 7;
Collapse | Copy Code Collapse | Copy Code

' 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--; }
Collapse | Copy Code

Selection Statements Select Case n

Collapse | Copy Code

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; }
Collapse | Copy Code

FOR Loops

Collapse | Copy Code

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; }
Collapse | Copy Code

Hiding Base Class Public Class BaseCls

Collapse | Copy Code

' The element to be shadowed

public class BaseCls {

Members

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 = 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 }

// 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 { // 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(); } }
Collapse | Copy Code

WHILE Loops

Collapse | Copy Code

' Test at While n < ' Same n += 1 End While

start of loop 100 . as n = n + 1. '

while (n < 100) n++;

Parameter Passing by ' The argument Y is 'passed by value. Value

Collapse | Copy Code

Collapse | Copy Code

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

/* 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);

' extra parentheses. ABC((x))

Collapse | Copy Code Collapse | Copy Code Parameter Passing by Public Sub ABC(ByRef y As Long) /* Note that there is no ' The parameter y is declared way to pass reference types Reference

'by referece: ' If ABC changes y, the changes are ' made to the value of x. End Sub ABC(x) ' Call the procedure.

(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 Try If x = 0 Then Handling

Collapse | Copy Code

Collapse | Copy Code

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

Collapse | Copy Code

Collapse | Copy Code

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

New Features of both languages in 2005 version


VB.NET Visual Basic 2005 has many new and improved language features -- such as inheritance, interfaces, overriding, shared members, and overloading -- that make it a powerful objectoriented programming language. As a Visual Basic developer, you can now create 1. multithreaded, scalable applications using explicit multithreading. This language has following new features, C# With the release of Visual Studio 2005, the C# language has been updated to version 2.0. This language has following new features:

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 1. Continue Statement, which immediately skips arity. Parameters can also be forced to be specific types. to the next iteration of a Do, For, 2. Iterators make it easier to dictate how a or While loop. for each loop will iterate over a 2. IsNot operator, which you can avoid using the Not andIs operators in an awkward order. collection's contents. Collapse | Copy Code 3. 3. Using...End. Using statement block // Iterator Example ensures disposal of a system resource when public class NumChar your code leaves the block for any reason.
{ string[] saNum = { "One", "Two", "Three", Public Sub setbigbold( _ "Four", "Five", "Six", ByVal c As Control) "Seven", "Eight", "Nine", Using nf As New _ "Zero"}; System.Drawing.Font("Arial",_ public 12.0F, FontStyle.Bold) System.Collections.IEnumerator c.Font = nf GetEnumerator() c.Text = "This is" &_ { "12-point Arial bold" foreach (string num in saNum) End Using yield return num; End Sub } Explicit Zero Lower Bound on an Array, } Visual Basic now permits an array declaration to // Create an instance of // the collection class specify the lower bound (0) of each dimension NumChar oNumChar = new NumChar(); along with the upper bound. // Iterate through it with foreach foreach (string num in oNumChar) Unsigned Types, Visual Basic now supports Console.WriteLine(num);
Collapse | Copy Code

4.

5.

unsigned integer data types (UShort, UInteger, and ULong) as well as the 3. Partial type definitions allow a single signed type SByte. type, such as a class, to be split into

6. Operator Overloading, Visual Basic now allows multiple files. The Visual Studio designer you to define a standard operator (such uses this feature to separate its as +, &, Not, or Mod) on a class or structure you generated code from user code. 4. Nullable types allow a variable to have defined. 7. Partial Types, to separate generated code from contain a value that is undefined. your authored code into separate source files. 5. Anonymous Method is now possible to 8. Visual Basic now supports type parameters on pass a block of code as a parameter. generic classes, structures, interfaces, Anywhere a delegate is expected, a code procedures, and delegates. A corresponding block can be used instead: There is no type argument specifies at compilation time the need to define a new method. Collapse | Copy Code data type of one of the elements in the generic type. button1.Click += 9. Custom Events. You can declare custom events delegate { MessageBox.Show( "Click!") }; by using the Custom keyword as a modifier for the Eventstatement. In a custom event, you6. . The namespace alias qualifier (::) specify exactly what happens when code adds provides more control over accessing namespace members. The global :: alias or removes an event handler to or from the allows to access the root namespace that event, or when code raises the event. 10. Compiler Checking Options, The /nowarn and may be hidden by an entity in your code. 7. Static classes are a safe and /warnaserror options provide more control over how warnings are handled. Each one of these convenient way of declaring a class compiler options now takes a list of warning IDs containing static methods that cannot be as an optional parameter, to specify to which instantiated. In C# v1.2 you would have defined the class constructor as private warnings the option applies. 11. There are eight new command-line compiler to prevent the class being instantiated. 8. 8. There are eight new compiler options: options: a. /langversion option: Can be used to a. The /codepage option specifies which specify compatibility with a specific codepage to use when opening source files. version of the language. b. The /doc option generates an XML b. documentation file based on comments within /platform option: Enables you to target IPF (IA64 or Itanium) and AMD64 your code. c. The /errorreport option provides a convenient architectures. c. #pragma warning: Used to disable and way to report a Visual Basic internal compiler enable individual warnings in code. error to Microsoft. d. The /filealign option specifies the size of d. /linkresource option: Contains additional options. sections in your output file. e. /errorreport option: Can be used to e. The /noconfig option causes the compiler to report internal compiler errors to ignore the Vbc.rsp file. Microsoft over the Internet. f. The /nostdlib option prevents the import f. ofmscorlib.dll, which defines the entire System /keycontainer and /keyfile: Support specifying cryptographic keys. 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.

Conclusion
I think that this article will help you understand both language features and also you can choose a language based on your taste. I will update this article in future if there are any changes.

Potrebbero piacerti anche