Jump to content

Comparison of C Sharp and Visual Basic .NET: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
→‎Language history: Don't put stuff like "As you may recall"
m WP:REFerence WP:CITation parameters: reorders, respaces, update-standardize-conforms. WP:LINK update-standardize. MOS:COMMENT add. WP:CATEGORYs move.
 
(33 intermediate revisions by 25 users not shown)
Line 1: Line 1:
{{Short description|Comparison of two programming languages}}
{{Correct title|title=Comparison of C# and Visual Basic .NET|reason=hash}}
{{Correct title|title=Comparison of C# and Visual Basic .NET|reason=hash}}
{{Comparison of programming languages}}
{{ProgLangCompare}}


[[C Sharp (programming language)|C#]] and [[Visual Basic .NET]] are the two primary languages used to program on the [[.NET Framework]].
[[C Sharp (programming language)|C#]] and [[Visual Basic (.NET)]] are the two main [[programming language]]s used to program on the [[.NET]] framework.


==Language history==
==Language history==
C# and VB.NET are syntactically very different languages with very different histories.
C# and VB.NET are very different languages in [[Syntax (programming languages)|syntax]] and history.


As the name suggests, the C# syntax is based on the core [[C (programming language)|C programming language]] originally developed by [[Dennis Ritchie]] at [[Bell Labs]] (AT&T) in the 1970s.<ref>{{cite web |url=http://cm.bell-labs.com/cm/cs/who/dmr/chist.html |archive-url=https://wayback.archive-it.org/all/20150203070752/http://cm.bell-labs.com/cm/cs/who/dmr/chist.html |url-status=dead |archive-date=2015-02-03 |title=Chistory |publisher=Cm.bell-labs.com |accessdate=2013-08-18 }}</ref> [[Java (programming language)|Java]] and C++ are two other programming languages whose syntax is also based on the C syntax,<ref>{{cite web|url=http://www.freejavaguide.com/history.html |title=History of Java programming language |publisher=Freejavaguide.com |date= |accessdate=2013-08-18}}</ref> so they share a common look and feel. See [[Comparison of Java and C Sharp]] for more on this topic.
As the name suggests, the C# syntax is based on the core [[C (programming language)|C programming language]] originally developed by [[Dennis Ritchie]] at [[Bell Labs]] (AT&T) in the 1970s.<ref>{{cite report |last1=Ritchie |first1=Dennis |author-link=Dennis Ritchie |date=April 1993 |url=https://www.bell-labs.com/usr/dmr/www/chist.html |archive-url=https://wayback.archive-it.org/all/20150203070752/http://cm.bell-labs.com/cm/cs/who/dmr/chist.html |url-status=live |archive-date=2015-02-03 |title=Chistory |publisher=Bell Labs |access-date=2013-08-18}}</ref> [[Java (programming language)|Java]] and C++ are two other programming languages whose syntax is also based on the C syntax,<ref>{{cite web|url=http://www.freejavaguide.com/history.html |title=History of Java programming language |publisher=Freejavaguide.com |access-date=2013-08-18}}</ref> so they share a common look and feel. See [[Comparison of C Sharp and Java]] for more on this topic.


BASIC's roots go back to [[Dartmouth College]].<ref>[http://www.dartmouth.edu/basicfifty/basic.html "BASIC at Dartmouth"]</ref> BASIC (Beginner's All-purpose Symbolic Instruction Code) was developed in the 1960s as a method to overcome the difficulties of using ASSEMBLY language written for processor specific and/or brand name specific main frames and hardware. Programming was hardware dependent by design more so for marketing reasons than to preserve the logical composition of programming that should transcend hardware. (Microsoft's claim to fame with its operating system was to free consumers from hardware specific devices by encapsulating those task within its operating system.) Code became "portable" due to the compiler, and in fact, both Visual Basic .NET and C# use the same CLR (Common Language Runtime) today. Microsoft and HP were interested in creating an ISO standard language, which was the original goal, however; HP dropped its support, and the ISO computer language never materialized as an International Standard.
BASIC's roots go back to [[Dartmouth College]].<ref>[http://www.dartmouth.edu/basicfifty/basic.html "BASIC at Dartmouth"]</ref> [[BASIC]] (Beginner's All-purpose Symbolic Instruction Code) was developed in the 1960s as a method to overcome the difficulties of using assembly language written for processor-specific and/or brand name specific mainframes and hardware. Programming was hardware dependent by design more so for marketing reasons than to preserve the logical composition of programming that should transcend hardware. (Microsoft's claim to fame with its operating system was to free consumers from hardware-specific devices by encapsulating those tasks within its operating system.) Code became "portable" due to the compiler, and in fact, both Visual Basic .NET and C# use the same CLR (Common Language Runtime) today. Microsoft and HP were interested in creating an ISO standard language, which was the original goal, however; HP dropped its support, and the ISO computer language never materialized as an International Standard.


VB.NET has its roots in the [[BASIC]] language of the 1960s 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 1970s, 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 1980s, 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.<ref>{{cite web|url=http://www.forestmoon.com/BIRTHofVB/BIRTHofVB.html |title=The Birth of Visual Basic |publisher=Forestmoon.com |date= |accessdate=2013-08-18}}</ref> It competed directly against other RAD tools of the 1990s such as [[PowerBuilder]].<ref>{{cite web|url=http://www.lannigan.org/powersoft_powerbuilder_history.htm |title=Powersoft History PowerBuilder History |publisher=Lannigan.org |date= |accessdate=2013-08-18}}</ref> Even though Visual Basic was a successful development platform, it was discontinued after its 6th version (VB6) when Microsoft introduced the .NET Framework and its related Visual Studio development platform in the early 2000s. At that time, the current C++ and VB6 languages were used by Microsoft as the basis for two new programming languages in their new "Integrated Development Environment (IDE)". These languages were named C# and VB.NET
VB.NET finds its roots in BASIC. 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 1970s, 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 1980s, 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.<ref>{{cite web|url=http://www.forestmoon.com/BIRTHofVB/BIRTHofVB.html |title=The Birth of Visual Basic |publisher=Forestmoon.com |access-date=2013-08-18}}</ref> It competed directly against other RAD tools of the 1990s such as [[PowerBuilder]].<ref>{{cite web|url=http://www.lannigan.org/powersoft_powerbuilder_history.htm |title=Powersoft History PowerBuilder History |publisher=Lannigan.org |access-date=2013-08-18}}</ref> Even though Visual Basic was a successful development platform, it was discontinued after its 6th version (VB6) when Microsoft introduced the .NET Framework and its related Visual Studio development platform in the early 2000s. At that time, the current C++ and VB6 languages were used by Microsoft as the basis for two new programming languages in their new "Integrated Development Environment (IDE)". These languages were named C# and VB.NET.


In February 2017, Microsoft communicated their intent to end the "co-evolution" strategy between the two languages that had existed since 2010, and allow the two languages to again evolve independently. C# is now the dominant Microsoft-based development language. Developers will notice that VB 15 (first appearing in Visual Studio 2017) lacks certain language capabilities contained in the new C# 7.3.<ref>{{cite web|url=https://blogs.msdn.microsoft.com/dotnet/2017/02/01/the-net-language-strategy/|title=The .NET Language Strategy|date=February 2017}}</ref>
In February 2017, Microsoft communicated their intent to end the "co-evolution" strategy between the two languages that had existed since 2010 and allow the two languages to again evolve independently. C# is now the dominant Microsoft-based development language. Developers will notice that VB 15 (first appearing in Visual Studio 2017) lacks certain language capabilities contained in the new C# 7.3.<ref>{{cite web|url=https://blogs.msdn.microsoft.com/dotnet/2017/02/01/the-net-language-strategy/|title=The .NET Language Strategy|date=February 2017}}</ref>


==Language comparison==
==Language comparison==
Though C# and VB.NET are syntactically very different, that is where the differences mostly end.
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.<ref>{{cite web |last=Krill |first=Paul |url=http://www.infoworld.com/article/09/02/27/Microsoft_converging_programming_languages_1.html?R=printThis&A=/article/09/02/27/Microsoft_converging_programming_languages_1.html |title=Microsoft converging programming languages &#124; Developer World |publisher=InfoWorld |date=2009-02-27 |accessdate=2013-08-18 |archive-url=https://archive.is/20130126074556/http://www.infoworld.com/article/09/02/27/Microsoft_converging_programming_languages_1.html?R=printThis&A=/article/09/02/27/Microsoft_converging_programming_languages_1.html |archive-date=2013-01-26 |url-status=dead }}</ref> They compile to the same intermediate language (IL), which runs against the same .NET Framework runtime libraries.<ref>{{cite web|url=http://www.dotnet-guide.com/msintermediate.html |title=Microsoft Intermediate Language |publisher=Dotnet-guide.com |date= |accessdate=2013-08-18}}</ref> 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 task.
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.<ref>{{cite web |last=Krill |first=Paul |url=http://www.infoworld.com/article/09/02/27/Microsoft_converging_programming_languages_1.html?R=printThis&A=/article/09/02/27/Microsoft_converging_programming_languages_1.html |title=Microsoft converging programming languages &#124; Developer World |publisher=InfoWorld |date=2009-02-27 |access-date=2013-08-18 |archive-url=https://archive.today/20130126074556/http://www.infoworld.com/article/09/02/27/Microsoft_converging_programming_languages_1.html?R=printThis&A=/article/09/02/27/Microsoft_converging_programming_languages_1.html |archive-date=2013-01-26 |url-status=dead }}</ref> They compile to the same intermediate language (IL), which runs against the same .NET Framework runtime libraries.<ref>{{cite web|url=http://www.dotnet-guide.com/msintermediate.html |title=Microsoft Intermediate Language |publisher=Dotnet-guide.com |access-date=2013-08-18}}</ref> 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 task.
The only fundamental differences between the languages can be found in the implementation of interfaces and in the declaration, raising and handling of events. Although both languages are [[high-level programming language]]s, VB.NET maintains a slightly higher level of abstraction in some respects.
The only fundamental differences between the languages can be found in the implementation of interfaces and in the declaration, raising and handling of events. Although both languages are [[high-level programming language]]s, VB.NET maintains a slightly higher level of abstraction in some respects.


Line 26: Line 27:


==Development environment==
==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]] in C# compared to Visual Basic .NET, and did not offer background compilation for C#.<ref name="advbasics">{{cite web | url = http://msdn.microsoft.com/msdnmag/issues/05/06/AdvancedBasics/ | title = Scaling Up: The Very Busy Background Compiler | author = Matthew Gertz | publisher = [[MSDN Magazine]] | accessdate = 2008-12-16 | archive-url = https://web.archive.org/web/20080219185814/http://msdn.microsoft.com/msdnmag/issues/05/06/AdvancedBasics/ | archive-date = 2008-02-19 | url-status = dead }}</ref> Currently, the main differences in the development environments are additional features for Visual Basic .NET that originated in VB6, including:
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]] in C# compared to Visual Basic .NET, and did not offer background compilation for C#.<ref name="advbasics">{{cite web | url = http://msdn.microsoft.com/msdnmag/issues/05/06/AdvancedBasics/ | title = Scaling Up: The Very Busy Background Compiler | author = Matthew Gertz | publisher = [[MSDN Magazine]] | access-date = 2008-12-16 | archive-url = https://web.archive.org/web/20080219185814/http://msdn.microsoft.com/msdnmag/issues/05/06/AdvancedBasics/ | archive-date = 2008-02-19 | url-status = dead }}</ref> 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)
* The default namespace is hidden (but can be disabled)
* Certain project files are hidden (the user can show them)
* Certain project files are hidden (the user can show them)
* The auto-generated <code>My.*</code> namespaces contain many commonly used shortcuts brought over from VB6, such as methods for operating on the registry and application configuration file'''''
* The auto-generated <code>My.*</code> 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 [[Integrated development environment|IDE]] 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.<ref name="freepatentsonline.com">{{cite web|url=http://www.freepatentsonline.com/6804682.html|title=System and methodology providing compiler-assisted refactoring|publisher=Freepatentsonline.com|accessdate=24 February 2015}}</ref> Such is not the case with Visual Basic because the Error List panel is synchronized with the background compiler.
Background compilation is a feature of the Visual Studio [[Integrated development environment|IDE]] 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.<ref name="freepatentsonline.com">{{cite web|url=http://www.freepatentsonline.com/6804682.html|title=System and methodology providing compiler-assisted refactoring|publisher=Freepatentsonline.com|access-date=24 February 2015}}</ref> Such is not the case with Visual Basic because the Error List panel is synchronized with the background compiler.


Background compilation is less demanding on system resources and results in faster build cycles.<ref name="freepatentsonline.com"/> This is a particular advantage with large projects and can significantly reduce the time required to start debugging in the IDE.<ref name="freepatentsonline.com"/>
Background compilation is less demanding on system resources and results in faster build cycles.<ref name="freepatentsonline.com"/> This is a particular advantage with large projects and can significantly reduce the time required to start debugging in the IDE.<ref name="freepatentsonline.com"/>
Line 45: Line 46:
* Delegates for events don't need to be declared. They are implicitly declared in the declaration of the events.
* Delegates for events don't need to be declared. They are implicitly declared in the declaration of the events.
* Referring to an object using an unqualified dot reference, using the <code>With ... End With</code> structure
* Referring to an object using an unqualified dot reference, using the <code>With ... End With</code> structure
* XML Literals<ref name="csharpxml">{{cite web | url = http://www.infoq.com/news/2007/03/CSharp-XML | title = Does C# Need VB9's XML Literals? | author = Jonathan Allen | accessdate = 2009-01-13}}</ref>
* XML Literals<ref name="csharpxml">{{cite web | url = http://www.infoq.com/news/2007/03/CSharp-XML | title = Does C# Need VB9's XML Literals? | author = Jonathan Allen | access-date = 2009-01-13}}</ref>
* Inline date declarations, e.g. <code>#12/31/2000#</code>
* Inline date declarations, e.g. <code>#12/31/2000#</code>
* <code>Module</code> (although C#'s static classes with additional semantics, but each field must be individually declared as static)
* <code>Module</code> (although C#'s static classes with additional semantics, but each field must be individually declared as static)
* Members of <code>Module</code>s imported to the current file, can be accessed with no preceding container accessor<ref>{{cite web|url=http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.dateandtime.now.aspx |title=DateAndTime.Now Property (Microsoft.VisualBasic) |publisher=Msdn.microsoft.com |date=2015-02-18 |accessdate=2015-02-24}}</ref>
* Members of <code>Module</code>s imported to the current file, can be accessed with no preceding container accessor<ref>{{cite web|url=http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.dateandtime.now.aspx |title=DateAndTime.Now Property (Microsoft.VisualBasic) |publisher=Msdn.microsoft.com |date=2015-02-18 |access-date=2015-02-24}}</ref>
* The <code>My</code> namespace.<ref>{{cite web|url=http://msdn.microsoft.com/en-us/library/5btzf5yk.aspx |title=Development with My (Visual Basic) |publisher=Msdn.microsoft.com |date=2015-02-18 |accessdate=2015-02-24}}</ref>
* The <code>My</code> namespace.<ref>{{cite web|url=http://msdn.microsoft.com/en-us/library/5btzf5yk.aspx |title=Development with My (Visual Basic) |publisher=Msdn.microsoft.com |date=2015-02-18 |access-date=2015-02-24}}</ref>
* COM components and interoperability was more powerful in VB.NET, as the Object type is bound at runtime;<ref name="early-binding">{{cite web|url=http://visualbasic.about.com/od/usingvbnet/a/earlybind.htm|title=Early vs. Late Binding|publisher=Visualbasic.about.com|accessdate=24 February 2015|archive-url=https://web.archive.org/web/20150225004949/http://visualbasic.about.com/od/usingvbnet/a/earlybind.htm|archive-date=25 February 2015|url-status=dead}}</ref> however, C# 4.0 added the <code>dynamic</code> type, which functions as a late-bound form of Object
* COM components and interoperability was more powerful in VB.NET, as the Object type is bound at runtime;<ref name="early-binding">{{cite web|url=http://visualbasic.about.com/od/usingvbnet/a/earlybind.htm|title=Early vs. Late Binding|publisher=Visualbasic.about.com|access-date=24 February 2015|archive-url=https://web.archive.org/web/20150225004949/http://visualbasic.about.com/od/usingvbnet/a/earlybind.htm|archive-date=25 February 2015|url-status=dead}}</ref> however, C# 4.0 added the <code>dynamic</code> type, which functions as a late-bound form of Object
* Namespaces can be imported at the project level, so that they don't have to be imported into each individual file, as in C#
* Namespaces can be imported at the project level, so that they don't have to be imported into each individual file, as in C#
* Definition of conditional compiler constants
* Definition of conditional compiler constants
Line 74: Line 75:


===Features of C# not found in Visual Basic .NET===
===Features of C# not found in Visual Basic .NET===
* Use C# ref struct in VB.NET : Detailed information can be found, for example here : https://www.vbforums.com/showthread.php?889867-Use-C-ref-struct-in-VB-NET-Today-And-vote-against-preventing-this-in-Roslyn
* Multi-line comments. In VB this is handled in the Visual Studio IDE editor, which adds comment markers to selections.
*Multi-line comments. In VB this is handled in the Visual Studio IDE editor, which adds comment markers to selections.
* Static classes (classes which cannot contain any non-static members, although VB.NET's Modules are essentially static classes with additional semantics)
* Static classes (classes which cannot contain any non-static members, although VB.NET's Modules are essentially static classes with additional semantics)
* Can use <code>checked</code> and <code>unchecked</code> contexts for fine-grained control of overflow/underflow checking
* Can use <code>checked</code> and <code>unchecked</code> contexts for fine-grained control of overflow/underflow checking
Line 80: Line 82:
* The getter and setter of a property may implement separate interfaces. In VB you'd have to define two properties instead: a read-only property implementing one interface, and a write-only property implementing the other interface.
* The getter and setter of a property may implement separate interfaces. In VB you'd have to define two properties instead: a read-only property implementing one interface, and a write-only property implementing the other interface.
* Implicit interface implementation
* Implicit interface implementation
* Can use the coalesce operator <code>??</code> to return the first non-null value (ex. <code>null ?? null ?? 1</code> returns <code>1</code>). VB.NET would have to use the <code>If</code> function with two parameters.
* Can use the coalesce operator <code>??</code> to return the first non-null value (ex. <code>null ?? null ?? 1</code> returns <code>1</code>). VB.NET would have to use the <code>If</code> function with two parameters - e.g. <code>If(Nothing, If(Nothing, 1))</code> returns <code>1</code>.
* Pointers (in the unsafe context)
* Pointers (in the unsafe context)
* Conditional operator ?: <code>(someThingTrueOrFalse) ? whenTrue() : whenFalse();</code>
* Conditional operator ?: <code>(someThingTrueOrFalse) ? whenTrue() : whenFalse();</code>. VB.NET would have to use the <code>If</code> function with three parameters - i.e. <code>If(someThingTrueOrFalse, whenTrue(), whenFalse())</code>.


===Other characteristics of Visual Basic .NET not applicable to C#===
===Other characteristics of Visual Basic .NET not applicable to C#===
Line 89: Line 91:
* VB.NET identifiers are not case-sensitive.
* VB.NET identifiers are not case-sensitive.
* When assigning a value to a variable with a different [[data type]] (and with <code>Option Strict</code> not turned on), VB.NET will [[Type conversion|coerce]] the value if possible. This automatic coercion can sometimes lead to unexpected results, for example:
* When assigning a value to a variable with a different [[data type]] (and with <code>Option Strict</code> not turned on), VB.NET will [[Type conversion|coerce]] the value if possible. This automatic coercion can sometimes lead to unexpected results, for example:
<syntaxhighlight lang="vb">
<syntaxhighlight lang="vbnet">
Dim i As Integer = "1" 'Compiler automatically converts String to Integer
Dim i As Integer = "1" 'Compiler automatically converts String to Integer
Dim j As String = 1 'Compiler automatically converts Integer to String
Dim j As String = 1 'Compiler automatically converts Integer to String
Line 96: Line 98:
End If
End If
</syntaxhighlight>
</syntaxhighlight>
Although the default is for <code>Option Strict</code> to be off for backward compatibility reasons, it is recommended by Microsoft<ref>{{cite web|url=http://msdn.microsoft.com/en-us/library/zcd4xwzs.aspx |title=Option Strict Statement |publisher=Msdn.microsoft.com |date=2015-02-18 |accessdate=2015-02-24}}</ref> and widely considered to be good practice to turn <code>Option Strict</code> on, due to the fact that it increases application performance and reduces the possibility of naming errors and other programming mistakes.<ref>GetDotNetCode.com:{{cite web|url=http://www.getdotnetcode.com/gdncstore/free/Articles/OPTION%20STRICT%20ON.htm|title=Option Strict On|publisher=Getdotnetcode.com|accessdate=24 February 2015|url-status=dead|archiveurl=https://web.archive.org/web/20120313000454/http://www.getdotnetcode.com/gdncstore/free/Articles/OPTION%20STRICT%20ON.htm|archivedate=13 March 2012}}</ref>
Although the default is for <code>Option Strict</code> to be off for backward compatibility reasons, it is recommended by Microsoft<ref>{{cite web|url=http://msdn.microsoft.com/en-us/library/zcd4xwzs.aspx |title=Option Strict Statement |publisher=Msdn.microsoft.com |date=2015-02-18 |access-date=2015-02-24}}</ref> and widely considered to be good practice to turn <code>Option Strict</code> on, due to the fact that it increases application performance and reduces the possibility of naming errors and other programming mistakes.<ref>GetDotNetCode.com:{{cite web|url=http://www.getdotnetcode.com/gdncstore/free/Articles/OPTION%20STRICT%20ON.htm|title=Option Strict On|publisher=Getdotnetcode.com|access-date=24 February 2015|url-status=dead|archive-url=https://web.archive.org/web/20120313000454/http://www.getdotnetcode.com/gdncstore/free/Articles/OPTION%20STRICT%20ON.htm|archive-date=13 March 2012}}</ref>
* <code>Val()</code> function which also parses a null value while converting into double (In c# <code>Convert.ToDouble()</code> is used to convert any object into a double type value, but which throws an exception in the case of a null value)
* <code>Val()</code> function which also parses a null value while converting into double (In c# <code>Convert.ToDouble()</code> is used to convert any object into a double type value, but which throws an exception in the case of a null value)
* CInt, CStr, CByte, CDbl, CBool, CDate, CLng, CCur, CObj and a wide variety of conversion functions built into the language
* CInt, CStr, CByte, CDbl, CBool, CDate, CLng, CCur, CObj and a wide variety of conversion functions built into the language
Line 122: Line 124:
* <code>Me</code> vs <code>this</code> - a self-reference to the current object instance
* <code>Me</code> vs <code>this</code> - a self-reference to the current object instance
* <code>MustInherit</code> vs <code>abstract</code> - prevents a class from being directly instantiated, and forces consumers to create object references to only derived classes
* <code>MustInherit</code> vs <code>abstract</code> - prevents a class from being directly instantiated, and forces consumers to create object references to only derived classes
* <code>MustOverride</code> vs <code>abstract</code> - for forcing derived classes to override this method
* <code>MustOverride</code> vs <code>abstract</code> - for forcing derived classes to [[method overriding|override]] this method
* <code>MyBase</code> vs <code>base</code> - for referring to the base class from which the current class is derived
* <code>MyBase</code> vs <code>base</code> - for referring to the base class from which the current class is derived
* <code>NotInheritable</code> vs <code>sealed</code> - for declaring classes that may not be inherited
* <code>NotInheritable</code> vs <code>sealed</code> - for declaring classes that may not be inherited
* <code>NotOverridable</code> vs <code>sealed</code> - for declaring methods that may not be overridden by derived classes
* <code>NotOverridable</code> vs <code>sealed</code> - for declaring methods that may not be overridden by derived classes
* <code>Overridable</code> vs <code>virtual</code> - declares a method as being able to be overridden in derived classes
* <code>Overridable</code> vs <code>virtual</code> - declares a method as being able to be overridden in derived classes
* <code>Overrides</code> vs <code>override</code> - for marking a virtual method as overridden
* <code>Overrides</code> vs <code>override</code> - for marking a [[virtual method]] as overridden
* <code>Shared</code> vs <code>static</code> - for declaring methods that do not require an explicit instance of an object
* <code>Shared</code> vs <code>static</code> - for declaring methods that do not require an explicit instance of an object


Some C# keywords such as <code>sealed</code> 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.
Some C# keywords such as <code>sealed</code> 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.


{{example farm|date=February 2012}}
{{Excessive examples|date=February 2012}}


===Comments===
===Comments===
Line 165: Line 167:
''' XML 2nd line comment
''' XML 2nd line comment
''' XML 3rd line comment
''' XML 3rd line comment

REM Comment


#If COMMENT Then
#If COMMENT Then
Line 184: Line 188:
|
|
<syntaxhighlight lang="csharp">
<syntaxhighlight lang="csharp">
if (i<10) {
if (condition) {
// condition is true
// condition is true
} else if (othercondition) {
} else if (othercondition) {
Line 436: Line 440:


==Adoption and community support==
==Adoption and community support==
Both C# and VB.NET have high adoption rates, and very active developer communities and [[Microsoft]] fully supports both communities. [[.NET Framework]] developers widely use both VB.NET and C# as primary languages.<ref name="Wiltamuth"/><ref name="forrester"/> However, C# has more community activity on the Internet and there are more books available for C#. This may indicate either that there is more adoption of C# or that users need more help with it.
Both C# and VB.NET have high adoption rates, and very active developer communities and [[Microsoft]] fully supports both communities. [[.NET]] framework developers widely use both VB.NET and C# as primary languages.<ref name="Wiltamuth"/><ref name="forrester"/> However, C# has more community activity on the Internet and there are more books available for C#. This may indicate either that there is more adoption of C# or that users need more help with it.


Examples of community and industry adoption include:
Examples of community and industry adoption include:
* TIOBE Programming Community Index for July 2010 show that C# surpassed Visual Basic<ref name="tiobe">{{cite web | url = http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html | title = C# is rated higher than Visual Basic for the first time in history|publisher=Tiobe.com|accessdate=24 February 2015}}</ref>
* TIOBE Programming Community Index for July 2010 show that C# surpassed Visual Basic<ref name="tiobe">{{cite web |url=http://www.tiobe.com/index.php/content/paperinfo/tpci/ |title=C# is rated higher than Visual Basic for the first time in history |publisher=Tiobe.com |access-date=24 February 2015}}</ref>
*TIOBE Programming Community Index shows that VB.NET surpassed C# in 2018<ref>{{Cite web|url=https://www.tiobe.com/tiobe-index/|title=TIOBE Index {{!}} TIOBE - The Software Quality Company|website=www.tiobe.com|access-date=2019-03-27}}</ref>
*TIOBE Programming Community Index shows that VB.NET surpassed C# in 2018<ref>{{Cite web |url=https://www.tiobe.com/tiobe-index/ |title=TIOBE Index |website=TIOBE.com: The Software Quality Company |access-date=2019-03-27}}</ref>
*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#.<ref name="Wiltamuth">{{cite web | url = http://blogs.msdn.com/scottwil/archive/2010/03/09/vb-and-c-coevolution.aspx | title = VB and C# Coevolution | publisher = [[MSDN]] | accessdate = 2010-03-27}}</ref>
*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#.<ref name="Wiltamuth">{{cite web | url = http://blogs.msdn.com/scottwil/archive/2010/03/09/vb-and-c-coevolution.aspx | title = VB and C# Coevolution | publisher = [[MSDN]] | access-date = 2010-03-27}}</ref>
*A 2007 [[Forrester Research]] poll revealed that 59% of .NET developers used ''only'' [[VB.NET]] to create software.<ref name="forrester">{{cite web| url = http://www.linuxfordevices.com/c/a/News/Mono-brings-Visual-Basic-programs-to-Linux/| archive-url = https://archive.is/20120914001915/http://www.linuxfordevices.com/c/a/News/Mono-brings-Visual-Basic-programs-to-Linux/| url-status = dead| archive-date = 2012-09-14| title = Mono brings Visual Basic programs to Linux| publisher = [[Linux-Watch]]| accessdate = 2010-03-25}}</ref>
*A 2007 [[Forrester Research]] poll revealed that 59% of .NET developers used ''only'' [[VB.NET]] to create software.<ref name="forrester">{{cite web| url = http://www.linuxfordevices.com/c/a/News/Mono-brings-Visual-Basic-programs-to-Linux/| archive-url = https://archive.today/20120914001915/http://www.linuxfordevices.com/c/a/News/Mono-brings-Visual-Basic-programs-to-Linux/| url-status = dead| archive-date = 2012-09-14| title = Mono brings Visual Basic programs to Linux| publisher = [[Linux-Watch]]| access-date = 2010-03-25}}</ref>
*[[Visual Basic Express]] is the most popular download of all the [[Visual Studio Express]] downloads.<ref name="VSMagNov2007" />
*[[Visual Basic Express]] is the most popular download of all the [[Visual Studio Express]] downloads.<ref name="VSMagNov2007" />
*According to a November 2007 survey conducted by [[Visual Studio]] Magazine "41 percent said they used C#, 34 percent programmed in VB.NET, while 25 percent responded with 'other.'"<ref name="VSMagNov2007">{{cite web | url = http://visualstudiomagazine.com/columns/article.aspx?editorialsid=2333 | title = C#'s Exploding Mindshare | author = Patrick Meader | publisher = [[Visual Studio]] Magazine, November 2007 | accessdate = 2008-12-16}}</ref>
*According to a November 2007 survey conducted by [[Visual Studio]] Magazine "41 percent said they used C#, 34 percent programmed in VB.NET, while 25 percent responded with 'other.'"<ref name="VSMagNov2007">{{cite web | url = http://visualstudiomagazine.com/columns/article.aspx?editorialsid=2333 | title = C#'s Exploding Mindshare | author = Patrick Meader | publisher = [[Visual Studio]] Magazine, November 2007 | access-date = 2008-12-16 | archive-url = https://web.archive.org/web/20080420055513/http://visualstudiomagazine.com/columns/article.aspx?editorialsid=2333 | archive-date = 2008-04-20 | url-status = dead }}</ref>
* [[Stephen Wiley]], marketing product manager at [[Apress]] has reported "C# titles outsell VB.NET title books handily, by somewhere between a 2–1 and 3–1 margin."<ref name="VSMagNov2007" />
* [[Stephen Wiley]], marketing product manager at [[Apress]] has reported "C# titles outsell VB.NET title books handily, by somewhere between a 2–1 and 3–1 margin."<ref name="VSMagNov2007" />
* [[MSDN Blogs]], the blogging site for Microsoft employees, has 770,000 posts that discuss C#, while only 378,000 mention VB.Net (as of Feb 04, 2016){{citation needed|date=April 2012}}
* [[MSDN Blogs]], the blogging site for Microsoft employees, has 770,000 posts that discuss C#, while only 378,000 mention VB.Net (as of Feb 04, 2016){{citation needed|date=April 2012}}
Line 455: Line 459:


===J#===
===J#===
[[J sharp|J#]] 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.
[[Visual J Sharp|J#]] runs a distant fourth in .NET adoption. J# is a language mainly designed to ease 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===
===Additional .NET languages===
Line 472: Line 476:
*[https://web.archive.org/web/20080705061024/http://www.codeproject.com/dotnet/vbnet_c__difference.asp CodeProject VB vs C#]
*[https://web.archive.org/web/20080705061024/http://www.codeproject.com/dotnet/vbnet_c__difference.asp CodeProject VB vs C#]
*[http://www.harding.edu/fmccown/vbnet_csharp_comparison.html Syntactical differences between C# and VB.NET]
*[http://www.harding.edu/fmccown/vbnet_csharp_comparison.html Syntactical differences between C# and VB.NET]
*[https://www.ifourtechnolab.com/blog/differences-between-asp-net-and-asp-net-core-asp-net-vs-asp-net-core Differences Between Asp.Net and Asp.Net Core - Asp.Net Vs Asp.Net Core]


{{.NET}}
{{Common Language Infrastructure}}
{{Common Language Infrastructure}}


{{DEFAULTSORT:C Sharp and Visual Basic .Net comparison}}
{{DEFAULTSORT:C Sharp and Visual Basic .Net comparison}}
[[Category:.NET Framework]]
[[Category:.NET]]
[[Category:Articles with example BASIC code]]
[[Category:Articles with example C Sharp code]]
[[Category:BASIC programming language family]]
[[Category:BASIC programming language family]]
[[Category:C programming language family]]
[[Category:C programming language family]]
[[Category:Comparison of individual programming languages]]
[[Category:Comparison of individual programming languages]]
<!-- Hidden categories below -->
[[Category:Articles with example BASIC code]]
[[Category:Articles with example C Sharp code]]

Latest revision as of 04:47, 22 July 2024

C# and Visual Basic (.NET) are the two main programming languages used to program on the .NET framework.

Language history

[edit]

C# and VB.NET are very different languages in syntax and history.

As the name suggests, the C# syntax is based on the core C programming language originally developed by Dennis Ritchie at Bell Labs (AT&T) in the 1970s.[1] Java and C++ are two other programming languages whose syntax is also based on the C syntax,[2] so they share a common look and feel. See Comparison of C Sharp and Java for more on this topic.

BASIC's roots go back to Dartmouth College.[3] BASIC (Beginner's All-purpose Symbolic Instruction Code) was developed in the 1960s as a method to overcome the difficulties of using assembly language written for processor-specific and/or brand name specific mainframes and hardware. Programming was hardware dependent by design more so for marketing reasons than to preserve the logical composition of programming that should transcend hardware. (Microsoft's claim to fame with its operating system was to free consumers from hardware-specific devices by encapsulating those tasks within its operating system.) Code became "portable" due to the compiler, and in fact, both Visual Basic .NET and C# use the same CLR (Common Language Runtime) today. Microsoft and HP were interested in creating an ISO standard language, which was the original goal, however; HP dropped its support, and the ISO computer language never materialized as an International Standard.

VB.NET finds its roots in BASIC. 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 1970s, 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 1980s, 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.[4] It competed directly against other RAD tools of the 1990s such as PowerBuilder.[5] Even though Visual Basic was a successful development platform, it was discontinued after its 6th version (VB6) when Microsoft introduced the .NET Framework and its related Visual Studio development platform in the early 2000s. At that time, the current C++ and VB6 languages were used by Microsoft as the basis for two new programming languages in their new "Integrated Development Environment (IDE)". These languages were named C# and VB.NET.

In February 2017, Microsoft communicated their intent to end the "co-evolution" strategy between the two languages that had existed since 2010 and allow the two languages to again evolve independently. C# is now the dominant Microsoft-based development language. Developers will notice that VB 15 (first appearing in Visual Studio 2017) lacks certain language capabilities contained in the new C# 7.3.[6]

Language comparison

[edit]

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.[7] They compile to the same intermediate language (IL), which runs against the same .NET Framework runtime libraries.[8] 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 task. The only fundamental differences between the languages can be found in the implementation of interfaces and in the declaration, raising and handling of events. Although both languages are high-level programming languages, VB.NET maintains a slightly higher level of abstraction in some respects.

Runtime multi-language support

[edit]

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 languages should have the same level of access to all OS features, should be able to expose the same level of power and usability, 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, and Common Intermediate Language. Additionally all .NET languages have access to platform features including garbage collection, cross language inheritance, exception handling, and debugging. This allows the same output binary to be produced from any .NET programming language.

Development environment

[edit]

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 in C# compared to Visual Basic .NET, and did not offer background compilation for C#.[9] 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 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.[10] Such is not the case with Visual Basic because the Error List panel is synchronized with the background compiler.

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

Language features

[edit]

The bulk of the differences between C# and VB.NET from a technical perspective are syntactic sugar. 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.

Features of Visual Basic .NET not found in C#

[edit]
  • 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, which connects event handlers to object variables rather than to objects.
  • Firing of events is done with the RaiseEvent keyword, giving the IDE the chance to show a list of available events to pick from. RaiseEvent implicitly checks if there are any event handlers wired up. (in C# raising an event is syntactically identical to calling a procedure, and it requires an additional line of code to check for wired event handlers)
  • Delegates for events don't need to be declared. They are implicitly declared in the declaration of the events.
  • Referring to an object using an unqualified dot reference, using the With ... End With structure
  • XML Literals[11]
  • Inline date declarations, e.g. #12/31/2000#
  • Module (although C#'s static classes with additional semantics, but each field must be individually declared as static)
  • Members of Modules imported to the current file, can be accessed with no preceding container accessor[12]
  • The My namespace.[13]
  • COM components and interoperability was more powerful in VB.NET, as the Object type is bound at runtime;[14] however, C# 4.0 added the dynamic type, which functions as a late-bound form of Object
  • Namespaces can be imported at the project level, so that they don't have to be imported into each individual file, as in C#
  • Definition of conditional compiler constants
  • Property methods may take parameters
  • Properties can be passed to methods with ByRef parameters (ref parameters in C#). In C# you have to write three additional instructions: Declare a variable, copy the property value into the variable and copy the variable back to the property after the method call.
  • Enums can be defined inside interfaces
  • Case statements may contain inequality expressions, like Is >= 3. (in C# this can be mimicked by nested Else and If statements)
  • Overloads keyword specifies that a property or procedure redeclares one or more existing properties or procedures with the same name within the same class or the base class. (the lack of this keyword in C# might lead to inadvertent overloading)
  • Implements keyword to indicate which interfaces a class member implements. In C# a similar syntax exist, but it is optional and it can only be applied if the member implements a single interface.
  • Wie operator for pattern comparison of strings in a much simpler way than using regular expressions. (in C# the same is available with the Microsoft.VisualBasic.CompilerServices.LikeOperator.LikeString method, but not as a handy language key word)
  • Return statement is not required. Return can also be done by assigning the value to the function
  • Visual basic has built in constants like vbCrLf and vbTab
  • No out parameter modifier exists, because in VB all variables are automatically initialised.
  • The MyClass keyword behaves like an object variable referring to the current instance of a class as originally implemented. MyClass is similar to Me, but all method calls on it are treated as if the method were NotOverridable.
  • MyBase.New is used to explicitly call a base class constructor from a derived class constructor.
  • The My feature provides easy and intuitive access to a number of .NET Framework classes, enabling the Visual Basic user to interact with the computer, application, settings, resources, and so on.
  • Local variables (i.e. variables declared inside of a procedure) are automatically initialized.
  • Local variables can be declared with the Static modifier in order to preserve their value between calls to the procedure.
  • The Default declaration makes a property an index and able to use the shorter syntax for collection retrievals like MyCollection(5). C# has a similar construct reusing the keyword this as the name of the property. Multiple indexers can be declared using keys of different types e.g. MyCollection(5) oder MyCollection("Bob").
  • C# lacks the DirectCast (mapping to a single CLR instruction), strict type conversion can be achieved by the as operator which includes an additional runtime error protection.
  • C# lacks the End statement which abruptly terminates an application.
  • Lambda expressions inference Dim x = Function(n As Integer) n + 1

Features of C# not found in Visual Basic .NET

[edit]
  • Use C# ref struct in VB.NET : Detailed information can be found, for example here : https://www.vbforums.com/showthread.php?889867-Use-C-ref-struct-in-VB-NET-Today-And-vote-against-preventing-this-in-Roslyn
  • Multi-line comments. In VB this is handled in the Visual Studio IDE editor, which adds comment markers to selections.
  • Static classes (classes which cannot contain any non-static members, although VB.NET's Modules are essentially static classes with additional semantics)
  • Can use checked and unchecked contexts for fine-grained control of overflow/underflow checking
  • Iterative for-loops can contain multiple conditionals, such as for(int i = 0; i < 10 && somethingTrue; i++). This is a legacy of C, where the for statement is basically syntactic sugar for a while statement.
  • The getter and setter of a property may implement separate interfaces. In VB you'd have to define two properties instead: a read-only property implementing one interface, and a write-only property implementing the other interface.
  • Implicit interface implementation
  • Can use the coalesce operator ?? to return the first non-null value (ex. null ?? null ?? 1 returns 1). VB.NET would have to use the If function with two parameters - e.g. If(Nothing, If(Nothing, 1)) returns 1.
  • Pointers (in the unsafe context)
  • Conditional operator ?: (someThingTrueOrFalse) ? whenTrue() : whenFalse();. VB.NET would have to use the If function with three parameters - i.e. If(someThingTrueOrFalse, whenTrue(), whenFalse()).

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

[edit]
  • 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 identifiers are not case-sensitive.
  • When assigning a value to a variable with a different data type (and with Option Strict not turned on), VB.NET will coerce the value if possible. This automatic coercion can sometimes lead to unexpected results, 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
    MsgBox("Avoid using, but this message will appear!")
End If

Although the default is for Option Strict to be off for backward compatibility reasons, it is recommended by Microsoft[15] and widely considered to be good practice to turn Option Strict on, due to the fact that it increases application performance and reduces the possibility of naming errors and other programming mistakes.[16]

  • Val() function which also parses a null value while converting into double (In c# Convert.ToDouble() is used to convert any object into a double type value, but which throws an exception in the case of a null value)
  • CInt, CStr, CByte, CDbl, CBool, CDate, CLng, CCur, CObj and a wide variety of conversion functions built into the language

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

[edit]
  • 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)
  • C# identifiers are case-sensitive.
  • To assign the same value to multiple variables, you can use a=b=c.

Syntax comparisons

[edit]

Visual Basic .NET terminates a block of code with End BlockName statements (or Nächste statements, for a for loop) 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++ and Java. 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 apparent name, for example variable1 and Variable1. Visual Studio will correct (make uniform) the case of variables as they are typed in VB.NET. In some cases however, case sensitivity can be useful. C# programmers typically capitalize type and member names and leave field and variable names lowercase. This allows, for example, a fairly natural naming of method arguments: public int CalculateOrders(Customer customer). This can, however, 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

[edit]

Visual Basic is not case sensitive, which means that any combinations of upper and lower case letters in keywords are acceptable. 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 that the default 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 intern - access modifiers allowing inter-class but not inter-assembly reference, except for friend assemblies
  • 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
  • Overrides vs override - for marking a virtual method as overridden
  • 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.

Kommentare

[edit]
C# Visual Basic .NET
// Single line comment

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

/// XML single line comment

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

#if COMMENT
   multi-line comment via pre-processing 
   line 2
   line 3
#endif
' Single line comment

''' XML 1st line comment
''' XML 2nd line comment
''' XML 3rd line comment

REM Comment

#If COMMENT Then
   multi-line comment via pre-processing 
   line 2
   line 3
#End If

Intra-line comments not available

Conditionals

[edit]
C# Visual Basic .NET
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

[edit]
C# Visual Basic .NET
for (int i = 0; i < number; ++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
for (int i = 0; i <= 20; i += 2) {
    // loops from 0 to 20 by 2's
}
For i As Integer = 0 To 20 Step 2
    ' loops from 0 to 20 by 2's
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

Comparers

[edit]

Primitive types

[edit]
C# Visual Basic .NET
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) {
    // non-short-circuiting boolean operators
}
If a = b And c = d Or e = f Then
    ' non-short-circuiting boolean operators
End If
if (a == b && c == d || e == f) {
    // short-circuiting boolean operators
}
If a = b AndAlso c = d OrElse e = f Then
    ' short-circuiting boolean operators
End If

Object types

[edit]
C# Visual Basic .NET
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 == b) {
    // instances are equivalent
}
If a = b Then
    ' instances are equivalent
End If
if (a != 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 TypeOf a IsNot b Then
    ' types of a and b are not compatible
End If

Adoption and community support

[edit]

Both C# and VB.NET have high adoption rates, and very active developer communities and Microsoft fully supports both communities. .NET framework developers widely use both VB.NET and C# as primary languages.[17][18] However, C# has more community activity on the Internet and there are more books available for C#. This may indicate either that there is more adoption of C# or that users need more help with it.

Examples of community and industry adoption include:

  • TIOBE Programming Community Index for July 2010 show that C# surpassed Visual Basic[19]
  • TIOBE Programming Community Index shows that VB.NET surpassed C# in 2018[20]
  • 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#.[17]
  • A 2007 Forrester Research poll revealed that 59% of .NET developers used only VB.NET to create software.[18]
  • Visual Basic Express is the most popular download of all the Visual Studio Express downloads.[21]
  • According to a November 2007 survey conducted by Visual Studio Magazine "41 percent said they used C#, 34 percent programmed in VB.NET, while 25 percent responded with 'other.'"[21]
  • Stephen Wiley, marketing product manager at Apress has reported "C# titles outsell VB.NET title books handily, by somewhere between a 2–1 and 3–1 margin."[21]
  • MSDN Blogs, the blogging site for Microsoft employees, has 770,000 posts that discuss C#, while only 378,000 mention VB.Net (as of Feb 04, 2016)[citation needed]
  • Google Groups, a Usenet search engine, returns 35,200,000 hits for "VB .Net", and 244,000,000 for "C#" (as of Feb 04, 2016) [citation needed]
  • The 2018 Stack Overflow developers user survey stated that 35% of professional developers used C# while only 6.9% used VB.NET.[22]

Other languages

[edit]

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

[edit]

C++/CLI (a replacement for Managed Extensions for C++) 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#

[edit]

J# runs a distant fourth in .NET adoption. J# is a language mainly designed to ease 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

[edit]

All .NET languages compile down to Common Intermediate Language (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 to transform a .NET assembly into source code that is nearly identical to the original source. Code obfuscators 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.

References

[edit]
  1. ^ Ritchie, Dennis (April 1993). Chistory (Report). Bell Labs. Archived from the original on 2015-02-03. Retrieved 2013-08-18.
  2. ^ "History of Java programming language". Freejavaguide.com. Retrieved 2013-08-18.
  3. ^ "BASIC at Dartmouth"
  4. ^ "The Birth of Visual Basic". Forestmoon.com. Retrieved 2013-08-18.
  5. ^ "Powersoft History PowerBuilder History". Lannigan.org. Retrieved 2013-08-18.
  6. ^ "The .NET Language Strategy". February 2017.
  7. ^ Krill, Paul (2009-02-27). "Microsoft converging programming languages | Developer World". InfoWorld. Archived from the original on 2013-01-26. Retrieved 2013-08-18.
  8. ^ "Microsoft Intermediate Language". Dotnet-guide.com. Retrieved 2013-08-18.
  9. ^ Matthew Gertz. "Scaling Up: The Very Busy Background Compiler". MSDN Magazine. Archived from the original on 2008-02-19. Retrieved 2008-12-16.
  10. ^ a b c "System and methodology providing compiler-assisted refactoring". Freepatentsonline.com. Retrieved 24 February 2015.
  11. ^ Jonathan Allen. "Does C# Need VB9's XML Literals?". Retrieved 2009-01-13.
  12. ^ "DateAndTime.Now Property (Microsoft.VisualBasic)". Msdn.microsoft.com. 2015-02-18. Retrieved 2015-02-24.
  13. ^ "Development with My (Visual Basic)". Msdn.microsoft.com. 2015-02-18. Retrieved 2015-02-24.
  14. ^ "Early vs. Late Binding". Visualbasic.about.com. Archived from the original on 25 February 2015. Retrieved 24 February 2015.
  15. ^ "Option Strict Statement". Msdn.microsoft.com. 2015-02-18. Retrieved 2015-02-24.
  16. ^ GetDotNetCode.com:"Option Strict On". Getdotnetcode.com. Archived from the original on 13 March 2012. Retrieved 24 February 2015.
  17. ^ a b "VB and C# Coevolution". MSDN. Retrieved 2010-03-27.
  18. ^ a b "Mono brings Visual Basic programs to Linux". Linux-Watch. Archived from the original on 2012-09-14. Retrieved 2010-03-25.
  19. ^ "C# is rated higher than Visual Basic for the first time in history". Tiobe.com. Retrieved 24 February 2015.
  20. ^ "TIOBE Index". TIOBE.com: The Software Quality Company. Retrieved 2019-03-27.
  21. ^ a b c Patrick Meader. "C#'s Exploding Mindshare". Visual Studio Magazine, November 2007. Archived from the original on 2008-04-20. Retrieved 2008-12-16.
  22. ^ "Stack Overflow Developer Survey 2018". Stack Overflow. Retrieved 2018-04-22.


[edit]