C# to/from VB.Net Recipes

mskeel

Well-known member
Joined
Oct 30, 2003
Messages
913
Location
Virginia, USA
The differences between C# and VB have been growing smaller and smaller with each .Net release to the point where translating between them is mostly a trivial task. Despite this, newcomers to VB.Net are overwhelmed and confused by the mass of curly braces, semicolons, and strange compiler errors when copying and pasting code. The truth is that when it comes to the .Net Framework, C# and VB.Net are almost identical but there still are some major differences in syntax that can be very confusing.

Ill start with some of the basics. Please feel free to add to this list. The point is not to have an exhaustive list of conversion recipes, but to bring together enough information so that a newcomer to VB with no C# knowledge can read C#.

If you see a mistake, PM the person who wrote it so they can fix it.

Comments
C#:
//this is a one line comment
/* this is a
  multi-line comment */
///<summary>This is an XML comment</summary>
Code:
 this is a single line comment
<summary>This is an XML comment</summary>

Declaring Variables
C#:
int maxValue = 45;
MyClass super = new MyClass();
Code:
Dim maxValue as Integer = 45
Dim super1 as new MyClass
Dim super2 as MyClass = new MyClass

void functions/subs -- methods that do not return a value
C#:
public void SuperFunction()
{
   //...
}
Code:
Public Sub SuperFunction()
   ...
End Sub

Methods that return a value
C#:
public string SuperFunction()
{
   //...
}

public int AnotherSuperFunction()
{
   //...
}
Code:
Public Function SuperFunction() As String
   ...
End Function

Public Function AnotherSuperFunction() As Integer
   ...
End Function
 
Last edited by a moderator:
A few tools Ive used in the past to become more proficient in learning or translating something from C# I didt really understand or converting something in VB to C# to see how something was done:

VB.Net to C# Web Translation

C# to VB.Net Web Translation

Reflector shows you code for all procedures in an assembly in both C# & VB.Net

SharpStudio has it built into its IDE.

There were also some actual windows apps to download that did the same thing, but Ive been using the web apps if needed.

I know Reflector is 2.0 compatable/compliant, but Im not sure about the others.
 
Simple Loops

For Loop
C#:
for (int i = 0; i < 100; i++)
{
   //...
}
Code:
For i As Integer = 0 to 99
   ...
Next

For Each Loop

C#:
foreach (string item in stringList)
{
   //...
}
Code:
For Each item As String In stringList
   ...
Next

While Loop
C#:
bool done = false;
while (!done)
{
   //...
   done = true;
}
Code:
Dim done As Boolean = false
While Not done
   ...
   done = true
End While
 
Last edited by a moderator:
You raise a valid point but Im just going to throw this out there...if youre chaging your loop terminating conditions while within the loop then you are an idiot. Its not called a loop invariant for nothing!



Conditional Statements
C#:
if (condition)
{
   //...
}
else if (another_condition)
{
  //...
}
else
{
  //...
}
Code:
If condition Then
   ...
ElseIf another_condition Then
   ...
Else
   ...
End If

Logical Operators
Equals
CS - ==
VB - =

Not Equals
CS - !=
VB - <>

And
CS - &
VB - And

Short Circuited And (evaluates second condition only if first condition is true)
CS - &&
VB - AndAlso

Or
CS - |
VB - Or

Short Circuited Or (evaluates second condition only if first condition is false)
CS - ||
VB - OrElse

Not (Negate)
CS - !
VB - Not
 
Just in case anyone uses a C# for loop in a non-VBish fasion (it can be useful to do it, though it may be bad practice), here is the conversion:
Code:
[color=blue]for[/color]([i]initializingExpression[/i], [i]terminationExpression[/i], [i]iterationExpression[/i]) {
    [i]statements[/i]
}
Each expression, as well as the contents of the loop, may be converted to VB independently, then inserted into the following code listing.
Code:
[i]initializingExpression[/i]
[color=blue]While[/color] [i]terminationExpression[/i]
    [i]statements[/i]
    [i]iterationExpression[/i]
[color=blue]End While[/color]
To show what I mean, here is an example:
Code:
[COLOR=Green]// C#[/COLOR]
System.Collections.IEnumerator e = SomeCollection.GetEnumerator();
for([color=red]bool keepGoing = e.MoveNext()[/color]; [Color=blue]keepGoing[/color]; [COLOR=Purple]keepGoing = e.MoveNext()[/COLOR]) {
	[color=Sienna]Console.WriteLine(e.Current);[/color]
}


[COLOR=Green] VB[/COLOR]
Dim e As System.Collections.IEnumerator = SomeCollection.GetEnumerator()
[color=red]Dim keepGoing As Boolean = e.MoveNext()[/color]

While [color=blue]keepGoing[/color]
    [Color=Sienna]Console.WriteLine(e.Current)[/color]
    [color=purple]keepGoing = e.MoveNext()[/color]
End While
 
Inheritance
C#:
public class ClassName : InheritedClass
{
}

// Example
public class OptionsForm : System.Windows.Forms.Form
{
}
Code:
Public Class [i]ClassName[/i]
    Inherits [i]InheritedClass[/i]
End Class

 Example
Public Class MyForm
    Inherits System.Windows.Forms.Form
End Class
More information about Inheritance can be found in PlausiblyDamps tutorial Intro to Object Orientated Programming Part 2 - Simple Inheritance and Constructors

Properties
C#:
private ObjectType localVariable

public ObjectType PropertyName
{
    get { return localVariable; }
    set { localVariable = value; }
}

// Example
private string _name;

public string Name
{
    get { return _name; }
    set { _name = value; }
}
Code:
Dim [i]localVariable[/i] As [i]ObjectType[/i]
Public Property [i]localVariable[/i]() As [i]ObjectType[/i]
    Get
        Return [i]localVariable[/i]
    End Get
    Set(ByVal Value As String)
        [i]localVariable[/i] = Value
    End Set
End Property

 Example
Dim _name As String
Public Property Name() As String
    Get
        Return _name
    End Get
    Set(ByVal Value As String)
        _name = Value
    End Set
End Property
More information about Properties can be found in PlausiblyDamps tutorial Intro to Object Orientated Programming Part 2 - Properties

Constructors
C#:
public class ClassName
{
    public ClassName()
    {
        // this is the constructor without parameters
    }
    
    public ClassName(ObjectType variableName)
    {
        // an overloaded constructor accepting parameters
    }
}

// example
public class Person
{
    public Person()
    {
        // this is the constructor without parameters
    }
    
    public Person(string pName)
    {
        // an overloaded constructor accepting parameters
    }
}
Code:
Public Class [i]ClassName[/i]

    Public Sub New()
    End Sub

    Public Sub New(ByVal [i]variableName[/i]As [i]ObjectType[/i])
    End Sub 

End Class

 Example
Public Class Person

    Public Sub New()
    End Sub

    Public Sub New(ByVal name As String)
    End Sub 

End Class
More information about Constructors can be found in PlausiblyDamps tutorial Intro to Object Orientated Programming Part 2 - Constructors
 
Implementing Interfaces

Building on Cags inheritance post above, there is a distinction in VB between implementing an interface and inheriting from a class, but there is not in C#.
C#:
public class ClassName : ISomeInterface
{
   // Implement interface members along with other methods here...
}
Code:
Public Class [I]ClassName[/I]
   Implements ISomeInterface
    Implement interface members along with other methods here...
End Class
 
Implementing Interface Members

There are differences between implementing interfaces in VB and C#. VB allows you to implement a function of an interface with whatever name and visibility you like. C# only allows either a public method with the same name as the interfaces method or an unnamed private method. Sometimes there may be no direct conversion when it comes to interface implementation.
Code:
[Color=Magenta]<VB>[/Color]
[Color=blue]Interface[/color] IExample
    [Color=blue]Sub[/color] DoStuff()
    [Color=blue]Sub[/color] DoOtherStuff()
[Color=blue]End Interface[/color]

[Color=blue]Class[/color] Implementor
    [Color=blue]Implements[/color] IExample

    [Color=Green]Most common scenario: Public/Same name as interface method.[/Color]
    [Color=blue]Public Sub[/color] DoStuff() [Color=blue]Implements[/color] IExample.DoStuff
    [Color=blue]End Sub[/color]

    [Color=green]Custom name and private visibility.[/color]
    [Color=blue]Private Sub[/color] RandomName() [Color=blue]Implements[/color] IExample.DoOtherStuff
    [Color=blue]End Sub[/color]
[Color=blue]End Class[/color]


[Color=Magenta]<C#>[/Color]
[color=blue]interface[/color] IExample
{
    [color=blue]void[/color] DoStuff();
    [color=blue]void[/color] DoOtherStuff();
}

[color=blue]class[/color] Implementer:IExample
{
    [color=green]// Most common scenario: Implicit Implementation
    // What method of what interface this method implements is implied by its
    // name (must be public).[/color]
    [color=blue]public void[/color] DoStuff() {}

    [color=green]// Explicit Implementation
    // This function is private and has no name, and can not be accessed directly, but only
    // through the interface (you must cast to IExample).[/color]
    [color=blue]void[/color] IExample.DoOtherStuff() {}
}
 
Generics

Here is a basic generic definition in VB and in C#.
Code:
[color=magenta]<VB>[/color]
[color=blue]Class[/color] Pair(Of T)
    [color=blue]Public[/color] One [color=blue]As[/color] T
    [color=blue]Public[/color] Another [color=blue]As[/color] T
[color=blue]End Class[/color]

[color=magenta]<C#>[/color]
[COLOR=Blue]class[/COLOR] Pair<T> {
    [COLOR=Blue]public[/COLOR] T One;
    [COLOR=Blue]public[/COLOR] T Another;
}

The following are comparison of equivalent constraints.
Code:
[COLOR=Green]<Type must have default constructor>[/COLOR]
[COLOR=Blue]Class[/COLOR] HasDefaultConstructor([COLOR=Blue]Of [/COLOR]T [COLOR=Blue]As New[/COLOR])
[COLOR=Blue]class[/COLOR] HasDefaultConstructor<T> [COLOR=Blue]where[/COLOR] T : [COLOR=Blue]new[/COLOR]() { }

[COLOR=Green]<Type must be a reference type (class)>[/COLOR]
[color=blue]Class[/color] IsClass([color=blue]Of[/color] T [color=blue]As Class[/color])
[color=blue]class[/color] IsClass<T> [color=blue]where[/color] T : [color=blue]class[/color] { }

[COLOR=Green]<Type must be a value type (structure)>[/COLOR]
[color=blue]Class[/color] IsClass([color=blue]Of[/color] T [color=blue]As Structure[/color])
[color=blue]class[/color] IsClass<T> [color=blue]where[/color] T : [color=blue]struct[/color] { }

[COLOR=Green]<Type must inherit a certain base class>[/COLOR]
[color=blue]Class[/color] IsClass([color=blue]Of[/color] T [color=blue]As[/color] SomeBaseClass)
[color=blue]class[/color] IsClass<T> [color=blue]where[/color] T : SomeBaseClass { }

[COLOR=Green]<Type must implement a certain interface>[/COLOR]
[color=blue]Class[/color] IsClass([color=blue]Of[/color] T [color=blue]As[/color] IEnumerable)
[color=blue]class[/color] IsClass<T> [color=blue]where[/color] T : IEnumerable { }

[COLOR=Green]<Type must inherit or implement a generic type>[/COLOR]
[color=blue]Class[/color] IsClass([color=blue]Of[/color] T [color=blue]As[/color] IEnumerable<T>)
[color=blue]class[/color] IsClass<T> [color=blue]where[/color] T : IEnumerable<T> { }

[COLOR=Green]<Example of a combination of constraints>[/COLOR]
[COLOR=Blue]Class[/COLOR] HasDefaultConstructor([COLOR=Blue]Of [/COLOR]T [COLOR=Blue]As [/COLOR]{SomeBaseClass, IEnumerable, New}
[COLOR=Blue]class[/COLOR] HasDefaultConstructor<T> [COLOR=Blue]where[/COLOR] T : SomeBaseClass, IEnumerable, [COLOR=Blue]new[/COLOR]() { }
Note that VB requires the "new" constraint to be the first, whereas C# requires it to be the last. VB and C# both require that "class" and "structure" constraints come first. The "new" constraint can never be used in conjunction with the "class" or "structure" constraint. All three are mutually exclusive ("new" implies a class and "structure" implies a lack of a default constructor) so there is never any conflict between the three when it comes to positioning.

In both VB and C#, within code, the generic type parameters are used the same way (i.e. in the same exact manner as any other type).
 
Last edited by a moderator:
Back
Top