Comments Program Structure - Cheat Sheet

cheat.sheets.org
  • No tags were found...

Comments Program Structure - Cheat Sheet

This document is an authorized derivative of Frank McCown's "VB.NET andC# Comparison" (C) 2005 athttp://www.harding.edu/USER/fmccown/WWW/vbnet_csharp_comparison.htmlThis work is licensed under a Create Common LicenseEnumerationsVB.NETEnum ActionStart'Stop is a reserved word[Stop]RewindForwardEnd EnumC#enum Action {Start, Stop, Rewind, Forward};enum Status {Flunk = 50, Pass = 70, Excel =90};Enum StatusFlunk = 50Pass = 70Excel = 90End EnumDim a As Action = Action.StopIf a Action.Start Then _'Prints "Stop is 1"System.Console.WriteLine(a.ToString & " is " &a)'Prints 70System.Console.WriteLine(Status.Pass)'Prints PassSystem.Console.WriteLine(Status.Pass.ToString())Enum WeekdaysSaturdaySundayMondayTuesdayWednesdayThursdayFridayEnd Enum 'WeekdaysAction a = Action.Stop;if (a != Action.Start)//Prints "Stop is 1"System.Console.WriteLine(a + " is " +(int) a);// Prints 70System.Console.WriteLine((int)Status.Pass);// Prints PassSystem.Console.WriteLine(Status.Pass);enum Weekdays{Saturday, Sunday, Monday, Tuesday,Wednesday, Thursday, Friday}


This document is an authorized derivative of Frank McCown's "VB.NET andC# Comparison" (C) 2005 athttp://www.harding.edu/USER/fmccown/WWW/vbnet_csharp_comparison.htmlThis work is licensed under a Create Common LicenseLoopsVB.NET'Pre-test Loops:While c < 10c += 1End While Do Until c = 10c += 1LoopC#//Pre-test Loops: while (i < 10)i++;for (i = 2; i < = 10; i += 2)System.Console.WriteLine(i);'Post-test Loop:Do While c < 10c += 1LoopFor c = 2 To 10 Step 2System.Console.WriteLine(c)Next//Post-test Loop:doi++;while (i < 10);'Array or collection loopingDim names As String() = {"Steven", "SuOk", "Sarah"}For Each s As String In namesSystem.Console.WriteLine(s)Next// Array or collection loopingstring[] names = {"Steven", "SuOk","Sarah"};foreach (string s in names)System.Console.WriteLine(s);


This document is an authorized derivative of Frank McCown's "VB.NET andC# Comparison" (C) 2005 athttp://www.harding.edu/USER/fmccown/WWW/vbnet_csharp_comparison.htmlThis work is licensed under a Create Common LicenseArraysVB.NETDim nums() As Integer = {1, 2, 3}For i As Integer = 0 To nums.Length - 1Console.WriteLine(nums(i))Next'4 is the index of the last element, so it holds 5elementsDim names(4) As Stringnames(0) = "Steven"'Throws System.IndexOutOfRangeExceptionnames(5) = "Sarah"'Resize the array, keeping the existing'values (Preserve is optional)ReDim Preserve names(6)C#int[] nums = {1, 2, 3};for (int i = 0; i < nums.Length; i++)Console.WriteLine(nums[i]);// 5 is the size of the arraystring[] names = new string[5];names[0] = "Steven";// Throws System.IndexOutOfRangeExceptionnames[5] = "Sarah"// C# can't dynamically resize an array.//Just copy into new array.string[] names2 = new string[7];// or names.CopyTo(names2, 0);Array.Copy(names, names2, names.Length);Dim twoD(rows-1, cols-1) As SingletwoD(2, 0) = 4.5Dim jagged()() As Integer = { _New Integer(4) {}, New Integer(1) {}, NewInteger(2) {} }jagged(0)(4) = 5float[,] twoD = new float[rows, cols];twoD[2,0] = 4.5;int[][] jagged = new int[3][] {new int[5], new int[2], new int[3] };jagged[0][4] = 5;


This document is an authorized derivative of Frank McCown's "VB.NET andC# Comparison" (C) 2005 athttp://www.harding.edu/USER/fmccown/WWW/vbnet_csharp_comparison.htmlThis work is licensed under a Create Common LicenseFunctionsVB.NET'Pass by value (in, default), reference'(in/out), and reference (out)Sub TestFunc(ByVal x As Integer, ByRef y AsInteger,ByRef z As Integer)x += 1y += 1z = 5End SubC#// 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;}'c set to zero by defaultDim a = 1, b = 1, c As IntegerTestFunc(a, b, c)System.Console.WriteLine("{0} {1} {2}", a, b, c) '12 5int a = 1, b = 1, c; // c doesn't needinitializingTestFunc(a, ref b, out c);System.Console.WriteLine("{0} {1} {2}", a,b, c); // 1 2 5'Accept variable number of argumentsFunction Sum(ByVal ParamArray nums As Integer()) AsIntegerSum = 0For Each i As Integer In numsSum += iNextEnd Function 'Or use a Return statement like C#Dim total As Integer = Sum(4, 3, 2, 1) 'returns 10// 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'Optional parameters must be listed last'and must have a default valueSub SayHello(ByVal name As String,Optional ByVal prefix As String = "")System.Console.WriteLine("Greetings, " & prefix& " " & name)End SubSayHello("Steven", "Dr.")SayHello("SuOk")/* C# doesn't support optionalarguments/parameters.Just create two different versions of thesame function. */void SayHello(string name, string prefix) {System.Console.WriteLine("Greetings, " +prefix + " " + name);}void SayHello(string name) {SayHello(name, "");}


This document is an authorized derivative of Frank McCown's "VB.NET andC# Comparison" (C) 2005 athttp://www.harding.edu/USER/fmccown/WWW/vbnet_csharp_comparison.htmlThis work is licensed under a Create Common LicenseException HandlingVB.NETClass WithfinallyPublic Shared Sub Main()TryDim x As Integer = 5Dim y As Integer = 0Dim z As Integer = x / yConsole.WriteLine(z)Catch e As DivideByZeroExceptionSystem.Console.WriteLine("Error occurred")FinallySystem.Console.WriteLine("Thank you")End TryEnd Sub 'MainEnd Class 'WithfinallyC#class Withfinally{public static void Main(){try{int x = 5;int y = 0;int z = x/y;Console.WriteLine(z);}catch(DivideByZeroException e){System.Console.WriteLine("Erroroccurred");}finally{System.Console.WriteLine("Thankyou");}}}NamespacesVB.NETNamespace ASPAlliance.DotNet.Community...End NamespaceC#namespace ASPAlliance.DotNet.Community {...}'or// orNamespace ASPAllianceNamespace DotNetNamespace Community...End NamespaceEnd NamespaceEnd Namespacenamespace ASPAlliance {namespace DotNet {namespace Community {...}}}Imports ASPAlliance.DotNet.Communityusing ASPAlliance.DotNet.Community;


This document is an authorized derivative of Frank McCown's "VB.NET andC# Comparison" (C) 2005 athttp://www.harding.edu/USER/fmccown/WWW/vbnet_csharp_comparison.htmlThis work is licensed under a Create Common LicenseClasses / InterfacesVB.NET'Accessibility keywordsPublicPrivateFriendProtectedProtected FriendSharedC#//Accessibility keywordspublicprivateinternalprotectedprotected internalstatic'InheritanceClass ArticlesInherits Authors...End ClassImports SystemInterface IArticleSub Show()End Interface 'IArticle_Class IAuthorImplements IArticlePublic Sub Show()System.Console.WriteLine("Show() methodImplemented")End Sub 'Show'Entry point which delegates to C-style mainPrivate FunctionPublic Overloads Shared Sub Main()Main(System.Environment.GetCommandLineArgs())End Sub//Inheritanceclass Articles: Authors {...}using System;interface IArticle{void Show();}class IAuthor:IArticle{public void Show(){System.Console.WriteLine("Show() methodImplemented");}}public static void Main(string[] args){IAuthor author = new IAuthor();author.Show();}Overloads Public Shared Sub Main(args() AsString)Dim author As New IAuthor()author.Show()End Sub 'MainEnd Class 'IAuthor


This document is an authorized derivative of Frank McCown's "VB.NET andC# Comparison" (C) 2005 athttp://www.harding.edu/USER/fmccown/WWW/vbnet_csharp_comparison.htmlThis work is licensed under a Create Common LicenseConstructors / DestructorsVB.NETClass TopAuthorPrivate _topAuthor As IntegerPublic Sub New()_topAuthor = 0End SubPublic Sub New(ByVal topAuthor As Integer)Me._topAuthor = topAuthorEnd SubProtected Overrides Sub Finalize()'Desctructor code to free unmanaged resourcesMyBase.Finalize()End SubEnd ClassC#class TopAuthor {private int _topAuthor;public TopAuthor() {_topAuthor = 0;}public TopAuthor(int topAuthor) {this._topAuthor= topAuthor}~TopAuthor() {// Destructor code to free unmanagedresources.// Implicitly creates a Finalize method}}ObjectsVB.NETDim author As TopAuthor = New TopAuthorWith author.Name = "Steven".AuthorRanking = 3End Withauthor.Rank("Scott")author.Demote() 'Calling Shared method'orTopAuthor.Rank()C#TopAuthor author = new TopAuthor();//No "With" constructauthor.Name = "Steven";author.AuthorRanking = 3;author.Rank("Scott");TopAuthor.Demote() //Calling static methodDim author2 As TopAuthor = author 'Both refer tosame objectauthor2.Name = "Joe"System.Console.WriteLine(author2.Name) 'Prints Joeauthor = Nothing 'Free the objectIf author Is Nothing Then _author = New TopAuthorDim obj As Object = New TopAuthorIf TypeOf obj Is TopAuthor Then _System.Console.WriteLine("Is a TopAuthorobject.")TopAuthor author2 = author //Both refer tosame objectauthor2.Name = "Joe";System.Console.WriteLine(author2.Name)//Prints Joeauthor = null //Free the objectif (author == null)author = new TopAuthor();Object obj = new TopAuthor();if (obj is TopAuthor)SystConsole.WriteLine("Is a TopAuthorobject.");


This document is an authorized derivative of Frank McCown's "VB.NET andC# Comparison" (C) 2005 athttp://www.harding.edu/USER/fmccown/WWW/vbnet_csharp_comparison.htmlThis work is licensed under a Create Common LicenseStructsVB.NETStructure AuthorRecordPublic name As StringPublic rank As SinglePublic Sub New(ByVal name As String, ByVal rankAs Single)Me.name = nameMe.rank = rankEnd SubEnd StructureC#struct AuthorRecord {public string name;public float rank;public AuthorRecord(string name, floatrank) {this.name = name;this.rank = rank;}}Dim author As AuthorRecord = NewAuthorRecord("Steven", 8.8)Dim author2 As AuthorRecord = authorauthor2.name = "Scott"System.Console.WriteLine(author.name) 'PrintsStevenSystem.Console.WriteLine(author2.name) 'PrintsScottAuthorRecord author = newAuthorRecord("Steven", 8.8);AuthorRecord author2 = authorauthor.name = "Scott";SystemConsole.WriteLine(author.name);//Prints StevenSystem.Console.WriteLine(author2.name);//Prints Scott


This document is an authorized derivative of Frank McCown's "VB.NET andC# Comparison" (C) 2005 athttp://www.harding.edu/USER/fmccown/WWW/vbnet_csharp_comparison.htmlThis work is licensed under a Create Common LicensePropertiesVB.NETPrivate _size As IntegerPublic Property Size() As IntegerGetReturn _sizeEnd GetSet (ByVal Value As Integer)If Value < 0 Then_size = 0Else_size = ValueEnd IfEnd SetEnd PropertyC#private int _size;public int Size {get {return _size;}set {if (value < 0)_size = 0;else_size = value;}}foo.Size += 1foo.Size++;Imports SystemClass [Date]Public Property Day() As IntegerGetReturn dayEnd GetSetday = valueEnd SetEnd PropertyPrivate day As IntegerPublic Property Month() As IntegerGetReturn monthEnd GetSetmonth = valueEnd SetEnd PropertyPrivate month As IntegerPublic Property Year() As IntegerGetReturn yearEnd GetSetyear = valueEnd SetEnd PropertyPrivate year As IntegerPublic Function IsLeapYear(year As Integer) AsBooleanusing System;class Date{public int Day{get {return day;}set {day = value;}}int day;public int Month{get {return month;}set {month = value;}}int month;public int Year{get {return year;}set {year = value;}}int year;public bool IsLeapYear(int year){return year%4== 0 ? true: false;}


This document is an authorized derivative of Frank McCown's "VB.NET andC# Comparison" (C) 2005 athttp://www.harding.edu/USER/fmccown/WWW/vbnet_csharp_comparison.htmlThis work is licensed under a Create Common LicenseConsole I/OVB.NET'Special character constantsvbCrLf, vbCr, vbLf, vbNewLinevbNullStringvbTabvbBackvbFormFeedvbVerticalTab""Chr(65) 'Returns 'A'System.Console.Write("What's your name? ")Dim name As String = System.Console.ReadLine()System.Console.Write("How old are you? ")Dim age As Integer = Val(System.Console.ReadLine())System.Console.WriteLine("{0} is {1} years old.",name, age)'orSystem.Console.WriteLine(name & " is " & age & "years old.")Dim c As Integerc = System.Console.Read() 'Read single charSystem.Console.WriteLine(c) 'Prints 65 if userenters "A"C#//Escape sequences\n, \r\t\\\Convert.ToChar(65) //Returns 'A' -equivalent to Chr(num) in VB// or(char) 65System.Console.Write("What's your name? ");string name = SYstem.Console.ReadLine();System.Console.Write("How old are you? ");int age =Convert.ToInt32(System.Console.ReadLine());System.Console.WriteLine("{0} is {1} yearsold.", name, age);//orSystem.Console.WriteLine(name + " is " +age + " years old.");int c = System.Console.Read(); //Readsingle charSystem.Console.WriteLine(c); //Prints 65 ifuser enters "A"


This document is an authorized derivative of Frank McCown's "VB.NET andC# Comparison" (C) 2005 athttp://www.harding.edu/USER/fmccown/WWW/vbnet_csharp_comparison.htmlThis work is licensed under a Create Common LicenseFile I/OVB.NETImports System.IOC#using System.IO;'Write out to text fileDim writer As StreamWriter = File.CreateText("c:\myfile.txt")writer.WriteLine("Out to file.")writer.Close()//Write out to text fileStreamWriter writer = 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 NothingConsole.WriteLine(line)line = reader.ReadLine()End Whilereader.Close()//Read all lines from text fileStreamReader reader = File.OpenText("c:\\myfile.txt");string line = reader.ReadLine();while (line != null) {Console.WriteLine(line);line = reader.ReadLine();}reader.Close();'Write out to binary fileDim str As String = "Text data"Dim num As Integer = 123Dim binWriter As New BinaryWriter(File.OpenWrite("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()//Write out to binary filestring str = "Text data";int num = 123;BinaryWriter binWriter = newBinaryWriter(File.OpenWrite("c:\\myfile.dat"));binWriter.Write(str);binWriter.Write(num);binWriter.Close();//Read from binary fileBinaryReader binReader = newBinaryReader(File.OpenRead("c:\\myfile.dat"));str = binReader.ReadString();num = binReader.ReadInt32();binReader.Close();

More magazines by this user
Similar magazines