And C# Comparison
And C# Comparison
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html
Program Structure
Comments
Data Types
Constants
Enumerations
Operators
Choices
Loops
Arrays
Functions
Strings
Regular Expressions
Exception Handling
Namespaces
VB.N ET
Program Structure
Imports System
using System;
Namespace Hello
Class HelloWorld
Overloads Shared Sub Main(ByVal args() As String)
Dim name As String = "VB.NET"
namespace Hello {
public class HelloWorld {
public static void Main(string[] args) {
string name = "C#";
C#
VB.N ET
VB.N ET
Value Types
Boolean
Byte, SByte
Char
Short, UShort, Integer, UInteger, Long, ULong
Single, Double
Decimal
Date (alias of System.DateTime)
structures
1 of 14
Comments
C#
// Single line
/* Multiple
line */
/// <summary>XML comments on single line</summary>
/** <summary>XML comments on multiple lines</summary> */
Data Types
C#
Value Types
bool
byte, sbyte
char
short, ushort, int, uint, long, ulong
float, double
decimal
DateTime (not a built-in C# type)
structs
8/22/2014 9:50 AM
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html
enumerations
enumerations
Reference Types
Object
String
arrays
delegates
Reference Types
object
string
arrays
delegates
Initializing
Dim correct As Boolean = True
Dim b As Byte = &H2A 'hex or &O52 for octal
Dim person As Object = Nothing
Dim name As String = "Dwight"
Dim grade As Char = "B"c
Dim today As Date = #12/31/2010 12:15:00 PM#
Dim amount As Decimal = 35.99@
Dim gpa As Single = 2.9!
Dim pi As Double = 3.14159265
Dim lTotal As Long = 123456L
Dim sTotal As Short = 123S
Dim usTotal As UShort = 123US
Dim uiTotal As UInteger = 123UI
Dim ulTotal As ULong = 123UL
Initializing
bool correct = true;
byte b = 0x2A; // hex
object person = null;
string name = "Dwight";
char grade = 'B';
DateTime today = DateTime.Parse("12/31/2010 12:15:00 PM");
decimal amount = 35.99m;
float gpa = 2.9f;
double pi = 3.14159265; // or 3.14159265D
long lTotal = 123456L;
short sTotal = 123;
ushort usTotal = 123;
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}
Dim stu2 = New With {Key .Name = "Bob", .Gpa = 2.9}
Anonymous Types
var stu = new {Name = "Sue", Gpa = 3.5};
var stu2 = new {Name = "Bob", Gpa = 2.9}; // no Key equivalent
Type Information
Dim x As Integer
Console.WriteLine(x.GetType())
' Prints System.Int32
Console.WriteLine(GetType(Integer)) ' Prints System.Int32
Console.WriteLine(TypeName(x))
' Prints Integer
Type Information
int x;
Console.WriteLine(x.GetType());
// Prints System.Int32
Console.WriteLine(typeof(int));
// Prints System.Int32
Console.WriteLine(x.GetType().Name); // prints Int32
VB.N ET
Constants
C#
VB.N ET
2 of 14
Enumerations
C#
8/22/2014 9:50 AM
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html
Enum Action
Start
[Stop] ' Stop is a reserved word
Rewind
Forward
End Enum
Enum Status
Flunk = 50
Pass = 70
Excel = 90
End Enum
Action a = Action.Stop;
if (a != Action.Start)
Console.WriteLine(a + " is " + (int) a);
Console.WriteLine(Status.Pass)
' Prints 70
Console.WriteLine(Status.Pass.ToString())
' Prints Pass
Operators
VB.N ET
Comparison
= < > <= >= <>
Comparison
== < > <= >= !=
Arithmetic
+ - * /
Mod
\ (integer division)
^ (raise to a power)
Arithmetic
+ - * /
% (mod)
/ (integer division if both operands are ints)
Math.Pow(x, y)
Assignment
= += -= *= /= \= ^= <<= >>= &=
Assignment
= += -= *= /= %= &= |= ^= <<= >>= ++ --
Bitwise
And Or Xor Not
Bitwise
& | ^
<<
>>
<<
>>
Logical
AndAlso OrElse And Or Xor Not
Logical
&& || & | ^ !
String Concatenation
&
String Concatenation
+
VB.N ET
Choices
// Null-coalescing operator
x = y ?? 5; // if y != null then x = y, else x = 5
// Ternary/Conditional operator
greeting = age < 20 ? "What's up?" : "Hello";
3 of 14
C#
C#
8/22/2014 9:50 AM
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html
' Use _ to break up long single line or use implicit line break
If whenYouHaveAReally < longLine And
itNeedsToBeBrokenInto2 > Lines Then _
UseTheUnderscore(charToBreakItUp)
'If x > 5 Then
x *= y
ElseIf x = 5 OrElse y Mod 2 = 0 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
if (x > 5)
x *= y;
else if (x == 5 || y % 2 == 0)
x += y;
else if (x < 10)
x -= y;
else
x /= y;
Loops
VB.N ET
Pre-test Loops:
C#
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
// no "until" keyword
while (c < 10)
c++;
Post-test Loop:
Post-test Loops:
Do
c += 1
Loop While c < 10
do
c++;
while (c < 10);
4 of 14
Do
c += 1
Loop Until c = 10
8/22/2014 9:50 AM
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html
Arrays
VB.N ET
C#
' Resize the array, keeping the existing values (Preserve is optional)
ReDim Preserve names(6)
Functions
VB.N ET
C#
' Pass by value (in, default), reference (in/out), and reference (out)
// 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) void TestFunc(int x, ref int y, out int z) {
x++;
x += 1
y += 1
y++;
z=5
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
' 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("Mom")
VB.N ET
5 of 14
Strings
C#
Escape sequences
\r // carriage-return
\n // line-feed
\t // tab
\\ // backslash
\" // quote
8/22/2014 9:50 AM
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html
vbVerticalTab
""
// String concatenation
string school = "Harding\t";
school = school + "University"; // school is "Harding (tab) University"
school += "University"; // Same thing
' Chars
Dim letter As Char = school.Chars(0) ' letter is H
letter = "Z"c
' letter is Z
letter = Convert.ToChar(65)
' letter is A
letter = Chr(65)
' same thing
Dim word() As Char = school.ToCharArray() ' word holds Harding
// Chars
char letter = school[0];
// letter is H
letter = 'Z';
// letter is Z
letter = Convert.ToChar(65);
// letter is A
letter = (char)65;
// same thing
char[] word = school.ToCharArray(); // word holds Harding
// String literal
string filename = @"c:\temp\x.dat"; // Same as "c:\\temp\\x.dat"
// String comparison
string mascot = "Bisons";
if (mascot == "Bisons") // true
if (mascot.Equals("Bisons")) // true
if (mascot.ToUpper().Equals("BISONS")) // true
if (mascot.CompareTo("Bisons") == 0) // true
' Substring
s = mascot.Substring(2, 3)) ' s is "son"
// Substring
s = mascot.Substring(2, 3))
' Replacement
s = mascot.Replace("sons", "nomial")) ' s is "Binomial"
// Replacement
s = mascot.Replace("sons", "nomial"))
' Split
Dim names As String = "Michael,Dwight,Jim,Pam"
Dim parts() As String = names.Split(",".ToCharArray())
slot
' x is -5
VB.N ET
6 of 14
// Date to string
DateTime dt = new DateTime(1973, 10, 12);
string s = dt.ToString("MMM dd, yyyy");
// Oct 12, 1973
// int to string
int x = 2;
string y = x.ToString();
// y is "2"
// string to int
int x = Convert.ToInt32("-5");
' y is "2"
// s is "Binomial"
// Split
string names = "Michael,Dwight,Jim,Pam";
' One name in each string[] parts = names.Split(",".ToCharArray()); // One name in each slot
// s is "son"
// x is -5
// Mutable string
System.Text.StringBuilder buffer = new System.Text.StringBuilder("two
");
buffer.Append("three ");
buffer.Insert(0, "one ");
buffer.Replace("two", "TWO");
Console.WriteLine(buffer);
// Prints "one TWO three"
Regular Expressions
C#
Imports System.Text.RegularExpressions
using System.Text.RegularExpressions;
8/22/2014 9:50 AM
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html
' 03
' 15
' pm
VB.N ET
Exception Handling
C#
// Throw an exception
Exception up = new Exception("Something is really wrong.");
throw up; // ha ha
// Catch an exception
try {
y = 0;
x = 10 / y;
}
catch (Exception ex) { // Argument is optional, no "When" keyword
Console.WriteLine(ex.Message);
}
finally {
Microsoft.VisualBasic.Interaction.Beep();
}
VB.N ET
7 of 14
Namespaces
Namespace Harding.Compsci.Graphics
...
End Namespace
namespace Harding.Compsci.Graphics {
...
}
' or
// or
Namespace Harding
Namespace Compsci
Namespace Graphics
...
End Namespace
namespace Harding {
namespace Compsci {
namespace Graphics {
...
}
C#
8/22/2014 9:50 AM
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html
End Namespace
End Namespace
Imports Harding.Compsci.Graphics
using Harding.Compsci.Graphics;
VB.N ET
Access Modifiers
Public
Private
Friend
Protected
Protected Friend
Access Modifiers
public
private
internal
protected
protected internal
Class Modifiers
MustInherit
NotInheritable
Class Modifiers
abstract
sealed
static
Method Modifiers
MustOverride
NotInheritable
Shared
Overridable
Method Modifiers
abstract
sealed
static
virtual
// Partial classes
partial class Competition {
...
}
' Inheritance
Class FootballGame
Inherits Competition
...
End Class
// Inheritance
class FootballGame : Competition {
...
}
// Interface definition
interface IAlarmClock {
void Ring();
DateTime CurrentDateTime { get; set; }
}
// Extending an interface
interface IAlarmClock : IClock {
...
}
// Interface implementation
class WristWatch : IAlarmClock, ITimer {
public void Ring() {
Console.WriteLine("Wake up!");
}
VB.N ET
8 of 14
C#
C#
8/22/2014 9:50 AM
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html
Class SuperHero
Inherits Person
// Default constructor
public SuperHero() {
powerLevel = 0;
name = "Super Bison";
}
static SuperHero() {
// Static constructor invoked before 1st instance is created
}
VB.N ET
~SuperHero() {
// Destructor implicitly creates a Finalize method
}
}
Using Objects
hero.Defend("Laura Jones")
hero.Rest()
' Calling Shared method
' or
SuperHero.Rest()
hero.Defend("Laura Jones");
SuperHero.Rest(); // Calling static method
Dim hero2 As SuperHero = hero ' Both reference the same object
hero2.Name = "WormWoman"
Console.WriteLine(hero.Name) ' Prints WormWoman
hero = Nothing
9 of 14
C#
if (hero == null)
hero = new SuperHero();
8/22/2014 9:50 AM
VB.N ET
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html
Structs
Structure Student
Public name As String
Public gpa As Single
struct Student {
public string name;
public float gpa;
stu2.name = "Sue"
Console.WriteLine(stu.name) ' Prints Bob
Console.WriteLine(stu2.name) ' Prints Sue
stu2.name = "Sue";
Console.WriteLine(stu.name); // Prints Bob
Console.WriteLine(stu2.name); // Prints Sue
VB.N ET
Properties
VB.N ET
10 of 14
C#
// Auto-implemented properties
public string Name { get; set; }
public int Size { get; protected set; }
C#
Generics
C#
8/22/2014 9:50 AM
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html
public T GetItem() {
return list[rand.Next(10)];
}
}
VB.N ET
void SayHello(string s) {
Console.WriteLine("Hello, " + s);
}
C#
11 of 14
string Uppercase(string s) {
return s.ToUpper();
}
8/22/2014 9:50 AM
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html
Console.WriteLine("false")
End If
End Sub
VB.N ET
Console.WriteLine("false");
}
Events
MsgArrivedEvent += new
MsgArrivedEventHandler(My_MsgArrivedEventCallback);
MsgArrivedEvent("Test message"); // Throws exception if obj is null
MsgArrivedEvent -= new
MsgArrivedEventHandler(My_MsgArrivedEventCallback);
Imports System.Windows.Forms
Dim WithEvents MyButton As Button ' WithEvents can't be used on local
variable
MyButton = New Button
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
VB.N ET
12 of 14
C#
using System.Windows.Forms;
Button MyButton = new Button();
MyButton.Click += new System.EventHandler(MyButton_Click);
void MyButton_Click(object sender, System.EventArgs e) {
MessageBox.Show(this, "Button was clicked", "Info",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
LINQ
int[] nums = { 5, 8, 2, 1, 6 };
' Displays 5 8 6
For Each n As Integer In results
Console.Write(n & " ")
Next
// Displays 5 8 6
foreach (int n in results)
Console.Write(n + " ");
Console.WriteLine(results.Count())
'3
Console.WriteLine(results.First())
'5
Console.WriteLine(results.Last())
'6
Console.WriteLine(results.Average())
' 6.33333
Console.WriteLine(results.Count());
// 3
Console.WriteLine(results.First());
// 5
Console.WriteLine(results.Last());
// 6
Console.WriteLine(results.Average());
// 6.33333
Student[] Students = {
new Student{ Name = "Bob", Gpa = 3.5 },
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
C#
8/22/2014 9:50 AM
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html
' Sue
VB.N ET
Console.WriteLine(goodStudents.First().Name);
Attributes
C#
<Author("Sue", Version:=3)>
Class Shape
<IsTested()>
Sub Move()
' Do something...
End Sub
End Class
VB.N ET
[IsTested]
void Move() {
// Do something...
}
}
Console I/O
Dim c As Integer
c = Console.Read()
Console.WriteLine(c)
VB.N ET
13 of 14
// Sue
File I/O
Imports System.IO
using System.IO;
C#
C#
8/22/2014 9:50 AM
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html
Home
14 of 14
8/22/2014 9:50 AM