Help me out here. I'm trying to make a list of things that come to mind when a VB.NET programmer wants to use C#
. These could also be used when converting code between VB.NET and C#, OR any C# newbie could look these up to get some insight
todo list: Bitwise operators, event handlers in full detail, virtual/new/shadows keywords
I'm just typing these up here, so please double check for typos and errors and let me know!
Keywords
in C# variables are ByVal by default, so no keyword is used for ByVal
use ref instead of VB's ByRef
C# also has the in and out keywords that you can use (you can look them up on MSDN)
use base in C# instead of VB's MyBase
use this in C# instead of VB's Me
to the best of my understanding VB's MyClass doesnt exist in C# so you should just use this (correct me if I'm wrong)
use null in C# instead of VB's Nothing
Some of the things that don't exist in C#
Optional parameters don't exist in C#. You can have multiple function definitions or if applicable, use params(scroll down and see the param array example)
The Redim keyword does not exist in C#
C# doesn't have Modules. Use a class instead
C# doesn't support With ... End With blocks
Examples:
vb: MustInherit class
c# abstract class
vb: NotInheritable class
c#: sealed class
vb: Public MustOverride Function foo() As Boolean
c#: public abstract bool foo();
vb: Public Shared counter As Integer
c#: public static int counter;
vb: Shared Function foo() As Boolean
c# static bool foo ()
vb: MustOverride Property name() As String
c#: abstract string name{get;set;}
Implementing an interface
VB: Public Class someClass : Implements IDisposable
c# public class someClass:IDisposable
Inheriting from a class
vb: Public Class myClass: Inherits someClass
c#: public class myClass: someClass
Importing a namespace
vb: Imports System
C#: using System;
Characters
use single quotes in C#, and double quotes followed by a c in VB
VB: Dim c As Char = "a"c
C# char c = 'a';
C# Strings
C# recognizes '\' as a escape character so if you want to use \ in a text you have to use two \\'s. If this is annoying you can put a @ in front of the string and use single slashes. These two are equivalent
string s1 = "c:\\windows\\system32";
string s2 = @"c:\windows\system32";
C# also lets you access a string as a character array, using brackets (you can only read values this way):
PHP Code:
string test = "cell#: 000-000-0000";
char c1 = test[0],
c2 = test[4];
Console.WriteLine (c1.ToString() + c2.ToString());//outputs "c#"
String concatenation
VB: & or + operators, either one
C#: + operator
New line character
(You could use Environment.NewLine in either language)
Note: Usually if you want to go to a new line you use "\n" in C#. I think you use \r\n when you write to a file. Someone needs to explain this (has something to do with unix systems as well
)
VB: vbCrLf
C#: "\r\n"
Modulus
VB: Mod (ie, 19 Mod 9)
C#: % (ie, 19%9)
Power
VB: 2^3
C#: no operators, use Math.Pow (2,3)
Attributes
VB: enclose the attribute in anguled brackets < >
C#: enclose the attribute in brackets [ ]
Assigning variables
in C# you can use the '=' equal sign to assign a value to multiple variables:
PHP Code:
int a, b, c, d;
// Assign 0 to a, b, c, and d
a = b = c = d = 0;
// You could also initialize multiple items at once
int e = 1,
f = 2,
g = 3;
Indexor (Default property)
vb:
VB Code:
Private _item As Integer
Default Public Property item(ByVal index As Integer) As Integer
Get
Return _item
End Get
Set(ByVal Value As Integer)
_item = Value
End Set
End Property
C#:
PHP Code:
private int item;
public int this[int index]
{
get
{
return this.item;
}
set
{
this.item = value;
}
}
Creating a readonly property
vb:
VB Code:
Public ReadOnly Property count() As Integer
Get
Return -1
End Get
End Property
C#:
PHP Code:
public int i
{
get
{
return -1;
}
}
Creating a ParamArray
vb: Public Function paramArrEx(ByVal ParamArray items() As Integer) As Integer
c#: public int paramArrEx(params int[] items)
Overriding a function
VB Code:
Protected Overrides Sub SetVisibleCore(ByVal value As Boolean)
MyBase.SetVisibleCore(value)
End Sub
PHP Code:
protected override void SetVisibleCore(bool value)
{
base.SetVisibleCore (value);
}
Declaring an API function
vb:
VB Code:
'add this on top: Imports System.Runtime.InteropServices
<DllImport("user32.dll")> _
Public Shared Function LockWindowUpdate(ByVal handle As IntPtr) As Boolean
End Function
C#:
PHP Code:
//Add this on top: using System.Runtime.InteropServices;
[DllImport("user32.dll")]
public static extern bool LockWindowUpdate (IntPtr handle);
Type checking
VB Code:
Dim val As Object = 123
' These two if statements work the same.
If (val.GetType() Is GetType(Integer)) Then
End If
If (TypeOf (val) Is Integer) Then
End If
C#:
PHP Code:
object val = 123;
//These two if statements work the same.
if (val is int)
{/* Do something*/}
if (val.GetType()==typeof(int))
{/* Do something*/}
Type Casting
You can use both DirectCast() and CType in VB.NET
VB:
VB Code:
Dim val As Object = 123
Dim intVal As Integer = CType(val, Integer)
C#:
PHP Code:
object val = 123;
int intVal = (int)val;
char c = (char)125; // Get character with ascii code 125
Using For loops
Note: when using for-loops or do-loops you can use continue; in C#. The continue "statement passes control to the next iteration of the enclosing iteration statement in which it appears" (MSDN). Correct me if I'm wrong but I don't think this exists in VB.NET
vb:
VB Code:
Dim numbers As Integer() = {1, 2, 3, 4, 5}
For i As Integer = 0 To numbers.Length - 1
Console.WriteLine(numbers(i).ToString())
Next
' Skip every other item by using Step 2 (increments i by 2 instead of 1)
For i As Integer = 0 To numbers.Length - 1 Step 2
Console.WriteLine(numbers(i).ToString())
Next
'For-Each
For Each num As Integer In numbers
Console.WriteLine(num.ToString())
Next
C#:
PHP Code:
int[] numbers = {1,2,3,4,5};
for (int i=0; i<numbers.Length; i++)
{
Console.WriteLine (numbers[i].ToString());
}
// Skip every other item by using i+=2 (increments i by 2 instead of 1)
for (int i=0; i<numbers.Length; i+=2)
Console.WriteLine (numbers[i].ToString());
// Foreach example
foreach (int num in numbers)
{
Console.WriteLine (num.ToString());
}
Do-While loops:
vb:
VB Code:
Dim count As Integer = 9
Do ' Print 9 through 1
Console.WriteLine(count.ToString())
count -= 1
Loop While (count > 0)
count = 9
Do While (count > 0) 'Same result as above
Console.WriteLine(count.ToString())
count -= 1
Loop
C#:
PHP Code:
int count = 9;
// Print 9 through 1
do
{
Console.WriteLine (count.ToString());
count--;
}while (count>0);
count = 9;
// Same result as above
while (count>0)
{
Console.WriteLine (count.ToString());
count--;
}
Select Case - or Switch statements:
vb:
VB Code:
Dim num As Integer = 1
Select Case num
Case 1
Case 2
Exit Select
Case 3
num = 9
Case 4
Return ' Return out of the function
Case Else
num += 1
End Select
C#:
PHP Code:
int num = 1;
switch (num)
{
case 1:
case 2:
break; // Exit switch statement
case 3:
num = 9;
// Always need to use break at the end of the statement,
// or the code keeps checking the other cases after this.
break;
case 4:
// Don't need to use break in this case
return;
default: // VB's Case Else
num += 1;
break;
}
Breaking out of functions, loops, etc
VB: Exit For, Exit While, Exit Do, Exit Select, Exit Sub, Exit Function, or Return in a Sub
C#: break in loops and switch statements, and return in functions
Exception handling
I wont include VB's old error handling because I think it's bad coding and obsolete.
VB.NET has the When clause that can be used but I believe C# does not have an equivalent:
vb:
VB Code:
' Used below with the WHEN clause
Dim catchIOErrors As Boolean = True
Try
' Code
Catch ioEx As System.IO.IOException When catchIOErrors
' Code (only catches if catchIOErrors is set to true)
Catch ex As SystemException
' Code
Catch
' Code
Finally
' Code
End Try
C#:
PHP Code:
// put your code inside the brackets
try
{}
catch (SystemException ex)
{}
catch
{}
finally
{}
Thread locks
vb:
VB Code:
SyncLock "myLock"
End SyncLock
C#:
PHP Code:
lock ("myLock")
{}
unsafe code:
Only applies to C#:
First right click on your project, click on properties, in the Configuration Properties section, under the Build section, set Allow Unsafe Code Blocks to true. Then you can put your unsafe code in an unsafe block: unsafe { // code here }
Event handlers
C# doesnt support the Handles clause
vb:
VB Code:
AddHandler Me.Click, AddressOf Form1_Click
RemoveHandler Me.Click, AddressOf Form1_Click
C#:
PHP Code:
this.Click += new EventHandler (Form1_Click);
this.Click -= new EventHandler (Form1_Click);
(more examples of event handling later, maybe
)
Stopping code execution
VB: Stop
C#: System.Diagnostics.Debugger.Break();