VB.NET and C # ComparisonThis is a quick reference guide to highlight some key syntactical differences between VB.NETand C #. Hope you find this useful! Thank you to Tom Shelton, Fergus Cooney, and others for your input. Also see Java and C # Comparison .
Comments Data Types Constants Enumerations Operators Choices Loops Arrays Functions Exception Handling Namespaces Classes / Interfaces Constructors / Destructors Objects Structs Properties Delegates / Events Console I / O File I / O
VB.NET C # Comments' Single line onlyRem Single line only // Single line / * Multiple line * //// XML comments on single line / ** XML comments on multiple lines * / Data Types Value TypesBooleanByteChar (example: "A "c) Short, Integer, LongSingle, DoubleDecimalDate Reference TypesObjectString Dim x As Integer Console.WriteLine (x.GetType ()) 'Prints System.Int32 Console.WriteLine (TypeName (x))' Prints Integer 'Type conversionDim d As Single = 3.5 DIM I AS INTEGER = CTYPE (D, Integer) 'set to 4 (banker's runk) i = cint (d)' Same Result as ctypei = int (d) 'set to 3 (int function truncates the decimal) Value TypeSboolbyte, sbytechar (example: 'A') short, ushort, int, uint, long, ulongfloat, doubledecimalDateTime (not a built-in C # type) Reference Typesobjectstring int x; Console.WriteLine (x.GetType ()); // Prints System .Int32console.writeline (TypeOf (int)); // prints system.int32 // type conversion float d = 3.5f; int i = (int) d; // set to 3 (truncates decimal) Con stantsConst MAX_STUDENTS As Integer = 25const int MAX_STUDENTS = 25; EnumerationsEnum Action Start [Stop] 'Stop is a reserved word Rewind Forward End Enum Enum Status Flunk = 50 Pass = 70 Excel = 90 End EnumDim a As Action = Action.Stop If a < > Action.start the _ console.writeline (a.tostring & "is" & a) 'prints "stop is 1" console.writeline (status.pass)' Prints 70 console.writeline (status.pass.tostring ()) 'Prints Pass Enum action {start, stop, rewind, forward}; enum status {flunk = 50, pass = 70, excel = 90}; action a = action.stop; if (a! =
Action.Start) Console.writeline (A "IS" (int) a); // prints "stop is 1" console.writeline ((int) status.pass); // Prints 70 console.writeline (status. Pass); //prints passoperty comparison = <> <=> = <> arithmetic - * / mod / (raise to a power) assignment = = - = * = / = / = ^ = << = >> = & = BitwiseAnd AndAlso Or OrElse Not << >> LogicalAnd AndAlso Or OrElse Not Note: AndAlso and OrElse are for short-circuiting logical evaluations String Concatenation & Comparison == <> <=> = = Arithmetic - * /%! (MOD) / (Integer Division if Both Operands Are INTS) Math.Pow (x, y) assignment = = - = * = / =% = & = | = ^ = << = >> = - Bitwise & | ^ ~ << >> Logical && ||! Note: && and || Perform Short-circuit Logical Evaluations String ConcateNation Choices Greeting = IIF (Age <20, "What's up?", "Hello") 'One line doesn' T Require "end if", no "else" if Language = "vb.net" the language = "verbose" 'Use: to put two comman DS ON SAME LINEIF X * = 5: Y * = 2 'preferredif x <> 100 and y <5 THEN X * = 5 y * = 2END IF' OR to BREAK UP ANY Long Single Command Use _if WhenyouhaveReally
= Y elseif x <10 THEN X - = y else x / = y end if select case color 'Must Be a primitive data type "pink", "red" r = 1 case "blue" B = 1 case " Green "G = 1 Case Else Other = 1 End Select Greeting = Age <20?" What's Up? ":" Hello "; if (x! = 100 && Y <5) {// Multiple Statements Must Be Enclosed in {} X * = 5; y * = 2;} no need for _ or: Since; is buy to terminate Each statement. If (x> 5) x * = y; ELSE IF (x == 5) x = Y; Else IF (x <10) x - = y; else x / = y; switch (color) {// must be integer or string case "pink": Case "Red": R ; Break; // Break IS Mandatory; No Fall-Through Case "Blue": B ; Break; Case "Green": G ; Break; Default: Other ; Break; // Break Necessary on default} loops
Pre-test loops: while c <10 c = 1 End while do until c = 10 c = 1 loopdo while c <10 c = 1 loop for c = 2 to 10 step 2 console.writeline (c) Next POST -Test Loops: Do C = 1 Loop While C <10 Do C = 1 Loop Until C = 10 'Array Or Collection LoopingDim Names As String () = {"Fred", "SUE", "Barney"} for Each SAS STRING IN Names Console.writeline (s) Next pre-test loops: // no "until" keywordwhile (i <10) i ; for (i = 2; i <= 10; i = 2) Console.WriteLine (i); Post-test loop: do i ; while (i <10); // array or collection loopingstring [] names = {"fred", "su", "barney"}; foreach (string s in name) Console.writeline (s); arrays Dim Nums () AS integer = {1, 2, 3} for i as integer = 0 to Nums.Length - 1 console.writeline (NUMS (i)) Next '4 is the index of f the last element, so it holds 5 elementsDim names (4) As String names (0) = "David" names (5) = "Bobby" 'Throws System.IndexOutOfRangeException' Resize the array, keeping the existing values (Preserve is optional Redim Preserve Names (6) DIM Twod (Rows-1, Cols-1) AS Single Twod (2, 0) = 4.5dim jagged () () AS integer = {_ new integer (4) {}, new integer 1) {}, new integer (2) {}} jagged (0) (4) = 5 int [] NUMS = {1, 2, 3}; for (int i = 0; I T Dynamically Resize An Array. Just Copy Into New Array.String [] Names2 = New String [7]; Array.copy (Names, Names2, Names.Length); // OR Names.copyTo (Names2, 0); Float [ , = new float [rows, cols]; Twod [2,0] = 4.5f; int [] [] jagged = new int rt [3] [] {new int [5], new int [2], new INT [3]}; jagged [0] [4] = 5; functions' pass by value (in, default), Reference (In / out), and reference (out) Sub testfunc (byval x as integer, byref y Integer, byref z as integer) x = 1 y = 1 z = 5 End Sub Dim a = 1, b = 1, c as integer 'c set to zero by Default TestFunc (A, B, C) Console.writeline ("{0} {1} {2}", a, b, c) '1 2 5' Accept variable number of arguments function sum (byval paramarray nums as integer ()) AS integer sum = 0 for Each I as integer In nums Sum = i Next End Function 'Or use Return statement like C # Dim total As Integer = Sum (4, 3, 2, 1)' returns 10 'Optional parameters must be listed last and must have a default value Sub SayHello (ByVal Name As String, O Ptional byval prefix as string = "") Console.writeline ("Greetings," & Prefix & "& name) End Subsayhello (" StrangeLove "," Dr. ") Sayhello (" Madonna ") // Pass by Value (in , default (in / out), and reference (out) Void TestFunc (int X, ref int y, out ution) {x ; y ; z = 5;} int a = 1, b = 1, c ; // c doesn't Need InitializingTestFunc (A, Ref B, Out C); console.writeline ("{0} {1} {2}", A, B, C); // 1 2 5 // ACCEPT Variable number of argumentsint sum (params int [] NUMS) {int sum = 0; Foreach (INT I in NUMS) SUM = I; Return Sum;} int total = sum (4, 3, 2, 1); // Returns 10 / * C # doesn't support optional arguments / parameters. Just create two ,,,,,,,,,,,,, (string name, string prefix) {Console.WriteLine ( "Greetings," prefix "" name);} void SayHello (string name) {SayHello (name, "");} Exception Handling 'Deprecated unstructured error handlingOn error Goto myerrorhandler ... myerrorhandler: console.writeline ("Something IS Really Wrong.") Throw except ("Something is real Wrong.") Throw ex be= 0 x = 10 / YCATCH EX AS Exception WHEN Y = 0 'Argument and When is optional console.writeline (ex.Message) Finally Beep () end Exception Up = New Exception ("Something is real wrong."); Throw up; // ha ha try {y = 0; x = 10 / y ;} catch (Exception EX) {// argument is optional, no "when" keyword console.writeline (ex. // must use unmanaged messagebeep api function to beep} namespaces namespace harding.com psci.Graphics ... End Namespace 'or Namespace Harding Namespace Compsci Namespace Graphics ... End Namespace End Namespace End Namespace Imports Harding.Compsci.Graphics namespace Harding.Compsci.Graphics {...} // or namespace Harding {namespace Compsci {namespace Graphics {...}}} using Harding.Compsci.Graphics; Classes / Interfaces Accessibility keywords PublicPrivateFriend ProtectedProtected FriendShared 'InheritanceClass FootballGame Inherits Competition ... End Class' Interface definitionInterface IAlarmClock ... End Interface // Extending an interface Interface IAlarmClock Inherits IClock ... End Interface // Interface implementationClass WristWatch Implements IAlarmClock, ITimer ... End Class Accessibility keywords publicprivateinternalprotectedprotected internalstatic // Inheritanceclass FootballGame: Competition {... } // interface definitioninterface IAlarmClock {...} // Extending an interface interface IAlarmClock: IClock {...} // interface implementationclass WristWatch: IAlarmClock, ITimer {...} Constructors / DestructorsClass SuperHero Private _powerLevel As Integer Public Sub New () _powerLevel = 0 End Sub Public Sub New (ByVal powerLevel As Integer) Me._powerLevel = powerLevel End Sub Protected Overrides Sub Finalize () 'Desctructor code to free unmanaged resources MyBase.Finalize () End SubEnd class class SuperHero {private int _powerLevel Public superhero () {_powerLevel = 0;} P ublic SuperHero (int powerLevel) {this._powerLevel = powerLevel;} ~ SuperHero () {// Destructor code to free unmanaged resources // Implicitly creates a Finalize method.}} Objects Dim hero As SuperHero = New SuperHero With hero .Name = "Spamman" .powerlevel = 3 end with helo.defend ("laura Jones" Hero.Rest () 'calling shared method' orsuperhero.rest () Dim Hero2 as superhero = Hero 'Both Refer to Same Object Hero2.name = " Wormwoman "console.writeline (HERO.NAME) 'Prints Wormwoman Hero = Nothing' Free The Object if Hero is nothing the Object if hero = new superhero dim obj as object = New superhero if TypeOf obj is superhero dam ("is a superhero object.") Superhero Hero = new superhero (); // no "with" constructhero.name = "spamman"; HERO.POWERLEVEL = 3; Hero .Defend ("laura Jones"); Superhero.Rest (); // Calling static method superhero Hero2 = Hero; // Both Refer to Same Object Hero2.name = "Wormwoman"; console.writeline (HERO.NAME); / / Prints Wormwoman Hero = NULL; // Free The Object if (Hero == Null) Hero = New Superhero (); Object Obj = New Superhero (); IF (Obj Is Superhero) Console.writeline ("IS A Superhero Object. "); Structs Structure StudentRecord Public name As String Public gpa As Single Public Sub New (ByVal name As String, ByVal gpa As Single) Me.name = name Me.gpa = gpa End Sub End Structure Dim stu As StudentRecord = New StudentRecord ( "Bob", 3.5) DIM Stu2 as studEntRecord = stu stu2.name = "SUE" console.writeline (stu.name) 'Prints Bob console.writeline (stu2.name)' PrintS SuStruct Stud000Record {Publi c string name; public float gpa; public StudentRecord (string name, float gpa) {this.name = name; this.gpa = gpa;}} StudentRecord stu = new StudentRecord ( "Bob", 3.5f); StudentRecord stu2 = stu ; stu2.name = "Sue"; Console.WriteLine (stu.name); // Prints BobConsole.WriteLine (stu2.name); // Prints SueProperties Private _size As IntegerPublic Property Size () As Integer Get Return _size End Get Set (Byval value as integer) if value <0 THEN _SIZE = 0 else _size = value end if End set dendy foo.size = 1private int _size; public int Size {get {return _size;} set {if (value <0) _size = 0; else _size = value;}} foo.Size ; Delegates / Events Delegate Sub MsgArrivedEventHandler (ByVal message As String) Event MsgArrivedEvent As MsgArrivedEventHandler 'or to define an event which declares a delegate implicitlyEvent MsgArrivedEvent (ByVal message As String) AddHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback' Will not throw an exception if obj is NothingRaiseEvent MsgArrivedEvent ( "Test message") RemoveHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback Imports System.Windows.Forms Dim WithEvents MyButton As Button 'WithEvents can not be used on local variableMyButton = New Button Private Sub MyButton_Click (ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyButton.Click MessageBox.Show ( ME, "Button Was Clicked", "Info", _ MessageBoxButtons.ok, MessageBoxicon.information) End Sub Delegate Void MsgarriveDeventhandler (String message); event MsgArrivedEventHandler MsgArrivedEvent; // Delegates must be used with events in C # MsgArrivedEvent = new MsgArrivedEventHandler (My_MsgArrivedEventCallback); MsgArrivedEvent ( "Test message"); // Throws exception if obj is nullMsgArrivedEvent - = new MsgArrivedEventHandler ( My_MsgArrivedEventCallback); using System.Windows.Forms; Button MyButton = new Button (); MyButton.Click = new System.EventHandler (MyButton_Click); private void MyButton_Click (object sender, System.EventArgs e) {MessageBox.Show (this, "Button Was Clicked", "Info", MessageBoxButtons.ok, MessageBoxicon.Information; } Console I / O Special character constantsvbCrLf, vbCr, vbLf, vbNewLine vbNullString vbTab vbBack vbFormFeed vbVerticalTab "" Chr (65) 'Returns' A' Console.Write ( "What's your name?") Dim name As String = Console.ReadLine ( ) Console.write ("How old are you?") DIM AGE AS Integer = Val (console.readline ()) console.writeline ("{0} is {1} Years Old.", Name, AGE) 'OR Console .Writeline (Name & "IS" & AGE & "Years Old.") DIM C AS INTEGER C = Console.read () 'Read Single Char Console.Writeline (c)' Prints 65 if User Enters "a" escape sequences / n, / r / t /// "Convert.toCHAR (65) // Returns 'A' - Equivalent to chr (num) in vb // or (char) 65 console.write (" What's your name? "); String name = console.readline (); console.write ("How old is you?"); int Age = convert.Toint32 (console.readline ()); console.writeLine ("{0} is {1} years old ", name, agn); // Orconsole.writeline (Name " IS " AGE " Years Old. "); INT C = console.read (); // read single charconsole.writeLine (C); / / Prints 65 if User Enter S "a" File I / O Imports System.io 'Write Out To Text Filedim Writer as Streamwriter = file.createtext ("c: /myfile.txt") Writer.Writeline ("Out to File.") Writer.close ( ) 'Read All Lines from text filedim reader as streamreader = file.opentext ("c: /myfile.txt") DIM line As string = Reader.Readline () while not line is nothing console.writeline (line) line = reader. Readline () end should iele () 'Write out to binary filedim str as string = "text data" DIM NUM AS INTEGER =