You are on page 1of 29

VB.

NET Program Structure C#

Imports System using System;

Namespace Hello namespace Hello {


Class HelloWorld public class HelloWorld {
Overloads Shared Sub Main(ByVal args() As public static void Main(string[] args) {
String) string name = "C#";
Dim name As String = "VB.NET"
// See if an argument was passed from the
'See if an argument was passed from the command line
command line if (args.Length == 1)
If args.Length = 1 Then name = args(0) name = args[0];

Console.WriteLine("Hello, " & name & "!") Console.WriteLine("Hello, " + name + "!");
End Sub }
End Class }
End Namespace }

VB.NET Comments C#

// Single line
' Single line only /* Multiple
line */
REM Single line only /// <summary>XML comments on single
line</summary>
''' <summary>XML comments</summary> /** <summary>XML comments on multiple
lines</summary> */

VB.NET Data Types C#

Value Types Value Types


Boolean bool
Byte, SByte byte, sbyte
Char char
Short, UShort, Integer, UInteger, Long, ULong short, ushort, int, uint, long, ulong
Single, Double float, double
Decimal decimal
Date (alias of System.DateTime) DateTime (not a built-in C# type)
structures structs
enumerations enumerations

Reference Types Reference Types


objects objects
String string
arrays arrays
delegates delegates

Initializing Initializing
Dim correct As Boolean = True bool correct = true;
Dim b As Byte = &H2A 'hex or &O52 for octal byte b = 0x2A; // hex
Dim person As Object = Nothing object person = null;
Dim name As String = "Dwight" string name = "Dwight";
Dim grade As Char = "B"c char grade = 'B';
Dim today As Date = #12/31/2010 12:15:00 PM# DateTime today = DateTime.Parse("12/31/2010
Dim amount As Decimal = 35.99@ 12:15:00 PM");
Dim gpa As Single = 2.9! decimal amount = 35.99m;
Dim pi As Double = 3.14159265 float gpa = 2.9f;
Dim lTotal As Long = 123456L double pi = 3.14159265; // or 3.14159265D
Dim sTotal As Short = 123S long lTotal = 123456L;
Dim usTotal As UShort = 123US short sTotal = 123;
Dim uiTotal As UInteger = 123UI ushort usTotal = 123;
Dim ulTotal As ULong = 123UL uint uiTotal = 123; // or 123U
ulong ulTotal = 123; // or 123UL
Nullable Types
Dim x? As Integer = Nothing Nullable Types
int? x = null;
Anonymous Types
Dim stu = New With {.Name = "Sue", .Gpa = 3.4} Anonymous Types
Dim stu2 = New With {Key .Name = "Bob", .Gpa = var stu = new {Name = "Sue", Gpa = 3.5};
2.9} var stu2 = new {Name = "Bob", Gpa = 2.9}; // no
Key equivalent
Implicitly Typed Local Variables
Dim s = "Hello!" Implicitly Typed Local Variables
Dim nums = New Integer() {1, 2, 3} var s = "Hello!";
Dim hero = New SuperHero With {.Name = "Batman"} var nums = new int[] { 1, 2, 3 };
var hero = new SuperHero() { Name = "Batman" };
Type Information
Dim x As Integer Type Information
Console.WriteLine(x.GetType()) ' System.Int32 int x;
Console.WriteLine(GetType(Integer)) ' System.Int32 Console.WriteLine(x.GetType()); //
Console.WriteLine(TypeName(x)) ' Integer System.Int32
Console.WriteLine(typeof(int)); //
Dim c as New Circle System.Int32
isShape = TypeOf c Is Shape ' True if c is a Shape Console.WriteLine(x.GetType().Name); // Int32

isSame = o1 Is o2 // True if o1 and o2 reference Circle c = new Circle();


same object isShape = c is Shape; // true if c is a Shape

Type Conversion / Casting isSame = Object.ReferenceEquals(o1, o2) // true if


Dim d As Single = 3.5 o1 and o2 reference same object
Dim i As Integer = CType(d, Integer) ' set to 4
(Banker's rounding) Type Conversion / Casting
i = CInt(d) ' same result as CType float d = 3.5f;
i = Int(d) ' set to 3 (Int function truncates the i = Convert.ToInt32(d); // Set to 4 (rounds)
decimal) int i = (int)d; // set to 3 (truncates decimal)

Dim s As New Shape


Dim c As Circle = TryCast(s, Circle) ' Returns Shape s = new Shape();
Nothing if type cast fails Circle c = s as Circle; // Returns null if type cast fails
c = DirectCast(s, Circle) ' Throws c = (Circle)s; // Throws InvalidCastException if type
InvalidCastException if type cast fails cast fails

VB.NET Constants C#

Const MAX_STUDENTS As Integer = 25 const int MAX_STUDENTS = 25;

' Can set to a const or var; may be initialized in a // Can set to a const or var; may be initialized in a
constructor constructor
ReadOnly MIN_DIAMETER As Single = 4.93 readonly float MIN_DIAMETER = 4.93f;

VB.NET Enumerations C#

Enum Action enum Action {Start, Stop, Rewind, Forward};


Start enum Status {Flunk = 50, Pass = 70, Excel = 90};
[Stop] ' Stop is a reserved word
Rewind Action a = Action.Stop;
Forward if (a != Action.Start)
End Enum Console.WriteLine(a + " is " + (int) a); // "Stop is 1"

Enum Status Console.WriteLine((int) Status.Pass); // 70


Flunk = 50 Console.WriteLine(Status.Pass); // Pass
Pass = 70
Excel = 90
End Enum

Dim a As Action = Action.Stop


If a <> Action.Start Then _
Console.WriteLine(a.ToString & " is " & a) ' "Stop
is 1"

Console.WriteLine(Status.Pass) ' 70
Console.WriteLine(Status.Pass.ToString) ' Pass

VB.NET Operators C#

Comparison
Comparison
== < > <= >= !=
= < > <= >= <>

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

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

Bitwise
Bitwise
And Or Xor Not << >>
& | ^ ~ << >>

Logical
Logical
AndAlso OrElse And Or Xor Not
&& || & | ^ !

Note: AndAlso and OrElse perform short-circuit logical


Note: && and || perform short-circuit logical
evaluations
evaluations

String Concatenation
String Concatenation
&
+
VB.NET Choices C#

' Null-coalescing operator if called with 2 arguments // Null-coalescing operator


x = If(y, 5) ' if y is not Nothing then x = y, else x = 5 x = y ?? 5; // if y != null then x = y, else x = 5

' Ternary/Conditional operator (IIf evaluates 2nd and // Ternary/Conditional operator


3rd expressions) greeting = age < 20 ? "What's up?" : "Hello";
greeting = If(age < 20, "What's up?", "Hello")
if (age < 20)
' One line doesn't require "End If" greeting = "What's up?";
If age < 20 Then greeting = "What's up?" else
If age < 20 Then greeting = "What's up?" Else greeting = "Hello";
greeting = "Hello"
// Multiple statements must be enclosed in {}
' Use : to put two commands on same line if (x != 100 && y < 5) {
If x <> 100 AndAlso y < 5 Then x *= 5 : y *= 2 x *= 5;
y *= 2;
' Preferred }
If x <> 100 AndAlso y < 5 Then
x *= 5
y *= 2
End If No need for _ or : since ; is used to terminate each
statement.
' Use _ to break up long single line or use implicit line
break
If whenYouHaveAReally < longLine And
itNeedsToBeBrokenInto2 > Lines Then _ if (x > 5)
UseTheUnderscore(charToBreakItUp) x *= y;
else if (x == 5 || y % 2 == 0)
'If x > 5 Then x += y;
x *= y else if (x < 10)
ElseIf x = 5 OrElse y Mod 2 = 0 Then x -= y;
x += y else
ElseIf x < 10 Then x /= y;
x -= y
Else
x /= y
End If // Every case must end with break or goto case
switch (color) { // Must be integer or
Select Case color ' Must be a primitive data type string
Case "pink", "red" case "pink":
r += 1 case "red": r++; break;
Case "blue" case "blue": b++; break;
b += 1 case "green": g++; break;
Case "green" default: other++; break; // break necessary
g += 1 on default
Case Else }
other += 1
End Select

VB.NET Loops C#
Pre-test Loops: Pre-test Loops:

While c < 10 Do Until c = 10 // no "until" keyword


c += 1 c += 1 while (c < 10)
End While Loop c++;

Do While c < 10 For c = 2 To 10 Step 2


c += 1 Console.WriteLine(c) for (c = 2; c <= 10; c += 2)
Loop Next Console.WriteLine(c);

Post-test Loops:
Post-test Loop:
Do Do
c += 1 c += 1 do
Loop While c < 10 Loop Until c = 10 c++;
while (c < 10);

' Array or collection looping


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

' Breaking out of loops


Dim i As Integer = 0 // Breaking out of loops
While (True) int i = 0;
If (i = 5) Then Exit While while (true) {
i += 1 if (i == 5)
End While break;
i++;
}
' Continue to next iteration
For i = 0 To 4 // Continue to next iteration
If i < 4 Then Continue For for (i = 0; i <= 4; i++) {
Console.WriteLine(i) ' Only prints 4 if (i < 4)
Next continue;
Console.WriteLine(i); // Only prints 4
}

VB.NET Arrays 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] = "David";
names(0) = "David" names[5] = "Bobby"; // Throws
names(5) = "Bobby" ' Throws System.IndexOutOfRangeException
System.IndexOutOfRangeException
// Add two elements, keeping the existing values
' Resize the array, keeping the existing values Array.Resize(ref names, 7);
(Preserve is optional)
ReDim Preserve names(6) float[,] twoD = new float[rows, cols];
Dim twoD(rows-1, cols-1) As Single twoD[2,0] = 4.5f;
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 jagged[0][4] = 5;
Integer(2) {} }
jagged(0)(4) = 5

VB.NET Functions C#

' Pass by value (in, default), reference (in/out), // Pass by value (in, default), reference (in/out),
and reference (out) and reference (out)
Sub TestFunc(ByVal x As Integer, ByRef y As void TestFunc(int x, ref int y, out int z) {
Integer, ByRef z As Integer) x++;
x += 1 y++;
y += 1 z = 5;
z=5 }
End Sub
int a = 1, b = 1, c; // c doesn't need initializing
Dim a = 1, b = 1, c As Integer ' c set to zero by TestFunc(a, ref b, out c);
default Console.WriteLine("{0} {1} {2}", a, b, c); // 1 2 5
TestFunc(a, b, c)
Console.WriteLine("{0} {1} {2}", a, b, c) ' 1 2 5 // Accept variable number of arguments
int Sum(params int[] nums) {
' Accept variable number of arguments int sum = 0;
Function Sum(ByVal ParamArray nums As foreach (int i in nums)
Integer()) As Integer sum += i;
Sum = 0 return sum;
For Each i As Integer In nums }
Sum += i
Next int total = Sum(4, 3, 2, 1); // returns 10
End Function ' Or use Return statement like C#
/* C# 4.0 supports optional parameters. Previous
Dim total As Integer = Sum(4, 3, 2, 1) ' returns 10 versions required function overloading. */
void SayHello(string name, string prefix = "") {
' Optional parameters must be listed last and must Console.WriteLine("Greetings, " + prefix + " " +
have a default value name);
Sub SayHello(ByVal name As String, Optional ByVal }
prefix As String = "")
Console.WriteLine("Greetings, " & prefix & " " & SayHello("Strangelove", "Dr.");
name) SayHello("Mom");
End Sub

SayHello("Strangelove", "Dr.")
SayHello("Mom")

VB.NET Strings C#

Special character constants (all also accessible from Escape sequences


ControlChars class) \r // carriage-return
vbCrLf, vbCr, vbLf, vbNewLine \n // line-feed
vbNullString \t // tab
vbTab \\ // backslash
vbBack \" // quote
vbFormFeed
vbVerticalTab
"" // String concatenation
string school = "Harding\t";
' String concatenation (use & or +) school = school + "University"; // school is "Harding
Dim school As String = "Harding" & vbTab (tab) University"
school = school & "University" ' school is "Harding school += "University"; // Same thing
(tab) University"
school &= "University" ' Same thing (+= does the // Chars
same) char letter = school[0]; // letter is H
letter = 'Z'; // letter is Z
' Chars letter = Convert.ToChar(65); // letter is A
Dim letter As Char = school.Chars(0) ' letter is H letter = (char)65; // same thing
letter = "Z"c ' letter is Z char[] word = school.ToCharArray(); // word holds
letter = Convert.ToChar(65) ' letter is A Harding
letter = Chr(65) ' same thing
Dim word() As Char = school.ToCharArray ' word holds // String literal
Harding string filename = @"c:\temp\x.dat"; // Same as
"c:\\temp\\x.dat"
' No string literal operator
Dim filename As String = "c:\temp\x.dat" // String comparison
string mascot = "Bisons";
' String comparison if (mascot == "Bisons") // true
Dim mascot As String = "Bisons" if (mascot.Equals("Bisons")) // true
If (mascot = "Bisons") Then ' true if (mascot.ToUpper().Equals("BISONS")) // true
If (mascot.Equals("Bisons")) Then ' true if (mascot.CompareTo("Bisons") == 0) // true
If (mascot.ToUpper().Equals("BISONS")) Then ' true
If (mascot.CompareTo("Bisons") = 0) Then ' true // String matching - No Like equivalent, use Regex

' String matching with Like - Regex is more powerful


If ("John 3:16" Like "Jo[Hh]? #:*") Then 'true // Substring
s = mascot.Substring(2, 3)) // son
' Substring s = "testing".Substring(1, 3); // est (no Mid)
s = mascot.Substring(2, 3)) ' son
s = Mid("testing", 2, 3) ' est // Replacement
s = mascot.Replace("sons", "nomial")) // Binomial
' Replacement
s = mascot.Replace("sons", "nomial")) ' s is // Split
"Binomial" string names = "Michael,Dwight,Jim,Pam";
string[] parts = names.Split(",".ToCharArray()); //
' Split One name in each slot
Dim names As String = "Michael,Dwight,Jim,Pam"
Dim parts() As String = // Date to string
names.Split(",".ToCharArray()) ' One name in each DateTime dt = new DateTime(1973, 10, 12);
slot string s = dt.ToString("MMM dd, yyyy"); // Oct 12,
1973
' Date to string
Dim dt As New DateTime(1973, 10, 12) // int to string
Dim s As String = "My birthday: " & dt.ToString("MMM int x = 2;
dd, yyyy") ' Oct 12, 1973 string y = x.ToString(); // y is "2"

' Integer to String // string to int


Dim x As Integer = 2 int x = Convert.ToInt32("-5"); // x is -5
Dim y As String = x.ToString() ' y is "2"
// Mutable string
' String to Integer System.Text.StringBuilder buffer = new
System.Text.StringBuilder("two ");
Dim x As Integer = Convert.ToInt32("-5") ' x is -5
buffer.Append("three ");
buffer.Insert(0, "one ");
' Mutable string buffer.Replace("two", "TWO");
Dim buffer As New System.Text.StringBuilder("two ") Console.WriteLine(buffer); // Prints "one TWO three"
buffer.Append("three ")
buffer.Insert(0, "one ")
buffer.Replace("two", "TWO")
Console.WriteLine(buffer) ' Prints "one TWO
three"

VB.NET Regular Expressions C#

Imports System.Text.RegularExpressions using System.Text.RegularExpressions;

' Match a string pattern // Match a string pattern


Dim r As New Regex("j[aeiou]h?. \d:*", Regex r = new Regex(@"j[aeiou]h?. \d:*",
RegexOptions.IgnoreCase Or _ RegexOptions.IgnoreCase |
RegexOptions.Compiled) RegexOptions.Compiled);
If (r.Match("John 3:16").Success) Then 'true if (r.Match("John 3:16").Success) // true
Console.WriteLine("Match") Console.WriteLine("Match");
End If

' Find and remember all matching patterns // Find and remember all matching patterns
Dim s As String = "My number is 305-1881, not 305- string s = "My number is 305-1881, not 305-1818.";
1818." Regex r = new Regex("(\\d+-\\d+)");
Dim r As New Regex("(\d+-\d+)") // Matches 305-1881 and 305-1818
Dim m As Match = r.Match(s) ' Matches 305-1881 for (Match m = r.Match(s); m.Success; m =
and 305-1818 m.NextMatch())
While m.Success Console.WriteLine("Found number: " + m.Groups[1]
Console.WriteLine("Found number: " & + " at position " +
m.Groups(1).Value & " at position " _ m.Groups[1].Index);
& m.Groups(1).Index.ToString)
m = m.NextMatch()
End While
// Remeber multiple parts of matched pattern
' Remeber multiple parts of matched pattern Regex r = new Regex("@(\d\d):(\d\d) (am|pm)");
Dim r As New Regex("(\d\d):(\d\d) (am|pm)") Match m = r.Match("We left at 03:15 pm.");
Dim m As Match = r.Match("We left at 03:15 pm.") if (m.Success) {
If m.Success Then Console.WriteLine("Hour: " + m.Groups[1]); //
Console.WriteLine("Hour: " & m.Groups(1).ToString) 03
' 03 Console.WriteLine("Min: " + m.Groups[2]); //
Console.WriteLine("Min: " & m.Groups(2).ToString) 15
' 15 Console.WriteLine("Ending: " + m.Groups[3]); //
Console.WriteLine("Ending: " & pm
m.Groups(3).ToString) ' pm }
End If
// Replace all occurrances of a pattern
' Replace all occurrances of a pattern Regex r = new Regex("h\\w+?d",
Dim r As New Regex("h\w+?d", RegexOptions.IgnoreCase);
RegexOptions.IgnoreCase) string s = r.Replace("I heard this was HARD!",
Dim s As String = r.Replace("I heard this was HARD!", "easy")); // I easy this was easy!
"easy") ' I easy this was easy!
// Replace matched patterns
' Replace matched patterns string s = Regex.Replace("123 < 456", @"(\d+) .
Dim s As String = Regex.Replace("123 < 456", "(\d+) (\d+)", "$2 > $1"); // 456 > 123
. (\d+)", "$2 > $1") ' 456 > 123
// Split a string based on a pattern
' Split a string based on a pattern string names = "Michael, Dwight, Jim, Pam";
Dim names As String = "Michael, Dwight, Jim, Pam" Regex r = new Regex(@",\s*");
Dim r As New Regex(",\s*") string[] parts = r.Split(names); // One name in each
Dim parts() As String = r.Split(names) ' One name in slot
each slot

VB.NET Exception Handling C#

' Throw an exception // Throw an exception


Dim ex As New Exception("Something is really wrong.") Exception up = new Exception("Something is really
Throw ex wrong.");
throw up; // ha ha
' Catch an exception
Try // Catch an exception
y=0 try {
x = 10 / y y = 0;
Catch ex As Exception When y = 0 ' Argument and x = 10 / y;
When is optional }
Console.WriteLine(ex.Message) catch (Exception ex) { // Argument is optional, no
Finally "When" keyword
Beep() Console.WriteLine(ex.Message);
End Try }
finally {
' Deprecated unstructured error handling Microsoft.VisualBasic.Interaction.Beep();
On Error GoTo MyErrorHandler }
...
MyErrorHandler: Console.WriteLine(Err.Description)

VB.NET Namespaces C#

Namespace Harding.Compsci.Graphics namespace Harding.Compsci.Graphics {


... ...
End Namespace }

' or // or

Namespace Harding namespace Harding {


Namespace Compsci namespace Compsci {
Namespace Graphics namespace Graphics {
... ...
End Namespace }
End Namespace }
End Namespace }

Imports Harding.Compsci.Graphics using Harding.Compsci.Graphics;

VB.NET Classes & Interfaces C#


Access Modifiers Access Modifiers
Public public
Private private
Friend internal
Protected protected
Protected Friend protected internal

Class Modifiers Class Modifiers


MustInherit abstract
NotInheritable sealed
static
Method Modifiers
MustOverride Method Modifiers
NotInheritable abstract
Shared sealed
Overridable static
virtual
' All members are Shared
Module No Module equivalent - just use static class

' Partial classes // Partial classes


Partial Class Team partial class Team {
... ...
Protected name As String protected string name;
Public Overridable Sub DisplayName() public virtual void DislpayName() {
Console.WriteLine(name) Console.WriteLine(name);
End Sub }
End Class

' Inheritance // Inheritance


Class FootballTeam class FootballTeam : Team {
Inherits Team ...
... public override void DislpayName() {
Public Overrides Sub DisplayName() Console.WriteLine("** " + name + " **");
Console.WriteLine("** " + name + " **") }
End Sub }
End Class

' Interface definition // Interface definition


Interface IAlarmClock interface IAlarmClock {
Sub Ring() void Ring();
Property TriggerDateTime() As DateTime DateTime CurrentDateTime { get; set; }
End Interface }

' Extending an interface // Extending an interface


Interface IAlarmClock interface IAlarmClock : IClock {
Inherits IClock ...
... }
End Interface

' Interface implementation // Interface implementation


Class WristWatch class WristWatch : IAlarmClock, ITimer {
Implements IAlarmClock, ITimer
public void Ring() {
Public Sub Ring() Implements IAlarmClock.Ring Console.WriteLine("Wake up!");
Console.WriteLine("Wake up!") }
End Sub
public DateTime TriggerDateTime { get; set; }
Public Property TriggerDateTime As DateTime ...
Implements IAlarmClock.TriggerDateTime }
...
End Class

VB.NET Constructors & Destructors C#

Class SuperHero class SuperHero : Person {


Inherits Person
private int powerLevel;
Private powerLevel As Integer private string name;
Private name As String

' Default constructor // Default constructor


Public Sub New() public SuperHero() {
powerLevel = 0 powerLevel = 0;
name = "Super Bison" name = "Super Bison";
End Sub }

Public Sub New(ByVal powerLevel As Integer) public SuperHero(int powerLevel)


Me.New("Super Bison") ' Call other constructor : this("Super Bison") { // Call other constructor
Me.powerLevel = powerLevel this.powerLevel = powerLevel;
End Sub }

Public Sub New(ByVal name As String) public SuperHero(string name)


MyBase.New(name) ' Call base classes' : base(name) { // Call base classes' constructor
constructor this.name = name;
Me.name = name }
End Sub
static SuperHero() {
Shared Sub New() // Static constructor invoked before 1st instance is
' Shared constructor invoked before 1st instance is created
created }
End Sub
~SuperHero() {
Protected Overrides Sub Finalize() // Destructor implicitly creates a Finalize method
' Destructor to free unmanaged resources }
MyBase.Finalize()
End Sub }
End Class

VB.NET Using Objects C#


Dim hero As SuperHero = New SuperHero SuperHero hero = new SuperHero();
' or
Dim hero As New SuperHero

With hero // No "With" but can use object initializers


.Name = "SpamMan" SuperHero hero = new SuperHero() { Name =
.PowerLevel = 3 "SpamMan", PowerLevel = 3 };
End With
hero.Defend("Laura Jones");
hero.Defend("Laura Jones") SuperHero.Rest(); // Calling static method
hero.Rest() ' Calling Shared method
' or
SuperHero.Rest()
SuperHero hero2 = hero; // Both reference the same
Dim hero2 As SuperHero = hero ' Both reference the object
same object hero2.Name = "WormWoman";
hero2.Name = "WormWoman" Console.WriteLine(hero.Name); // Prints WormWoman
Console.WriteLine(hero.Name) ' Prints WormWoman
hero = null ; // Free the object
hero = Nothing ' Free the object
if (hero == null)
If hero Is Nothing Then _ hero = new SuperHero();
hero = New SuperHero
Object obj = new SuperHero();
Dim obj As Object = New SuperHero if (obj is SuperHero)
If TypeOf obj Is SuperHero Then _ Console.WriteLine("Is a SuperHero object.");
Console.WriteLine("Is a SuperHero object.")
// Mark object for quick disposal
' Mark object for quick disposal using (StreamReader reader =
Using reader As StreamReader = File.OpenText("test.txt")) {
File.OpenText("test.txt") string line;
Dim line As String = reader.ReadLine() while ((line = reader.ReadLine()) != null)
While Not line Is Nothing Console.WriteLine(line);
Console.WriteLine(line) }
line = reader.ReadLine()
End While
End Using

VB.NET Structs C#

Structure Student struct Student {


Public name As String public string name;
Public gpa As Single public float gpa;

Public Sub New(ByVal name As String, ByVal gpa As public Student(string name, float gpa) {
Single) this.name = name;
Me.name = name this.gpa = gpa;
Me.gpa = gpa }
End Sub }
End Structure
Student stu = new Student("Bob", 3.5f);
Dim stu As Student = New Student("Bob", 3.5) Student stu2 = stu;
Dim stu2 As Student = stu
stu2.name = "Sue";
stu2.name = "Sue" Console.WriteLine(stu.name); // Prints Bob
Console.WriteLine(stu.name) ' Prints Bob Console.WriteLine(stu2.name); // Prints Sue
Console.WriteLine(stu2.name) ' Prints Sue

VB.NET Properties C#

' Auto-implemented properties are new to VB10 // Auto-implemented properties


Public Property Name As String public string Name { get; set; }
Public Property Size As Integer = -1 ' Default public int Size { get; protected set; } // Set default
value, Get and Set both Public value in constructor

' Traditional property implementation // Traditional property implementation


Private mName As String private string name;
Public Property Name() As String public string Name {
Get get {
Return mName return name;
End Get }
Set(ByVal value As String) set {
mName = value name = value;
End Set }
End Property }

' Read-only property // Read-only property


Private mPowerLevel As Integer private int powerLevel;
Public ReadOnly Property PowerLevel() As Integer public int PowerLevel {
Get get {
Return mPowerLevel return powerLevel;
End Get }
End Property }

' Write-only property // Write-only property


Private mHeight As Double private double height;
Public WriteOnly Property Height() As Double public double Height {
Set(ByVal value As Double) set {
mHeight = If(value < 0, mHeight = 0, mHeight = height = value < 0 ? 0 : value;
value) }
End Set }
End Property

VB.NET Generics C#

' Enforce accepted data type at compile-time // Enforce accepted data type at compile-time
Dim numbers As New List(Of Integer) List<int> numbers = new List<int>();
numbers.Add(2) numbers.Add(2);
numbers.Add(4) numbers.Add(4);
DisplayList(Of Integer)(numbers) DisplayList<int>(numbers);

' Subroutine can display any type of List // Function can display any type of List
Sub DisplayList(Of T)(ByVal list As List(Of T)) void DisplayList<T>(List<T> list) {
For Each item As T In list foreach (T item in list)
Console.WriteLine(item) Console.WriteLine(item);
Next }
End Sub
// Class works on any data type
' Class works on any data type class SillyList<T> {
Class SillyList(Of T) private T[] list = new T[10];
Private list(10) As T private Random rand = new Random();
Private rand As New Random
public void Add(T item) {
Public Sub Add(ByVal item As T) list[rand.Next(10)] = item;
list(rand.Next(10)) = item }
End Sub
public T GetItem() {
Public Function GetItem() As T return list[rand.Next(10)];
Return list(rand.Next(10)) }
End Function }
End Class
// Limit T to only types that implement IComparable
' Limit T to only types that implement IComparable T Maximum<T>(params T[] items) where T :
Function Maximum(Of T As IComparable)(ByVal IComparable<T> {
ParamArray items As T()) As T T max = items[0];
Dim max As T = items(0) foreach (T item in items)
For Each item As T In items if (item.CompareTo(max) > 0)
If item.CompareTo(max) > 0 Then max = item max = item;
Next return max;
Return max }
End Function

VB.NET Delegates & Lambda Expressions C#

Delegate Sub HelloDelegate(ByVal s As String) delegate void HelloDelegate(string s);

Sub SayHello(ByVal s As String) void SayHello(string s) {


Console.WriteLine("Hello, " & s) Console.WriteLine("Hello, " + s);
End Sub }

' Create delegate that calls SayHello // C# 1.0 delegate syntax with named method
Dim hello As HelloDelegate = AddressOf SayHello HelloDelegate hello = new HelloDelegate(SayHello);
hello("World") ' Or hello.Invoke("World") hello("World"); // Or hello.Invoke("World");

' Use lambda expression (anonymous method) instead // C# 2.0 delegate syntax with anonymous method
of a delegate HelloDelegate hello2 = delegate(string s) {
Dim hello2 = Sub(x) Console.WriteLine("Hello, " & x) Console.WriteLine("Hello, " + s);
hello2("World") };
hello2("World");

// C# 3.0 delegate syntax with lambda expression


HelloDelegate hello3 = s => {
Console.WriteLine("Hello, " + s); };
hello3("World");
' Use Func(Of T, TResult) delegate to call Uppercase
Dim convert As Func(Of String, String) = AddressOf // Use Func<in T, out TResult> delegate to call
Uppercase Uppercase
Console.WriteLine(convert("test")) Func<string, string> convert = Uppercase;
Console.WriteLine(convert("test"));
Function Uppercase(s As String) As String
Return s.ToUpper string Uppercase(string s) {
End Function return s.ToUpper();
}
' Declare and invoke lambda expression
Console.WriteLine((Function(num As Integer) num + // Declare and invoke Func using a lambda expression
1)(2)) Console.WriteLine(new Func<int, int>(num => num +
' Pass lambda expression as an argument 1)(2));
TestValues(Function(x, y) x Mod y = 0)
// Pass lamba expression as an argument
Sub TestValues(ByVal f As Func(Of Integer, Integer, TestValues((x, y) => x % y == 0);
Boolean))
If f(8, 4) Then void TestValues(Func<int, int, bool> f) {
Console.WriteLine("true") if (f(8, 4))
Else Console.WriteLine("true");
Console.WriteLine("false") else
End If Console.WriteLine("false");
End Sub }

VB.NET Extension Methods C#

Imports System.Runtime.CompilerServices public static class StringExtensions {


public static int VowelCount(this string s) {
Module StringExtensions return s.Count(c =>
<Extension()> "aeiou".Contains(Char.ToLower(c)));
Public Function VowelCount(ByVal s As String) As }
Integer }
Return s.Count(Function(c)
"aeiou".Contains(Char.ToLower(c)))
End Function
End Module // Using the extension method
Console.WriteLine("This is a test".VowelCount());
' Using the extension method
Console.WriteLine("This is a test".VowelCount)

VB.NET Events 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 delegate // Delegates must be used with events in C#
implicitly
Event MsgArrivedEvent(ByVal message As String)
MsgArrivedEvent += new
AddHandler MsgArrivedEvent, AddressOf MsgArrivedEventHandler(My_MsgArrivedEventCallback);
My_MsgArrivedCallback MsgArrivedEvent("Test message"); // Throws
' Won't throw an exception if obj is Nothing exception if obj is null
RaiseEvent MsgArrivedEvent("Test message") MsgArrivedEvent -= new
RemoveHandler MsgArrivedEvent, AddressOf MsgArrivedEventHandler(My_MsgArrivedEventCallback);
My_MsgArrivedCallback

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

VB.NET LINQ C#

Dim nums() As Integer = {5, 8, 2, 1, 6} int[] nums = { 5, 8, 2, 1, 6 };

' Get all numbers in the array above 4 // Get all numbers in the array above 4
Dim results = From n In nums var results = from n in nums
Where n > 4 where n > 4
Select n select n;

' Same thing using lamba expression // Same thing using lamba expression
results = nums.Where(Function(n) n > 4) results = nums.Where(n => n > 4);

' Displays 5 8 6 // Displays 5 8 6


For Each n As Integer In results foreach (int n in results)
Console.Write(n & " ") Console.Write(n + " ");
Next

Console.WriteLine(results.Count()) '3 Console.WriteLine(results.Count()); // 3


Console.WriteLine(results.First()) '5 Console.WriteLine(results.First()); // 5
Console.WriteLine(results.Last()) '6 Console.WriteLine(results.Last()); // 6
Console.WriteLine(results.Average()) ' 6.33333 Console.WriteLine(results.Average()); // 6.33333

results = results.Intersect({5, 6, 7}) '56 results = results.Intersect(new[] {5, 6, 7}); // 5 6


results = results.Concat({5, 1, 5}) '56515 results = results.Concat(new[] {5, 1, 5}); // 5 6 5 1
results = results.Distinct() '561 5
results = results.Distinct(); // 5 6 1
Dim Students() As Student = {
New Student With {.Name = "Bob", .Gpa = 3.5}, Student[] Students = {
New Student With {.Name = "Sue", .Gpa = 4.0}, new Student{ Name = "Bob", Gpa = 3.5 },
New Student With {.Name = "Joe", .Gpa = 1.9} new Student{ Name = "Sue", Gpa = 4.0 },
} new Student{ Name = "Joe", Gpa = 1.9 }
};
' Get a list of students ordered by Gpa with Gpa >= 3.0
Dim goodStudents = From s In Students // Get a list of students ordered by Gpa with Gpa >=
Where s.Gpa >= 3.0 3.0
Order By s.Gpa Descending var goodStudents = from s in Students
Select s where s.Gpa >= 3.0
orderby s.Gpa descending
Console.WriteLine(goodStudents.First.Name) ' Sue select s;

Console.WriteLine(goodStudents.First().Name); //
Sue

VB.NET Collections C#

Popular classes in System.Collections (stored as Popular classes in System.Collections (stored as Object)


Object) ArrayList
ArrayList Hashtable
Hashtable Queue
Queue Stack
Stack
Popular classes in System.Collections.Generic (stored as
Popular classes in System.Collections.Generic (stored type T)
as type T) List<T>
List(Of T) SortedList<TKey, TValue>
SortedList(Of TKey, TValue) Dictionary<TKey, TValue>
Dictionary(Of TKey, TValue) Queue<T>
Queue(Of T) Stack<T>
Stack(Of T)
Popular classes in System.Collections.Concurrent
Popular classes in System.Collections.Concurrent (thread safe)
(thread safe) BlockingCollection<T>
BlockingCollection(Of T) ConcurrentDictionary<TKey, TValue>
ConcurrentDictionary(Of TKey, TValue) ConcurrentQueue<T>
ConcurrentQueue(Of T) ConcurrentStack<T>
ConcurrentStack(Of T)
No equivalent to Microsoft.VisualBasic.Collection
Microsoft.VisualBasic (not recommended)
Collection
// Store ID and name
var students = new Dictionary<int, string>
' Store ID and name {
Dim students As New Dictionary(Of Integer, String) { 123, "Bob" },
From { 444, "Sue" },
{ { 555, "Jane" }
{123, "Bob"}, };
{444, "Sue"},
{555, "Jane"} students.Add(987, "Gary");
} Console.WriteLine(students[444]); // Sue

students.Add(987, "Gary") // Display all


Console.WriteLine(students(444)) ' Sue foreach (var stu in students) {
Console.WriteLine(stu.Key + " = " + stu.Value);
' Display all }
For Each stu In students
Console.WriteLine(stu.Key & " = " & stu.Value)
Next // Method iterator for custom iteration over a collection
static
' Method iterator for custom iteration over a collection System.Collections.Generic.IEnumerable<int>
Iterator Function OddNumbers(ByVal lastNum As OddNumbers(int lastNum)
Integer) As System.Collections.IEnumerable {
For num = 1 To lastNum for (var num = 1; num <= lastNum; num++)
If num Mod 2 = 1 Then if (num % 2 == 1)
Yield num yield return num;
End If }
Next
End Function // 1 3 5 7
foreach (double num in OddNumbers(7))
'1357 {
For Each num In OddNumbers(7) Console.Write(num + " ");
Console.Write(num & " ") }
Next

VB.NET Attributes C#

' Attribute can be applied to anything // Attribute can be applied to anything


Public Class IsTestedAttribute public class IsTestedAttribute : Attribute
Inherits Attribute {
End Class }

' Attribute can only be applied to classes or structs // Attribute can only be applied to classes or structs
< AttributeUsage(AttributeTargets.Class Or [AttributeUsage(AttributeTargets.Class |
AttributeTargets.Struct)> AttributeTargets.Struct)]
Public Class AuthorAttribute public class AuthorAttribute : Attribute {
Inherits Attribute
public string Name { get; set; }
Public Property Name As String public int Version { get; set; }
Public Property Version As Integer = 0
public AuthorAttribute(string name) {
Public Sub New(ByVal name As String) Name = name;
Me.Name = name Version = 0;
End Sub }
End Class }

<Author("Sue", Version:=3)> [Author("Sue", Version = 3)]


Class Shape class Shape {

<IsTested()> [IsTested]
Sub Move() void Move() {
' Do something... // Do something...
End Sub }
End Class }

VB.NET Console I/O C#

Console.Write("What's your name? ") Console.Write("What's your name? ");


Dim name As String = Console.ReadLine() string name = Console.ReadLine();
Console.Write("How old are you? ") Console.Write("How old are you? ");
Dim age As Integer = Val(Console.ReadLine()) int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("{0} is {1} years old.", name, age) Console.WriteLine("{0} is {1} years old.", name, age);
' or // or
Console.WriteLine(name & " is " & age & " years old.") 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" int c = Console.Read(); // Read single char
Console.WriteLine(c); // Prints 65 if user enters "A"

VB.NET File I/O C#

Imports System.IO using System.IO;

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


Dim writer As StreamWriter = StreamWriter writer =
File.CreateText("c:\myfile.txt") File.CreateText("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 = StreamReader reader =
File.OpenText("c:\myfile.txt") File.OpenText("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 binWriter = new
BinaryWriter(File.OpenWrite("c:\myfile.dat")) BinaryWriter(File.OpenWrite("c:\\myfile.dat"));
binWriter.Write(str) binWriter.Write(str);
binWriter.Write(num) binWriter.Write(num);
binWriter.Close() binWriter.Close();

' Read from binary file // Read from binary file


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

This work is licensed under a Creative Commons License.


Last modified: April 4, 2016

Produced by Frank McCown, Harding University Computer Science Dept


Please send any corrections or comments to fmccown@harding.edu.

Home
Java Program Structure C#

using System;
package hello;
namespace Hello {
public class HelloWorld { public class HelloWorld {
public static void main(String[] args) { public static void Main(string[] args) {
String name = "Java"; string name = "C#";

// See if an argument was passed from the // See if an argument was passed from the
command line command line
if (args.length == 1) if (args.Length == 1)
name = args[0]; name = args[0];

System.out.println("Hello, " + name + "!"); Console.WriteLine("Hello, " + name + "!");


} }
} }
}

Java Comments C#

// Single line
// Single line
/* Multiple
/* Multiple
line */
line */
/// XML comments on a single line
/** Javadoc documentation comments */
/** XML comments on multiple lines */

Java Data Types C#

Primitive Types Value Types


boolean bool
byte byte, sbyte
char char
short, int, long short, ushort, int, uint, long, ulong
float, double float, double, decimal
structures, enumerations

Reference Types Reference Types


Object (superclass of all other classes) object (superclass of all other classes)
String string
arrays, classes, interfaces arrays, classes, interfaces, delegates

Conversions Convertions

// int to String // int to string


int x = 123; int x = 123;
String y = Integer.toString(x); // y is "123" String y = x.ToString(); // y is "123"

// String to int // string to int


y = "456"; y = "456";
x = Integer.parseInt(y); // x is 456 x = int.Parse(y); // or x = Convert.ToInt32(y);
// double to int // double to int
double z = 3.5; double z = 3.5;
x = (int) z; // x is 3 (truncates decimal) x = (int) z; // x is 3 (truncates decimal)

Java Constants C#

// May be initialized in a constructor const double PI = 3.14;


final double PI = 3.14;
// Can be set to a const or a variable. May be initialized
in a constructor.
readonly int MAX_HEIGHT = 9;

Java Enumerations C#

enum Action {Start, Stop, Rewind, Forward}; enum Action {Start, Stop, Rewind, Forward};

// Special type of class enum Status {Flunk = 50, Pass = 70, Excel = 90};
enum Status {
Flunk(50), Pass(70), Excel(90); No equivalent.
private final int value;
Status(int value) { this.value = value; }
public int value() { return value; }
};

Action a = Action.Stop; Action a = Action.Stop;


if (a != Action.Start) if (a != Action.Start)
System.out.println(a); // Prints "Stop" Console.WriteLine(a); // Prints "Stop"

Status s = Status.Pass; Status s = Status.Pass;


System.out.println(s.value()); // Prints "70" Console.WriteLine((int) s); // Prints "70"

Java Operators C#

Comparison Comparison
== < > <= >= != == < > <= >= !=

Arithmetic Arithmetic
+ - * / + - * /
% (mod) % (mod)
/ (integer division if both operands are ints) / (integer division if both operands are ints)
Math.Pow(x, y) Math.Pow(x, y)

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

Bitwise Bitwise
& | ^ ~ << >> >>> & | ^ ~ << >>

Logical Logical
&& || & | ^ ! && || & | ^ !
Note: && and || perform short-circuit logical Note: && and || perform short-circuit logical
evaluations evaluations

String Concatenation String Concatenation


+ +

Java Choices C#

greeting = age < 20 ? "What's up?" : "Hello"; greeting = age < 20 ? "What's up?" : "Hello";

if (x < y) if (x < y)
System.out.println("greater"); Console.WriteLine("greater");

if (x != 100) { if (x != 100) {
x *= 5; x *= 5;
y *= 2; y *= 2;
} }
else else
z *= 6; z *= 6;

int selection = 2; string color = "red";


switch (selection) { // Must be byte, short, int, switch (color) { // Can be any
char, or enum predefined type
case 1: x++; // Falls through to next case if case "red": r++; break; // break is
no break mandatory; no fall-through
case 2: y++; break; case "blue": b++; break;
case 3: z++; break; case "green": g++; break;
default: other++; default: other++; break; // break necessary
} on default
}

Java Loops C#

while (i < 10) while (i < 10)


i++; i++;

for (i = 2; i <= 10; i += 2) for (i = 2; i <= 10; i += 2)


System.out.println(i); Console.WriteLine(i);

do do
i++; i++;
while (i < 10); while (i < 10);

for (int i : numArray) // foreach construct foreach (int i in numArray)


sum += i; sum += i;

// for loop can be used to iterate through any // foreach can be used to iterate through any
Collection collection
import java.util.ArrayList; using System.Collections;
ArrayList<Object> list = new ArrayList<Object>(); ArrayList list = new ArrayList();
list.add(10); // boxing converts to instance of Integer list.Add(10);
list.add("Bisons"); list.Add("Bisons");
list.add(2.3); // boxing converts to instance of list.Add(2.3);
Double
foreach (Object o in list)
for (Object o : list) Console.WriteLine(o);
System.out.println(o);

Java Arrays C#

int nums[] = {1, 2, 3}; or int[] nums = {1, 2, 3}; int[] nums = {1, 2, 3};
for (int i = 0; i < nums.length; i++) for (int i = 0; i < nums.Length; i++)
System.out.println(nums[i]); Console.WriteLine(nums[i]);

String names[] = new String[5]; string[] names = new string[5];


names[0] = "David"; names[0] = "David";

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


twoD[2][0] = 4.5; twoD[2,0] = 4.5f;

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


jagged[0] = new int[5]; new int[5], new int[2], new int[3] };
jagged[1] = new int[2]; jagged[0][4] = 5;
jagged[2] = new int[3];
jagged[0][4] = 5;

Java Functions C#

// Return single value // Return no value // Return single value // Return no value
int Add(int x, int y) { void PrintSum(int x, int y) int Add(int x, int y) { void PrintSum(int x, int y)
return x + y; { return x + y; {
} System.out.println(x + } Console.WriteLine(x +
y); y);
int sum = Add(2, 3); } int sum = Add(2, 3); }

PrintSum(2, 3); PrintSum(2, 3);

// Primitive types and references are always passed by // Pass by value (default), in/out-reference (ref), and
value out-reference (out)
void TestFunc(int x, Point p) { void TestFunc(int x, ref int y, out int z, Point p1, ref
x++; Point p2) {
p.x++; // Modifying property of the object x++; y++; z = 5;
p = null; // Remove local reference to object p1.x++; // Modifying property of the object
} p1 = null; // Remove local reference to object
p2 = null; // Free the object
class Point { }
public int x, y;
} class Point {
public int x, y;
Point p = new Point(); }
p.x = 2;
int a = 1; Point p1 = new Point();
TestFunc(a, p); Point p2 = new Point();
System.out.println(a + " " + p.x + " " + (p == null) ); p1.x = 2;
// 1 3 false int a = 1, b = 1, c; // Output param doesn't need
initializing
TestFunc(a, ref b, out c, p1, ref p2);
Console.WriteLine("{0} {1} {2} {3} {4}",
a, b, c, p1.x, p2 == null); // 1 2 5 3 True
// Accept variable number of arguments
int Sum(int ... nums) { // Accept variable number of arguments
int sum = 0; int Sum(params int[] nums) {
for (int i : nums) int sum = 0;
sum += i; foreach (int i in nums)
return sum; sum += i;
} return sum;
}
int total = Sum(4, 3, 2, 1); // returns 10
int total = Sum(4, 3, 2, 1); // returns 10

Java Strings C#

// String concatenation // String concatenation


String school = "Harding "; string school = "Harding ";
school = school + "University"; // school is "Harding school = school + "University"; // school is "Harding
University" University"

// String comparison // String comparison


String mascot = "Bisons"; string mascot = "Bisons";
if (mascot == "Bisons") // Not the correct way to do if (mascot == "Bisons") // true
string comparisons if (mascot.Equals("Bisons")) // true
if (mascot.equals("Bisons")) // true if (mascot.ToUpper().Equals("BISONS")) // true
if (mascot.equalsIgnoreCase("BISONS")) // true if (mascot.CompareTo("Bisons") == 0) // true
if (mascot.compareTo("Bisons") == 0) // true
Console.WriteLine(mascot.Substring(2, 3)); // Prints
System.out.println(mascot.substring(2, 5)); // Prints "son"
"son"
// My birthday: Oct 12, 1973
// My birthday: Oct 12, 1973 DateTime dt = new DateTime(1973, 10, 12);
java.util.Calendar c = new string s = "My birthday: " + dt.ToString("MMM dd,
java.util.GregorianCalendar(1973, 10, 12); yyyy");
String s = String.format("My birthday: %1$tb %1$te,
%1$tY", c); // Mutable string
System.Text.StringBuilder buffer = new
// Mutable string System.Text.StringBuilder("two ");
StringBuffer buffer = new StringBuffer("two "); buffer.Append("three ");
buffer.append("three "); buffer.Insert(0, "one ");
buffer.insert(0, "one "); buffer.Replace("two", "TWO");
buffer.replace(4, 7, "TWO"); Console.WriteLine(buffer); // Prints "one TWO three"
System.out.println(buffer); // Prints "one TWO
three"
Java Exception Handling C#

// Must be in a method that is declared to throw this Exception up = new Exception("Something is really
exception wrong.");
Exception ex = new Exception("Something is really throw up; // ha ha
wrong.");
throw ex;
try {
try { y = 0;
y = 0; x = 10 / y;
x = 10 / y; } catch (Exception ex) { // Variable "ex" is optional
} catch (Exception ex) { Console.WriteLine(ex.Message);
System.out.println(ex.getMessage()); } finally {
} finally { // Code that always gets executed
// Code that always gets executed }
}

Java Namespaces C#

package harding.compsci.graphics; namespace Harding.Compsci.Graphics {


...
}

or

namespace Harding {
namespace Compsci {
namespace Graphics {
...
}
}
}

// Import single class // Import single class


import harding.compsci.graphics.Rectangle; using Rectangle =
Harding.CompSci.Graphics.Rectangle;
// Import all classes
import harding.compsci.graphics.*; // Import all class
using Harding.Compsci.Graphics;

Java Classes / Interfaces C#

Accessibility keywords Accessibility keywords


public public
private private
protected internal
static protected
protected internal
static

// Inheritance // Inheritance
class FootballGame extends Competition { class FootballGame : Competition {
... ...
} }

// Interface definition // Interface definition


interface IAlarmClock { interface IAlarmClock {
... ...
} }

// Extending an interface // Extending an interface


interface IAlarmClock extends IClock { interface IAlarmClock : IClock {
... ...
} }

// Interface implementation // Interface implementation


class WristWatch implements IAlarmClock, ITimer { class WristWatch : IAlarmClock, ITimer {
... ...
} }

Java Constructors / Destructors C#

class SuperHero { class SuperHero {


private int mPowerLevel; private int mPowerLevel;

public SuperHero() { public SuperHero() {


mPowerLevel = 0; mPowerLevel = 0;
} }

public SuperHero(int powerLevel) { public SuperHero(int powerLevel) {


this.mPowerLevel= powerLevel; this.mPowerLevel= powerLevel;
} }

~SuperHero() {
// No destructors, just override the finalize method
// Destructor code to free unmanaged resources.
protected void finalize() throws Throwable {
// Implicitly creates a Finalize method.
super.finalize(); // Always call parent's finalizer
}
}
}
}

Java Objects C#

SuperHero hero = new SuperHero(); SuperHero hero = new SuperHero();

hero.setName("SpamMan"); hero.Name = "SpamMan";


hero.setPowerLevel(3); hero.PowerLevel = 3;

hero.Defend("Laura Jones"); hero.Defend("Laura Jones");


SuperHero.Rest(); // Calling static method SuperHero.Rest(); // Calling static method

SuperHero hero2 = hero; // Both refer to same object SuperHero hero2 = hero; // Both refer to same object
hero2.setName("WormWoman"); hero2.Name = "WormWoman";
System.out.println(hero.getName()); // Prints Console.WriteLine(hero.Name); // Prints
WormWoman WormWoman

hero = null; // Free the object hero = null ; // Free the object
if (hero == null) if (hero == null)
hero = new SuperHero(); hero = new SuperHero();

Object obj = new SuperHero(); Object obj = new SuperHero();


System.out.println("object's type: " + Console.WriteLine("object's type: " +
obj.getClass().toString()); obj.GetType().ToString());
if (obj instanceof SuperHero) if (obj is SuperHero)
System.out.println("Is a SuperHero object."); Console.WriteLine("Is a SuperHero object.");

Java Properties C#

private int mSize; private int mSize;

public int getSize() { return mSize; } public int Size {


public void setSize(int value) { get { return mSize; }
if (value < 0) set {
mSize = 0; if (value < 0)
else mSize = 0;
mSize = value; else
} mSize = value;
}
}
int s = shoe.getSize();
shoe.setSize(s+1); shoe.Size++;

Java Structs C#

struct StudentRecord {
public string name;
public float gpa;

No structs in Java. 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"

Java Console I/O C#


java.io.DataInput in = new Console.Write("What's your name? ");
java.io.DataInputStream(System.in); string name = Console.ReadLine();
System.out.print("What is your name? "); Console.Write("How old are you? ");
String name = in.readLine(); int age = Convert.ToInt32(Console.ReadLine());
System.out.print("How old are you? "); Console.WriteLine("{0} is {1} years old.", name, age);
int age = Integer.parseInt(in.readLine()); // or
System.out.println(name + " is " + age + " years Console.WriteLine(name + " is " + age + " years old.");
old.");
int c = Console.Read(); // Read single char
Console.WriteLine(c); // Prints 65 if user enters "A"
int c = System.in.read(); // Read single char
System.out.println(c); // Prints 65 if user enters "A" // The studio costs $499.00 for 3 months.
Console.WriteLine("The {0} costs {1:C} for {2}
// The studio costs $499.00 for 3 months. months.\n", "studio", 499.0, 3);
System.out.printf("The %s costs $%.2f for %d
months.%n", "studio", 499.0, 3); // Today is 06/25/2004
Console.WriteLine("Today is " +
// Today is 06/25/04 DateTime.Now.ToShortDateString());
System.out.printf("Today is %tD\n", new
java.util.Date());

Java File I/O C#

import java.io.*; using System.IO;

// Character stream writing // Character stream writing


FileWriter writer = new FileWriter("c:\\myfile.txt"); StreamWriter writer =
writer.write("Out to file.\n"); File.CreateText("c:\\myfile.txt");
writer.close(); writer.WriteLine("Out to file.");
writer.Close();
// Character stream reading
FileReader reader = new FileReader("c:\\myfile.txt"); // Character stream reading
BufferedReader br = new BufferedReader(reader); StreamReader reader =
String line = br.readLine(); File.OpenText("c:\\myfile.txt");
while (line != null) { string line = reader.ReadLine();
System.out.println(line); while (line != null) {
line = br.readLine(); Console.WriteLine(line);
} line = reader.ReadLine();
reader.close(); }
reader.Close();
// Binary stream writing
FileOutputStream out = new
FileOutputStream("c:\\myfile.dat"); // Binary stream writing
out.write("Text data".getBytes()); BinaryWriter out = new
out.write(123); BinaryWriter(File.OpenWrite("c:\\myfile.dat"));
out.close(); out.Write("Text data");
out.Write(123);
// Binary stream reading out.Close();
FileInputStream in = new
FileInputStream("c:\\myfile.dat"); // Binary stream reading
byte buff[] = new byte[9]; BinaryReader in = new
in.read(buff, 0, 9); // Read first 9 bytes into buff BinaryReader(File.OpenRead("c:\\myfile.dat"));
String s = new String(buff); string s = in.ReadString();
int num = in.read(); // Next is 123 int num = in.ReadInt32();
in.close(); in.Close();

You might also like