Complete Comparison for VB.NET and C#

This article explains about advantages, differences and new features of VB.NET and C#.

Contents

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:

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 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 most 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 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.

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 tools 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 coming 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.

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

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 return a value

Sub

void

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> EndStructure

struct, class, interface

Initialize an object (constructors)

SubNew()

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

' The argument Y is
'passed by value.
PublicSub ABC( _
ByVal y AsLong)
'If ABC changes y, the
' changes do not affect x.
EndSub
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

PublicSub ABC(ByRef y AsLong)
' The parameter y is declared
'by referece:
' If ABC changes y, the changes are
' made to the value of x.
EndSub
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(refint x)
{
...
}
// Calling the method:
ABC(ref i);

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,

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

IsNot operator, which you can avoid using the Not and Is operators in an awkward order.

3. Using...End. Using statement block ensures disposal of a system resource when your code leaves the block for any reason.

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.

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.

Compiler Checking Options, The /nowarn and /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 option applies.

There are eight new command-line compiler options:

The /codepage option specifies which codepage to use when opening source files.

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

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

The /filealign option specifies the size of sections in your output file.

The /noconfig option causes the compiler to ignore the Vbc.rsp file.

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

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

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

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 arity. Parameters can also be forced to be specific types.

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

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.

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

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.

button1.Click +=
delegate { MessageBox.Show(
"Click!") };

. 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.

Static classes 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.

8. There are eight new compiler options:

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

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

#pragma warning: Used to disable and enable individual warnings in code.

/linkresource option: Contains additional options.

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

/keycontainer and /keyfile: Support specifying cryptographic keys.

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.

History

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

Share

About the Author

Amalorpavanathan Yagulasamy (AMAL) is a Software Engineer for Protech Solution Inc. and has designed and implemented projects for Arkansas Child Support, Arkansas Budgetting, Michigan Child Support , Massachusetts Child Support, National Informatics Center-India and Indian Oil Corporation. His background is in developing relational databases and n-tier applications on Windows platforms in CMM Level Standards. He can be reached at amal_forum@hotmail.com

VB.net (starting with 2005, I believe) added a better "iif" which works like C#'s ?: operator (it does not evaluate expressions until necessary). The operator is simply "If" and is used like a function:

v = If(i < a.length, a[i], Nothing)

This should be considered superior to the old "iif" function in all normal cases.

I've seen references in various places - including this article - about the performance hit of the VB.NET background compiler (BC) for large projects.

But just how large does a project need to be for this to be an issue? We have a 12 project solution containing about 200,000+ lines of VB.NET code that doesn't seem to have any BC performance issues, even on our most modest development systems (mine is an old 1.7Ghz 1.5GB XP system). And we haven't applied any of the "tweaks" that are supposed to improve the BC's performance (because we haven't needed to!).

Is this possibly another one of those phantom "problems" that gets passed around as fact, but has very little real basis?

But even if we WERE having performance issues with the BC, I would be hard-pressed to give it up. All the other differences between VB.NET and C# such as syntax and case-sensitivity and whatever pale in comparison to the immediate feedback that the BC provides.

Debugging:
C# lets you used QuickWatch to view not only the flat objects but also to drill down through indexed items
VB.NET states that an indexed property cannot be displayed making debugging very difficult.

if(!o.Equals(null))
{
Console.WriteLine("I'm an object");
} // Checking whether the object is not equal to null. - .Equals(...) has some implications with inheritance, but not in this case when you're only comparing against a null.

if(o is object)
{
Console.WriteLine("I'm an object");
} // The "is" keyword is checking whether the object is a type of "object"! don't use it unless you have the basic understanding of type casting. (and it shouldn't use for such cases anyway).

I think this kind of topic should be made extensible like having a Wiki for it. (although i have no doubt that this article is not bad either)
Anyone come across a good one? Does it have official site from MS for this kind of topic?

Cause I am also interested to find out differences on 2008 features too and other things that this article could have overlooked. A complete list is good since I would like to venture into the details of the languages which some features I could under utilize or unaware.

In 'Advantages of both languages' for C# you indicate 'using', but of course VB does have this since 2005.
Also, you might want to add 'Support for XML literals' on the VB side (in 2008), which is not available in C#.
On the C# side, you're missing 'anonymous methods', which isn't available in VB.

In the 'Keyword Differences' section, you state that C# has no equivalent to 'Shadows' - the C# equivalent is 'new'.
Also, for the 'Call Windows API' section, 'Declares' is the legacy approach (which is still allowed). The more standard .NET approach is an
empty 'Shared' method with the DLLImport attribute.

'AddressOf' in VB is totally unrelated to the unsafe C# '&' operator.

The built-in VB casting macros (CInt, CStr, etc.) are more accurately converted to the System.Convert methods, where they exist (e.g., CInt is better approximated in C# by System.Convert.ToInt32).
The VB 'DirectCast' macro is closer to the C# cast however.

You also might want to add an entry for TryCast (VB) and 'as' (C#) - these are equivalent.

Recently, I was trying to communicate Vis C# Express with a simulation software through COM. When the simulation software finishes its processing it triggers an event called SimulationFinished. Handling this event in a method within C#, let C# recognize the simulation is over. However, nothing more can be done; even a label change in the form cannot be accomplish.

Surprisingly, when the similar implementation is done in VB6Pro; when the event SimulationFinished is triggered at the end of the simulation, some other methods can be processed.

Is there any difference in dealing with COM events?

Thanks in Advance

Bc

PS: The simulation software provides a COM reference library for both VB and C#