Comparison of C sharp and Visual Basic .NET
Encyclopedia
C# and Visual Basic .NET
Visual Basic .NET
Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework...

 are the two primary languages used to program on the .NET Framework
.NET Framework
The .NET Framework is a software framework that runs primarily on Microsoft Windows. It includes a large library and supports several programming languages which allows language interoperability...

.

Language history

C# and VB.NET are syntactically very different languages with very different history. As the name suggests, the C# syntax is based on the core C language originally developed by Bell Labs (AT&T) in the 1970s and eventually evolved into the fully object oriented C++ language still in use today. Much of the Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

 syntax is also based on this same C++ language, which is one of the reasons the two share a common look and feel. See Comparison of Java and C Sharp for more on this topic.

VB.NET has its roots in the BASIC language of the '60s with its name being an acronym for "Beginner's All-purpose Symbolic Instruction Code". In its beginning, BASIC was used in the college community as a "basic" language for first exposure to computer programming and the acronym represented the language accurately. In the '70s, the language was picked up by microcomputer manufacturers of the era to be used as both a simple ROM embedded programming language as well as a quasi operating system for input/output control. In the early '80s, the language was picked up by Microsoft and expanded significantly beyond its original intent into their "Visual Basic" language/platform that was sold throughout the 1990s as a "rapid application development" (RAD) tool for Windows programming. It competed directly against other RAD tools of the 1990s such as PowerBuilder. Even though Visual Basic was a successful development platform, it was discontinued after its 6th version (VB6) when Microsoft introduced the .NET Framework
.NET Framework
The .NET Framework is a software framework that runs primarily on Microsoft Windows. It includes a large library and supports several programming languages which allows language interoperability...

 and its related Visual Studio development platform in the early 2000s.

Language comparison

Though C# and VB.NET are syntactically very different, that is where the differences mostly end.
Microsoft developed both of these languages to be part of the same .NET Framework development platform. They are both developed, managed, and supported by the same language development team at Microsoft. They compile to the same intermediate language (IL), which runs against the same .NET Framework runtime libraries. Although there are some differences in the programming constructs (discussed further below), their differences are primarily syntactic and, assuming one avoids the Visual Basic "Compatibility" libraries provided by Microsoft to aid conversion from VB6, almost every command in VB has an equivalent command in C# and vice versa. Lastly, both languages reference the same Base Classes of the .NET Framework to extend their functionality. As a result, with few exceptions, a program written in either language can be run through a simple syntax converter to translate to the other. There are many open source and commercially available products for this purpose.

Runtime multi-language support

One of the main goals of .NET has been its multi-language support. The intent of the design was that all of the various Microsoft
Microsoft
Microsoft Corporation is an American public multinational corporation headquartered in Redmond, Washington, USA that develops, manufactures, licenses, and supports a wide range of products and services predominantly related to computing through its various product divisions...

 languages should have the same level of access to all OS
Operating system
An operating system is a set of programs that manage computer hardware resources and provide common services for application software. The operating system is the most important type of system software in a computer system...

 features, should be able to expose the same level of power and usability
Usability
Usability is the ease of use and learnability of a human-made object. The object of use can be a software application, website, book, tool, machine, process, or anything a human interacts with. A usability study may be conducted as a primary job function by a usability analyst or as a secondary job...

, and simplify calling from a module in one language to that written in another language.

In implementation, all .NET programming languages share the same runtime engine, uniform Abstract syntax tree
Abstract syntax tree
In computer science, an abstract syntax tree , or just syntax tree, is a tree representation of the abstract syntactic structure of source code written in a programming language. Each node of the tree denotes a construct occurring in the source code. The syntax is 'abstract' in the sense that it...

, and Common Intermediate Language
Common Intermediate Language
Common Intermediate Language is the lowest-level human-readable programming language defined by the Common Language Infrastructure specification and is used by the .NET Framework and Mono...

. Additionally all .NET languages have access to platform features including garbage collection, cross language inheritance, exception handling
Exception handling
Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution....

, and debugging
Debugging
Debugging is a methodical process of finding and reducing the number of bugs, or defects, in a computer program or a piece of electronic hardware, thus making it behave as expected. Debugging tends to be harder when various subsystems are tightly coupled, as changes in one may cause bugs to emerge...

. This allows the same output binary to be produced from any .NET programming language.

Development environment

Visual Studio provides minor differences in the development environment for C# and VB.Net. With each subsequent release of Visual Studio, the differences between development environments for these languages have been reduced. For instance early versions of Visual Studio had poor support for Intellisense
IntelliSense
IntelliSense is Microsoft's implementation of autocompletion, best known for its use in the Microsoft Visual Studio integrated development environment...

 in C# compared to Visual Basic .NET, and did not offer background compilation for C#. Currently, the main differences in the development environments are additional features for Visual Basic .NET that originated in VB6, including:
  • The default namespace is hidden (but can be disabled)
  • Certain project files are hidden (the user can show them)
  • The auto-generated My.* namespaces contain many commonly-used shortcuts brought over from VB6, such as methods for operating on the registry and application configuration file


Background compilation is a feature of the Visual Studio IDE
Integrated development environment
An integrated development environment is a software application that provides comprehensive facilities to computer programmers for software development...

 whereby code is compiled as it is written by the programmer with the purpose of identifying compilation errors without requiring the solution to be built. This feature has been available for Visual Basic since .NET 1.1 and was present in early versions of Visual Studio for Visual Basic .NET. However, background compilation is a relatively new concept for Visual C# and is available with service pack 1 for Visual Studio 2008 Standard Edition and above. A distinct disadvantage for C# is that the Error List panel does not update until the solution is rebuilt. Refactoring large projects in C# is made more difficult by the need to frequently rebuild the solution in order to highlight compilation errors. Such is not the case with Visual Basic because the Error List panel is synchronised with the background compiler.

Background Compilation is less demanding on system resources and results in faster build cycles. This is a particular advantage with large projects and can significantly reduce the time required to start debugging in the IDE.

Language features

The bulk of the differences between C# and VB.NET from a technical perspective are syntactic sugar
Syntactic sugar
Syntactic sugar is a computer science term that refers to syntax within a programming language that is designed to make things easier to read or to express....

.That is, most of the features are in both languages, but some things are easier to do in one language than another. Many of the differences between the two languages are actually centered around the IDE
Integrated development environment
An integrated development environment is a software application that provides comprehensive facilities to computer programmers for software development...

.

Features of Visual Basic .NET not found in C#

  • Variables can be declared using the WithEvents construct. This construct is available so that a programmer may select an object from the Class Name drop down list and then select a method from the Declarations drop down list to have the Method signature automatically inserted
  • Auto-wireup of events, VB.NET has the Handles syntax for events
  • Marshalling
    Marshalling (computer science)
    In computer science, marshalling is the process of transforming the memory representation of an object to a data format suitable for storage or transmission...

     an object for multiple actions using an unqualified dot reference. This is done using the With ... End With structure
  • IsNumeric
    Is functions
    The Is functions are a set of functions in Microsoft's Visual Basic 6, Visual Basic for Applications, VBScript, and Visual Basic .NET...

    evaluates whether a string can be cast into a numeric value (the equivalent for C# requires using int.TryParse)
  • XML Literals
  • Inline date declarations by using #1/1/2000# syntax (M/dd/yyyy).
  • Module (although C#'s sealed static classes with additional semantics, but each field has to individually be declared as static)
  • Members of Modules imported to the current file, can be access with no preceding container accessor (See Now for example)
  • The My namespace
  • COM components and interoperability was more powerful in VB.NET as the Object type is bound at runtime, however C#4.0 added the dynamic type which functions as a late bound form of Object.
  • Namespaces can be imported in project level, so they don't have to be imported to each individual file, like C#
  • In-line exceptions filtering by a Boolean expression, using "When expression" blocks. It can be achieved in C# using a catch block followed by if block.
  • With instruction Executes a series of instructions repeatedly refer to a single object or structure. (similar to the third bullet point above)

Features of C# not found in Visual Basic .NET

  • Allows blocks of unsafe code (like C++/CLI) via the unsafe keyword
  • Partial Interfaces
  • Multi-line comments (note that the Visual Studio IDE supports multi-line commenting for Visual Basic .NET)
  • Static classes (Classes which cannot contain any non-static members, although VB's Modules are essentially sealed static classes with additional semantics)
  • Can use checked and unchecked contexts for fine-grained control of overflow/underflow checking

Other characteristics of Visual Basic .NET not applicable to C#

  • Conversion of Boolean value True to Integer may yield -1 or 1 depending on the conversion used
  • Assigning and comparing variables uses the same token, =. Whereas C# has separate tokens, for comparison and = to assign a value
  • VB.NET is not case-sensitive.
  • Type checking is less strict by default. If the default is left in place, It will auto convert type without notifying programmer, for example:


Dim i As Integer = "1" 'Compiler automatically converts String to Integer
Dim j As String = 1 'Compiler automatically converts Integer to String
If i = j Then 'Compiler does cast and compare between i and j
MessageBox.Show("Avoid using, but this message will appear!")
End If

It should be noted that although the default is for 'Option Strict' is off, it is recommended by Microsoft and widely considered to be a good practice to turn 'Option Strict' "on", due to the fact it increases application performance, and eliminates the chance of naming errors and other programming mistakes.
  • Val function which also parses a null value while converting into double (In c# Convert.ToDouble is used to convert any object into double type value, but which throws exception in case of a null value)
  • CInt, CStr, CByte, CDbl, CBool, CByte, CDate, CLng, CCur, CObj and a wide variety of converting functions built in the language

Other characteristics of C# not applicable to Visual Basic .NET

  • By default, numeric operations are not checked. This results in slightly faster code, at the risk that numeric overflows will not be detected. However, the programmer can place arithmetic operations into a checked context to activate overflow checking. (It can be done in Visual Basic by checking an option)
  • Addition and string concatenation use the same token, +. Visual Basic .NET, however, has separate tokens, + for addition and & for concatenation, although + can be used for concatenation as well.
  • In Visual Basic .NET property methods may take parameters
  • C# is case-sensitive.

Syntax comparisons
Visual Basic .NET terminates a block of code with End BlockName statements (or Next statements, for a for loop
For loop
In computer science a for loop is a programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement....

) which are more familiar for programmers with experience using T-SQL. In C#, the braces, {}, are used to delimit blocks, which is more familiar to programmers with experience in other widely-deployed languages such as C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

 and Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

. Additionally, in C# if a block consists of only a single statement, the braces may be omitted.

C# is case sensitive while Visual Basic .NET is not. Thus in C# it is possible to have two variables with the same name, for example variable1 and Variable1. Visual Studio will correct the case of variables as they are typed in VB.NET. In many cases however, case sensitivity
Case sensitivity
Text sometimes exhibits case sensitivity; that is, words can differ in meaning based on differing use of uppercase and lowercase letters. Words with capital letters do not always have the same meaning when written with lowercase letters....

 can be useful. C# programmers typically capitalize type names and leave member and variable names lowercase. This allows, for example, fairly natural naming of method arguments: public int CalculateOrders(Customer customer). Of course, this can cause problems for those converting C# code to a case-insensitive language, such as Visual Basic, or to those unaccustomed to reading a case sensitive language.

Keywords

Visual Basic is not case sensitive, which means any combinations of upper and lower cases in keywords are acceptable. However Visual Studio automatically converts all Visual Basic keywords to the default capitalised forms, e.g. "Public", "If".

C# is case sensitive and all C# keywords are in lower cases.

Visual Basic and C# share most keywords, with the difference being the default (Remember Visual Basic is not case sensitive) Visual Basic keywords are the capitalised versions of the C# keywords, e.g. "Public" vs "public", "If" vs "if".

A few keywords have very different versions in Visual Basic and C#:
  • Friend vs internal - access modifiers allowing inter-class but not intra-assembly reference
  • Me vs this - a self-reference to the current object instance
  • MustInherit vs abstract - prevents a class from being directly instantiated, and forces consumers to create object references to only derived classes
  • MustOverride vs abstract - for forcing derived classes to override this method
  • MyBase vs base - for referring to the base class from which the current class is derived
  • NotInheritable vs sealed - for declaring classes that may not be inherited
  • NotOverridable vs sealed - for declaring methods that may not be overridden by derived classes
  • Overridable vs virtual - declares a method as being able to be overridden in derived classes
  • Shared vs static - for declaring methods that do not require an explicit instance of an object


Some C# keywords such as sealed represent different things when applied to methods as opposed to when they are applied to class definitions. VB.NET, on the other hand, uses different keywords for different contexts.

Comments

C# Visual Basic .NET
Visual Basic .NET
Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework...


//Single line comment

/*Multi-line comment
line 2
line 3*/

///XML single line comment

/**XML multi-line comment
line 2
line 3*/

'Single line comment


Multi-line comment not available


XML single line comment


XML multi-line comment not available
---------------------------

Conditionals

C# Visual Basic .NET
Visual Basic .NET
Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework...



if (condition)
{
// condition is true
}


If condition Then
' condition is true
End If


if (condition)
{
// condition is true
}
else
{
// condition is false
}


If condition Then
' condition is true
Else
' condition is false
End If


if (condition)
{
// condition is true
}
else if (othercondition)
{
// condition is false and othercondition is true
}


If condition Then
' condition is true
ElseIf othercondition Then
' condition is false and othercondition is true
End If


if (condition)
{
// condition is true
}
else if (othercondition)
{
// condition is false and othercondition is true
}
else
{
// condition and othercondition are false
}


If condition Then
' condition is true
ElseIf othercondition Then
' condition is false and othercondition is true
Else
' condition and othercondition false
End If

Loops

C# Visual Basic .NET
Visual Basic .NET
Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework...



for (int i = 0; i <= number - 1; i++)
{
// loop from zero up to one less than number
}


For i As Integer = 0 To number - 1
' loop from zero up to one less than number
Next


for (int i = number; i >= 0; i--)
{
// loops from number down to zero
}


For i As Integer = number To 0 Step -1
' loops from number down to zero
Next


break; //breaks out of a loop


Exit For 'breaks out of a for loop


Exit While 'breaks out of a while loop


Exit Do 'breaks out of a do loop

Primitive types

C# Visual Basic .NET
Visual Basic .NET
Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework...



if (a b)
{
// equal
}


If a = b Then
' equal
End If


if (a != b)
{
// not equal
}

Or:

if (!(a

b))
{
// not equal
}



If a <> b Then
' not equal
End If

Or:

If Not a = b Then
' not equal
End If

if (a b & c

d > e

f)
{
// multiple comparisons
}


If a = b And c = d Or e = f Then
' multiple comparisons
End If


if (a

b && c

d
e f)
{
// short-circuiting comparisons
}


If a = b AndAlso c = d OrElse e = f Then
' short-circuiting comparisons
End If

Object types

C# Visual Basic .NET
Visual Basic .NET
Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework...



if (Object.ReferenceEquals(a, b))
{
// variables refer to the same instance
}


If a Is b Then 'Can also be written as If Object.ReferenceEquals(a, b) Then
' variables refer to the same instance
End If


if (!Object.ReferenceEquals(a, b))
{
// variables do not refer to the same instance
}


If a IsNot b Then
' variables do not refer to the same instance
End If


if (a.Equals(b))
{
// instances are equivalent
}


If a = b Then 'Or a.Equals(b)
' instances are equivalent
End If


if (! a.Equals(b))
{
// not equivalent
}


If a <> b Then
' not equivalent
End If


var type = typeof(int);


Dim type = GetType(Integer)


if (a is b)
{
// types of a and b are compatible
}


If TypeOf a Is b Then
' types of a and b are compatible
End If


if (!(a is b))
{
// types of a and b are not compatible
}


If Not TypeOf a Is b Then
' types of a and b are not compatible
End If

Note: these examples for equivalence tests assume neither the variable "a" nor the variable "b" is a Null reference (Nothing in Visual Basic.NET). If "a" were null, the C# evaluation of the .equals method would throw a NullReferenceException, whereas the VB.NET = operator would return true if both were null, or false if only one was null (and evaluate the equals method if neither were null). They also assume that the .equals method and the = operator are implemented for the class type in question.
Omitted for clarity, the exact transliteration would be:

C#

if(object.equals(a,b))

VB.NET

If a = b Then

Adoption and community support
Both C# and VB.NET have high adoption rates, and very active developer communities and Microsoft
Microsoft
Microsoft Corporation is an American public multinational corporation headquartered in Redmond, Washington, USA that develops, manufactures, licenses, and supports a wide range of products and services predominantly related to computing through its various product divisions...

 fully supports both communities. Most .NET Framework
.NET Framework
The .NET Framework is a software framework that runs primarily on Microsoft Windows. It includes a large library and supports several programming languages which allows language interoperability...

 developers use C# as their primary language. C# has an advantage in terms of the level of community activity on the Internet and there are more books available for C#.

Examples of community and industry adoption include:
  • TIOBE Programming Community Index for July 2010 show that C# finally surpassed Visual Basic
  • Telerik Survey 2009 suggested that C# (69%) further strengthens its dominance over VB.NET (30%) as the primary programming language.
  • Telerik Survey 2008 suggested that C# (63%) had surpassed VB.NET (34%) as the primary programming language.
  • A 2007 Forrester Research
    Forrester Research
    Forrester Research is an independent technology and market research company that provides its clients with advice about technology's impact on business and consumers. Forrester Research has five research centers in the US: Cambridge, Massachusetts; New York, New York; San Francisco, California;...

     poll revealed that 59% of .NET developers used only VB.NET to create software.
  • Visual Basic Express is the most popular download of all the Visual Studio Express downloads.
  • An original C# language designer, Scott Wiltamuth, stated in a March 2010 blog that the "most reliable numbers we have... show roughly equal adoption" for VB.NET and C#.
  • According to a survey conducted by Visual Studio Magazine "41 percent said they used C#, 34 percent programmed in VB.NET, while 25 percent responded with 'other.'"
  • Stephen Wiley
    Stephen Wiley
    Stephen Wiley is recognized as the first artist to have recorded a full-length Christian rap album with his 1985 release on the Brentwood Records label, Bible Break, a fact which was acknowledged by T-Bone in his song "Our History" on his own album entitled GospelAlphaMegaFunkyBoogieDiscoMusic in...

    , marketing product manager at Apress
    Apress
    Apress, Inc. is a publisher of information technology books, based in New York City. It is a division of Springer Science+Business Media.Apress was founded by authors Gary Cornell and Dan Appleman. Its original name was Author's Press, shortened to APress, then Apress. In 2003, Apress purchased...

     has reported "C# titles outsell VB.NET title books handily, by somewhere between a 2–1 and 3–1 margin."
  • MSDN Blogs
    MSDN Blogs
    MSDN Blogs is Microsoft's blog site where many of its employees blog to a public audience. It has both individual blogs and product or feature-related blogs...

    , the blogging site for Microsoft employees, has 27,500 posts that discuss C#, while only 8,880 mention VB.Net (as of November 15, 2007)
  • Google Groups
    Google Groups
    Google Groups is a service from Google Inc. that supports discussion groups, including many Usenet newsgroups, based on common interests. The service was started in 1995 as Deja News, and was transitioned to Google Groups after a February 2001 buyout....

    , a Usenet
    Usenet
    Usenet is a worldwide distributed Internet discussion system. It developed from the general purpose UUCP architecture of the same name.Duke University graduate students Tom Truscott and Jim Ellis conceived the idea in 1979 and it was established in 1980...

     search engine, returns 36,900 hits for "VB .Net", and 65,700 for C#

C++/CLI (formerly Managed C++)

C++/CLI
C++/CLI
C++/CLI is Microsoft's language specification intended to supersede Managed Extensions for C++. It is a complete revision that aims to simplify the older Managed C++ syntax . C++/CLI is standardized by Ecma as ECMA-372...

 (a replacement for Managed Extensions for C++
Managed Extensions for C++
Managed Extensions for C++ or just Managed C++ is a now deprecated Microsoft set of deviations from C++, including grammatical and syntactic extensions, keywords and attributes, to bring the C++ syntax and language to the .NET Framework...

) does not have the adoption rate of C# or VB.NET, but does have a significant following. C++/CLI syntactically, stylistically, and culturally is closest to C#. However, C++/CLI stays closer to its C++ roots than C# does. C++/CLI directly supports pointers, destructors, and other unsafe program concepts which are not supported or limited in the other languages. It allows the direct use of both .NET code and standard C++ code. C++/CLI is used for porting native/legacy C++ applications into the .NET framework, or cases where the programmer wants to take more control of the code; but this control comes at a significant cost of ease of use and readability. Many of the automated tools that come with Visual Studio have reduced functionality when interacting with C++ code. This is because reflection cannot provide as much information about the code as it can for C# and VB.net

J#

J#
J Sharp
Visual J# |sharp]]') programming language is a discontinued transitional language for programmers of Java and Visual J++ languages, so they may use their existing knowledge and applications on .NET Framework....

 runs a distant fourth in terms of adoption. J# is a language primarily designed to ease the transition of Java applications to the .NET framework; it allows developers to leave much of their Java or J++ code unchanged while still running it in the .NET framework, thus allowing them to migrate small pieces of it into another .NET language, such as C#, individually. J# does not receive the same level of updates as the other languages, and does not have the same level of community support. For example, Visual Studio 2005 Team System supports automatic generation of Unit Tests in C#, VB.Net, and C++, but excludes J#. J# has been discontinued and is not included in Visual Studio 2008 or newer versions, since the existing J# feature set largely meets customer needs and usage of J# is declining.

Additional .NET languages

All .NET languages compile down to Common Intermediate Language
Common Intermediate Language
Common Intermediate Language is the lowest-level human-readable programming language defined by the Common Language Infrastructure specification and is used by the .NET Framework and Mono...

 (CIL), which contains rich metadata and is functionally and logically equivalent to the original .NET language code. For these reasons, while it is possible to code directly in CIL, it is rarely done. The equivalency of CIL to .NET language code permits tools such as .NET Reflector
.NET Reflector
.NET Reflector is a proprietary software utility for Microsoft .NET combining class browsing, static analysis and decompilation, originally written by Lutz Roeder. MSDN Magazine named it as one of the Ten Must-Have utilities for developers, and Scott Hanselman listed it as part of his "Big Ten...

 to transform a .NET assembly into source code that is nearly identical to the original source. Code obfuscators
Obfuscated code
Obfuscated code is source or machine code that has been made difficult to understand for humans. Programmers may deliberately obfuscate code to conceal its purpose or its logic to prevent tampering, deter reverse engineering, or as a puzzle or recreational challenge for someone reading the source...

are often used to guard against this, and operate by directly modifying the CIL of an assembly in order to make it difficult or impossible to de-compile to a higher level .NET language.
External links
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK