Date post: | 02-Jun-2018 |
Category: |
Documents |
Upload: | nitin-birari |
View: | 230 times |
Download: | 0 times |
of 16
8/11/2019 Vb and c# Comaprison
1/16
Comments
VB.NET
'Single line only
RemSingleline only
C#
// Single line
/* Multipleline *//// XML comments on single line
/** XML comments on multiple lines */
Program Structure
VB.NET
ImportsSystem
NamespaceMyNameSpace
ClassHelloWorld
'Entry point which delegates to C-style mainPrivate Function
PublicOverloadsSharedSubMain()
Main(System.Environment.GetCommandLineArgs())
EndSub
OverloadsSharedSubMain(args() AsString)System.Console.WriteLine("Hello World")
EndSub'Main
EndClass'HelloWorld End Namespace'MyNameSpace
C#
usingSystem
Namespace MyNameSpace
{
classHelloWorld
{staticvoidMain(string[] args)
{
System.Console.WriteLine("HelloWorld")
}
}}
8/11/2019 Vb and c# Comaprison
2/16
Data Types
VB.NET
'Value TypesBoolean
ByteChar(example: "A")
Short, Integer, LongSingle, Double
Decimal
Date
'Reference Types
ObjectString
Dimx AsInteger
System.Console.WriteLine(x.GetType())
System.Console.WriteLine(TypeName(x))
'Type conversion
Dimd AsSingle=3.5
Dimi AsInteger=CType(d, Integer)i =CInt(d)
i =Int(d)
C#
//Value Typesbool
byte, sbytechar(example: 'A')
short, ushort, int, uint, long, ulongfloat, double
decimal
DateTime
//Reference Types
objectstring
intx;
Console.WriteLine(x.GetType())
Console.WriteLine(typeof(int))
//Type conversion
floatd =3.5;
inti =(int) d
Constants
VB.NET
ConstMAX_AUTHORS AsInteger=25
ReadOnlyMIN_RANK AsSingle=5.00
C#
constintMAX_AUTHORS =25;
readonlyfloatMIN_RANKING =5.00;
8/11/2019 Vb and c# Comaprison
3/16
Enumerations
VB.NET
EnumActionStart
'Stop is a reserved word[Stop]
RewindForward
EndEnum
EnumStatusFlunk =50
Pass =70
Excel =90EndEnum
Dima AsAction =Action.StopIfa Action.Start Then_'Prints "Stop is 1"
System.Console.WriteLine(a.ToString & " is "
& a)
'Prints 70System.Console.WriteLine(Status.Pass)
'Prints Pass
System.Console.WriteLine(Status.Pass.ToString())
EnumWeekdaysSaturdaySunday
Monday
TuesdayWednesdayThursday
Friday
EndEnum'Weekdays
C#
enumAction {Start, Stop, Rewind,Forward};
enumStatus {Flunk =50, Pass =70, Excel=90};
Action a =Action.Stop;if(a !=Action.Start)
//Prints "Stop is 1"
System.Console.WriteLine(a +" is "+(int) a);
// Prints 70
System.Console.WriteLine((int)Status.Pass);// Prints Pass
System.Console.WriteLine(Status.Pass);
enumWeekdays
{Saturday, Sunday, Monday, Tuesday,
Wednesday, Thursday, Friday
}
8/11/2019 Vb and c# Comaprison
4/16
Operators
VB.NET
'Comparison= < > =
'Arithmetic
+ - * /
Mod\ (integerdivision)^ (raisetoa power)
'Assignment
= += -= *= /= \= ^= = &=
'BitwiseAnd AndAlso Or OrElse Not >
'Logical
And AndAlso Or OrElse Not
'String Concatenation&
C#
//Comparison == < > = !=
//Arithmetic
+ - * /
% (mod)/ (integer division ifboth operands areints)
Math.Pow(x, y)
//Assignment
= += -= *= /= %= &= |= ^= = ++ --
//Bitwise
& | ^ ~ >
//Logical&& || !
//String Concatenation
+
8/11/2019 Vb and c# Comaprison
5/16
Choices
VB.NET
greeting =IIf(age < 20, "What's up?", "Hello")
'One line doesn't require "End If", no "Else"
Iflanguage ="VB.NET"ThenlangType ="verbose"
'Use: to put two commands on same line
Ifx 100 Andy < 5 Thenx *= 5 : y *= 2
'Preferred
Ifx 100 Andy < 5 Then
x *= 5y *= 2
EndIf
'or to break up any long single command use _IfhenYouHaveAReally < longLine And_itNeedsToBeBrokenInto2 > Lines Then_
UseTheUnderscore(charToBreakItUp)
Ifx > 5 Thenx *= y
ElseIfx =5 Thenx += y
ElseIfx < 10 Then
x -= y
Else
x /= yEndIf
'Must be a primitive data type
SelectCasecolorCase"black", "red"r += 1
Case"blue"
b += 1
Case"green"g += 1
CaseElse
other += 1
EndSelect
C#
greeting =age < 20 ? "What's up?":
"Hello";
if(x !=100 && y < 5){
// Multiple statements must be enclosedin {}
x *= 5;y *= 2;
}
if(x > 5)x *= y;
elseif(x == 5)x += y;
elseif(x < 10)
x -= y;else
x /= y;
//Must be integer or stringswitch(color){
case"black":
case"red": r++;break;case"blue"
break;
case"green": g++;break;default: other++;
break;
}
8/11/2019 Vb and c# Comaprison
6/16
Loops
VB.NET
'Pre-test Loops:Whilec < 10
c += 1EndWhileDoUntilc =10
c += 1
Loop
'Post-test Loop:
DoWhilec < 10
c += 1Loop
Forc =2 To10 Step2
System.Console.WriteLine(c)Next
'Array or collection looping
Dimnames AsString() ={"Steven", "SuOk","Sarah"}ForEachs AsStringInnames
System.Console.WriteLine(s)
Next
C#
//Pre-test Loops: while (i < 10)i++;
for(i =2; i < =10; i += 2)System.Console.WriteLine(i);
//Post-test Loop:do
i++;
while(i < 10);
// Array or collection loopingstring[] names ={"Steven", "SuOk","Sarah"};
foreach(strings innames)
System.Console.WriteLine(s);
Arrays
VB.NET
Dimnums() AsInteger={1, 2, 3}Fori AsInteger=0 Tonums.Length -1
Console.WriteLine(nums(i))Next
C#
int[] nums ={1, 2, 3};for(inti =0; i < nums.Length; i++)
Console.WriteLine(nums[i]);
8/11/2019 Vb and c# Comaprison
7/16
'4 is the index of the last element, so it holds5 elementsDimnames(4) AsString
names(0) ="Steven"
'Throws System.IndexOutOfRangeException
names(5) ="Sarah"
'Resize the array, keeping the existing'values (Preserve is optional)ReDimPreservenames(6)
DimtwoD(rows-1, cols-1) AsSingletwoD(2, 0) =4.5
Dimjagged()() AsInteger={ _NewInteger(4) {}, NewInteger(1) {}, New
Integer(2) {} }
jagged(0)(4) =5
// 5 is the size of the array
string[] names =newstring[5];names[0] ="Steven";
// Throws System.IndexOutOfRangeException
names[5] ="Sarah"
// C# can't dynamically resize an array.
//Just copy into new array.string[] names2 =newstring[7];// or names.CopyTo(names2, 0);
Array.Copy(names, names2, names.Length);
float[,] twoD =newfloat[rows, cols];
twoD[2,0] =4.5;
int[][] jagged =newint[3][] {
newint[5], newint[2], newint[3] };jagged[0][4] =5;
Functions
VB.NET
'Pass by value (in, default), reference'(in/out), and reference (out)SubTestFunc(ByValx AsInteger, ByRefy AsInteger,
ByRefz AsInteger)x += 1y += 1
z =5
EndSub
'c set to zero by default
Dima =1, b =1, c AsInteger
TestFunc(a, b, c)
System.Console.WriteLine("{0} {1} {2}", a, b, c)'1 2 5
C#
// Pass by value (in, default), reference//(in/out), and reference (out)voidTestFunc(intx, refinty, outintz) {
x++;y++;z =5;
}
inta =1, b =1, c; // c doesn't needinitializing
TestFunc(a, refb, outc);
System.Console.WriteLine("{0} {1} {2}",a, b, c); // 1 2 5
8/11/2019 Vb and c# Comaprison
8/16
'Accept variable number of arguments
FunctionSum(ByValParamArraynums AsInteger())AsInteger
Sum =0
ForEachi AsIntegerInnums
Sum += i
Next
EndFunction'Or use a Return statement like C#
Dimtotal AsInteger=Sum(4, 3, 2, 1) 'returns10
'Optional parameters must be listed last
'and must have a default valueSubSayHello(ByValname AsString,
OptionalByValprefix AsString="")
System.Console.WriteLine("Greetings, "&prefix& " "& name)
EndSub
SayHello("Steven", "Dr.")
SayHello("SuOk")
// Accept variable number of arguments
intSum(paramsint[] nums) {
intsum =0;foreach(inti innums)
sum += i;
returnsum;
}
inttotal =Sum(4, 3, 2, 1); // returns10
/* C# doesn't support optionalarguments/parameters.Just create two different versions of thesame function. */
voidSayHello(stringname, stringprefix){
System.Console.WriteLine("Greetings, "+prefix +" "+name);
}
voidSayHello(stringname) {
SayHello(name, "");
}
Exception Handling
VB.NET
ClassWithfinallyPublicSharedSubMain()
TryDimx AsInteger=5Dimy AsInteger=0
Dimz AsInteger=x /y
Console.WriteLine(z)
Catche AsDivideByZeroException
System.Console.WriteLine("Erroroccurred")
FinallySystem.Console.WriteLine("Thank you")
EndTry
EndSub'MainEndClass'Withfinally
C#
class Withfinally{
publicstaticvoidMain(){try
{
intx =5;
inty =0;
intz =x/y;
Console.WriteLine(z);
}catch(DivideByZeroException e)
{
System.Console.WriteLine("Erroroccurred");
}
finally
8/11/2019 Vb and c# Comaprison
9/16
{
System.Console.WriteLine("Thankyou");
}
}
}
Namespaces
VB.NET
NamespaceASPAlliance.DotNet.Community
...
EndNamespace
'or
NamespaceASPAllianceNamespaceDotNet
NamespaceCommunity
...EndNamespace
EndNamespace
EndNamespace
ImportsASPAlliance.DotNet.Community
C#
namespaceASPAlliance.DotNet.Community {
...
}
// or
namespaceASPAlliance {
namespaceDotNet {
namespaceCommunity {
...}
}
}
usingASPAlliance.DotNet.Community;
Classes / Interfaces
VB.NET
'Accessibility keywordsPublicPrivate
Friend
ProtectedProtectedFriend
Shared
'Inheritance
ClassArticles
InheritsAuthors...
EndClass
ImportsSystem
C#
//Accessibility keywordspublicprivate
internal
protectedprotectedinternal
static
//Inheritance
classArticles: Authors {
...}
usingSystem;
8/11/2019 Vb and c# Comaprison
10/16
InterfaceIArticleSubShow()
EndInterface'IArticle
_
ClassIAuthor
ImplementsIArticle
PublicSubShow()
System.Console.WriteLine("Show() methodImplemented")
EndSub'Show
'Entry point which delegates to C-style mainPrivate Function
PublicOverloadsSharedSubMain()
Main(System.Environment.GetCommandLineArgs())
EndSub
OverloadsPublicSharedSubMain(args() AsString)
Dimauthor AsNewIAuthor()
author.Show()
EndSub'Main
EndClass'IAuthor
interfaceIArticle
{voidShow();
}
classIAuthor:IArticle
{
publicvoidShow(){System.Console.WriteLine("Show()
method Implemented");
}
publicstaticvoidMain(string[] args)
{IAuthor author =newIAuthor();author.Show();
}
}
Constructors / Destructors
VB.NET
ClassTopAuthorPrivate_topAuthor AsInteger
PublicSubNew()_topAuthor =0
EndSub
PublicSubNew(ByValtopAuthor AsInteger)
Me._topAuthor =topAuthor
EndSub
ProtectedOverridesSubFinalize()
'Desctructor code to free unmanaged resources
MyBase.Finalize()EndSub
EndClass
C#
classTopAuthor {privateint_topAuthor;
publicTopAuthor() {_topAuthor =0;
}
publicTopAuthor(inttopAuthor) {
this._topAuthor= topAuthor
}
~TopAuthor() {
// Destructor code to free unmanagedresources.
// Implicitly creates a Finalizemethod
}
8/11/2019 Vb and c# Comaprison
11/16
}
Objects
VB.NET
Dimauthor AsTopAuthor =NewTopAuthor
Withauthor
.Name ="Steven"
.AuthorRanking =3EndWith
author.Rank("Scott")
author.Demote() 'Calling Shared method
'orTopAuthor.Rank()
Dimauthor2 AsTopAuthor =author 'Both refer tosame object
author2.Name ="Joe"
System.Console.WriteLine(author2.Name) 'Prints
Joe
author =Nothing'Free the object
Ifauthor IsNothingThen_author =NewTopAuthor
Dimobj AsObject=NewTopAuthor
IfTypeOfobj IsTopAuthor Then_System.Console.WriteLine("Is a TopAuthor
object.")
C#
TopAuthor author =newTopAuthor();
//No "With" construct
author.Name ="Steven";author.AuthorRanking =3;
author.Rank("Scott");
TopAuthor.Demote() //Calling staticmethod
TopAuthor author2 =author //Both referto same object
author2.Name ="Joe";System.Console.WriteLine(author2.Name)
//Prints Joe
author =null//Free the object
if(author == null)author =newTopAuthor();
Object obj =newTopAuthor();if(obj isTopAuthor)
SystConsole.WriteLine("Is a TopAuthorobject.");
Structs
VB.NET
StructureAuthorRecordPublicname AsString
Publicrank AsSingle
PublicSubNew(ByValname AsString, ByVal
rank AsSingle)Me.name =name
Me.rank =rankEndSub
EndStructure
Dimauthor AsAuthorRecord =NewAuthorRecord("Steven", 8.8)Dimauthor2 AsAuthorRecord =author
C#
structAuthorRecord {publicstringname;
publicfloatrank;
publicAuthorRecord(stringname, float
rank) {
this.name =name;
this.rank =rank;}
}
AuthorRecord author =newAuthorRecord("Steven", 8.8);AuthorRecord author2 =author
8/11/2019 Vb and c# Comaprison
12/16
author2.name ="Scott"
System.Console.WriteLine(author.name) 'PrintsStevenSystem.Console.WriteLine(author2.name) 'PrintsScott
author.name ="Scott";
SystemConsole.WriteLine(author.name);//Prints Steven
System.Console.WriteLine(author2.name);//Prints Scott
Properties
VB.NET
Private_size AsInteger
PublicPropertySize() AsIntegerGet
Return_size
EndGet
Set(ByValValue AsInteger)
IfValue < 0 Then
_size =0
Else_size =Value
EndIf
EndSetEndProperty
C#
privateint_size;
publicintSize {get {
return_size;
}
set {
if(value < 0)
_size =0;
else_size =value;
}
}
8/11/2019 Vb and c# Comaprison
13/16
foo.Size += 1
ImportsSystem
Class[Date]
PublicPropertyDay() AsInteger
GetReturnday
EndGet
Set
day=value
EndSetEndProperty
PrivatedayAsInteger
PublicPropertyMonth() AsInteger
Get
ReturnmonthEndGet
Set
month=value
EndSetEndProperty
PrivatemonthAsInteger
PublicPropertyYear() AsInteger
Get
ReturnyearEndGetSet
year=value
EndSetEndPropertyPrivateyearAsInteger
PublicFunctionIsLeapYear(yearAsInteger)AsBoolean
Return(IfyearMod4 =0 ThenTrueElseFalse)
EndFunction'IsLeapYear
PublicSubSetDate(dayAsInteger, monthAsInteger,yearAsInteger)
Me.day=day
Me.month=monthMe.year=year
EndSub'SetDate
EndClass'[Date]
foo.Size++;
usingSystem;
classDate
{
publicintDay{
get {
returnday;
}set {
day =value;
}
}
intday;
publicintMonth{get {
returnmonth;
}
set {month =value;
}
}
intmonth;
publicintYear{
get {returnyear;
}
set {year =value;
}
}
intyear;
publicboolIsLeapYear(intyear)
{
returnyear%4== 0 ? true: false;
}
publicvoidSetDate (intday, intmonth, intyear)
{
this.day =day;
this.month =month;this.year =year;
}
}
Delegates / Events
VB.NET
DelegateSubMsgArrivedEventHandler(ByValmessage
AsString)
C#
delegatevoidMsgArrivedEventHandler(stringmessage);
8/11/2019 Vb and c# Comaprison
14/16
EventMsgArrivedEvent AsMsgArrivedEventHandler
'or to define an event which declares a
'delegate implicitly
EventMsgArrivedEvent(ByValmessage AsString)
AddHandlerMsgArrivedEvent, AddressOfMy_MsgArrivedCallback'Won't throw an exception if obj is Nothing
RaiseEventMsgArrivedEvent("Test message")
RemoveHandlerMsgArrivedEvent, AddressOfMy_MsgArrivedCallback
ImportsSystem.Windows.Forms
'WithEvents can't be used on local variableDimWithEventsMyButton AsButton
MyButton =NewButton
PrivateSubMyButton_Click(ByValsender AsSystem.Object, _
ByVale AsSystem.EventArgs) HandlesMyButton.Click
MessageBox.Show(Me, "Button was clicked","Info", _
MessageBoxButtons.OK,MessageBoxIcon.Information)EndSub
eventMsgArrivedEventHandlerMsgArrivedEvent;
//Delegates must be used with events inC#
MsgArrivedEvent += newMsgArrivedEventHandler
(My_MsgArrivedEventCallback);//Throws exception if obj is null
MsgArrivedEvent("Test message");
MsgArrivedEvent -= newMsgArrivedEventHandler
(My_MsgArrivedEventCallback);
usingSystem.Windows.Forms;
Button MyButton =newButton();
MyButton.Click += newSystem.EventHandler(MyButton_Click);
privatevoidMyButton_Click(objectsender, System.EventArgs e) {
MessageBox.Show(this, "Button wasclicked", "Info",
MessageBoxButtons.OK,MessageBoxIcon.Information);}
Console I/O
VB.NET
'Special character constantsvbCrLf, vbCr, vbLf, vbNewLinevbNullString
vbTab
vbBack
vbFormFeed
vbVerticalTab
""
Chr(65) 'Returns 'A'
System.Console.Write("What's your name? ")Dimname AsString=System.Console.ReadLine()System.Console.Write("How old are you? ")
Dimage AsInteger=
C#
//Escape sequences\n, \r\t
\\
\
Convert.ToChar(65) //Returns 'A' -equivalent to Chr(num) in VB// or
(char) 65
System.Console.Write("What's your name?");
8/11/2019 Vb and c# Comaprison
15/16
Val(System.Console.ReadLine())
System.Console.WriteLine("{0} is {1} yearsold.", name, age)'or
System.Console.WriteLine(name & " is "& age & "years old.")
Dimc AsInteger
c =System.Console.Read() 'Read single char
System.Console.WriteLine(c) 'Prints 65 if userenters "A"
stringname =SYstem.Console.ReadLine();
System.Console.Write("How old are you?");intage =Convert.ToInt32(System.Console.ReadLine());
System.Console.WriteLine("{0} is {1}
years old.", name, age);
//or
System.Console.WriteLine(name +" is "+age +" years old.");
intc =System.Console.Read(); //Readsingle charSystem.Console.WriteLine(c); //Prints 65if user enters "A"
File I/O
VB.NET
ImportsSystem.IO
'Write out to text file
Dimwriter AsStreamWriter =File.CreateText
("c:\myfile.txt")writer.WriteLine("Out to file.")
writer.Close()
'Read all lines from text file
Dimreader AsStreamReader =File.OpenText
C#
usingSystem.IO;
//Write out to text file
StreamWriter writer =File.CreateText
("c:\\myfile.txt");writer.WriteLine("Out to file.");
writer.Close();
//Read all lines from text file
StreamReader reader =File.OpenText
8/11/2019 Vb and c# Comaprison
16/16