Results 1 to 20 of 20

Thread: VB.NET to C# conversion - tips

Threaded View

  1. #1

    Thread Starter
    l33t! MrPolite's Avatar
    Join Date
    Sep 2001
    Posts
    4,428

    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 abcd;
    // Assign 0 to a, b, c, and d
    0;

    // You could also initialize multiple items at once
    int e 1,
        
    2,
        
    3

    Indexor (Default property)
    vb:
    VB Code:
    1. Private _item As Integer
    2.     Default Public Property item(ByVal index As Integer) As Integer
    3.         Get
    4.             Return _item
    5.         End Get
    6.         Set(ByVal Value As Integer)
    7.             _item = Value
    8.         End Set
    9.     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:
    1. Public ReadOnly Property count() As Integer
    2.         Get
    3.             Return -1
    4.         End Get
    5.     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:
    1. Protected Overrides Sub SetVisibleCore(ByVal value As Boolean)
    2.     MyBase.SetVisibleCore(value)
    3. End Sub
    PHP Code:
    protected override void SetVisibleCore(bool value)
    {
        
    base.SetVisibleCore (value);

    Declaring an API function
    vb:
    VB Code:
    1. 'add this on top: Imports System.Runtime.InteropServices
    2. <DllImport("user32.dll")> _
    3. Public Shared Function LockWindowUpdate(ByVal handle As IntPtr) As Boolean
    4. 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:
    1. Dim val As Object = 123
    2. ' These two if statements work the same.
    3. If (val.GetType() Is GetType(Integer)) Then
    4. End If
    5. If (TypeOf (val) Is Integer) Then
    6. 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:
    1. Dim val As Object = 123
    2. 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:
    1. Dim numbers As Integer() = {1, 2, 3, 4, 5}
    2. For i As Integer = 0 To numbers.Length - 1
    3.     Console.WriteLine(numbers(i).ToString())
    4. Next
    5.  
    6. ' Skip every other item by using Step 2 (increments i by 2 instead of 1)
    7. For i As Integer = 0 To numbers.Length - 1 Step 2
    8.     Console.WriteLine(numbers(i).ToString())
    9. Next
    10.  
    11. 'For-Each
    12. For Each num As Integer In numbers
    13.     Console.WriteLine(num.ToString())
    14. Next
    C#:
    PHP Code:
    int[] numbers = {1,2,3,4,5};
    for (
    int i=0i<numbers.Lengthi++)
    {
        
    Console.WriteLine (numbers[i].ToString());
    }

    // Skip every other item by using i+=2 (increments i by 2 instead of 1)
    for (int i=0i<numbers.Lengthi+=2)
        
    Console.WriteLine (numbers[i].ToString());

    // Foreach example
    foreach (int num in numbers)
    {
        
    Console.WriteLine (num.ToString());

    Do-While loops:
    vb:
    VB Code:
    1. Dim count As Integer = 9
    2. Do     ' Print 9 through 1
    3.     Console.WriteLine(count.ToString())
    4.     count -= 1
    5. Loop While (count > 0)
    6.  
    7. count = 9
    8. Do While (count > 0)       'Same result as above
    9.     Console.WriteLine(count.ToString())
    10.     count -= 1
    11. 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:
    1. Dim num As Integer = 1
    2. Select Case num
    3.     Case 1
    4.     Case 2
    5.         Exit Select
    6.     Case 3
    7.         num = 9
    8.     Case 4
    9.         Return              ' Return out of the function
    10.  
    11.     Case Else
    12.         num += 1
    13. 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:
    1. ' Used below with the WHEN clause
    2. Dim catchIOErrors As Boolean = True
    3.  
    4. Try
    5.     ' Code
    6. Catch ioEx As System.IO.IOException When catchIOErrors
    7.     ' Code (only catches if catchIOErrors is set to true)
    8. Catch ex As SystemException
    9.     ' Code
    10. Catch
    11.     ' Code
    12. Finally
    13.     ' Code
    14. End Try
    C#:
    PHP Code:
    // put your code inside the brackets
    try
    {}
    catch (
    SystemException ex)
    {}
    catch 
    {}
    finally
    {} 

    Thread locks
    vb:
    VB Code:
    1. SyncLock "myLock"
    2. 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:
    1. AddHandler Me.Click, AddressOf Form1_Click
    2. 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!!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width