Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Comparison of C#, Clarion# and VB.

NET
This is a quick reference guide to highlight some key syntactical differences between C#, Clarion# and VB.NET (version 2).
NOTE: Clarion.NET and the Clarion# language are currently in alpha test, and various areas of the documentation are incomplete
and in a state of flux. Therefore, it’s very likely that some of the entries will change as new information becomes available.

Program Structure
C# Clarion# VB.NET
using System; PROGRAM Imports System
NAMESPACE(Hello)
namespace Hello { USING(System) Namespace Hello
public class HelloWorld { MAP Class HelloWorld
public static void Main(string[] args) { END Overloads Shared Sub Main(ByVal args() As String)
string name = "C#"; Dim name As String = "VB.NET"
Name &STRING
//See if an argument was passed from the command line 'See if an argument was passed from the command line
if (args.Length == 1) CODE If args.Length = 1 Then name = args(0)
name = args[0]; Name = 'Clarion#'
!See if an argument was passed from the command line Console.WriteLine("Hello, " & name & "!")
Console.WriteLine("Hello, " + name + "!"); IF COMMAND('1') <> '' End Sub
} Name = COMMAND('1') End Class
} END End Namespace
} Console.WriteLine('Hello, '& Name & '!')

Comments
C# Clarion# VB.NET
//Single line !Single line 'Single line only
REM Single line only

/* Multiple !~ Multiple
lines */ lines ~!

///<summary>XML comments on single line</summary> !!!<summary>XML comments on single line</summary> '''<summary>XML comments</summary>

/** <summary> !!!<summary>


XML comments on multiple lines !!! XML comments on multiple lines
</summary> */ !!!</summary>
Data Types
C# Clarion# VB.NET
// Value Types ! Value Types ' Value Types
bool BOOL Boolean
byte, sbyte BYTE, SBYTE Byte, SByte
char CHAR, CSTRING, PSTRING, CLASTRING Char
short, ushort, int, uint, long, ulong SHORT, USHORT, SIGNED, UNSIGNED, LONG, ULONG, CLALONG Short, UShort, Integer, UInteger, Long, ULong
float, double SREAL, REAL, BFLOAT4, BFLOAT8 Single, Double
decimal DECIMAL, PDECIMAL, CLADECIMAL Decimal
DateTime //not a built-in C# type DATE, TIME, CLADATE, CLATIME Date

// Reference Types ! Reference Types ' Reference Types


object &OBJECT Object
string &STRING String

// Initializing ! Initializing ' Initializing


bool correct = true; Correct BOOL(True) Dim correct As Boolean = True
byte b = 0x2A; //hex H BYTE(02Ah) !hex Dim b As Byte = &H2A 'hex
O BYTE(052o) !octal Dim o As Byte = &O52 'octal
object person = null; B BYTE(01101b) !binary Dim person As Object = Nothing
string name = "Mike"; Person &OBJECT Dim name As String = "Mike"
char grade = 'B'; Name &STRING Dim grade As Char = "B"c
DateTime today = DateTime.Parse("12/31/2007 12:15:00"); Name = 'Mike' Dim today As Date = #12/31/2007 12:15:00 PM#
decimal amount = 35.99m; Grade CHAR('B') Dim amount As Decimal = 35.99@
float gpa = 2.9f; Today DATE Dim gpa As Single = 2.9!
double pi = 3.14159265; Today = DATE(12,31,2007) Dim pi As Double = 3.14159265
long lTotal = 123456L; Amount DECIMAL(35.99) Dim lTotal As Long = 123456L
short sTotal = 123; GPA SREAL(2.9) Dim sTotal As Short = 123S
ushort usTotal = 123; Pi REAL(3.14159265) Dim usTotal As UShort = 123US
uint uiTotal = 123; lTotal LONG(123456) Dim uiTotal As UInteger = 123UI
ulong ulTotal = 123; sTotal SHORT(123) Dim ulTotal As ULong = 123UL
usTotal USHORT(123)
uiTotal UNSIGNED(123)
ulTotal ULONG(123)

// Type Information ! Type Information ' Type Information


int x; X SIGNED Dim x As Integer
Console.WriteLine(x.GetType()); //Prints System.Int32 Console.WriteLine(X.GetType()) !Prints System.Int32 Console.WriteLine(x.GetType()) 'Prints System.Int32
Console.WriteLine(typeof(int)); //Prints System.Int32 Console.WriteLine(TYPEOF(SIGNED)) !Prints System.Int32 Console.WriteLine(GetType(Integer)) 'Prints System.Int32
Console.WriteLine(x.GetType().Name); //Prints Int32 Console.WriteLine(X.GetType().Name) !Prints Int32 Console.WriteLine(TypeName(x)) 'Prints Integer

// Type Conversion ! Type Conversion ' Type Conversion


float d = 3.5f; D SREAL(3.5) Dim d As Single = 3.5
int i = (int)d; //set to 3 (truncates decimal) I SIGNED Dim i As Integer = CType(d, Integer) 'set to 4 (Banker's rounding)
I = D !Implicitly truncate to 3 i = CInt(d) 'same result as CType
I = D AS SIGNED !Explicitly truncate to 3 i = Int(d) 'set to 3 (Int function truncates the decimal)
Constants
C# Clarion# VB.NET
const int MAX_STUDENTS = 25; ! CONST and READONLY unsupported. Const MAX_STUDENTS As Integer = 25
! Use EQUATEs or regular data types instead.
// Can set to a const or var; may be initialized in a constructor MAX_STUDENTS EQUATE(25) !Instead of CONST; will auto-convert 'Can set to a const or var; may be initialized in a constructor
readonly float MIN_DIAMETER = 4.93f; MIN_DIAMETER SREAL(4.93) !READONLY is unsupported ReadOnly MIN_DIAMETER As Single = 4.93

Enumerations
C# Clarion# VB.NET
enum Action {Start, Stop, Rewind, Forward}; Action ENUM Action ENUM !Alternate syntax Enum Action
Start ITEM Start Start
Stop ITEM Stop [Stop] 'Stop is a reserved word
Rewind ITEM Rewind Rewind
Forward ITEM Forward Forward
END END End Enum

enum Status { Status ENUM Enum Status


Flunk = 50, Flunk(50) Flunk = 50
Pass = 70, Pass (70) Pass = 70
Excel = 90 Excel(90) Excel = 90
}; END End Enum

Action a = Action.Stop; A Action(Action.Stop) Dim a As Action = Action.Stop


if (a != Action.Start) IF (A <> Action.Start) If a <> Action.Start Then _
Console.WriteLine(a + " is " + (int) a); //Prints "Stop is 1" Console.WriteLine(A.ToString() &'is '& A) !Prints "Stop is 1" Console.WriteLine(a.ToString & " is " & a) 'Prints "Stop is 1"
END
Console.WriteLine((int) Status.Pass); //Prints 70 Console.WriteLine(Status.Pass + 0) !Prints 70 Console.WriteLine(Status.Pass) 'Prints 70
Console.WriteLine(Status.Pass); //Prints Pass Console.WriteLine(Status.Pass) !Prints Pass Console.WriteLine(Status.Pass.ToString()) 'Prints Pass

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

// Arithmetic ! Arithmetic ' Arithmetic


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

// Assignment ! Assignment ' Assignment


= += -= *= /= %= &= |= ^= <<= >>= ++ -- = += -= *= /= %= &= = += -= *= /= \= ^= <<= >>= &=
:= !"Smart" replacement for = and &=

// Bitwise ! Bitwise ' Bitwise


& | ^ ~ << >> BAND(val,mask) BOR(val,mask) BXOR(val,mask) BSHIFT(val,count) And Or Xor Not << >>
// Logical ! Logical ' Logical
&& || & | ^ ! AND OR XOR NOT AndAlso OrElse And Or Xor Not

// Note: && and || perform short-circuit logical evaluations ! Note: AND and OR perform short-circuit logical evaluations ' Note: AndAlso and OrElse perform short-circuit logical evaluations

// String Concatenation ! String Concatenation ' String Concatenation


+ & &

Choices
C# Clarion# VB.NET
greeting = age < 20 ? "What's up?" : "Hello"; Greeting = CHOOSE(Age < 20, 'What''s up?', 'Hello') greeting = IIf(age < 20, "What's up?", "Hello")

if (age < 20) ! One line requires THEN (or ;) ' One line doesn't require End If
greeting = "What's up?"; IF Age < 20 THEN Greeting = 'What''s up?' END If age < 20 Then greeting = "What's up?"
else IF Age < 20; Greeting = 'What''s up?'ELSE Greeting = 'Hello' END If age < 20 Then greeting = "What's up?" Else greeting = "Hello"
greeting = "Hello";

// Semi-colon ";" is used to terminate each statement, ! Use semi-colon (;) to put two commands on same line. ' Use colon (:) to put two commands on same line
// so no line continuation character is necessary. ! A period (.) may replace END in single line constructs, If x <> 100 AndAlso y < 5 Then x *= 5 : y *= 2
! but it is discouraged for multi-line constructs.
IF X <> 100 AND Y < 5 THEN X *= 5; Y *= 2. !Period is OK here

// Multiple statements must be enclosed in {} ! Multi-line is more readable (THEN is optional on multi line) ' Multi-line is more readable
if (x != 100 && y < 5) { IF X <> 100 AND Y < 5 THEN IF X <> 100 AND Y < 5 If x <> 100 AndAlso y < 5 Then
x *= 5; X *= 5 X *= 5 x *= 5
y *= 2; Y *= 2 Y *= 2 y *= 2
} END . !Period is hard to see here End If

! To break up any long single line use | (pipe) ' To break up any long single line use _
IF WhenYouHaveAReally < LongLine | If whenYouHaveAReally < longLine AndAlso _
AND ItNeedsToBeBrokenInto2 > Lines itNeedsToBeBrokenInto2 > Lines Then _
UseThePipe(CharToBreakItUp) UseTheUnderscore(charToBreakItUp)
END

if (x > 5) IF X > 5 If x > 5 Then


x *= y; X *= Y x *= y
else if (x == 5) ELSIF X = 5 ElseIf x = 5 Then
x += y; X += Y x += y
else if (x < 10) ELSIF X < 10 ElseIf x < 10 Then
x -= y; X -= Y x -= y
else ELSE Else
x /= y; X /= Y x /= y
END End If
// Every case must end with break or goto case CASE Color !Any data type or expression Select Case color 'Must be a primitive data type
switch (color) { //Must be integer or string OF 'pink' OROF 'red' Case "pink", "red"
case "pink" : R += 1 r += 1
case "red" : r++; break; OF 'blue' Case "blue"
case "blue" : b++; break; B += 1 b += 1
case "green": g++; break; OF 'green' Case "green"
default: other++; break; //break necessary on default G += 1 g += 1
} ELSE Case Else
Other += 1 other += 1
END End Select

CASE Value
OF 0.00 TO 9.99; RangeName = 'Ones'
OF 10.00 TO 99.99; RangeName = 'Tens'
OF 100.00 TO 999.99; RangeName = 'Hundreds'
!etc.
ELSE ; RangeName = 'Zillions'
END

EXECUTE Stage !Integer value or expression


Stage1 ! expression equals 1
Stage2 ! expression equals 2
Stage3 ! expression equals 3
ELSE
StageOther ! expression equals some other value
END

Loops
C# Clarion# VB.NET
// Pre-test Loops ! Pre-test Loops ' Pre-test Loops
while (c < 10) LOOP WHILE C < 10 LOOP UNTIL C = 10 While c < 10 Do Until c = 10
c++; C += 1 C += 1 c += 1 c += 1
END END End While Loop
// no "until" keyword
LOOP C = 2 TO 10 BY 2 Do While c < 10 For c = 2 To 10 Step 2
for (c = 2; c <= 10; c += 2) Console.WriteLine(C) c += 1 Console.WriteLine(c)
Console.WriteLine(c); END Loop Next

// Post-test Loop ! Post-test Loops ' Post-test Loops


do LOOP LOOP Do Do
c++; C += 1 C += 1 c += 1 c += 1
while (c < 10); WHILE c < 10 UNTIL C = 10 Loop While c < 10 Loop Until c = 10

// Untested Loop ! Untested Loops ' Untested Loop


for (;;) { LOOP LOOP 3 TIMES Do
//break logic inside !Break logic inside Console.WriteLine //break logic inside
} END END Loop
// Array or collection looping ! Array or collection looping ' Array or collection looping
string[] names = {"Fred", "Sue", "Barney"}; Names &STRING,DIM(3) Dim names As String() = {"Fred", "Sue", "Barney"}
foreach (string s in names) S &STRING For Each s As String In names
Console.WriteLine(s); CODE Console.WriteLine(s)
Names[1] := 'Fred'; Names[2] := 'Sue'; Names[3] := 'Barney' Next
FOREACH S IN Names
Console.WriteLine(S)
END

// Breaking out of loops ! Breaking out of loops ' Breaking out of loops
int i = 0; I SHORT(0) Dim i As Integer = 0
while (true) { CODE While (True)
if (i == 5) LOOP If (i = 5) Then Exit While
break; IF I = 5 THEN BREAK. i += 1
i++; I += 1 End While
} END

// Continue to next iteration ! Continue to next iteration ' Continue to next iteration
for (i = 0; i < 5; i++) { LOOP I = 0 TO 4 For i = 0 To 4
if (i < 4) IF I < 4 THEN CYCLE. If i < 4 Then Continue For
continue; Console.WriteLine(I) Console.WriteLine(i) 'Only prints 4
Console.WriteLine(i); //Only prints 4 END Next
}

Arrays
C# Clarion# VB.NET
int[] nums = {1, 2, 3}; Nums SIGNED,DIM(3) Dim nums() As Integer = {1, 2, 3}
for (int i = 0; i < nums.Length; i++) I SIGNED For i As Integer = 0 To nums.Length - 1
Console.WriteLine(nums[i]); CODE Console.WriteLine(nums(i))
Nums[1] = 1; Nums[2] = 2; Nums[3] = 3 Next
LOOP I = 1 TO Nums.Length
Console.WriteLine(Nums[I])
END

// 5 is the size of the array ! 5 is the size of the array ' 4 is the index of the last element, so it holds 5 elements
string[] names = new string[5]; Names &STRING,DIM(5) Dim names(4) As String
names[0] = "David"; CODE names(0) = "David"
names[5] = "Bobby"; //Throws System.IndexOutOfRangeException Names[1] := 'David' names(5) = "Bobby" 'Throws System.IndexOutOfRangeException
Names[6] := 'Bobby' !Caught by compiler
I = 6
Names[I] := 'Bobby' !Throws System.IndexOutOfRangeException

// C# can't dynamically resize arrays, so copy into new array ! Clarion# can't dynamically resize arrays, so copy into new array ' Resize the array, keeping existing values (Preserve is optional)
string[] names2 = new string[7]; Names2 &STRING[] ReDim Preserve names(6)
Array.Copy(names, names2, names.Length); CODE
// or Names2 := NEW STRING[7]
names.CopyTo(names2, 0); Array.Copy(Names, Names2, Names.Length) !or
Names.CopyTo(Names2, 0)

float[,] twoD = new float[rows, cols]; TwoD SREAL[,] Dim twoD(rows-1, cols-1) As Single
twoD[2,0] = 4.5f; CODE twoD(2, 0) = 4.5
TwoD := NEW SREAL[Rows, Cols]
TwoD[3,1] = 4.5
// Jagged arrays ! Jagged arrays unsupported ' Jagged arrays
int[][] jagged = new int[3][] { Dim jagged()() As Integer = { _
new int[5], new int[2], new int[3] }; New Integer(4) {}, New Integer(1) {}, New Integer(2) {} }
jagged[0][4] = 5; jagged(0)(4) = 5

Functions
C# Clarion# VB.NET
// Pass by value(in,default), reference(in/out), and reference(out) ! Pass by value(in,default), reference(in/out), and reference(out) ' Pass by value(in,default), reference(in/out), and reference(out)
void TestFunc(int x, ref int y, out int z) { TestFunc PROCEDURE(SIGNED X, *SIGNED Y, *SIGNED Z) Sub TestFunc(ByVal x As Integer, ByRef y As Integer, _
x++; CODE ByRef z As Integer)
y++; X += 1 x += 1
z = 5; Y += 1 y += 1
} Z = 5 z = 5
RETURN !Optional, if not returning a value End Sub

int a = 1, b = 1, c; //c doesn't need initializing A UNSIGNED(1) Dim a = 1, b = 1, c As Integer 'c set to zero by default
TestFunc(a, ref b, out c); B UNSIGNED(1) TestFunc(a, b, c)
Console.WriteLine("{0} {1} {2}", a, b, c); //1 2 5 C UNSIGNED !C doesn’t need initializing Console.WriteLine("{0} {1} {2}", a, b, c) '1 2 5
CODE
TestFunc(A, B, C)
Console.WriteLine('{{0} {{1} {{2}', A, B, C) !1 2 5

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

Total# = Sum(4, 3, 2, 1) !returns 10

/* C# doesn't support optional arguments/parameters. ! Optional parameters without default value ' Optional parameters must be listed last and have a default value
Just create two different versions of the same function. */ ! (When omitted, value parameters default to 0 or an empty string) Sub SayHello(ByVal name As String, Optional ByVal prefix As String = "")
void SayHello(string name, string prefix) { ! (Use OMITTED to detect the omission) Console.WriteLine("Greetings, " & prefix & " " & name)
Console.WriteLine("Greetings, " + prefix + " " + name); SayHello PROCEDURE(STRING Name, <STRING Prefix>) End Sub
}
void SayHello(string name) { ! Optional parameters with default value SayHello("Strangelove", "Dr.")
SayHello(name, ""); SayHello("Madonna")
! (Valid only on simple numeric types)
}
! (OMITTED will not detect the omission — the default is passed)
SayHello PROCEDURE(STRING Name, BYTE Age = 20)
Strings
C# Clarion# VB.NET
// Escape sequences ! Special Characters ' Special Character Constants
\r //carriage-return <13> !carriage-return vbCrLf, vbCr, vbLf, vbNewLine
\n //line-feed <10> !line-feed vbNullString
\t //tab <9> !tab vbTab
\\ //backslash vbBack
<n> !character with the ASCII value=n (see above)
\" //quote vbFormFeed
<< !less-than vbVerticalTab
{{ !left-curly-brace ""
'' !single-quote
{n} !Repeat previous character "n" times

// String concatenation ! String concatenation ' String concatenation (use & or +)


string school = "Harding\t"; School &STRING Dim school As String = "Harding" & vbTab
school = school + "University"; Univ CLASTRING('University') !Clarion string class school = school & "University"
// school is "Harding(tab)University" CODE 'school is "Harding(tab)University"
School = 'Harding<9>'
School = School & Univ
!School is "Harding(tab)University"

// Chars ! Chars ' Chars


char letter = school[0]; //letter is H Letter CHAR Dim letter As Char = school.Chars(0) 'letter is H
letter = Convert.ToChar(65); //letter is A Word CHAR[] letter = Convert.ToChar(65) 'letter is A
letter = (char)65; //same thing CODE letter = Chr(65) 'same thing
char[] word = school.ToCharArray(); //word holds Harding Letter = School[1] !Letter is H Dim word() As Char = school.ToCharArray() 'word holds Harding
Letter = Convert.ToChar(65) !Letter is A
Letter = '<65>' !Same thing
Word = School.ToCharArray !Word holds Harding

// String literal ! No string literal operator ' No string literal operator


string msg = @"File is c:\temp\x.dat"; Msg &STRING Dim msg As String = "File is c:\temp\x.dat"
// same as CODE
string msg = "File is c:\\temp\\x.dat"; Msg = 'File is c:\temp\x.dat'

// String comparison ! String comparison ' String comparison


string mascot = "Bisons"; Mascot &STRING Dim mascot As String = "Bisons"
if (mascot == "Bisons") //true CODE If (mascot = "Bisons") Then 'true
if (mascot.Equals("Bisons")) //true Mascot = 'Bisons' If (mascot.Equals("Bisons")) Then 'true
if (mascot.ToUpper().Equals("BISONS")) //true IF Mascot = 'Bisons' !true If (mascot.ToUpper().Equals("BISONS")) Then 'true
if (mascot.CompareTo("Bisons") == 0) //true IF Mascot.Equals('Bisons') !true If (mascot.CompareTo("Bisons") = 0) Then 'true
IF Mascot.ToUpper().Equals('BISONS') !true
IF UPPER(Mascot) = 'BISONS' !true
IF Mascot.CompareTo('Bisons') = 0 !true

// Substring ! Substring ' Substring


Console.WriteLine(mascot.Substring(2, 3)); //Prints "son" Console.WriteLine(Mascot.Substring(2, 3)) !Prints "son" Console.WriteLine(mascot.Substring(2, 3)) 'Prints "son"
Console.WriteLine(SUB(Mascot, 3, 3)) !Prints "son"
Console.WriteLine(Mascot[3 : 6]) !Prints "son"
// String matching ! String matching ' String matching
// No exact equivalent to Like - use regular expressions ! No exact equivalent to Like - use regular expressions or MATCH If ("John 3:16" Like "Jo[Hh]? #:*") Then 'true

using System.Text.RegularExpressions; USING(System.Text.RegularExpressions) Imports System.Text.RegularExpressions 'More powerful than Like


Regex r = new Regex(@"Jo[hH]. \d:*"); R &Regex Dim r As New Regex("Jo[hH]. \d:*")
if (r.Match("John 3:16").Success) //true A &STRING If (r.Match("John 3:16").Success) Then 'true
B &STRING
C &STRING
CODE
R := NEW Regex('Jo[hH]. \d:*')
IF R.Match('John 3:16').Success !true
A = 'Richard'
B = 'RICHARD'
C = 'R*'
IF MATCH(A,B,MATCH:Simple+Match:NoCase) !true: case insensitive
IF MATCH(A,B,MATCH:Soundex) !true: soundex
IF MATCH(A,C) !true: wildcard (default)
IF MATCH('Fireworks on the fourth', '{{4|four}th', |
MATCH:Regular+Match:NoCase) !true: RegEx
IF MATCH('July 4th fireworks', '{{4|four}th', |
MATCH:Regular+Match:NoCase) !true: RegEx

// My birthday: Sep 3, 1964 ! My birthday: Sep 3, 1964 ' My birthday: Sep 3, 1964
DateTime dt = new DateTime(1964, 9, 3); DT DateTime Dim dt As New DateTime(1964, 9, 3)
string s = "My birthday: " + dt.ToString("MMM dd, yyyy"); S &STRING Dim s As String = "My birthday: " & dt.ToString("MMM dd, yyyy")
CODE
DT = NEW DateTime(1964, 9, 3)
S = 'My birthday: '& DT.ToString('MMM dd, yyyy')

// Mutable string ! Mutable string ' Mutable string


System.Text.StringBuilder buffer = Buffer System.Text.StringBuilder('two ') Dim buffer As New System.Text.StringBuilder("two ")
new System.Text.StringBuilder("two "); CODE buffer.Append("three ")
buffer.Append("three "); Buffer.Append('three ') buffer.Insert(0, "one ")
buffer.Insert(0, "one "); Buffer.Insert(0, 'one ') buffer.Replace("two", "TWO")
buffer.Replace("two", "TWO"); Buffer.Replace('two', 'TWO') Console.WriteLine(buffer) 'Prints "one TWO three"
Console.WriteLine(buffer); //Prints "one TWO three" Console.WriteLine(Buffer) !Prints "one TWO three"

Exception Handling
C# Clarion# VB.NET
// Throw an exception ! Throw an exception ' Throw an exception
Exception ex = new Exception("Something is really wrong."); Ex &Exception('Something is really wrong.') Dim ex As New Exception("Something is really wrong.")
throw ex; CODE Throw ex
THROW Ex
// Catch an exception ! Catch an exception ' Catch an exception
try { TRY Try
y = 0; y = 0; y = 0
x = 10 / y; x = 10 / y; x = 10 / y
} CATCH(Exception Ex) !Argument is optional, no "When" keyword Catch ex As Exception When y = 0 'Argument and When is optional
catch (Exception ex) { //Argument is optional, no "When" keyword Console.WriteLine(Ex.Message); Console.WriteLine(ex.Message)
Console.WriteLine(ex.Message); FINALLY Finally
} BEEP Beep()
finally { END End Try
//Requires reference to the Microsoft.VisualBasic.dll
//assembly (pre .NET Framework v2.0) ' Deprecated unstructured error handling
Microsoft.VisualBasic.Interaction.Beep(); On Error GoTo MyErrorHandler
} ...
MyErrorHandler: Console.WriteLine(Err.Description)

Namespaces
C# Clarion# VB.NET
namespace Harding.Compsci.Graphics { NAMESPACE(Harding.Compsci.Graphics) Namespace Harding.Compsci.Graphics
... ...
} End Namespace

// or ' or

namespace Harding { !Progressive, nested namespaces unsupported Namespace Harding


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

using Harding.Compsci.Graphics; USING(Harding.Compsci.Graphics) Imports Harding.Compsci.Graphics

Classes / Interfaces
C# Clarion# VB.NET
// Accessibility keywords ! Accessibility keywords ' Accessibility keywords
public PUBLIC Public
private PRIVATE Private
internal INTERNAL Friend
protected PROTECTED Protected
protected internal PROTECTED INTERNAL Protected Friend
static STATIC Shared

// Inheritance ! Inheritance ' Inheritance


class FootballGame : Competition { FootballGame CLASS(Competition) Class FootballGame
... ... Inherits Competition
} END ...
End Class
// Interface definition ! Interface definition ' Interface definition
interface IAlarmClock { IAlarmClock INTERFACE Interface IAlarmClock
... ... ...
} END End Interface

// Extending an interface ! Extending an interface ' Extending an interface


interface IAlarmClock : IClock { IAlarmClock INTERFACE(IClock) Interface IAlarmClock
... ... Inherits IClock
} END ...
End Interface

// Interface implementation ! Interface implementation ' Interface implementation


class WristWatch : IAlarmClock, ITimer { WristWatch CLASS,IMPLEMENTS(IAlarmClock),IMPLEMENTS(ITimer) Class WristWatch
... ... Implements IAlarmClock, ITimer
} END ...
End Class

Constructors / Destructors
C# Clarion# VB.NET
class SuperHero { SuperHero CLASS Class SuperHero
private int _powerLevel; _PowerLevel UNSIGNED,PRIVATE Private _powerLevel As Integer
Construct PROCEDURE,PUBLIC
public SuperHero() { Construct PROCEDURE(UNSIGNED PowerLevel),PUBLIC Public Sub New()
_powerLevel = 0; Destruct PROCEDURE _powerLevel = 0
} END End Sub

public SuperHero(int powerLevel) { SuperHero.Construct PROCEDURE Public Sub New(ByVal powerLevel As Integer)
this._powerLevel= powerLevel; CODE Me._powerLevel = powerLevel
} SELF._PowerLevel = 0 End Sub

~SuperHero() { SuperHero.Construct PROCEDURE(UNSIGNED PowerLevel) Protected Overrides Sub Finalize()


//Destructor code to free unmanaged resources. CODE 'Destructor code to free unmanaged resources
//Implicitly creates a Finalize method SELF._PowerLevel = PowerLevel MyBase.Finalize()
} End Sub
} SuperHero.Destruct PROCEDURE End Class
CODE
!Destructor code to free unmanaged resources.

Using Objects
C# Clarion# VB.NET
SuperHero hero = new SuperHero(); Hero &SuperHero Dim hero As SuperHero = New SuperHero
Hero2 &SuperHero 'or
Obj &Object Dim hero As New SuperHero
CODE
Hero &= NEW SuperHero

// No "With" construct ! No "With" construct With hero


hero.Name = "SpamMan"; hero.Name = 'SpamMan' .Name = "SpamMan"
hero.PowerLevel = 3; hero.PowerLevel = 3 .PowerLevel = 3
End With
hero.Defend("Laura Jones"); Hero.Defend('Laura Jones') hero.Defend("Laura Jones")
SuperHero.Rest(); //Calling static method SuperHero.Rest() !Calling static method hero.Rest() 'Calling Shared method
'or
SuperHero.Rest()

SuperHero hero2 = hero; //Both reference the same object Hero2 &= Hero !Both reference the same object Dim hero2 As SuperHero = hero 'Both reference the same object
hero2.Name = "WormWoman"; Hero2.Name = 'WormWoman' hero2.Name = "WormWoman"
Console.WriteLine(hero.Name); //Prints WormWoman Console.WriteLine(Hero.Name) !Prints "WormWoman" Console.WriteLine(hero.Name) 'Prints WormWoman

hero = null ; //Free the object Hero &= NULL !Free the object hero = Nothing 'Free the object

if (hero == null) IF Hero &= NULL If hero Is Nothing Then _


hero = new SuperHero(); Hero &= NEW SuperHero hero = New SuperHero
END

Object obj = new SuperHero(); Obj &= NEW SuperHero(); Dim obj As Object = New SuperHero
if (obj is SuperHero) IF Obj IS SuperHero If TypeOf obj Is SuperHero Then _
Console.WriteLine("Is a SuperHero object."); Console.WriteLine('Is a SuperHero object.') Console.WriteLine("Is a SuperHero object.")
END

// Mark object for quick disposal ! No equivalent to USING(Resource) to mark for quick disposal ' Mark object for quick disposal
using (StreamReader reader = File.OpenText("test.txt")) { Using reader As StreamReader = 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

Structs
C# Clarion# VB.NET
struct StudentRecord { StudentRecord STRUCT Structure StudentRecord
public string name; Name &STRING,PUBLIC Public name As String
public float gpa; GPA SREAL,PUBLIC Public gpa As Single
Construct PROCEDURE(STRING Name,SREAL GPA),PUBLIC
public StudentRecord(string name, float gpa) { INLINE Public Sub New(ByVal name As String, ByVal gpa As Single)
this.name = name; CODE Me.name = name
this.gpa = gpa; SELF.Name = Name Me.gpa = gpa
} SELF.GPA = GPA End Sub
} END End Structure
END

StudentRecord stu = new StudentRecord("Bob", 3.5f); Stu StudentRecord('Bob', 3.5) Dim stu As StudentRecord = New StudentRecord("Bob", 3.5)
StudentRecord stu2 = stu; Stu2 StudentRecord Dim stu2 As StudentRecord = stu
CODE
stu2.name = "Sue"; Stu2.Name = 'Sue' stu2.name = "Sue"
Console.WriteLine(stu.name); //Prints Bob Console.WriteLine(Stu.Name) !Prints Bob Console.WriteLine(stu.name) 'Prints Bob
Console.WriteLine(stu2.name); //Prints Sue Console.WriteLine(Stu2.Name) !Prints Sue Console.WriteLine(stu2.name) 'Prints Sue
Properties
C# Clarion# VB.NET
private int _size; _Size UNSIGNED,PRIVATE Private _size As Integer
Size PROPERTY,UNSIGNED,PUBLIC
public int Size { INLINE Public Property Size() As Integer
get { GETTER Get
return _size; CODE Return _size
} RETURN SELF._Size End Get
set { //parameter is always "value" SETTER !parameter is always "Value" Set (ByVal Value As Integer)
if (value < 0) CODE If Value < 0 Then
_size = 0; IF Value < 0 _size = 0
else SELF._Size = 0 Else
_size = value; ELSE _size = Value
} SELF._Size = Value End If
} END End Set
END End Property

! Rather than use INLINE, you may define Get_PropertyName


! and Set_PropertyName methods separately.
ClassName.Get_Size PROCEDURE
CODE
RETURN SELF._Size
ClassName.Set_Size PROCEDURE(UNSIGNED pValue)
CODE
SELF._Size = CHOOSE(pValue < 0, 0, pValue)

// Usage ! Usage ' Usage


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

Delegates / Events
C# Clarion# VB.NET
MAP
delegate void MsgArrivedEventHandler(string message); MsgArrivedEventHandler PROCEDURE(STRING Message),DELEGATE Delegate Sub MsgArrivedEventHandler(ByVal message As String)
END

event MsgArrivedEventHandler MsgArrivedEvent; MsgArrivedEvent EVENT,MsgArrivedEventHandler Event MsgArrivedEvent As MsgArrivedEventHandler

// Events must use explicitly-defined delegates in C# ! Events must use explicitly-defined delegates in Clarion# ' or to define an event which declares a delegate implicitly
Event MsgArrivedEvent(ByVal message As String)

MsgArrivedEvent += new MsgArrivedEvent += My_MsgArrivedEventCallback AddHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback


MsgArrivedEventHandler(My_MsgArrivedEventCallback); ' Won't throw an exception if obj is Nothing
MsgArrivedEvent("Test message"); //Throws exception if obj is null MsgArrivedEvent('Test message') RaiseEvent MsgArrivedEvent("Test message")
MsgArrivedEvent -= new MsgArrivedEvent -= My_MsgArrivedEventCallback RemoveHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback
MsgArrivedEventHandler(My_MsgArrivedEventCallback);
using System; USING(System) Imports System
using System.Windows.Forms; USING(System.Windows.Forms) Imports System.Windows.Forms

public class MyClass { MyForm CLASS,TYPE,NETCLASS,PARTIAL Public Class MyForm


Button MyButton; MyButton &Button Dim WithEvents MyButton As Button
Init PROCEDURE
MyButton_Click PROCEDURE(Object Sender, EventArgs E)
END

public void Init() { MyForm.Init PROCEDURE Public Sub Init


MyButton = new Button(); CODE MyButton = New Button
MyButton.Click += new EventHandler(MyButton_Click); MyButton &= NEW Button End Sub
} SELF.MyButton.Click += SELF.MyButton_Click

private void MyButton_Click(object sender, EventArgs e) { MyForm.MyButton_Click PROCEDURE(Object Sender, EventArgs E) Private Sub MyButton_Click(ByVal sender As Object, _
MessageBox.Show("Button was clicked", "Info", CODE ByVal e As EventArgs) Handles MyButton.Click
MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show('Button was clicked', 'Info', | MessageBox.Show(Me, "Button was clicked", "Info", _
} MessageBoxButtons.OK, MessageBoxIcon.Information) MessageBoxButtons.OK, MessageBoxIcon.Information)
} End Sub
End Class

Console I/O
C# Clarion# VB.NET
Name &STRING
Age UNSIGNED
C UNSIGNED
CODE
Console.Write("What's your name? "); Console.Write('What's your name? ') Console.Write("What's your name? ")
string name = Console.ReadLine(); Name = Console.ReadLine() Dim name As String = Console.ReadLine()
Console.Write("How old are you? "); Console.Write('How old are you? ') Console.Write("How old are you? ")
int age = Convert.ToInt32(Console.ReadLine()); Age = Convert.ToInt32(Console.ReadLine()) Dim age As Integer = Val(Console.ReadLine())
Console.WriteLine("{0} is {1} years old.", name, age); Console.WriteLine("{{0} is {{1} years old.", Name, Age); Console.WriteLine("{0} is {1} years old.", name, age)
// or ! or ' or
Console.WriteLine(name + " is " + age + " years old."); Console.WriteLine(Name + 'is '+ age + 'years old.'); Console.WriteLine(name & " is " & age & " years old.")

Dim c As Integer
int c = Console.Read(); //Read single char C = Console.Read() !Read single char c = Console.Read() 'Read single char
Console.WriteLine(c); //Prints 65 if user enters "A" Console.WriteLine(C) !Prints 65 if user enters "A" 0 Console.WriteLine(c) 'Prints 65 if user enters "A"

File I/O
C# Clarion# VB.NET
using System.IO; USING(System.IO) Imports System.IO

// Write out to text file ! Write out to text file ' Write out to text file
StreamWriter writer = File.CreateText("c:\\myfile.txt"); Writer &StreamWriter Dim writer As StreamWriter = File.CreateText("c:\myfile.txt")
writer.WriteLine("Out to file."); CODE writer.WriteLine("Out to file.")
writer.Close(); Writer &= File.CreateText('c:\myfile.txt') writer.Close()
Writer.WriteLine('Out to file.')
Writer.Close()
// Read all lines from text file ! Read all lines from text file ' Read all lines from text file
StreamReader reader = File.OpenText("c:\\myfile.txt"); Reader &StreamReader Dim reader As StreamReader = File.OpenText("c:\myfile.txt")
string line = reader.ReadLine(); Line &STRING Dim line As String = reader.ReadLine()
while (line != null) { CODE While Not line Is Nothing
Console.WriteLine(line); Reader &= File.OpenText('c:\myfile.txt') Console.WriteLine(line)
line = reader.ReadLine(); Line = Reader.ReadLine() line = reader.ReadLine()
} LOOP WHILE NOT Line &= NULL End While
reader.Close(); Console.WriteLine(Line) reader.Close()
Line = Reader.ReadLine()
END
Reader.Close()

// Write out to binary file ! Write out to binary file ' Write out to binary file
string str = "Text data"; Str &STRING Dim str As String = "Text data"
int num = 123; Num SIGNED(123) Dim num As Integer = 123
BinaryWriter binWriter = BinWriter &BinaryWriter Dim binWriter As New BinaryWriter(File.OpenWrite("c:\myfile.dat"))
new BinaryWriter(File.OpenWrite("c:\\myfile.dat")); CODE binWriter.Write(str)
binWriter.Write(str); Str = 'Text data' binWriter.Write(num)
binWriter.Write(num); BinWriter &= NEW BinaryWriter(File.OpenWrite('c:\myfile.dat')) binWriter.Close()
binWriter.Close(); BinWriter.Write(Str)
BinWriter.Write(Num)
BinWriter.Close()

// Read from binary file ! Read from binary file ' Read from binary file
BinaryReader binReader = BinReader &BinaryReader Dim binReader As New BinaryReader(File.OpenRead("c:\myfile.dat"))
new BinaryReader(File.OpenRead("c:\\myfile.dat")); CODE str = binReader.ReadString()
str = binReader.ReadString(); BinReader &= NEW BinaryReader(File.OpenRead('c:\myfile.dat')) num = binReader.ReadInt32()
num = binReader.ReadInt32(); Str = BinReader.ReadString() binReader.Close()
binReader.Close(); Num = BinReader.ReadInt32()
BinReader.Close()

Based upon adocument by Frank McCown (www.harding.edu/fmccown/vbnet_csharp_comparison.html). Licensed under a Creative Commons License (creativecommons.org/licenses/by-sa/2.0).
Clarion# examples provided by Mike Hanson (www.boxsoft.net). Last updated December 17, 2007.

You might also like