Results 1 to 20 of 20

Thread: VB.NET to C# conversion - tips

  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!!

  2. #2

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

    Re: VB to C# tips

    Enumerators
    VB
    VB Code:
    1. Enum Programmers
    2.     VB = 1
    3.     CSharp
    4.     Delphi
    5.     Java
    6. End Enum
    7.  
    8. Enum myBits As Byte
    9.     bit1
    10.     bit2
    11. 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:
    1. ' Array of 9 elements (upper bound of 8)
    2. Dim numbers1(8) As Integer
    3. ' These two lines work the same
    4. Dim numbers2 As Integer() = {1, 2, 3, 4, 5}
    5. Dim numbers3 As Integer() = New Integer() {1, 2, 3, 4, 5}
    6.  
    7. ' 2D array
    8. Dim twoD_Arr(,) As Integer = {{1, 2}, {2, 4}, {3, 5}}
    9. ' Jagged array
    10. Dim jaggedArr()() As Integer = New Integer()() {New Integer() {1}, _
    11.     New Integer() {1, 2, 3, 4}, _
    12.     New Integer() {9}}
    13.  
    14. ' Accessing array elements: change the first element to 9
    15. numbers1(0) = 9
    16.  
    17. ' C# doesn't support the Redim statement
    18. Dim arr() As Integer
    19. ReDim arr(5)          ' Resize to array of length 6
    20. ' Resize to array of length 6 - Preserve values
    21. 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:
    1. Public Class Person
    2.     ' Default constructor
    3.     Public Sub New()
    4.     End Sub
    5.     Public Sub New(ByVal name As String)
    6.     End Sub
    7. End Class
    8.  
    9.  
    10. Public Class Employee : Inherits Person
    11.     ' Call the the Employee constructor that accepts a string
    12.     Public Sub New()
    13.         ' This call has to be the first line in this sub
    14.         Me.New("no name!")
    15.     End Sub
    16.  
    17.     ' Call the base constructor (Person's constructor)
    18.     Public Sub New(ByVal name As String)
    19.         ' This call has to be the first line in this sub
    20.         MyBase.New(name)
    21.     End Sub
    22. 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:
    1. Public Class test
    2.     Protected Overrides Sub Finalize()
    3.         MyBase.Finalize()
    4.     End Sub
    5. 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:
    1. Dim temp As Object
    2. ' Using  "Is" because object is a reference types and
    3. ' reference types cannot be checked using the equal sign
    4. If (Me Is temp) Then Return
    5.  
    6. Dim i As Integer = 5
    7. 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:
    1. Private Function isPositive(ByVal num As Integer) As String
    2.     ' If num>=0 returns "positive" otherwise returns "negative"
    3.     Return IIf(num >= 0, "positive", "negative")
    4. 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>="positive" "negative");

    Bitwise operators
    VB:
    VB Code:
    1. Dim a As Integer = 8
    2. Dim b As Integer = 32
    3. Dim flag As Boolean = False
    4.  
    5. Console.WriteLine(Not flag)        ' outputs true
    6. Console.WriteLine(False And True)      ' logical And
    7. Console.WriteLine(a And b)         ' bitwise And
    8. Console.WriteLine(a Or b)                  ' bitwise Or
    9. Console.WriteLine(Not a)           ' bitwise complement
    10. 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 (b);          // bitwise And
    Console.WriteLine (b);          // bitwise Or
    Console.WriteLine (~a);             // bitwise complement
    Console.WriteLine (0xA 0x9);      // Exclusive or (XOR) between 0xA and 0x9 
    Structures
    vb:
    VB Code:
    1. Public Structure PointAPI
    2.     Public X As Integer
    3.     Public Y As Integer
    4.  
    5.     ' NOTE: function variable names can be the same as class variables,
    6.     ' but to access them you'd have to use "me"
    7.     Public Sub New(ByVal X As Integer, ByVal Y As Integer)
    8.         Me.X = X
    9.         Me.Y = Y
    10.     End Sub
    11. 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 Xint Y)
        {
            
    this.X;
            
    this.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!!

  3. #3

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

    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!!

  4. #4

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

    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!!

  5. #5

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

    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!!

  6. #6
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: VB.NET to C# conversion - tips

    MP, here are 2 links that can complement what you have posted

    http://support.microsoft.com/?kbid=308470
    http://msdn.microsoft.com/library/de...quivalents.asp

  7. #7
    Frenzied Member Asgorath's Avatar
    Join Date
    Sep 2004
    Location
    Saturn
    Posts
    2,036

    Re: VB.NET to C# conversion - tips

    "The dark side clouds everything. Impossible to see the future is."

  8. #8
    Hyperactive Member GlenW's Avatar
    Join Date
    Nov 2001
    Location
    Gateshead, England
    Posts
    479

    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.

  9. #9
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    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.

  10. #10
    Frenzied Member tr333's Avatar
    Join Date
    Nov 2004
    Location
    /dev/st0
    Posts
    1,605

    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'.
    CSS layout comes in to the 21st century with flexbox!
    Just another Perl hacker,

  11. #11

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

    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 I was supposed to update with events and other stuff... havent had time soon I hope!
    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!!

  12. #12
    Fanatic Member uniquegodwin's Avatar
    Join Date
    Jul 2005
    Location
    Chennai,India
    Posts
    694

    Re: VB.NET to C# conversion - tips

    Thanks Mr.Polite,this is Great...Even I wish you could keep this thread sticky on top
    Godwin

    Help someone else with what someone helped you!

  13. #13
    Fanatic Member uniquegodwin's Avatar
    Join Date
    Jul 2005
    Location
    Chennai,India
    Posts
    694

    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:
    1. 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!

  14. #14
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    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);

  15. #15
    Fanatic Member uniquegodwin's Avatar
    Join Date
    Jul 2005
    Location
    Chennai,India
    Posts
    694

    Re: VB.NET to C# conversion - tips

    Thanks Matt That is Great
    Godwin

    Help someone else with what someone helped you!

  16. #16
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Pinas
    Posts
    11,123

    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 I was supposed to update with events and other stuff... havent had time soon I hope!
    Any further update?
    Regards,


    As a gesture of gratitude please consider rating helpful posts. c",)

    Some stuffs: Mouse Hotkey | Compress file using SQL Server! | WPF - Rounded Combobox | WPF - Notify Icon and Balloon | NetVerser - a WPF chatting system

  17. #17
    Hyperactive Member tailz's Avatar
    Join Date
    Jul 2002
    Posts
    306

    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

  18. #18
    Hyperactive Member tailz's Avatar
    Join Date
    Jul 2002
    Posts
    306

    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)

  19. #19
    type Woss is new Grumpy; wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,682

    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).
    I don't live here any more.

  20. #20
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    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
  •  



Click Here to Expand Forum to Full Width