VB.Net and C # Comparison (VB.NET and C # syntax comparison)

xiaoxiao2021-03-06  70

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 othersfor 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 onlyRemSingle line only // Single line / * Multipleline * //// 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 number number = 3.5; int Numint = (int) Numde cimal; // set to3 (truncates decimal) ConstantsConstMAX_STUDENTS As Integer = 25const int MAX_STUDENTS = 25; EnumerationsEnum Action Start [Stop] 'Stopis a reserved wordRewind Forward End Enum EnumStatus Flunk = 50 Pass = 70 Excel = 90 End EnumDim a As Action = Action.stop if a <> action.Start Ten console.writeline (a) 'prints1 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, Rew, 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 passoperty comparison = <> <=> = < > Arithmetic - * / MOD / (Integer Division) ^ (Raise to a power) assignment = = - = * = / = / = ^ = << = >> = & = BitwiseandAlSo ororeLse Not << >> Logicaland Andalso OroRsenot NOTE: ANDALSO AND ORELSE ARE for short-circateation & comparison == <> <=> =! = Arithmetic - * /% (MOD) / (Integer Division if Both Operands Are INTS) Math.Pow (x, y ) Assignment = = - = * = / =% = & = | = ^ = << = >> = - Bitwise & | ^ ~ << >> Logical && ||! Note: && and || Perform Short- Circait Logical Evaluations 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 Same Lineif x * = 5: y * = 2' or to break up any long single command use _ifwhenyouhaveareLines

THEN

Usetheunderscore (ChartobreakiTup)

'IF x> 5 THEN X * = y elseifx = 5 THEN X = y else = 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) {// Multiple Statements Must Be enclosed in {} x * = 5; y * = 2;} no need for _ or: Since; is buy to terminate each stat. 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 stringcase "PINK": case "Red : R ; Break; // Break is Mandatory; No Fall-Throughcase "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 untric c = 10c = 1 loopdo while c <10 C = 1 loop for c = 2 to 10 step 2 console.writeline (c) Next Post-test POST-TEST LOOPS: DOC = 1 Loop While C <10 DOC = 1 Loop Until C = 10 'Array or Collection LoopingDim Names As String () = {"Fred", "SUE", "Barney"} for each s AS Stringin Names Console.writeline (s) Next pre-test loops: // no "unsil" 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 iSthe 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 optional) ReDim Preserve names (6) DIM TWOD (R OWS-1, COLS-1) As Single Twod (2, 0) = 4.5dim jagged () () AS integer = {_ new integer (4) {}, new integer (1) {}, new integer (2) {} (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), Andreference (out) Sub testfunc (Byval x as integer, byref y as integer , Byref z as integer) x = 1Y = 1 z = 5 End Sub Dim a = 1, b = 1, c as integer 'cset to zero by default testfunc (a, b, c) console.writeline ("{ 0} {1} {2} ", a, b, c) '12 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 belisted lastand must have a default value Sub SayHello (ByVal name As String, Optional byval prefix as string = "") Con Sole.writeline ("Greetings," & Prefix & "" End Subsayhello ("STRANGELOVE", "Dr.") Sayhello ("Madonna" // pass by value (in, default), Reference (in / out Andreference (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'tsupport 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 Tryy = 0x = 10 / yCatch ex As ExceptionWhen y = 0 'Argument and When is optionalConsole.WriteLine (ex.Message) Finally Beep () End Try Exception up = new Exception ( "Something "); throw up; // ha ha try {y = 0; x = 10 / y;} catch (exception ex) {// argument is optional, no" when "keywordconsole.writeline (ex.Message (} finally {// must use unmanaged messagebeep api function to beep} namespaces namespace harding.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 'InheritanceClassFootballGameinHeritsCompetition ... End Class'

Interface definitionInterface IAlarmClock ... End Interface // Extending an interfaceInterface IAlarmClock Inherits IClock ... End Interface // Interface implementationClass WristWatchImplements IAlarmClock, ITimer ... End Class Accessibility keywords publicprivateinternalprotectedprotected internalstatic // InheritanceclassFootballGame: Competition {...} // Interface definitioninterface IAlarmClock {...} // Extending an interfaceinterface IAlarmClock: IClock {...} // Interface implementationclass WristWatch: IAlarmClock, ITimer {...} Constructors / DestructorsClass SuperHeroPrivate_powerLevel As Integer Public Sub New () _powerLevel = 0 End Sub public Sub New (ByVal powerLevel As Integer) Me._powerLevel = powerLevel End SubProtected 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;} ~ superh ero () {// 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 hero.Defend ( "Laura ") 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 Then _ hero = New SuperHero Dim obj As Object = New SuperHero If TypeOf obj Is SuperHero Then _Console.WriteLine SuperHero hero = new SuperHero () ( "Is a SuperHero object.");

// no "with" constructhero.name = "spamman"; hero.powerLevel = 3; Hero.Defend ("Laura Jones"); superhero.Rest (); // call 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 Suestruct StudentRecord {public string name; public float gpa; public StudentRecord (string name, float gpa) {this.name = name; this.gpa = gpa;}} StudentRecord stu = new StudENTRECORD ("Bob", 3.5F); S tudentRecord stu2 = stu; stu2.name = "Sue"; Console.WriteLine (stu.name); // Prints BobConsole.WriteLine (stu2.name); // Prints SueProperties Private _size As IntegerPublic Property Size () As IntegerGet Return _size End get set (byval value as integer) if value <0 THEN _SIZE = 0 else _size = value end if End vendy = value) = 1Private int _size; public int size {get {return_size;} set {ix 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 # msgarrivedend = new msgarrivedendhandler (my_msgarrivedev) entCallback); 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 vbvertagetab "" chr (65) 'Returns'A' Console.write ("What's your name?"

DIM Name as string = console.readline () Console.write ("How old is you?") DIM AGE AS INTEGER = VAL (Console.Readline ()) Console.Writeline ("{0} is {1} Years Old ", name, age) (Name &" IS "& Age &" Years Old. ") DIM C AS INTEGER C = Console.Read () 'Read Single Char Console.Writeline (C)' Prints 65 IF User Entes "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, AGE); // Orconsole.writeline (Name "IS" AGE "Years Old."); Int c = console.read (); // Read Single Charconsole.writeline (c); // Prints 65 if User Enters "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: / MY File.txt ") Dim line as string = reader.readline () while not line is nothing console.writeline (" line = "& line) line = reader.readline () end while ready.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.close () Dim Binreader AS New binaryReader (File.Openread ("c: /myfile.dat") Str = binreader.readstring () Num =

BinReader.Readint32 () binReader.close () Using system.io; streamwriter write = 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: