VB.Net and C # Comparison

xiaoxiao2021-03-06  19

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.NETC # Comments' Single line onlyRem Single line only // Single line / * Multiple line * //// XML comments on single line / ** XML comments on multiple lines * / Data TypesValue TypesBooleanByteChar (example: "A" c ) Short, Integer, LongSingle, DoubleDecimalDateReference TypesObjectStringDim 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 Rounding) i = CINT (D)' Same Result AS CTYPEI = INT (D) 'Set to 3 (int function truncates the decimal) Value TypeesBoolbyte, Sbytechar (Example: 'A') short, ushort, int, uint, long, ulongfloat, doubledecimalDateTime (not a built-in C # type) Reference Typesobjectstringint 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) ConstantScons . T MAX_STUDENTS As Integer = 25 'Can be set to a const or a variable May be initialized in a constructor ReadOnly MIN_DIAMETER As Single = 4.93 const int MAX_STUDENTS = 25;.. // Can be set to a const or a variable May be . initialized in a constructor readonly float MIN_DIAMETER = 4.93f; 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, rebind, 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) ); // prints 70 console.writeline (status.pass); //prints passopertyComparison = <=> = <> arithmetic - * / mod / (Integer Division) ^ (raise to a power) Assignment = == * = / = / = ^ = << = >> = & = BitwiseAnd AndAlso Or OrElse Not << >> LogicalAnd AndAlso Or OrElse NotNote: AndAlso and OrElse are for short-circuiting logical evaluationsString Concatenation & Comparison == < > <=> =! = Arithmetic - * /% (MOD) / (Integer Division if Both Operands Are INTS) Math.Pow (x, y) assignment = = - = * = / =% = & = | = ^ = << = >> = --Bitwise & | ^ ~ << >> Logical && ||! Note: && and || Perform Short-Circuit L Ogical Evaluationsstring 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 <> 100 and y <5 THEN X * = 5: Y * = 2' preferredif x <> 100 and y <5 TEN X * = 5 y * =

2End If '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 endselect 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 && y <5) {// Multiple Statements Must Be enclosed in {} x * = 5; y * = 2;} no need; is buy i @ @> 5 (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) Redi M 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) = 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, Optio nal ByVal prefix As String = "") Console.WriteLine ( "Greetings," & prefix & "" & name) End SubSayHello ( "Strangelove", "Dr.") SayHello ( "Madonna") 'Accept variable number of arguments Function SUM (Byval Paramarray Nums As INTEGER ()) AS Integer Sum = 0 for Each I AS Integer in Num 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 Sayello (Byval Name As String, Optional Byval Prefix As String =

"") Console.Writeline ("Greetings," & Prefix & "" 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 doeesn ' 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 ( "Some Throw ex try y = 0 x = 10 / YCATCH EX as Exception WHEN Y = 0 'argument and when is optional console.writeline (ex.Message) Finally Beep () endException 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 EXMESSAGE);} finally {// must use unmanaged messagebeep API function to beep} namespaces namespace harding.compsci.graphics ... End Namespace '

orNamespace Harding Namespace Compsci Namespace Graphics ... End Namespace End Namespace End NamespaceImports 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 I mplementationclass 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 Classclass 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 helo .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 WormWomanhero = Nothing' Free the object If hero Is Nothing Then _ hero = New SuperHeroDim obj As Object = New SuperHero If TypeOf obj Is SuperHero Then _ Console .Writeline ("IS A Superhero Object.") Superhero Hero = New Superhero (); // no "with" constructhero.name = "spamman"; hero.defevel = 3; Hero.defend ("laura Jones"); superhero .Rest (); // Calling static methodsuperhero 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 ("IS superhero) Console.Writeline (" IS A Superhero Object. "); StructStructure StudientRecord P ublic 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 StructureDim 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); StudentRecord stu2 = stu; stu2.name = "Sue"; Console.WriteLine (stu.name); // Prints BobConsole.WriteLine (stu2.name); // Prints SuePropertiesPrivate _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 End Propertyfoo.Size = 1private int _size; public int Size { get {return _size;} set {if (value <0) _size = 0; else _size = value;}} foo.Size ; Delegates / EventsDelegate 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_MsgArrive dCallbackImports System.Windows.FormsDim WithEvents MyButton As Button 'WithEvents can not be used on local variableMyButton = New ButtonPrivate 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 Subdelegate void MsgArrivedEventHandler (string message); event MsgArrivedEventHandler MsgArrivedEvent; // Delegates must be used with events in C # MsgArrivedEvent = new MsgArrivedEventHandler ( MY_MSGARRIVEVENTCALLBACK; 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 / OSpecial 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 area you?") DIM AGE AS INTEGER = VAL ("{0} is {1} YEARS OLD.", Name, ageline ("{0} is {1}" 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, / tt t" u"verert cc 'A' - Equivalen T to Chr (NUM) IN VB // OR (Char) 65Console.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 "); int c = console.read (); // read single charconsole.writeline (c); // prints 65 if user entss" a "File I / Oimports 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 = reader.readline () end while ready.close () 'Write out to binary filedim str as string = "text data" DIM NUM AS Integer = 123 Dim Binwriter As New BinaryWriter ("c: /myfile.dat")) binwriter.write (str) binwriter.write (NUM) binwriter.close () 'Read from binary Filedim Binreader As New BinaryReader File.openread ("c: /myfile.dat")) Str = binreader.readstring () Num = binreader.readInt32 () binreader.close () Using system.io; // Write out to text filestreamwriter Writer = file.createtext ("c: //myfile.txt"); Writer.writeline ("Out to File."); Writer.close (); // r c es es = file.opentext ("c: // myfile .txt "); string line = reader.readline (); while (line! = null) {console.writeLine (line); line = RE ADER.READLINE ();} reader.close (); // Write out to binary filestring str = "text data"; int Num = 123; binarywriter binwriter = new binarywriter ("c: //myfile.dat) ")); binWriter.write (STR); binwriter.write (Num); binwriter.close (); // read from binary filebinaryreader binreader = new binaryReader (File.OpenRead (" c: //myfile.dat "))) ; str = binreader.readstring (); Num = binreader.readint32 (); binReader.close ();

Page last modified: