Professional Documents
Culture Documents
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> */
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
VB.NET Constants C#
' 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#
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
&& || & | ^ !
String Concatenation
String Concatenation
&
+
VB.NET Choices C#
VB.NET Loops C#
Pre-test Loops: Pre-test Loops:
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);
VB.NET Arrays C#
' 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#
' 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 Namespaces C#
' or // or
VB.NET Structs C#
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#
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
' 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");
VB.NET Events C#
' 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#
' 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);
Console.WriteLine(goodStudents.First().Name); //
Sue
VB.NET Collections C#
VB.NET Attributes C#
' 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 }
<IsTested()> [IsTested]
Sub Move() void Move() {
' Do something... // Do something...
End Sub }
End Class }
' 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();
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];
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 */
Conversions Convertions
Java Constants C#
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; }
};
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
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;
Java Loops C#
do do
i++; i++;
while (i < 10); while (i < 10);
// 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]);
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); }
// 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#
// 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#
or
namespace Harding {
namespace Compsci {
namespace Graphics {
...
}
}
}
// Inheritance // Inheritance
class FootballGame extends Competition { class FootballGame : Competition {
... ...
} }
~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 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();
Java Properties C#
Java Structs C#
struct StudentRecord {
public string name;
public float gpa;
stu2.name = "Sue";
Console.WriteLine(stu.name); // Prints "Bob"
Console.WriteLine(stu2.name); // Prints "Sue"