vb.net and c# comparison
this 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.
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 only
rem single line only // single line
/* multiple
line */
/// xml comments on single line
/** xml comments on multiple lines */
data types
value types
boolean
byte
char (example: "a"c)
short, integer, long
single, double
decimal
date
reference types
object
string
dim x as integer
console.writeline(x.gettype()) ' prints system.int32
console.writeline(typename(x)) ' prints integer
' type conversion
dim numdecimal as single = 3.5
dim numint as integer
numint = ctype(numdecimal, integer) ' set to 4 (banker's rounding)
numint = cint(numdecimal) ' same result as ctype
numint = int(numdecimal) ' set to 3 (int function truncates the decimal)
value types
bool
byte, sbyte
char (example: 'a')
short, ushort, int, uint, long, ulong
float, double
decimal
datetime (not a built-in c# type)
reference types
object
string
int x;
console.writeline(x.gettype()); // prints system.int32
console.writeline(typeof(int)); // prints system.int32
// type conversion
double numdecimal = 3.5;
int numint = (int) numdecimal; // set to 3 (truncates decimal)
constants
const max_students as integer = 25 const int max_students = 25;
enumerations
enum action
start
[stop] ' stop is a reserved word
rewind
forward
end enum
enum status
flunk = 50
pass = 70
excel = 90
end enum
dim a as action = action.stop
if a <> action.start then console.writeline(a) ' prints 1
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, rewind, 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 pass
operators
comparison
= < > <= >= <>
arithmetic
+ - * /
mod
/ (integer division)
^ (raise to a power)
assignment
= += -= *= /= /= ^= <<= >>= &=
bitwise
and andalso or orelse not << >>
logical
and andalso or orelse not
note: andalso and orelse are for short-circuiting logical evaluations
string concatenation
&
comparison
== < > <= >= !=
arithmetic
+ - * /
% (mod)
/ (integer division if both operands are ints)
math.pow(x, y)
assignment
= += -= *= /= %= &= |= ^= <<= >>= ++ --
bitwise
& | ^ ~ << >>
logical
&& || !
note: && and || perform short-circuit logical evaluations
string concatenation
+
choices
greeting = iif(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 then x *= 5 : y *= 2
' or to break up any long single command use _
if whenyouhaveareally < longline and itneedstobebrokeninto2 > 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
end if
select 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) { // multiple statements must be enclosed in {}
x *= 5;
y *= 2;
}
no need for _ or : since ; is used to terminate each statement.
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 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
loop
do 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 looping
dim names as string() = {"fred", "sue", "barney"}
for each s as string in names
console.writeline(s)
next
pre-test loops:
// no "until" keyword
while (i < 10)
i++;
for (i = 2; i < = 10; i += 2)
console.writeline(i);
post-test loop:
do
i++;
while (i < 10);
// array or collection looping
string[] names = {"fred", "sue", "barney"};
foreach (string s in names)
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 the last element, so it holds 5 elements
dim 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(rows-1, cols-1) as single
twod(2, 0) = 4.5
dim jagged()() as integer = { _
new integer(4) {}, new integer(1) {}, new integer(2) {} }
jagged(0)(4) = 5
int[] nums = {1, 2, 3};
for (int i = 0; i < nums.length; i++)
console.writeline(nums[i]);
// 5 is the size of the array
string[] names = new string[5];
names[0] = "david";
names[5] = "bobby"; // throws system.indexoutofrangeexception
// c# doesn't can'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[,] twod = new float[rows, cols];
twod[2,0] = 4.5f;
int[][] jagged = new int[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 as 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, optional byval prefix as string = "")
console.writeline("greetings, " & prefix & " " & name)
end sub
sayhello("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 doesn't need initializing
testfunc(a, ref b, out c);
console.writeline("{0} {1} {2}", a, b, c); // 1 2 5
// accept variable number of arguments
int 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 handling
on error goto myerrorhandler
...
myerrorhandler: console.writeline(err.description)
dim ex as new exception("something is really wrong.")
throw ex
try
y = 0
x = 10 / y
catch ex as exception when y = 0 ' argument and when is optional
console.writeline(ex.message)
finally
beep()
end try
exception up = new exception("something is really wrong.");
throw up; // ha ha
try {
y = 0;
x = 10 / y;
}
catch (exception ex) { // argument is optional, no "when" keyword
console.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
public
private
friend
protected
protected friend
shared
' inheritance
class footballgame
inherits competition
...
end class
' interface definition
interface ialarmclock
...
end interface
// extending an interface
interface ialarmclock
inherits iclock
...
end interface
// interface implementation
class wristwatch
implements ialarmclock, itimer
...
end class
accessibility keywords
public
private
internal
protected
protected internal
static
// inheritance
class footballgame : competition {
...
}
// interface definition
interface ialarmclock {
...
}
// extending an interface
interface ialarmclock : iclock {
...
}
// interface implementation
class wristwatch : ialarmclock, itimer {
...
}
constructors / destructors
class 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 sub
end class class 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 hero
.name = "spamman"
.powerlevel = 3
end with
hero.defend("laura jones")
hero.rest() ' calling shared method
' or
superhero.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("is a superhero object.")
superhero hero = new superhero();
// no "with" construct
hero.name = "spamman";
hero.powerlevel = 3;
hero.defend("laura jones");
superhero.rest(); // calling 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 sue
struct 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 bob
console.writeline(stu2.name); // prints sue
properties
private _size as integer
public 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 property
foo.size += 1
private int _size;
public int size {
get {
return _size;
}
set {
if (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 implicitly
event msgarrivedevent(byval message as string)
addhandler msgarrivedevent, addressof my_msgarrivedcallback
' won't throw an exception if obj is nothing
raiseevent msgarrivedevent("test message")
removehandler msgarrivedevent, addressof my_msgarrivedcallback
imports system.windows.forms
dim withevents mybutton as button ' withevents can't be used on local variable
mybutton = 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#
msgarrivedevent += new msgarrivedeventhandler(my_msgarrivedeventcallback);
msgarrivedevent("test message"); // throws exception if obj is null
msgarrivedevent -= 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 constants
vbcrlf, 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 are you? ")
dim age as integer = val(console.readline())
console.writeline("{0} is {1} years old.", name, age)
' 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, /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 are you? ");
int age = convert.toint32(console.readline());
console.writeline("{0} is {1} years old.", name, age);
// or
console.writeline(name + " is " + age + " years old.");
int c = console.read(); // read single char
console.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:/myfile.txt")
dim line as string = reader.readline()
while not line is nothing
console.writeline("line=" & line)
line = reader.readline()
end while
reader.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.write(num)
binwriter.close()
dim binreader as new binaryreader (file.openread("c:/myfile.dat"))
str = binreader.readstring()
num = binreader.readint32()
binreader.close()