-
Jun 14th, 2005, 08:51 PM
#1
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# . 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();
Last edited by MrPolite; Jul 12th, 2005 at 02:00 AM.
rate my posts if they help ya!
Extract thumbnail without reading the whole image file: (C# - VB)
Apply texture to bitmaps: (C# - VB)
Extended console library: (VB)
Save JPEG with a certain quality (image compression): (C# - VB )
VB.NET to C# conversion tips!!
-
Jun 14th, 2005, 08:52 PM
#2
Re: VB to C# tips
Enumerators
VB
VB Code:
Enum Programmers
VB = 1
CSharp
Delphi
Java
End Enum
Enum myBits As Byte
bit1
bit2
End Enum
C#:
PHP Code:
enum Programmers
{
VB = 1,
CSharp,
Delphi,
Java
}
enum myBits:byte
{
bit1,
bit2
}
Some examples of Arrays
Access aray elements in vb with() and with [] in C#
Note that when initializing an array in visual basic, the number that you pass inside the () is the upper bound of the array and not its size. The size of the array is the upperbound +1. In C# the number that you pass inside the brackets [] to initialize an array is the actual array size.
VB:
VB Code:
' Array of 9 elements (upper bound of 8)
Dim numbers1(8) As Integer
' These two lines work the same
Dim numbers2 As Integer() = {1, 2, 3, 4, 5}
Dim numbers3 As Integer() = New Integer() {1, 2, 3, 4, 5}
' 2D array
Dim twoD_Arr(,) As Integer = {{1, 2}, {2, 4}, {3, 5}}
' Jagged array
Dim jaggedArr()() As Integer = New Integer()() {New Integer() {1}, _
New Integer() {1, 2, 3, 4}, _
New Integer() {9}}
' Accessing array elements: change the first element to 9
numbers1(0) = 9
' C# doesn't support the Redim statement
Dim arr() As Integer
ReDim arr(5) ' Resize to array of length 6
' Resize to array of length 6 - Preserve values
ReDim Preserve arr(5)
C#:
PHP Code:
// Array of 9 elements
int[] numbers1 = new int[9];
// These two lines work the same
int[] numbers2 = {1,2,3,4,5};
int[] numbers3 = new int[]{1,2,3,4,5};
// 2D array
int[,] twoD_Arr = {{1,2}, {2,4}, {3,5}};
// Jagged array
int[][] jaggedArr = {new int[]{1},
new int[]{1,2,3,4},
new int[]{9}};
// Accessing array elements: change the first element to 9
numbers1[0] = 9;
Hex numbers
VB: &H followed by the number in hex (ie, f42 would be &HF42 )
C#: 0x followed by the number in hex (ie, f42 would be 0xf42 )
Constructors
VB: declare a subrutine with the New keyword as its name
VB Code:
Public Class Person
' Default constructor
Public Sub New()
End Sub
Public Sub New(ByVal name As String)
End Sub
End Class
Public Class Employee : Inherits Person
' Call the the Employee constructor that accepts a string
Public Sub New()
' This call has to be the first line in this sub
Me.New("no name!")
End Sub
' Call the base constructor (Person's constructor)
Public Sub New(ByVal name As String)
' This call has to be the first line in this sub
MyBase.New(name)
End Sub
End Class
C#: specify the scope (ie, public, private, ...) followed by the class name:
PHP Code:
public class Person
{
// Default constructor
public Person()
{}
public Person(string name)
{}
}
public class Employee:Person
{
// Call the the Employee constructor that accepts a string
public Employee()
:this("no name!")
{
}
// Call the base constructor (Person's constructor)
public Employee(string name)
:base(name)
{
}
}
Destructors (Finilizers)
vb:
VB Code:
Public Class test
Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub
End Class
C#:
PHP Code:
public class test
{
~test()
{
base.Finalize();
}
}
If Statements
use != in C# instead of VB's <>. Use && in place of AndAlso, and || in place of VB's OrElse. Use ! in place of vb's Not.
vb:
VB Code:
Dim temp As Object
' Using "Is" because object is a reference types and
' reference types cannot be checked using the equal sign
If (Me Is temp) Then Return
Dim i As Integer = 5
If (i = 5) Then Return ' Using the equal sing for a value type
C#:
PHP Code:
// C# uses "==" both for reference and value types
object temp = null;
if (this == temp) return;
int i = 5;
if (i==5) return;
Conditional operator (VB's IIf):
vb: IIf (conditional expression, true part, false part)
VB Code:
Private Function isPositive(ByVal num As Integer) As String
' If num>=0 returns "positive" otherwise returns "negative"
Return IIf(num >= 0, "positive", "negative")
End Function
C#: conditional expression ? true part : false part
PHP Code:
private string isPositive (int num)
{
//If num>=0 returns "positive" otherwise returns "negative"
return (num>=0 ? "positive" : "negative");
}
Bitwise operators
VB:
VB Code:
Dim a As Integer = 8
Dim b As Integer = 32
Dim flag As Boolean = False
Console.WriteLine(Not flag) ' outputs true
Console.WriteLine(False And True) ' logical And
Console.WriteLine(a And b) ' bitwise And
Console.WriteLine(a Or b) ' bitwise Or
Console.WriteLine(Not a) ' bitwise complement
Console.WriteLine(&HA Xor &H9) ' Exclusive or (XOR) between 0xA and 0x9
C#:
PHP Code:
int a=8,
b=32;
bool flag = false;
Console.WriteLine (!flag); // outputs true
Console.WriteLine (false & true); // logical And
Console.WriteLine (a & b); // bitwise And
Console.WriteLine (a | b); // bitwise Or
Console.WriteLine (~a); // bitwise complement
Console.WriteLine (0xA ^ 0x9); // Exclusive or (XOR) between 0xA and 0x9
Structures
vb:
VB Code:
Public Structure PointAPI
Public X As Integer
Public Y As Integer
' NOTE: function variable names can be the same as class variables,
' but to access them you'd have to use "me"
Public Sub New(ByVal X As Integer, ByVal Y As Integer)
Me.X = X
Me.Y = Y
End Sub
End Structure
C#
PHP Code:
public struct PointAPI
{
public int X;
public int Y;
// NOTE: function variable names can be the same as class variables,
// but to access them you'd have to use "this"
public PointAPI (int X, int Y)
{
this.X = X;
this.Y = Y;
}
}
Last edited by MrPolite; Jun 15th, 2005 at 11:42 PM.
rate my posts if they help ya!
Extract thumbnail without reading the whole image file: (C# - VB)
Apply texture to bitmaps: (C# - VB)
Extended console library: (VB)
Save JPEG with a certain quality (image compression): (C# - VB )
VB.NET to C# conversion tips!!
-
Jun 15th, 2005, 03:29 PM
#3
Re: VB to C# tips
reserved space... ignore this post
rate my posts if they help ya!
Extract thumbnail without reading the whole image file: (C# - VB)
Apply texture to bitmaps: (C# - VB)
Extended console library: (VB)
Save JPEG with a certain quality (image compression): (C# - VB )
VB.NET to C# conversion tips!!
-
Jun 15th, 2005, 03:30 PM
#4
Re: VB to C# tips
reserved space again... ignore this post
rate my posts if they help ya!
Extract thumbnail without reading the whole image file: (C# - VB)
Apply texture to bitmaps: (C# - VB)
Extended console library: (VB)
Save JPEG with a certain quality (image compression): (C# - VB )
VB.NET to C# conversion tips!!
-
Jun 15th, 2005, 11:13 PM
#5
Re: VB to C# tips
reserved space again... ignore this post
rate my posts if they help ya!
Extract thumbnail without reading the whole image file: (C# - VB)
Apply texture to bitmaps: (C# - VB)
Extended console library: (VB)
Save JPEG with a certain quality (image compression): (C# - VB )
VB.NET to C# conversion tips!!
-
Jun 16th, 2005, 08:17 AM
#6
Re: VB.NET to C# conversion - tips
-
Jun 16th, 2005, 09:53 AM
#7
Re: VB.NET to C# conversion - tips
"The dark side clouds everything. Impossible to see the future is."
-
Jun 16th, 2005, 02:33 PM
#8
Hyperactive Member
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.
-
Jun 16th, 2005, 05:43 PM
#9
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.
-
Jul 12th, 2005, 12:23 AM
#10
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'.
-
Jul 12th, 2005, 02:03 AM
#11
Re: VB.NET to C# conversion - tips
rate my posts if they help ya!
Extract thumbnail without reading the whole image file: (C# - VB)
Apply texture to bitmaps: (C# - VB)
Extended console library: (VB)
Save JPEG with a certain quality (image compression): (C# - VB )
VB.NET to C# conversion tips!!
-
Sep 9th, 2005, 01:54 AM
#12
-
Sep 9th, 2005, 02:04 AM
#13
Fanatic Member
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...??
Godwin
Help someone else with what someone helped you!
-
Sep 9th, 2005, 08:31 AM
#14
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);
-
Sep 9th, 2005, 08:39 AM
#15
-
Jan 10th, 2006, 02:02 AM
#16
Re: VB.NET to C# conversion - tips
Originally Posted by MrPolite
hey thanks fixed it
I almost forgot I had posted this thread before I was supposed to update with events and other stuff... havent had time soon I hope!
Any further update?
-
Jul 24th, 2007, 05:48 AM
#17
Hyperactive Member
Re: VB.NET to C# conversion - tips
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
-
Jul 24th, 2007, 06:05 AM
#18
Hyperactive Member
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)
-
Jul 24th, 2007, 06:56 AM
#19
Re: VB.NET to C# conversion - tips
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).
I don't live here any more.
-
Jul 24th, 2007, 09:12 AM
#20
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|