VB.NET to C# conversion - tips
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# :D. 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:D
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:D )
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:D)
Stopping code execution
VB: Stop
C#: System.Diagnostics.Debugger.Break();
Re: VB.NET to C# conversion - tips
Re: VB.NET to C# conversion - tips
Re: VB.NET to C# conversion - tips
I think what you are doing is a good idea, for some people.
However; for others, me for example, the best way to learn C# after 10 years of VB and VB.net, was to stop thinking about the 'old ways' and ONLY program in C#, for about 3 months.
I found it much more efficient to forget VB and learn, almost from new, how to program in C#.
Obviously I knew the important bits, that aren't language specific, and only had to find out how to do what I wanted to in the new language.
The above comments do not apply to Java, the best way to learn a language as anally retentive as it is is to become a religious zealot and give up all your friends and family. :)
Re: VB.NET to C# conversion - tips
well i think one of the benefits of something like this is often times I find code examples on the net that are written in C# and I need to convert them to VB. So as a VB developer, knowing the difference between the 2 helps. Same goes for a C# only developer who finds some VB.NET examples.
I wonder if MS will ever work in a merger with the 2 and just have 1 overall preferred language for the .net environment and whatever comes next.
Re: VB.NET to C# conversion - tips
i think this should be made a sticky...
and there is also a typo in the section "Breaking out of functions, loops, etc" - 'Exit White' should be 'Exit While'.
Re: VB.NET to C# conversion - tips
Quote:
Originally Posted by tr333
i think this should be made a sticky...
and there is also a typo in the section "Breaking out of functions, loops, etc" - 'Exit White' should be 'Exit While'.
hey thanks:) fixed it
I almost forgot I had posted this thread before:D I was supposed to update with events and other stuff... havent had time:D:D soon I hope!
Re: VB.NET to C# conversion - tips
Thanks Mr.Polite,this is Great...Even I wish you could keep this thread sticky on top :)
Re: VB.NET to C# conversion - tips
Mr.Polite,how to pass parameters in c#...
like...
in vb.net...take for example..we use..
VB Code:
Dim _Filestream As New System.IO.FileStream("c:\countsvalue.txt", IO.FileMode.Open)
Notice how we pass parameters...like "filename","openmode" etc...
how do I do the same in c#...passing parameters...??
Re: VB.NET to C# conversion - tips
params are passed very much the same way. Variables are declared a little different though... so your VB code line would look something like
Code:
System.IO.FileStream _Filestream = new FileStream("C:\\coutsvalue.txt",IO.FileMode.Open);
Re: VB.NET to C# conversion - tips
Thanks Matt :) That is Great
Re: VB.NET to C# conversion - tips
Quote:
Originally Posted by MrPolite
hey thanks:) fixed it
I almost forgot I had posted this thread before:D I was supposed to update with events and other stuff... havent had time:D:D soon I hope!
Any further update? :)
Re: VB.NET to C# conversion - tips
Quote:
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
Correcting you :] May only apply to 2.0 of the Framework (?) but just use:
Code:
For num as integer = 1 to 10
If num = 5 Then
Continue For 'Skips to the "Next" statement
End if
Console.WriteLine(num.ToString())
Next
Re: VB.NET to C# conversion - tips
Short-Circuiting
Common Issue but for C# peeps moving to VB.NET its probably worth mentioning that you need to use "AndAlso" or "OrElse" instead of "And" or "Or" if you want to short-circuit like C# does by default with && and ||
Also the "IIF" statement in VB.NET will evaluate BOTH results unlike in C# which will only evaluate the required result.
Also I believe IIF is a lot lot lot slower than using a standard IF statement (in VB.NET)
Re: VB.NET to C# conversion - tips
Quote:
Originally Posted by tailz
Short-Circuiting
Common Issue but for C# peeps moving to VB.NET its probably worth mentioning that you need to use "AndAlso" or "OrElse" instead of "And" or "Or" if you want to short-circuit like C# does by default with && and ||
Also the "IIF" statement in VB.NET will evaluate BOTH results unlike in C# which will only evaluate the required result.
Also I believe IIF is a lot lot lot slower than using a standard IF statement (in VB.NET)
IIF is a function call. if() is basically 2 or three opcodes so yes if(0 is a great deal faster.
C# has the ?: operator which can be used instead of IIF and is actually just the same as an if() statement (more or less).
Re: VB.NET to C# conversion - tips
VB9 will support a shortcircuiting operator using the If keyword (yay)
http://www.panopticoncentral.net/arc.../08/20433.aspx