P. 1
Comparison of C Sharp and Visual Basic

Comparison of C Sharp and Visual Basic

|Views: 110|Likes:
Published by DIBUSENGA

More info:

Published by: DIBUSENGA on May 01, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as DOCX, PDF, TXT or read online from Scribd
See more
See less

06/03/2011

pdf

text

original

Comparison of C Sharp and Visual Basic .

NET
From Wikipedia, the free encyclopedia

C# and Visual Basic are the two primary languages used to program on the .NET Framework.

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 [1] and eventually evolved into the fully object oriented C++ language still in use today. Much of the Java syntax is also based on this same C++ language,[2] 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.[3] 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.[4] 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.[5] It competed directly against other RAD tools of the 1990s such as PowerBuilder.[6] 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.

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.[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 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 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
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:
y y y

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 synchronised 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]

Features of C# not found in Visual Basic . most of the features are in both languages. so they don't have to be imported to each individual file.NET y y y y y 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 . That is.0 added the dynamic type which functions as a late bound form of Object.NET from a technical perspective are syntactic sugar. This is done using the With .TryParse) XML Literals[11] Inline date declarations by using #1/1/2000# syntax (M/dd/yyyy).[13] It can be achieved in C# using a catch block followed by if block. 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 . Features of Visual Basic .NET as the Object type is bound at runtime. like C# In-line exceptions filtering by a Boolean expression. 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. can be access with no preceding container accessor (See Now for example) The My namespace COM components and interoperability was more powerful in VB. using "When expression" blocks.[12] however C#4.NET has the Handles syntax for events Marshalling an object for multiple actions using an unqualified dot reference. Namespaces can be imported in project level. 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.. Module (although C#'s sealed static classes with additional semantics. End With structure IsNumeric evaluates whether a string can be cast into a numeric value (the equivalent for C# requires using int. With instruction Executes a series of instructions repeatedly refer to a single object or structure.Language features The bulk of the differences between C# and VB.NET not found in C# y y y y y y y y y y y y y Variables can be declared using the WithEvents construct.NET) Static classes (Classes which cannot contain any non-static members.. but each field has to individually be declared as static) Members of Modules imported to the current file. VB.

although + can be used for concatenation as well. {}. in C# if a block consists of only a single statement. + for addition and & for concatenation.ToDouble() is used to convert any object into double type value. and eliminates the chance of naming errors and other programming mistakes.NET. +. CCur. but which y throws exception in case of a null value) CInt. 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. the braces may be omitted. It will auto convert type without notifying programmer.NET is not case-sensitive. If the default is left in place. In C#. Visual Basic . numeric operations are not checked. Whereas C# has separate tokens. .NET property methods may take parameters C# is case-sensitive. However. at the risk that numeric overflows will not be detected. CByte. it is recommended by Microsoft[14] and widely considered to be a good to turn 'Option Strict' "on". This results in slightly faster code. Syntax comparisons Visual Basic . CDate. Additionally. == for comparison and = to assign a value VB.NET y y y y By default. for a for loop) which are more familiar for programmers with experience using TSQL. however. the braces. (It can be done in Visual Basic by checking an option) Addition and string concatenation use the same token.[15] y Val() function which also parses a null value while converting into double (In c# Convert. CByte. has separate tokens. due to the fact it increases application performance.Other characteristics of Visual Basic . CLng. CStr. Type checking is less strict by default. are use to delimit blocks. In Visual Basic .Show("Avoid using. CBool. =. CDbl. CObj and a wide variety of converting functions built in the language Other characteristics of C# not applicable to Visual Basic .NET terminates a block of code with End BlockName statements (or Next statements.NET not applicable to C# y y y y 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. the programmer can place arithmetic operations into a checked context to activate overflow checking. but this message will appear!") End If It should be noted that although the default is for 'Option Strict' is off. which is more familiar to programmers with experience in other widely-deployed languages such as C++ and Java.

e. In many cases however. Visual Basic and C# share most keywords. Of course. on the other hand.declares a method as being able to be overridden in derived classes Shared vs static . "If" vs "if".NET. "If". or to those unaccustomed to reading a case sensitive language. C# programmers typically capitalize type names and leave member and variable names lowercase.for declaring classes that may not be inherited NotOverridable vs sealed .access modifiers allowing inter-class but intra-assembly reference Me vs this . which means any combinations of upper and lower cases in keywords are acceptable.for forcing derived classes to override this method MyBase vs base . for example. However Visual Studio automatically converts all Visual Basic keywords to the default capitalised forms. and forces consumers to create object references to only derived classes MustOverride vs abstract . "Public". such as Visual Basic.NET. VB. Visual Studio will correct the case of variables as they are typed in VB.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.prevents a class from being directly instantiated. case sensitivity can be useful. Keywords Visual Basic is not case sensitive. with the difference being the default (Remember Visual Basic is not case sensitive) Visual Basic keywords are the capitalised versions of the C# keywords. A few keywords have very different versions in Visual Basic and C#: y y y y y y y y y Friend vs internal . this can cause problems for those converting C# code to a case-insensitive language. C# is case sensitive and all C# keywords are in lower cases. e.g. for example variable1 and Variable1.NET is not. fairly natural naming of method arguments: public int CalculateOrders(Customer customer). uses different keywords for different contexts. Thus in C# it is possible to have two variables with the same name.C# is case sensitive while Visual Basic .a self-reference to the current object instance MustInherit vs abstract . .g.for declaring methods that may not be overridden by derived classes Overridable vs virtual .for referring to the base class from which the current class is derived NotInheritable vs sealed . This allows. "Public" vs "public".

NET Multi-line comment not available '''XML single line comment XML multi-line comment not available Conditionals C# if (condition) { // condition is true } if (condition) { // condition is true } else { // condition is false } if (condition) { // condition is true } else if (othercondition) { // condition is false and othercondition is true } if (condition) { // condition is true } else if (othercondition) { // condition is false and othercondition is true } else { // condition and othercondition are false } Visual Basic .NET If condition Then ' condition is true End If If condition Then ' condition is true Else ' condition is false End If If condition Then ' condition is true ElseIf othercondition Then ' condition is false and othercondition is true End If If condition Then ' condition is true ElseIf othercondition Then ' condition is false and othercondition is true Else ' condition and othercondition false End If .Comments C# //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 Visual Basic .

Loops C# for (int i = 0.NET For i as integer = 0 To number . i--) { // loops from number down to zero } break. //breaks out of a loop Visual Basic .1 ' loop from zero up to one less than number Next For i as integer = number To 0 Step -1 ' loops from number down to zero Next 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 Primitive types C# if (a == b) { // equal } if (a != b) { // not equal } Visual Basic . i++) { // loop from zero up to one less than number } for (int i = number.1. i >= 0. i <= number .NET If a = b Then ' equal End If If a <> b Then ' not equal End If Or: if (!(a == b)) //can also be written as (a != b) { // not equal } if (a == b & c == d | e == f) { // multiple comparisons } if (a == b && c == d || e == f) { // short-circuiting comparisons } Or: If Not a = b Then ' not equal End If If a = b And c = d Or e = f Then ' multiple comparisons End If If a = b AndAlso c = d OrElse (e = f) Then ' short-circuiting comparisons End If .

Equals(b)) { // instances are equivalent } if (! a. b)) If a Is b Then 'Can also be written as If { Object.ReferenceEquals(a. the C# evaluation of the .NET). b) Then // variables refer to the same ' variables refer to the same instance instance End If } if (!Object.Equals(b)) { // not equivalent } var type = typeof(int). whereas the VB. if (a is b) { // types of a and b are compatible } if (!(a is b)) { // types of a and b are not compatible } If a = b Then 'Or a. If "a" were null. Omitted for clarity.ReferenceEquals(a.equals method would throw a NullReferenceException.equals(a.NET = operator would return true if both were null.Equals(b) ' instances are equivalent End If If a <> b Then ' not equivalent End If Dim type = GetType(Integer) If TypeOf a Is b Then ' types of a and b are compatible End If 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. or false if only one was null (and evaluate the equals method if neither were null).Object types C# Visual Basic .NET If a = b Then ============================Wiki Ends===================================== . the exact transliteration would be: C# if(object. b)) If a IsNot b Then { ' variables do not refer to the same // variables do not refer to instance the same instance End If } if (a.equals method and the = operator are implemented for the class type in question.b)) VB.ReferenceEquals(a.NET if (Object. They also assume that the .

Long.DateTime) Reference Types .NET Program Structure using System.VB.NET" // See if an argument was passed from the command line 'See if an argument was passed from the command line if (args. UShort. uint. Console. ushort.NET Data Types Value Types bool byte.WriteLine("Hello.WriteLine("Hello. Dim name As String = "VB.NET and C# Comparison This is a quick reference guide to highlight some key syntactical differences between VB. " + name + "!"). ULong Single. long. Hope you find this useful! Thank you to Tom Shelton. Integer.NET Comments C# ' Single line only REM Single line only ''' <summary>XML comments</summary> // Single line /* Multiple line */ /// <summary>XML comments on single line</summary> /** <summary>XML comments on multiple lines</summary> */ VB.Length = 1 Then name = args(0) name = args[0]. SByte Char Short. Fergus Cooney. UInteger.NET and C#. int. Double Decimal Date (alias of System. and others for your VB. ulong float.Length == 1) If args. End Sub } End Class } End Namespace } VB. Steven Swafford. Gjuro Kladaric. C# Imports System Namespace Hello namespace Hello { Class HelloWorld public class HelloWorld { Overloads Shared Sub Main(ByVal args() As public static void Main(string[] args) { String) string name = "C#". sbyte char short. " & name & "!") Console. double decimal DateTime (not a built-in C# type) Reference Types C# Value Types Boolean Byte.

Type Conversion / Casting float d = 3.Parse("12/31/2010 12:15:00 PM"). DateTime today = DateTime. var hero = new SuperHero() { Name = "Batman" }.GetType()). // Set to 4 (rounds) int i = (int)d. // set to 3 (truncates decimal) object o = 2. int i = (int)o. Console. double pi = 3. // Returns null if type cast fails . float gpa = 2.WriteLine(GetType(Integer)) ' Prints System. 3} Dim hero = New SuperHero With {.9! Dim pi As Double = 3. 2.5f. string name = "Dwight". uint uiTotal = 123. // hex object person = null.Name). // prints Int32 Circle c = new Circle(). // Throws InvalidCastException if type cast fails Shape s = new Shape(). var nums = new int[] { 1. // Prints System. char grade = 'B'. Type Information int x. i = Convert. decimal amount = 35. Circle) ' Returns Nothing if type cast fails object string Initializing bool correct = true.Object String Initializing Dim correct As Boolean = True Dim b As Byte = &H2A 'hex or &O52 for octal Dim person As Object = Nothing Dim name As String = "Dwight" Dim grade As Char = "B"c Dim today As Date = #12/31/2010 12:15:00 PM# Dim amount As Decimal = 35.Name = "Batman"} Type Information Dim x As Integer Console.WriteLine(x.Int32 Console. // Prints System. Circle c = s as Circle. Implicitly Typed Local Variables var s = "Hello!". ulong ulTotal = 123.WriteLine(x.Int32 Console.Int32 Console. Integer) ' set to 4 (Banker's rounding) i = CInt(d) ' same result as CType i = Int(d) ' set to 3 (Int function truncates the decimal) Dim o As Object = 2 i = DirectCast(o.5 Dim i As Integer = CType(d. if (c is Shape) Console.GetType()) ' Prints System.99@ Dim gpa As Single = 2.GetType(). Integer) ' Throws InvalidCastException if type cast fails Dim s As New Shape Dim c As Circle = TryCast(s.ToInt32(d).14159265 Dim lTotal As Long = 123456L Dim sTotal As Short = 123S Dim usTotal As UShort = 123US Dim uiTotal As UInteger = 123UI Dim ulTotal As ULong = 123UL Implicitly Typed Local Variables Dim s = "Hello!" Dim nums = New Integer() {1. byte b = 0x2A.99m.14159265.WriteLine("c is a Shape"). long lTotal = 123456L. ushort usTotal = 123.9f.Int32 Console. short sTotal = 123. 2.WriteLine(x. 3 }.WriteLine(TypeName(x)) ' Prints Integer Dim c as New Circle If TypeOf c Is Shape Then _ Console.WriteLine("c is a Shape") Type Conversion / Casting Dim d As Single = 3.WriteLine(typeof(int)).

Action a = Action. C# Const MAX_STUDENTS As Integer = 25 ' Can set to a const or var. may be initialized in a // Can set to a const or var.WriteLine(Status.ToString()) ' Prints Pass enum Action {Start.93f.WriteLine(Status. enum Status {Flunk = 50.WriteLine(a.NET Constants const int MAX_STUDENTS = 25.NET Enumerations C# Enum Action Start [Stop] ' Stop is a reserved word Rewind Forward End Enum Enum Status Flunk = 50 Pass = 70 Excel = 90 End Enum Dim a As Action = Action.Start) Console. Stop.Stop If a <> Action.Start Then _ Console.Pass). y) Assignment = += -= *= /= %= &= |= ^= <<= >>= ++ -Bitwise .* / % (mod) / (integer division if both operands are ints) Math. Rewind. Forward}.* / Mod \ (integer division) ^ (raise to a power) Assignment = += -= *= /= \= ^= <<= >>= &= Bitwise Arithmetic + .93 readonly float MIN_DIAMETER = 4.Pass.Pow(x.WriteLine((int) Status. VB.NET Operators Comparison == < > <= >= != C# Comparison = < > <= >= <> Arithmetic + . Excel = 90}.ToString & " is " & a) Prints "Stop is 1" ' Prints 70 Console. Pass = 70.Pass) Console. "Stop is 1" // Prints Console.Stop. // Prints Pass ' VB.WriteLine(Status.Pass). // Prints 70 Console. if (a != Action.VB.WriteLine(a + " is " + (int) a). may be initialized in a constructor constructor ReadOnly MIN_DIAMETER As Single = 4.

' One line doesn't require "End If" else If age < 20 Then greeting = "What's up?" If age < 20 Then greeting = "What's up?" Else greeting = "Hello". } ' Preferred If x <> 100 AndAlso y < 5 Then x *= 5 y *= 2 No need for _ or : since . "Hello") if (age < 20) greeting = "What's up?". greeting = If(age < 20.And Or Xor Not << >> Logical AndAlso OrElse And Or Xor Not & | ^ ~ << >> Logical && || & | ^ ! Note: AndAlso and OrElse perform short-circuit Note: && and || perform short-circuit logical logical evaluations evaluations String Concatenation & String Concatenation + VB. ' Use _ to break up long single line or use implicit line break If whenYouHaveAReally < longLine And itNeedsToBeBrokenInto2 > Lines Then _ UseTheUnderscore(charToBreakItUp) if (x > 5) x *= y. x += y else ElseIf x < 10 Then x /= y. greeting = "Hello" // Multiple statements must be enclosed in {} ' Use : to put two commands on same line if (x != 100 && y < 5) { If x <> 100 AndAlso y < 5 Then x *= 5 : y *= x *= 5. x -= y Else x /= y End If // Every case must end with break or goto case Select Case color ' Must be a primitive data switch (color) { // Must be integer or type string Case "pink". 2 y *= 2. x *= y else if (x < 10) ElseIf x = 5 OrElse y Mod 2 = 0 Then x -= y. else if (x == 5 || y % 2 == 0) 'If x > 5 Then x += y. is used to terminate each End If statement. "red" case "pink": .NET Choices C# ' Ternary/Conditional operator (IIf evaluates 2nd // Ternary/Conditional operator and 3rd expressions) greeting = age < 20 ? "What's up?" : "Hello". "What's up?".

NET Loops Pre-test Loops: Do Until c = 10 c += 1 Loop // no "until" keyword while (c < 10) c++. C# Pre-test Loops: While c < 10 c += 1 End While Do While c < 10 c += 1 Loop For c = 2 To 10 Step 2 Console. c <= 10. // break necessary VB.r += 1 Case "blue" b += 1 Case "green" g += 1 Case Else other += 1 End Select case "red": r++. Post-test Loops: Do c += 1 Loop While c < 10 Do c += 1 Loop Until c = 10 Post-test Loop: do c++. "Sue". case "green": g++.WriteLine(s). default: other++. // Only prints 4 } ' Continue to next iteration For i = 0 To 4 If i < 4 Then Continue For Console. case "blue": b++. while (true) { if (i == 5) break. "Sue". c += 2) Next Console. on default } break. ' Array or collection looping Dim names As String() = {"Fred". "Barney"}.WriteLine(i) ' Only prints 4 Next . foreach (string s in names) Console. } // Continue to next iteration for (i = 0. Console. break.WriteLine(c) for (c = 2. while (c < 10). break. i++) { if (i < 4) continue. break. "Barney"} For Each s As String In names Console. i <= 4. // Breaking out of loops int i = 0.WriteLine(c).WriteLine(s) Next ' Breaking out of loops Dim i As Integer = 0 While (True) If (i = 5) Then Exit While i += 1 End While // Array or collection looping string[] names = {"Fred". i++.WriteLine(i).

CopyTo(names2. names.WriteLine(nums(i)) Next ' 4 is the index of the last element. twoD[2. ref b. default).Length).VB. b. } int a = 1. z = 5. // Throws System. 0) = 4. b = 1. cols-1) As Single twoD(2. new int[2]. // c doesn't need initializing TestFunc(a. // 1 2 5 by default TestFunc(a. C# Dim nums() As Integer = {1.Length . ref int y. New Integer(2) {} } jagged(0)(4) = 5 VB. float[. cols]. and reference (out) Sub TestFunc(ByVal x As Integer.IndexOutOfRangeException // C# can't dynamically resize an array. Array. a. b = 1. names[5] = "Bobby". y++. c As Integer ' c set to zero Console.IndexOutOfRangeException ' Resize the array. b. 2.5 Dim jagged()() As Integer = { _ New Integer(4) {}.WriteLine("{0} {1} {2}". New Integer(1) {}. int[][] jagged = new int[3][] { new int[5]. Function Sum(ByVal ParamArray nums As foreach (int i in nums) Integer()) As Integer sum += i. i++) Console. string[] names2 = new string[7]. b. c) ' 1 2 5 // Accept variable number of arguments int Sum(params int[] nums) { ' Accept variable number of arguments int sum = 0. 3}. Just copy into new array. 3} For i As Integer = 0 To nums.Length. names2.0] = 4. out int z) { x++. c. names[0] = "David". Dim a = 1. so it holds 5 elements Dim names(4) As String names(0) = "David" names(5) = "Bobby" ' Throws System. 0). a.WriteLine("{0} {1} {2}". out c). for (int i = 0. Dim twoD(rows-1. new int[3] }. and reference (out) void TestFunc(int x.NET Arrays int[] nums = {1.5f. i < nums. jagged[0][4] = 5.] twoD = new float[rows. c).Copy(names. default).NET Functions C# ' Pass by value (in. 2. keeping the existing values (Preserve is optional) ReDim Preserve names(6) // 5 is the size of the array string[] names = new string[5]. ByRef y As Integer. . c) Console. reference (in/out).1 Console. // or names.WriteLine(nums[i]). ByRef z As Integer) x += 1 y += 1 z=5 End Sub // Pass by value (in. reference (in/out).

Sum = 0 For Each i As Integer In nums Sum += i Next End Function ' Or use Return statement like C# return sum. if (mascot == "Bisons") // true .dat".ToChar(65). // returns 10 /* C# 4. Previous versions required function overloading.ToCharArray() ' string msg = "File is c:\\temp\\x. 3. " + prefix + " " + name).0 supports optional parameters. Optional SayHello("Strangelove".NET Strings Escape sequences \r // carriage-return \n // line-feed \t // tab \\ // backslash \" // quote C# Special character constants (all also accessible from ControlChars class) vbCrLf. 2. // same thing letter = "Z"c ' letter char[] word = school. // letter is H letter = 'Z'.ToChar(65) ' letter is A // String literal ' same letter = Chr(65) string msg = @"File is c:\temp\x. vbCr. } int total = Sum(4.ToCharArray(). 1). ' Optional parameters must be listed last and } must have a default value Sub SayHello(ByVal name As String. word holds Harding ' No string literal operator Dim msg As String = "File is c:\temp\x. ' Chars // letter is Z Dim letter As Char = school.dat". // school is "Harding (tab) University" // Chars char letter = school[0]. 2. */ Dim total As Integer = Sum(4. // letter is A H letter = (char)65. 1) ' returns void SayHello(string name. thing // same as Dim word() As Char = school. vbLf."). // word holds is Z Harding letter = Convert. vbNewLine vbNullString vbTab vbBack vbFormFeed vbVerticalTab "" ' String concatenation (use & or +) Dim school As String = "Harding" & vbTab school = school & "University" ' school is "Harding (tab) University" // String concatenation string school = "Harding\t". school = school + "University". string prefix = "") { 10 Console. Console.dat" // String comparison string mascot = "Bisons". "Dr. 3. ByVal prefix As String = "") SayHello("Mom").Chars(0) ' letter is letter = Convert.") SayHello("Mom") VB.WriteLine("Greetings. " & prefix & " " & name) End Sub SayHello("Strangelove".WriteLine("Greetings. "Dr.

Text.Jim.Append("three "). buffer. "TWO") Console.Dwight.Replace("sons".Equals("BISONS")) // true if (mascot.ToString("MMM dd.ToInt32("-5") is -5 ' Mutable string Dim buffer As New System. 10.Text. yyyy").CompareTo("Bisons") == 0) // true // Split string names = "Michael.CompareTo("Bisons") = 0) Then ' s = mascot.Pam". "one ") buffer.Insert(0.Regex is more s = mascot. "nomial")) ' s is "Binomial" ' Split Dim names As String = "Michael.ToInt32("-5").ToCharArray()).StringBuilder("two ") buffer.StringBuilder buffer = new System. // Oct 12.Text. buffer. string[] parts = names. 3)) ' s is "son" ' Replacement s = mascot.ToCharArray()) ' One name in each slot ' Date to string Dim dt As New DateTime(1973.Split(".No Like equivalent.Substring(2.".StringBuilder("two ").Equals("Bisons")) Then ' true If (mascot.' String comparison Dim mascot As String = "Bisons" If (mascot = "Bisons") Then ' true // String matching .WriteLine(buffer) ' Prints "one TWO three" .Dwight. "TWO").Replace("two".Substring(2.Jim. "nomial")) powerful "Binomial" If ("John 3:16" Like "Jo[Hh]? #:*") Then 'true ' Substring s = mascot. yyyy") ' Oct 12. 1973 // int to string int x = 2. "one ").ToString("MMM dd. 12). // Prints "one TWO three" 'x ' String to Integer Dim x As Integer = Convert.".Insert(0.ToUpper().Pam" Dim parts() As String = names. 10. // x is -5 ' y is "2" // Mutable string System. // One name in each slot // Date to string DateTime dt = new DateTime(1973.ToString() // s is if (mascot. 1973 ' Integer to String Dim x As Integer = 2 Dim y As String = x.Equals("Bisons")) // true if (mascot. string y = x.WriteLine(buffer).Equals("BISONS")) Then ' true // Substring If (mascot. 12) Dim s As String = "My birthday: " & dt. buffer.Split(". string s = dt. Console. use Regex If (mascot.ToUpper().Append("three ") buffer.Replace("sons".ToString().Replace("two". 3)) // s is "son" true // Replacement ' String matching with Like . // y is "2" // string to int int x = Convert.

WriteLine("Min: " + m. not 305-1818. Pam".Replace("I heard this was HARD!".Success) Then 'true Console.Index).Match(s). @"(\d+) .Groups(1).WriteLine("Match").Index.WriteLine("Ending: " + m. "easy")). Match m = r.Compiled) If (r. C# Imports System. Dwight. if (m. // 456 > 123 ' Replace matched patterns Dim s As String = Regex.RegularExpressions. "$2 > $1").Groups[1]. // Find and remember all matching patterns string s = "My number is 305-1881.IgnoreCase).WriteLine("Match") End If ' Find and remember all matching patterns Dim s As String = "My number is 305-1881.VB.Replace("123 < 456". // Remeber multiple parts of matched pattern Regex r = new Regex("@(\d\d):(\d\d) (am|pm)"). RegexOptions. Jim. // 15 Console. // 03 Console.WriteLine("Ending: " & m.Match(s) 1881 and 305-1818 While m.Split(names).Text.Match("John 3:16").WriteLine("Found number: " & m.ToString) ' 03 Console.Groups(3).NET Regular Expressions using System.Groups(2).Groups[3]). not 305-1818. // pm } // Replace all occurrances of a pattern Regex r = new Regex("h\\w+?d".Replace("123 < 456".Match("We left at 03:15 pm." Dim r As New Regex("(\d+-\d+)") ' Matches 305Dim m As Match = r. "(\d+) . (\d+)". ' Split a string based on a pattern string[] parts = r.ToString) ' 15 Console.WriteLine("Min: " & m. string s = r. Dwight.NextMatch() End While ' Remeber multiple parts of matched pattern Dim r As New Regex("(\d\d):(\d\d) (am|pm)") Dim m As Match = r.Match("John 3:16").Replace("I heard this was HARD!".WriteLine("Hour: " + m. "$2 > $1") ' 456 > 123 // Split a string based on a pattern string names = "Michael. m.NextMatch()) Console.ToString) ' pm End If ' Replace all occurrances of a pattern Dim r As New Regex("h\w+?d". RegexOptions. Regex r = new Regex("(\\d+-\\d+)").IgnoreCase Or _ RegexOptions. Jim. "easy") ' I easy this was easy! // Match a string pattern Regex r = new Regex(@"j[aeiou]h?."). // One name in each Dim names As String = "Michael.Groups[2]).Match("We left at 03:15 pm.Groups(1). RegexOptions.Success Console.\s*") .WriteLine("Hour: " & m. (\d+)".IgnoreCase) Dim s As String = r.Success Then Console.Groups[1]). // I easy this was easy! // Replace matched patterns string s = Regex.\s*").".Value & " at position " _ & m.Success) // true Console. \d:*".Compiled). RegexOptions.") If m.WriteLine("Found number: " + m.Success.Text. Pam" slot Dim r As New Regex(".IgnoreCase | RegexOptions.RegularExpressions ' Match a string pattern Dim r As New Regex("j[aeiou]h?. if (r. // Matches 305-1881 and 305-1818 for (Match m = r.Groups[1] + " at position " + m. Regex r = new Regex(@". \d:*". m = m.ToString) m = m.Groups(1).Success) { Console.

C# Namespace Harding.") Throw ex // Throw an exception Exception up = new Exception("Something is really wrong. } // or namespace Harding { namespace Compsci { namespace Graphics { . // ha ha ' Catch an exception // Catch an exception Try try { y=0 y = 0..Graphics { ..Dim parts() As String = r.NET Exception Handling C# ' Throw an exception Dim ex As New Exception("Something is really wrong....Compsci.NET Namespaces namespace Harding. } ' Deprecated unstructured error handling On Error GoTo MyErrorHandler . End Namespace ' or Namespace Harding Namespace Compsci Namespace Graphics .WriteLine(Err. MyErrorHandler: Console. no and When is optional Console.Compsci.WriteLine(ex.. } } } using Harding.Compsci.Compsci. End Namespace End Namespace End Namespace Imports Harding.Interaction.Beep().Message) "When" keyword Finally Console.. Catch ex As Exception When y = 0 ' Argument } catch (Exception ex) { // Argument is optional.Graphics. x = 10 / y x = 10 / y. throw up..Graphics .Split(names) ' One name in each slot VB.VisualBasic..")..Graphics . Beep() } End Try finally { Microsoft.Message).WriteLine(ex.Description) VB.

} . } // Interface implementation class WristWatch : IAlarmClock. } // Inheritance class FootballGame : Competition { . ITimer { public void Ring() { Console. } } // Extending an interface interface IAlarmClock : IClock { ..WriteLine("Wake up!"). ITimer Public Sub Ring() Implements IAlarmClock..VB... End Class ' Interface definition Interface IAlarmClock Sub Ring() Property TriggerDateTime() As DateTime End Interface ' Extending an interface Interface IAlarmClock Inherits IClock . DateTime CurrentDateTime { get... End Class ' Inheritance Class FootballGame Inherits Competition ..WriteLine("Wake up!") No Module equivalent .Ring Console.. End Interface ' Interface implementation Class WristWatch Implements IAlarmClock. } // Interface definition interface IAlarmClock { void Ring().NET Classes / Interfaces Access Modifiers public private internal protected protected internal Class Modifiers abstract sealed static Method Modifiers abstract sealed static virtual C# Access Modifiers Public Private Friend Protected Protected Friend Class Modifiers MustInherit NotInheritable Method Modifiers MustOverride NotInheritable Shared Overridable ' All members are Shared Module ' Partial classes Partial Class Competition .... set.just use static class // Partial classes partial class Competition { ..

powerLevel = powerLevel.TriggerDateTime .Rest().Rest() ' or // No "With" construct hero...Name = "SpamMan". SuperHero.NET Using Objects SuperHero hero = new SuperHero(). } public SuperHero(int powerLevel) { this. hero. hero.powerLevel = powerLevel End Sub Shared Sub New() ' Shared constructor invoked before 1st instance is created End Sub Protected Overrides Sub Finalize() ' Destructor to free unmanaged resources MyBase. public SuperHero() { powerLevel = 0.Name = "SpamMan" .Defend("Laura Jones")..Finalize() End Sub End Class static SuperHero() { // Static constructor invoked before 1st instance is created } ~SuperHero() { // Destructor implicitly creates a Finalize method } } VB.PowerLevel = 3 End With hero. // Calling static method .End Sub Public Property TriggerDateTime As DateTime Implements IAlarmClock. } C# Class SuperHero Private powerLevel As Integer Public Sub New() powerLevel = 0 End Sub Public Sub New(ByVal powerLevel As Integer) Me.NET Constructors / Destructors class SuperHero { private int powerLevel. set..PowerLevel = 3. C# Dim hero As SuperHero = New SuperHero ' or Dim hero As New SuperHero With hero . VB.Defend("Laura Jones") ' Calling Shared method hero. End Class } public DateTime TriggerDateTime { get. } .

while ((line = reader.5) Dim stu2 As StudentRecord = stu stu2.WriteLine(stu.gpa = gpa. Object obj = new SuperHero(). C# Structure StudentRecord Public name As String Public gpa As Single Public Sub New(ByVal name As String. // Prints Bob Console.txt") Dim line As String = reader.Name = "WormWoman"."). stu2.OpenText("test. 3.WriteLine(line).WriteLine(stu2.Rest() Dim hero2 As SuperHero = hero ' Both reference the same object hero2.WriteLine("Is a SuperHero object.gpa = gpa End Sub End Structure Dim stu As StudentRecord = New StudentRecord("Bob". Console.name = name.WriteLine(stu. } } StudentRecord stu = new StudentRecord("Bob".") ' Mark object for quick disposal Using reader As StreamReader = File. 3.name) ' Prints Bob Console.name).OpenText("test.name = name Me. this. float gpa) { this. StudentRecord stu2 = stu. } If hero Is Nothing Then _ hero = New SuperHero Dim obj As Object = New SuperHero If TypeOf obj Is SuperHero Then _ Console.name = "Sue" Console.ReadLine() End While End Using VB. // Free the object if (hero == null) hero = new SuperHero().WriteLine(stu2. // Prints WormWoman hero = null .WriteLine("Is a SuperHero object.name = "Sue".WriteLine(line) line = reader.SuperHero. if (obj is SuperHero) Console. // Prints Sue . public float gpa.WriteLine(hero.NET Structs struct StudentRecord { public string name. Console.Name = "WormWoman" Console.name).txt")) { string line.ReadLine() While Not line Is Nothing Console. // Both reference the same object hero2.WriteLine(hero.name) ' Prints Sue public StudentRecord(string name.5f).Name) ' Prints WormWoman hero = Nothing ' Free the object SuperHero hero2 = hero. // Mark object for quick disposal using (StreamReader reader = File.ReadLine()) != null) Console. ByVal gpa As Single) Me.Name).

} } // Set default VB. mHeight = value) End Set End Property // Traditional property implementation private string name.NET Delegates / Events C# Delegate Sub MsgArrivedEventHandler(ByVal message As String) Event MsgArrivedEvent As MsgArrivedEventHandler delegate void MsgArrivedEventHandler(string message). set. } set { name = value. AddressOf .NET Properties C# ' Auto-implemented properties are new to VB10 // Auto-implemented properties Public Property Name As String public string Name { get. mHeight = 0. // Delegates must be used with events in C# ' or to define an event which declares a delegate implicitly Event MsgArrivedEvent(ByVal message As MsgArrivedEvent += new String) MsgArrivedEventHandler(My_MsgArrivedEventCallback). MsgArrivedEvent("Test message"). public double Height { set { height = value < 0 ? 0 : value. Get and Set both Public value in constructor ' Traditional property implementation Private mName As String Public Property Name() As String Get Return mName End Get Set(ByVal value As String) mName = value End Set End Property ' Read-only property Private mPowerLevel As Integer Public ReadOnly Property PowerLevel() As Integer Get Return mPowerLevel End Get End Property ' Write-only property Private mHeight As Double Public WriteOnly Property Height() As Double Set(ByVal value As Double) mHeight = If(value < 0. } } // Read-only property private int powerLevel. event MsgArrivedEventHandler MsgArrivedEvent. protected set. // Throws exception if obj is null AddHandler MsgArrivedEvent.VB. } Public Property Size As Integer = -1 ' Default public int Size { get. } } // Write-only property private double height. public string Name { get { return name. } value. public int PowerLevel { get { return powerLevel.

