VB.Net and C # Syntax Compare Manual

zhaozj2021-02-08  236

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.

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 numDecimal As Single = 3.5 Dim numInt As IntegernumInt = CType (numDecimal, Integer) 'set to 4 (Banker's rounding) numInt = CInt (numDecimal)' same result as CTypenumInt = Int (numDecimal) '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 Double NumDec imal = 3.5; int numInt = (int) numDecimal; // set to 3 (truncates decimal) ConstantsConst 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) 'Prints 1 console.writeline (status.pass)' Prints 70 Dim S as Type = Gettype (status) console.writeline ([ENUM] .Getname (s, status.pass)) '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 (STATUS.PASS); // Prints Passoperator 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 Evaluation String ConcateNation Choices Greeting = IIF (age <20, "what's up?", "Hello") 'One Line Doesn't Require "Endiff", No "Else" if Language = "VB.Net" Then LangType = "verbose" 'Use: to put two commands on sa me lineIf x <> 100 Then x * = 5: y * = 2 'or to break up any long single command use _If whenYouHaveAReally Lines Then _ UseTheUnderscore (charToBreakItUp)' If x> 5 Then x * = y Elseif x = 5 THEN X = y elseif x <10 THEN X - = y else x / = y end if select case color '

Must be a primitive data type case "pink", "red" R = 1 case "blue" b = 1 case "green" g = 1 case else = 1 End select Greeting = Age <20? "What's UP? ":" Hello "; if (x! = 100) {// 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 Import 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;} public 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 Dim Writer As Streamwriter = file.createtext ("c: /myfile.txt") Writer.Writeline ("Out to File.") Writer.close () Dim Reader As StreamReader = File.opentext ("c: /myfile.txt") DIM line As string = reader.readline () while not line is nothing console.writeline ("line =" & line) line =reader.readline () end while reader .Close () DIM STR AS STRING = "Text Data" DIM NUM AS INTEGER = 123 DIM BINWRITER AS New BinaryWriter (File.OpenWrite "

C: /myfile.dat ") binwriter.write (STR) binwriter.write () Dim binreader as new binaryreader (" c: /myfile.dat ") Str = binReader. ReadString () Num = binreader.Readint32 () binreader.close () Using system.io; streamwriter Writer = file.createtext ("c: //myfile.txt"); Writer.writeline ("Out to File."); Writer.close (); streamreader reader = file.opentext ("c: //myfile.txt"); string line = reader.readline (); while (line! = null) {console.writeLine (line); line = Reader.readLine ();} reader.close (); string str = "text data"; int Num = 123; binarywriter binwriter = new binarywriter (File.OpenWrite ("c: //myfile.dat"); binwriter. Write (STR); binwriter.write (num); binwriter.close (); binaryreader binreader = new binaryreader (File.Openread ("c: //myfile.dat")); str = binreader.readstring (); Num = BinReader.readInt32 (); binreader.close (); Page Last Modified: