You are on page 1of 15

VB.

NET & C# QUICK REFERENCE CARD 
 

Comments
VB.NET C#
'Single line only // Single line
Rem Single line only /* Multiple
line */
/// XML comments on single line
/** XML comments on multiple lines */

Program Structure
VB.NET C#
Imports System using System
Namespace MyNameSpace Namespace MyNameSpace
{
Class HelloWorld class HelloWorld
'Entry point which delegates to C-style main {
Private Function static void Main(string[] args)
{
Public Overloads Shared Sub Main() System.Console.WriteLine("Hello
Main(System.Environment.GetCommandLineArgs()) World")
End Sub }
}
Overloads Shared Sub Main(args() As String) }
System.Console.WriteLine("Hello World")

End Sub 'Main

End Class 'HelloWorld End Namespace 'MyNameSpace

Data Types
VB.NET C#
'Value Types //Value Types
Boolean bool
Byte byte, sbyte
Char (example: "A") char (example: 'A')
Short, Integer, Long short, ushort, int, uint, long, ulong
Single, Double float, double
Decimal decimal
Date DateTime

'Reference Types //Reference Types


Object object
String string

Dim x As Integer int x;


System.Console.WriteLine(x.GetType()) Console.WriteLine(x.GetType())
System.Console.WriteLine(TypeName(x)) Console.WriteLine(typeof(int))

'Type conversion //Type conversion


Dim d As Single = 3.5 float d = 3.5;
Dim i As Integer = CType (d, Integer) int i = (int) d
i = CInt (d)
i = Int(d)
 
   


 
 

Constants
VB.NET C#
Const MAX_AUTHORS As Integer = 25 const int MAX_AUTHORS = 25;
ReadOnly MIN_RANK As Single = 5.00 readonly float MIN_RANKING = 5.00;

Enumerations
VB.NET C#
Enum Action enum Action {Start, Stop, Rewind, Forward};
Start enum Status {Flunk = 50, Pass = 70, Excel =
'Stop is a reserved word 90};
[Stop]
Rewind
Forward
End Enum

Enum Status
Flunk = 50
Pass = 70
Excel = 90
End Enum

Dim a As Action = Action.Stop Action a = Action.Stop;


If a <> Action.Start Then _ if (a != Action.Start)
'Prints "Stop is 1" //Prints "Stop is 1"
System.Console.WriteLine(a.ToString & " is " & System.Console.WriteLine(a + " is " +
a) (int) a);

'Prints 70 // Prints 70
System.Console.WriteLine(Status.Pass) System.Console.WriteLine((int) Status.Pass);
'Prints Pass // Prints Pass
System.Console.WriteLine(Status.Pass.ToString()) System.Console.WriteLine(Status.Pass);

Enum Weekdays
Saturday enum Weekdays
Sunday {
Monday Saturday, Sunday, Monday, Tuesday,
Tuesday Wednesday, Thursday, Friday
Wednesday }
Thursday
Friday
End Enum 'Weekdays

 
   


 
 

Operators
VB.NET C#
'Comparison //Comparison
= < > <= >= <> == < > <= >= !=

'Arithmetic //Arithmetic
+ - * / + - * /
Mod % (mod)
\ (integer division) / (integer division if both operands are ints)
^ (raise to a power) Math.Pow(x, y)

'Assignment //Assignment
= += -= *= /= \= ^= <<= >>= &= = += -= *= /= %= &= |= ^= <<= >>= ++ --

'Bitwise //Bitwise
And AndAlso Or OrElse Not << >> & | ^ ~ << >>

'Logical //Logical
And AndAlso Or OrElse Not && || !

'String Concatenation //String Concatenation


& +

 
   


 
 

Choices
VB.NET C#
greeting = IIf(age < 20, "What's up?", "Hello") greeting = 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 line


If x <> 100 And y < 5 Then x *= 5 : y *= 2

'Preferred if (x != 100 && y < 5)


If x <> 100 And y < 5 Then {
x *= 5 // Multiple statements must be enclosed in
y *= 2 {}
End If x *= 5;
y *= 2;
}

'or to break up any long single command use _


If henYouHaveAReally < longLine And _
itNeedsToBeBrokenInto2 > Lines Then _
UseTheUnderscore(charToBreakItUp)

If x > 5 Then if (x > 5)


x *= y x *= y;
ElseIf x = 5 Then else if (x == 5)
x += y x += y;
ElseIf x < 10 Then else if (x < 10)
x -= y x -= y;
Else else
x /= y x /= y;
End If

'Must be a primitive data type //Must be integer or string


Select Case color switch (color)
Case "black", "red" {
r += 1 case "black":
Case "blue" case "red": r++;
b += 1 break;
Case "green" case "blue"
g += 1 break;
Case Else case "green": g++;
other += 1 break;
End Select default: other++;
break;
}

 
   


 
 

Loops
VB.NET C#
'Pre-test Loops: //Pre-test Loops: while (i < 10)
While c < 10 i++;
c += 1 for (i = 2; i < = 10; i += 2)
End While Do Until c = 10 System.Console.WriteLine(i);
c += 1
Loop

'Post-test Loop:
Do While c < 10
c += 1 //Post-test Loop:
Loop do
i++;
while (i < 10);
For c = 2 To 10 Step 2
System.Console.WriteLine(c)
Next

'Array or collection looping


Dim names As String() = {"Steven", "SuOk",
"Sarah"} // Array or collection looping
For Each s As String In names string[] names = {"Steven", "SuOk", "Sarah"};
System.Console.WriteLine(s) foreach (string s in names)
Next System.Console.WriteLine(s);

 
   


 
 

Arrays
VB.NET C#
Dim nums() As Integer = {1, 2, 3} int[] nums = {1, 2, 3};
For i As Integer = 0 To nums.Length - 1 for (int i = 0; i < nums.Length; i++)
Console.WriteLine(nums(i)) Console.WriteLine(nums[i]);
Next

'4 is the index of the last element, so it holds 5 // 5 is the size of the array
elements string[] names = new string[5];
Dim names(4) As String names[0] = "Steven";
names(0) = "Steven" // Throws System.IndexOutOfRangeException
'Throws System.IndexOutOfRangeException names[5] = "Sarah"
names(5) = "Sarah"

// C# can't dynamically resize an array.


'Resize the array, keeping the existing //Just copy into new array.
'values (Preserve is optional) string[] names2 = new string[7];
ReDim Preserve names(6) // or names.CopyTo(names2, 0);
Array.Copy(names, names2, names.Length);

float[,] twoD = new float[rows, cols];


Dim twoD(rows-1, cols-1) As Single twoD[2,0] = 4.5;
twoD(2, 0) = 4.5

int[][] jagged = new int[3][] {


Dim jagged()() As Integer = { _ new int[5], new int[2], new int[3] };
New Integer(4) {}, New Integer(1) {}, New Integer(2) jagged[0][4] = 5;
{} }
jagged(0)(4) = 5

 
   


 
 

Functions
VB.NET C#
'Pass by value (in, default), reference // Pass by value (in, default), reference
'(in/out), and reference (out) //(in/out), and reference (out)
Sub TestFunc(ByVal x As Integer, ByRef y As void TestFunc(int x, ref int y, out int z) {
Integer, x++;
ByRef z As Integer) y++;
x += 1 z = 5;
y += 1 }
z = 5
End Sub

'c set to zero by default int a = 1, b = 1, c; // c doesn't need


initializing
Dim a = 1, b = 1, c As Integer TestFunc(a, ref b, out c);
TestFunc(a, b, c) System.Console.WriteLine("{0} {1} {2}", a, b,
System.Console.WriteLine("{0} {1} {2}", a, b, c) '1 c); // 1 2 5
2 5

// Accept variable number of arguments


'Accept variable number of arguments int Sum(params int[] nums) {
Function Sum(ByVal ParamArray nums As Integer()) As int sum = 0;
Integer foreach (int i in nums)
Sum = 0 sum += i;
For Each i As Integer In nums return sum;
Sum += i }
Next
End Function 'Or use a Return statement like C#
int total = Sum(4, 3, 2, 1); // returns 10
Dim total As Integer = Sum(4, 3, 2, 1) 'returns 10

/* C# doesn't support optional


'Optional parameters must be listed last arguments/parameters.
'and must have a default value Just create two different versions of the same
Sub SayHello(ByVal name As String, function. */
Optional ByVal prefix As String = "") void SayHello(string name, string prefix) {
System.Console.WriteLine("Greetings, " & prefix System.Console.WriteLine("Greetings, " +
& " " & name) prefix + " " + name);
End Sub }

void SayHello(string name) {


SayHello("Steven", "Dr.") SayHello(name, "");
SayHello("SuOk") }

 
   


 
 

Exception Handling
VB.NET C#
Class Withfinally class Withfinally
Public Shared Sub Main() {
Try public static void Main()
Dim x As Integer = 5 {
Dim y As Integer = 0 try
Dim z As Integer = x / y {
Console.WriteLine(z) int x = 5;
Catch e As DivideByZeroException int y = 0;
System.Console.WriteLine("Error int z = x/y;
occurred") Console.WriteLine(z);
Finally }
System.Console.WriteLine("Thank you") catch(DivideByZeroException e)
End Try {
End Sub 'Main System.Console.WriteLine("Error occurred");
End Class 'Withfinally }
finally
{
System.Console.WriteLine("Thank you");
}
}
}

Namespaces
VB.NET C#
Namespace ASPAlliance.DotNet.Community namespace ASPAlliance.DotNet.Community {
... ...
End Namespace }

'or // or

Namespace ASPAlliance namespace ASPAlliance {


Namespace DotNet namespace DotNet {
Namespace Community namespace Community {
... ...
End Namespace }
End Namespace }
End Namespace }

Imports ASPAlliance.DotNet.Community using ASPAlliance.DotNet.Community;

 
   


 
 

Classes / Interfaces
VB.NET C#
'Accessibility keywords //Accessibility keywords
Public public
Private private
Friend internal
Protected protected
Protected Friend protected internal
Shared static

'Inheritance //Inheritance
Class Articles class Articles: Authors {
Inherits Authors ...
... }
End Class

using System;
Imports System

interface IArticle
Interface IArticle {
Sub Show() void Show();
End Interface 'IArticle }
_

class IAuthor:IArticle
Class IAuthor {
Implements IArticle public void Show()
{
Public Sub Show() System.Console.WriteLine("Show() method
System.Console.WriteLine("Show() method Implemented");
Implemented") }
End Sub 'Show

'Entry point which delegates to C-style main public static void Main(string[] args)
Private Function {
Public Overloads Shared Sub Main() IAuthor author = new IAuthor();
Main(System.Environment.GetCommandLineArgs()) author.Show();
End Sub }
}

Overloads Public Shared Sub Main(args() As


String)
Dim author As New IAuthor()
author.Show()
End Sub 'Main
End Class 'IAuthor
 
   


 
 

Constructors / Destructors
VB.NET C#
Class TopAuthor class TopAuthor {
Private _topAuthor As Integer private int _topAuthor;

Public Sub New() public TopAuthor() {


_topAuthor = 0 _topAuthor = 0;
End Sub }

Public Sub New(ByVal topAuthor As Integer) public TopAuthor(int topAuthor) {


Me._topAuthor = topAuthor this._topAuthor= topAuthor
End Sub }

Protected Overrides Sub Finalize() ~TopAuthor() {


'Desctructor code to free unmanaged resources // Destructor code to free unmanaged
MyBase.Finalize() resources.
End Sub // Implicitly creates a Finalize method
End Class }
}

Objects
VB.NET C#
Dim author As TopAuthor = New TopAuthor TopAuthor author = new TopAuthor();
With author
.Name = "Steven" //No "With" construct
.AuthorRanking = 3 author.Name = "Steven";
End With author.AuthorRanking = 3;

author.Rank("Scott")
author.Demote() 'Calling Shared method author.Rank("Scott");
'or TopAuthor.Demote() //Calling static method
TopAuthor.Rank()

Dim author2 As TopAuthor = author 'Both refer to


same object TopAuthor author2 = author //Both refer to same
author2.Name = "Joe" object
System.Console.WriteLine(author2.Name) 'Prints author2.Name = "Joe";
Joe System.Console.WriteLine(author2.Name) //Prints
Joe

author = Nothing 'Free the object


author = null //Free the object

If author Is Nothing Then _


author = New TopAuthor if (author == null)
author = new TopAuthor();

Dim obj As Object = New TopAuthor


If TypeOf obj Is TopAuthor Then _ Object obj = new TopAuthor();
System.Console.WriteLine("Is a TopAuthor if (obj is TopAuthor)
object.") SystConsole.WriteLine("Is a TopAuthor object.");

 
   

10 
 
 

Structs
VB.NET C#
Structure AuthorRecord struct AuthorRecord {
Public name As String public string name;
Public rank As Single public float rank;

Public Sub New(ByVal name As String, ByVal public AuthorRecord(string name, float rank) {
rank As Single) this.name = name;
Me.name = name this.rank = rank;
Me.rank = rank }
End Sub }
End Structure

Dim author As AuthorRecord = New AuthorRecord author = new AuthorRecord("Steven",


AuthorRecord("Steven", 8.8) 8.8);
Dim author2 As AuthorRecord = author AuthorRecord author2 = author

author2.name = "Scott" author.name = "Scott";


System.Console.WriteLine(author.name) 'Prints SystemConsole.WriteLine(author.name); //Prints
Steven Steven
System.Console.WriteLine(author2.name) 'Prints System.Console.WriteLine(author2.name); //Prints
Scott Scott

 
   

11 
 
 

Properties
VB.NET C#
Private _size As Integer private int _size;

Public Property Size() As Integer public int Size {


Get get {
Return _size return _size;
End Get }
Set (ByVal Value As Integer) set {
If Value < 0 Then if (value < 0)
_size = 0 _size = 0;
Else else
_size = Value _size = value;
End If }
End Set }
End Property

foo.Size += 1 foo.Size++;

Imports System using System;


class Date
{
Class [Date] public int Day{
get {
Public Property Day() As Integer return day;
Get }
Return day set {
End Get day = value;
Set }
day = value }
End Set int day;
End Property
Private day As Integer
public int Month{
get {
Public Property Month() As Integer return month;
Get }
Return month set {
End Get month = value;
Set }
month = value }
End Set int month;
End Property
Private month As Integer
public int Year{
get {
Public Property Year() As Integer return year;
Get }
Return year set {
End Get year = value;
Set }
year = value }
End Set int year;
End Property
Private year As Integer
public bool IsLeapYear(int year)
{
Public Function IsLeapYear(year As Integer) As return year%4== 0 ? true: false;
Boolean }
Return(If year Mod 4 = 0 Then True Else public void SetDate (int day, int month,
False) int year)
End Function 'IsLeapYear {
this.day = day;
Public Sub SetDate(day As Integer, month As this.month = month;
Integer, this.year = year;
year As Integer) }

12 
 
Me.day = day }
Me.month = month
Me.year = year
End Sub 'SetDate
End Class '[Date]

Delegates / Events
VB.NET C#
Delegate Sub MsgArrivedEventHandler(ByVal message delegate void MsgArrivedEventHandler(string
As String) message);

Event MsgArrivedEvent As MsgArrivedEventHandler event MsgArrivedEventHandler MsgArrivedEvent;

'or to define an event which declares a //Delegates must be used with events in C#
'delegate implicitly
Event MsgArrivedEvent(ByVal message As String)
MsgArrivedEvent += new MsgArrivedEventHandler
(My_MsgArrivedEventCallback);
AddHandler MsgArrivedEvent, AddressOf //Throws exception if obj is null
My_MsgArrivedCallback MsgArrivedEvent("Test message");
'Won't throw an exception if obj is Nothing MsgArrivedEvent -= new MsgArrivedEventHandler
RaiseEvent MsgArrivedEvent("Test message") (My_MsgArrivedEventCallback);
RemoveHandler MsgArrivedEvent, AddressOf
My_MsgArrivedCallback

using System.Windows.Forms;

Imports System.Windows.Forms
Button MyButton = new Button();
MyButton.Click += new
'WithEvents can't be used on local variable System.EventHandler(MyButton_Click);
Dim WithEvents MyButton As Button
MyButton = New Button
private void MyButton_Click(object sender,
System.EventArgs e) {
Private Sub MyButton_Click(ByVal sender As MessageBox.Show(this, "Button was clicked",
System.Object, _ "Info",
ByVal e As System.EventArgs) Handles MessageBoxButtons.OK,
MyButton.Click MessageBoxIcon.Information);
MessageBox.Show(Me, "Button was clicked", "Info", }
_
MessageBoxButtons.OK,
MessageBoxIcon.Information)
End Sub

 
   

13 
 
 

Console I/O
VB.NET C#
'Special character constants //Escape sequences
vbCrLf, vbCr, vbLf, vbNewLine \n, \r
vbNullString \t
vbTab \\
vbBack \
vbFormFeed
vbVerticalTab
"" Convert.ToChar(65) //Returns 'A' - equivalent
Chr(65) 'Returns 'A' to Chr(num) in VB
// or
(char) 65
System.Console.Write("What's your name? ")
Dim name As String = System.Console.ReadLine()
System.Console.Write("How old are you? ") System.Console.Write("What's your name? ");
Dim age As Integer = Val(System.Console.ReadLine()) string name = SYstem.Console.ReadLine();
System.Console.WriteLine("{0} is {1} years old.", System.Console.Write("How old are you? ");
name, age) int age =
'or Convert.ToInt32(System.Console.ReadLine());
System.Console.WriteLine(name & " is " & age & " System.Console.WriteLine("{0} is {1} years
years old.") old.", name, age);
//or
Dim c As Integer System.Console.WriteLine(name + " is " + age
c = System.Console.Read() 'Read single char + " years old.");
System.Console.WriteLine(c) 'Prints 65 if user
enters "A"
int c = System.Console.Read(); //Read single
char
System.Console.WriteLine(c); //Prints 65 if
user enters "A"

 
   

14 
 
 

File I/O
VB.NET C#
Imports System.IO using System.IO;

'Write out to text file //Write out to text file


Dim writer As StreamWriter = File.CreateText StreamWriter writer = File.CreateText
("c:\myfile.txt") ("c:\\myfile.txt");
writer.WriteLine("Out to file.") writer.WriteLine("Out to file.");
writer.Close() writer.Close();

'Read all lines from text file //Read all lines from text file
Dim reader As StreamReader = File.OpenText StreamReader reader = File.OpenText
("c:\myfile.txt") ("c:\\myfile.txt");
Dim line As String = reader.ReadLine() string line = reader.ReadLine();
While Not line Is Nothing while (line != null) {
Console.WriteLine(line) Console.WriteLine(line);
line = reader.ReadLine() line = reader.ReadLine();
End While }
reader.Close() reader.Close();

'Write out to binary file //Write out to binary file


Dim str As String = "Text data" string str = "Text data";
Dim num As Integer = 123 int num = 123;
Dim binWriter As New BinaryWriter(File.OpenWrite BinaryWriter binWriter = new
("c:\myfile.dat")) BinaryWriter(File.OpenWrite
binWriter.Write(str) ("c:\\myfile.dat"));
binWriter.Write(num) binWriter.Write(str);
binWriter.Close() binWriter.Write(num);
binWriter.Close();

'Read from binary file


Dim binReader As New BinaryReader(File.OpenRead //Read from binary file
("c:\myfile.dat")) BinaryReader binReader = new
str = binReader.ReadString() BinaryReader(File.OpenRead
num = binReader.ReadInt32() ("c:\\myfile.dat"));
binReader.Close() str = binReader.ReadString();
num = binReader.ReadInt32();
binReader.Close();

15 
 

You might also like