public void Add(T item) { list[rand.Add(2). "Info".Object. } public T GetItem() { return list[rand. System. _ MessageBoxButtons. System.Windows.Next(10)]. Imports System. MessageBoxIcon.Windows.Forms. "Info". // Function can display any type of List void DisplayList<T>(List<T> list) { foreach (T item in list) Console. MyButton. MyButton.Next(10)] = item.Add(4) DisplayList(Of Integer)(numbers) ' Subroutine can display any type of List Sub DisplayList(Of T)(ByVal list As List(Of T)) For Each item As T In list Console.Information) End Sub VB.EventHandler(MyButton_Click). "Button was clicked".Add(2) numbers.Show(this. _ MessageBoxButtons.Add(4). "Button was clicked".My_MsgArrivedCallback MsgArrivedEvent -= new MsgArrivedEventHandler(My_MsgArrivedEventCallback).WriteLine(item) Next End Sub ' Class works on any data type Class SillyList(Of T) Private list(10) As T Private rand As New Random Public Sub Add(ByVal item As T) list(rand.NET Generics C# ' Enforce accepted data type at compile-time Dim numbers As New List(Of Integer) numbers. private Random rand = new Random().WriteLine(item).Information).Click += new Dim WithEvents MyButton As Button ' System. ByVal e As System. AddressOf My_MsgArrivedCallback using System.EventArgs e) { Private Sub MyButton_Click(ByVal sender As MessageBox. WithEvents can't be used on local variable MyButton = New Button private void MyButton_Click(object sender.Forms Button MyButton = new Button().EventArgs) Handles MessageBoxIcon. DisplayList<int>(numbers).OK. ' Won't throw an exception if obj is Nothing RaiseEvent MsgArrivedEvent("Test message") RemoveHandler MsgArrivedEvent. } // Class works on any data type class SillyList<T> { private T[] list = new T[10]. numbers.Next(10)) End Function End Class ' Limit T to only types that implement // Enforce accepted data type at compile-time List<int> numbers = new List<int>().Show(Me. numbers.Click } MessageBox.OK. } } // Limit T to only types that implement IComparable T Maximum<T>(params T[] items) where T : .Next(10)) = item End Sub Public Function GetItem() As T Return list(rand.

8.Distinct().Name = "Bob".Name = "Joe".WriteLine(goodStudents.Concat({5. // Get all numbers in the array above 4 var results = from value in nums where value > 4 select value. 1.Name) Student[] Students = { new Student{ Name = "Bob". 2. 7}) results = results.WriteLine(goodStudents.NET LINQ int[] nums = { 5. new Student{ Name = "Sue".CompareTo(max) > 0 Then max = } item Next Return max End Function VB.0}.GPA = 3. For Each item As T In items return max.33333 ' Displays 5 8 6 For Each n As Integer In results Console.WriteLine(results.0 orderby s.CompareTo(max) > 0) Dim max As T = items(0) max = item.WriteLine(results.9} } ' Get an ordered list of all students by GPA with GPA >= 3. GPA = 3. results = results.5 }. GPA = 4.Name). // 6. 6 }. .WriteLine(results. // 6 Console.Intersect({5. // 5 6 '56 // 5 6 5 1 results = results. 6.Name = "Sue". // 3 Console. IComparable)(ByVal ParamArray items As T()) foreach (T item in items) As T if (item.First()). 1. C# Dim nums() As Integer = {5. 1. If item.GPA >= 3. // 5 Console.Count()) '3 Console. 2.IComparable IComparable<T> { Function Maximum(Of T As T max = items[0]. New Student With {. 8.Write(n + " "). 5}) '56515 5 results = results.Last()).First().GPA = 1. 5}).Count()).GPA descending select s.9 } }.WriteLine(results.Last()) '6 Console.First()) '5 Console.Write(n & " ") Next Console. results = results. // Get an ordered list of all students by GPA with GPA >= 3.5}. 7}).WriteLine(results.0 Order By s.0 }.First.Concat(new[] {5.WriteLine(results. 6} ' Get all numbers in the array above 4 Dim results = From value In nums Where value > 4 Select value Console. . new Student{ Name = "Joe".0 var goodStudents = from s in Students where s. 6.GPA >= 3.33333 // Displays 5 8 6 foreach (int n in results) Console. Sue // . .GPA Descending Select s Console. New Student With {. Console.Intersect(new[] {5.0 Dim goodStudents = From s In Students Where s. GPA = 1.GPA = 4. // 5 6 1 Dim Students() As Student = { New Student With {.Average()) ' 6.WriteLine(results.Distinct() '561 results = results.WriteLine(results. 1.Average()).

Read().Write(num).dat")).OpenWrite("c:\myfile.ReadLine().IO ' Write out to text file Dim writer As StreamWriter = File.ReadLine().CreateText("c:\\myfile. // or Console.Read() ' Read single char Console. writer.Write(str). binWriter.ReadLine() End While reader.".WriteLine(c) ' Prints 65 if user enters "A" Console.txt"). string name = Console.' Sue VB. BinaryWriter binWriter = new BinaryWriter(File. Console."). line = reader.txt").dat")) binWriter.".WriteLine(c).IO.OpenText("c:\myfile.Close() ' Write out to binary file Dim str As String = "Text data" Dim num As Integer = 123 Dim binWriter As New BinaryWriter(File.WriteLine("Out to file. string line = reader.Close().") writer. age) ' or Console.OpenWrite("c:\\myfile. // Read single char Console.ReadLine() While Not line Is Nothing Console. int c = Console. name. // Read from binary file BinaryReader binReader = new . binWriter."). // Prints 65 if user enters "A" VB.Write(num) binWriter.CreateText("c:\myfile.Write("How old are you? ").WriteLine(name & " is " & age & " years old. int age = Convert.Close() ' Read from binary file Dim binReader As New // Write out to binary file string str = "Text data". while (line != null) { Console.ReadLine() Console. age). } reader.Close() ' Read all lines from text file Dim reader As StreamReader = File.WriteLine(name + " is " + age + " years old.WriteLine(line).Close().Write("What's your name? ") Dim name As String = Console. binWriter. C# Imports System. Console.WriteLine("{0} is {1} years old.WriteLine("{0} is {1} years old.txt") Dim line As String = reader.Write("What's your name? ").ToInt32(Console.Write("How old are you? ") Dim age As Integer = Val(Console.NET Console I/O C# Console.WriteLine("Out to file.OpenText("c:\\myfile. // Read all lines from text file StreamReader reader = File.") Dim c As Integer c = Console. writer.txt") writer.Write(str) binWriter. name.NET File I/O using System.Close().ReadLine().ReadLine()). int num = 123. // Write out to text file StreamWriter writer = File.ReadLine()) Console.WriteLine(line) line = reader.

num = binReader.ReadInt32() binReader.OpenRead("c:\myfile.ReadString().ReadString() num = binReader. . binReader.ReadInt32().dat")) str = binReader.Close() BinaryReader(File.Close(). str = binReader.dat")).OpenRead("c:\\myfile.BinaryReader(File.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->