VB.Net and C # Syntax Compare Manual

xiaoxiao2021-04-07  334

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 (INT)); // Prints System.Int32 // Type Conversion Double Nu mDecimal = 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 "end if", no "else" if Language = "vb.net" Then LangType = "verbose" 'Use: to put two commands on same 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 Other = 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 i (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 Mandatatory; 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 loop do 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 S AS 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 [] name = {"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 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 opti Onal) 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 , Optional Byval Prefix As String = "") Console.writeline ("Greetings," & Prefix & "& name) End Subsayhello (" StrangeLove "," Dr. ") Sayhello (" Madonna "// pass by value IN, Default, Reference (In / out), and reference (out) Void TestFunc (INT X, REF INT Y, OUT INT Z) {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 Different Versions of the Same Function. * / Void SayHello (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 (Err.Description) DIM EX AS NEW EXCEPTION ("Something IS Really Wrong.") Throw EX TRY Y = 0 x = 10 / YCATCH EX AS Exception When Y = 0 'Argument And when is optional console.writeline (ex. subssage) Finally Beep () end exam ("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.Message);} finally {// must use unmanaged messagebeep API function to beep} namespaces namespace Hardin g.Compsci.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)' Print Sue struct studEntRecord {PU blic 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 Sue Properties 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 dend version foo.size =

1 private 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 MsgarriveDeventHand ler (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 Ent ERS "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: