Research Library
 
White Paper

White Paper: WP-012p

Last Modified: June 30, 2003

 

A Showdown Between .NET Programming Languages: C#.NET versus  VB.NET

 

 

 

 

Author: 

Oleg Ogurok, (mail@thecramgroup.com)

Lead Systems Engineer, The Cram Group, LLC

 

 

 

 

Categories:

Development, Management

 

 

 

 

SUMMARY:

In 2002, Microsoft once again surprised many developers with its new creation, .NET. Based on a number of previously existing technologies such as Java Server Pages, regular expressions, XML, DOM, and many more, the company has once more set its goal of heavily influencing the computer software market. Microsoft’s new Visual Studio .NET product is by far the most sophisticated integrated development environment today.

Before starting a project, a crucial decision must be made as to which language to use throughout the entire development period. Mixing languages in a project is greatly discouraged; it creates difficulties in maintaining quality control. Most companies committed to Microsoft based technologies usually decide between C# and VB.NET.

 

 

Introduction

When developing software under the .NET environment, a company is free to use any of currently available .NET-enabled programming languages. As of today, such languages include the two major ones, C# and VB.NET, with relatively full framework functionality, and less popular and purpose specific ones such as J#, SML.NET, and AsmL. Other existing languages are currently being adopted for .NET.

In contrast to the older versions of Visual Basic and C++, at the present time, both languages have extremely similar syntaxes; several volunteers even wrote small helper scripts to convert between the two on a basic level. However, there are also vital differences that should not be overlooked.

 

DIFFERENCE 1. Verboseness

Let thy speech be short, comprehending much in a few words. – Aprocrypha

Generally, VB.NET is considered a wordy language. In most cases VB code is longer than the corresponding code in C#. This phenomenon is related to the fact that Visual Basic derived its syntax from Basic, a language developed in the mid 1970s. Back then, Basic’s grammar suffered from redundancy and unnecessary keywords, was error prone, and lacked structure.

For example, each “FOR” loop had to end with a corresponding “NEXT” statement, “IF” had to be terminated by “END IF,” and subroutines had to start with “SUB” and end with “END SUB.” The main reason Microsoft stuck with the nearly archaic syntax is to get earlier programmers up to speed with the new technology. C#, on the other hand, borrows its grammar from two relatively modern languages, Java and C++.

While the syntax has no effect on the execution time, it greatly affects the time spent reading through the source code to understand its function. When a programmer leaves a software company and another person is hired to replace him, it is important to shorten the time needed for the new person to get up to speed with the ongoing project because during such a “learning curve” the project does not progress.

Here is an example of code in VB.NET:

1

2

 

3

4

5

6

7

8

9

10

11

12

13

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        For I As Integer = 1 To 10

            Dim J As Integer = 0

            While J < 20

                Dim K As Integer = 0

                Do

                    'Statements to operate w/ current values of I, J, & K.

                Loop Until K >= 30

            End While

        Next I

    End Sub

End Class

And here is the same code in C#:

1

2

3

4

5

6

7

8

9

 

10

11

12

13

14

public class Form1

       private void Form1_Load(object sender, System.EventArgs e)

       {

              for (int i = 0; i <= 10; i++)

              {      int j = 0;

                     while (j < 20)

                     {      int k = 0;

                           do

                           {      // Statements to operate with current values of i, j, and k.

                           } while (k < 30);

                     }

}
}

}

As one may notice, VB.NET code uses long keywords (lines 10-13) to delimit blocks, where C# manages it by using just curly braces. Contents inside a block are usually indented to emphasize the structure; therefore using extra long keywords is overkill.

       

 

 

DIFFERENCE 2. Standards vs. Sloppy Code

When working on a software project in a group of people, it is essential to enforce certain standard coding practices, such as proper keyword spelling, naming conventions for variables, or proper library usage. Microsoft made a great effort to standardize library names and locations by putting them into namespace hierarchies. For example, StringBuffer, a class used to manipulate strings, is located under System.Text, while trigonometric functions such as sine or cosine may be found under System.Math.

However, VB.NET does a terrible job at keeping with standards by being case insensitive. Having the same word spelled as “class,” “Class,” and “CLASS” in one project negatively affects the readability of the source code. C# in contrast is entirely case sensitive. Thus it inflicts discipline and eliminates code ambiguity.

Another inconvenience in VB.NET is the absence of statement delimiters. In C#, statements are separated by a semicolon (“;”). Often, if a statement is wider than 80 characters, it is still possible to fit it on one line; however, scrolling through it is difficult. It is wiser to split the statement into several lines to increase its readability. The compiler will reassemble it upon compilation. The semicolon in a C# code acts like a period indicating an end of a sentence in a novel. For example in C#:

1

2

3

4

       string s = "This is a very long line. We don't need to " +

              "use any special characters because C# statements " +

              "are always delimited by semicolons " +

              "like the one at the end of this line";

Visual Basic.NET uses a different approach. Statements are implicitly separated by the “End of Line” also known as “Carriage Return – Line Feed” characters. Splitting long statements is permitted but only with an underscore “_” character at the end of each line, e.g., in VB.NET:

1

2

3

4

    Dim s As String

    s = "This is a very long line. We have to separate it with " & _

        "underscores in VB.NET because this language does not have " & _

        "statement delimiters"

Such a method not only makes the code look awkward, but is also one of the reasons VB.NET is so wordy. Any compiler’s job is to unmistakably identify statements, variables, keywords, etc. Most of it is done during the first stage of compiling, known as parsing. Writing an intelligent parser that can spot errors and not mistake them for a correct code is a challenging task.

One may think of such a difficult task as proofreading a poorly written essay lacking punctuation. Without commas and periods, there is no simple way to determine beginnings and endings of sentences, as well as pauses in them. In parallel, VB.NET compiler performs an enormous job figuring out the structure in a code that practically lacks the structure in the first place. To perform this task, the compiler relies heavily on VB.NET’s built-in extensive list of keywords such as “End If,” “End Sub,” “OrElse,” and many more, thus once again underlining the verboseness of the language.

 

DIFFERENCE 3. Maintainability and Code Documentation

The classical approach to writing documentation for the code is by maintaining the code and the documents in separate files. Such method requires a lot of effort of going back and forth between several files and maintaining them in sync. Microsoft has solved this problem by including XML documentation features in C#. This neat feature lets a programmer to “kill” two birds with one stone: write the code and document it on the way. For example:

1

2

3

4

5

6

7

8

9

       /// <summary>

       /// This method returns the sum of two numbers

       /// </summary>

       /// <param name="a">The first number</param>

       /// <param name="b">The second Number</param>

       /// <returns>The sum of both numbers</returns>

       public int Add(int a, int b)

       {      return a + b;

       }

Based on the lines that start with triple forward slashes (lines 1 through 6), the compiler generates an XML file, which in turn can have an XSLT style sheet applied to it in order to create professionally looking HTML help files. Microsoft even provides a sample style sheet with Visual Studio .NET. To the right is an example of a generated HTML documentation for the Add() method listed above.

Thus having both the code and its documentation reside next to each other in the same physical file reduces the chance of the API documentation pages becoming outdated.

Unfortunately, the XML documentation currently works with C# only; VB.NET lacks this feature.

 

DIFFERENCE 4. Memory Usage and Management

Memory is a terrible thing to waste!

When designing robust and scalable applications, proper memory management is crucial. For instance, the fact that some medical billing software can process 10,000 records within 2-3 seconds does not guarantee it will be as robust with 100,000. If the memory management is poorly implemented, the program may never return the results, or even run out of memory and result in a crash.

Notepad that comes with Windows 2000 is a real life example of a poorly scalable application. Certainly, it works well for editing small text files; however, do not try to open anything larger than several megabytes as it will take ages. The main problem with Notepad is that it tries to load the whole text file into memory; but what if the user only wants to see the first 50 lines? Wouldn’t it be wiser to load only the first 5-10 pages, and then load more as the user scrolls several pages down? Wouldn’t it be even more clever to free up the memory resources used by the first pages now that the user no longer needs to see them?

C# in this case is a life saver. A programmer can specify exactly when memory contents used by an object are no longer required and should be reclaimed for other use. Apart from the standard memory management (Garbage Collection [1] ) found in both languages, C#’s ‘using’ keyword allows a programmer to specify a block of code that can be reclaimed instantly upon exiting. For example:

1

2

3

4

5

6

7

8

9

10

       public void SmartMemoryUsage()

       {      TextPage pageOne = new TextPage();

              // load a page here

              using (pageOne)

              {      // allow user to read page here

                     pageOne.Show();

              }

              // here page is no longer needed

              // it is automatically disposed

       }

Once the code inside the using {…} block (lines 5 through 7) is done executing, the specified resource is removed from memory. This allows a programmer to have a more precise control over memory usage during the execution of his program.

 

DIFFERENCE 5. Platform Independence

C# is a platform independent language. Normally, .NET code written in any language is first compiled into Microsoft Intermediate Language (MSIL). Then during the execution, MSIL is once again compiled using JIT (just in time) compiler into platform specific code. Operating system is then capable of executing this code.

MSIL itself is a standard assembly language that can be adopted to run under any platform that either understands MSIL or has a virtual machine software that translates MSIL into something the platform can understand. In Microsoft Windows environment, JIT compiler acts as the virtual machine.

Although Microsoft has released virtual machine software for its products only, there are several open-source projects developing execution environments to run .NET code under UNIX and Macintosh. Currently two of them are Mono [2] and DotGNU [3] . Both are maintained by groups of volunteers and are available free of charge. Mono and DotGNU allow one to run precompiled .NET binaries on UNIX and MacOS X and up.

While both open-source products allow one to execute .NET code precompiled from any .NET language, the products only allow one to compile C# code and not VB.NET, because the latter is Microsoft’s proprietary language. Therefore VB.NET is not platform independent. This brings us to the last but not least important reason for choosing C#.NET over VB.NET.

 

DIFFERENCE 6. Open Standard

In 2000, Microsoft, Hewlett-Packard and Intel submitted C# and Common Language Infrastructure [4] (CLI) to the international standardization organization ECMA [5] thereby making it an open standard. Now vendors are free to develop their own versions of virtual machines compatible with the specification. C# is part of the open standard. Visual Basic.NET on the contrary is not, and Microsoft currently does not have plans to release its specifications to the public.

 

Summary

Having all the great features of C# listed above is more than enough to persuade a person to choose this language over Visual Basic.NET

Reasons to Choose VB.NET

Reasons to Choose C#.NET

·          Quick learning curve

·          More resources available and programmers skilled in VB

·          Support and integration with Microsoft products and solutions

 

·          Less wordy language

·          Standards enforced and coding sloppiness not allowed

·          Built-in documentation feature

·          Precise memory management tools

·          Platform independence

·          Open standard

 

 

Sources & References:


 

[1] Garbage Collection in .NET. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconprogrammingessentialsforgarbagecollection.asp

[2] Mono project. http://www.go-mono.com/

[3] DotGNU project. http://www.gnu.org/projects/dotgnu/

[4] The Common Language Infrastructure http://msdn.microsoft.com/netframework/using/understanding/cli/default.aspx

[5] International Standardization Organization ECMA. (http://msdn.microsoft.com/net/ecma/ and

http://www.ecma-international.org/)

Copyright © 2001 The Cram Group, LLC. All rights reserved.