• Saves Valuable Time
  • Trusted Accuracy for 12 Years
  • 15-Day Money-Back Guarantee

VB.NET and C# Equivalents


Equivalents were produced with Instant C# and Instant VB.      


VB.NET C#
Public
Private
Friend
Protected
Protected Friend
public
private
internal
protected
protected internal

Unsized Array

VB.NET C#
Dim myArray() As Integer int[] myArray = null;

Sized Array

VB.NET C#
Dim myArray(1) As Integer int[] myArray = new int[2];

Access Array Element

VB.NET C#
x = myArray(0) x = myArray[0];

Jagged Array

VB.NET C#
Dim myArray(1)() As Integer int[][] myArray = new int[2][];

Rectangular Array

VB.NET C#
Dim myArray(1, 2) As Integer int[,] myArray = new int[2, 3];

Resizing Array

VB.NET C#
ReDim Preserve myArray(newSize)
ReDim myArray(newSize)
System.Array.Resize(ref myArray, newSize + 1);
myArray = new foo[newSize + 1];

Initializing Array

VB.NET C#
myArray = New Integer(1) {1,2} myArray = new int[2] {1, 2};

Empty Array

VB.NET C#
Dim myArray As String() = New String() {} string[] myArray = new string[0];

Class Attribute

VB.NET C#
<Serializable()>
Public Class Foo
[Serializable()]
public class Foo

Method Attribute

VB.NET C#
<DebuggerHidden()>
Public Sub Method()
[System.Diagnostics.DebuggerHidden()]
public void Method()

Method Return Type Attribute

VB.NET C#
Public Function Method() As <ReturnAttribute> Integer [return: ReturnAttribute]
public int TestReturnValueAttribute()

Method Parameter Attribute

VB.NET C#
Public Sub Method(<xyz> ByVal x As Integer) public void Method([xyz] int x)
VB.NET C#
Integer
Boolean
String
Char
Single
Double
Date
Object
Decimal
Short
Long
Byte
SByte
UShort
UInteger
ULong
int
bool
string
char
float
double
System.DateTime (no built-in type)
object
decimal
short
long
byte
sbyte
ushort
uint
ulong
VB.NET C#
Sub Method(ByRef myParam As Integer)
End Sub
void Method(ref int myParam)
{
}
VB.NET C#


x = CBool(y)
x = CInt(y)
x = CDec(y)
x = CChar(y)
x = CStr(y)
x = CDate(y)
x = CObj(y)

x = CType(y, Foo)
x = DirectCast(y, Foo)
x = TryCast(y, Foo)
using System;

x = Convert.ToBoolean(y);
x = Convert.ToInt32(y);
x = Convert.ToDecimal(y);
x = Convert.ToChar(y);
x = Convert.ToString(y);
x = Convert.ToDateTime(y);
x = (object)y;

x = (Foo)y;
x = (Foo)y;
x = y as Foo;
VB.NET C#
Dim digits As New List(Of Integer)() From {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} List<int> digits = new List<int>() {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
VB.NET C#
#Const ONE = True
#Const TWO = 2

#If ONE
    'code for condition ONE
#ElseIf TWO Then
    'code for condition TWO
#Else
    'code for other cases
#End If
#define ONE
//#Const TWO = 2 - no C# equivalent

#if ONE
    //code for condition ONE
#elif TWO
    //code for condition TWO
#else
    //code for other cases
#endif

Local Constant

VB.NET C#
Const myConst As Integer = 2 const int myConst = 2;

Local Variable

VB.NET C#
Dim myVar As Integer = 2 int myVar = 2;

Inferred Types

VB.NET C#
Option Infer On
...
Dim myVar = 2
var myVar = 2;

Shared/Static Field

VB.NET C#
Public Shared S As Integer public static int S;

Read-Only Field

VB.NET C#
Public ReadOnly R As Integer = 2 public readonly int R = 2;

VB Static Local Variable

VB.NET C#
Sub Method()
    Static s As Integer
    s += 1
End Sub
private int Method_s;
void Method()
{
    Method_s += 1;
}
VB.NET C#
Class Foo
    Public Sub New()
        Me.New(0)
    End Sub

    Public Sub New(ByVal i As Integer)
    End Sub

    Protected Overrides Sub Finalize()
    End Sub
End Class
class Foo
{
    public Foo() : this(0)
    {
    }

    public Foo(int i)
    {
    }

    ~Foo()
    {
    }
}
VB.NET C#
Public Delegate Sub FooDelegate() public delegate void FooDelegate();

Basic Enum Declaration

VB.NET C#
Public Enum FormMode
    EditMode
    NewMode
End Enum
public enum FormMode
{
    EditMode,
    NewMode
}

Explicitly-Typed Enum

VB.NET C#
Public Enum FormMode As Byte
    EditMode
    NewMode
End Enum
public enum FormMode : byte
{
    EditMode,
    NewMode
}

Event Declarations

VB.NET C#
Public Event EventOne(ByVal p As Foo) 'implicit delegate

Public Event EventTwo As FooDelegate 'explicit delegate
public delegate void EventOneEventHandler(Foo p);
public event EventOneEventHandler EventOne;

public event FooDelegate EventTwo;

Event Wireups

VB.NET C#
AddHandler ControlA.Click, New ControlA.SomeEventHandler(AddressOf ControlA_Click)

AddHandler ControlA.Click, AddressOf ControlA_Click
ControlA.Click += new ControlA.SomeEventHandler(ControlA_Click);

ControlA.Click += ControlA_Click;

Strict Conversion of WithEvents/Handles

VB.NET C#
Class TestClass
    Private WithEvents MyField As FooDelegate

    Sub Method() Handles MyField.FooEvent
    End Sub
End Class
using System.Runtime.CompilerServices;
using System.Diagnostics;

class TestClass
{
    [AccessedThroughProperty(nameof(MyField))]
    private FooDelegate _MyField;
    private FooDelegate MyField
    {
        [DebuggerNonUserCode]
        get
        {
            return _MyField;
        }
        [MethodImpl(MethodImplOptions.Synchronized), DebuggerNonUserCode]
        set
        {
            if (_MyField != null)
                _MyField.FooEvent -= Method;

            _MyField = value;

            if (value != null)
                _MyField.FooEvent += Method;
        }
    }

    void Method()
    {
    }
}

Casual Conversion of WithEvents/Handles

VB.NET C#
Class TestClass
    Private WithEvents MyField As FooDelegate

    Sub Method() Handles MyField.FooEvent
    End Sub
End Class
class TestClass
{
    private FooDelegate MyField;

    void Method()
    {
    }

    public TestClass()
    {
        SubscribeToEvents();
    }

    private bool EventsSubscribed = false;
    private void SubscribeToEvents()
    {
        if (EventsSubscribed)
            return;
        else
            EventsSubscribed = true;

        MyField.FooEvent += Method;
    }
}
VB.NET C#
Try
    ...
Catch x As FooException
    ...
Catch y As BarException When z = 1
    ...
Finally
    ...
End Try
try
{
    ...
}
catch (FooException x)
{
    ...
}
catch (BarException y) when (z == 1)
{
    ...
}
finally
{
    ...
}
VB.NET C#
<System.Runtime.CompilerServices.Extension> _
Sub Extension(ByVal myParam As String)
    '...
End Sub
void Extension(this string myParam)
{
    //...
}

List

VB.NET C#
Dim myVar As New List(Of Integer) List<int> myVar = new List<int>();

Dictionary

VB.NET C#
Dim myVar As New Dictionary(Of String, Integer) Dictionary<string, int> myVar = new Dictionary<string, int>();

Defining a Generic Class

VB.NET C#
Public Class GenericClass (Of T) public class GenericClass<T>

Defining a Generic Class with a Constraint

VB.NET C#
Public Class GenericClass (Of T As SomeBase) public class GenericClass<T> where T: SomeBase

Defining a Generic Class with a 'new' Constraint

VB.NET C#
Public Class GenericClass (Of T As New) public class GenericClass<T> where T: new()

Defining a Generic Method

VB.NET C#
Public Function Compare(Of T)(param1 As T, param2 As T) As Integer public int Compare<T>(T param1, T param2)

Defining a Generic Method with a Constraint

VB.NET C#
Sub Swap(Of T As Class)(ByRef l As T, ByRef r As T) void Swap<T>(ref T l, ref T r) where T: class
VB.NET C#
Imports Foo
Imports Foo.Bar   ''Bar' is a type
using Foo;
using static Foo.Bar;   //'Bar' is a type

Basic Inheritance

VB.NET C#
Class Foo
    Inherits SomeBase

End Class
class Foo : SomeBase
{
}

Inheritance Keywords

VB.NET C#
MustInherit
MustOverride
Overrides
NotInheritable
NotOverridable
Shadows
abstract    (class)
abstract    (method)
override
sealed    (class)
sealed    (method)
new

Defining Interfaces

VB.NET C#
Public Interface IFoo
    Sub Method()
End Interface
public interface IFoo
{
    void Method();
}

Implementing Interfaces

VB.NET C#
Public Class Foo
    Implements IFoo

    Public Sub Method() Implements IFoo.Method
    End Sub
End Class
public class Foo : IFoo
{
    public void Method()
    {
    }
}

or:

public class Foo : IFoo
{
    void IFoo.Method()
    {
    }
}

Expression Lambda

VB.NET C#
myVar = Function(text As String) text.Length myVar = (string text) => text.Length;

Block Lambda

VB.NET C#
myVar = Function(text As String)
    Return text.Length
End Function
myVar = (string text) =>
{
    return text.Length;
}

Event Wireup with Lambda

VB.NET C#
AddHandler button.Click, Sub(src, e) Log(src, e) button.Click += (src, e) => Log(src, e);
VB.NET C#
Dim payingCustomers = From c In db.Customers
        Where c.Orders.Count > 0
        Select New With {Key .Email = c.Email, Key .Name = c.Name}
var payingCustomers = from c in db.Customers
        where c.Orders.Count > 0
        select new
        {
            Email = c.Email,
            Name = c.Name
        };

For Loop

VB.NET C#
For i As Integer = 1 To 9
Next i
for (int i = 1; i <= 9; i++)
{
}

For Each Loop

VB.NET C#
For Each s As String In StringList
Next S
foreach (string s in StringList)
{
}

While Loop

VB.NET C#
Do While condition
Loop

or:

While condition
End While
while (condition)
{
}

Do While Loop

VB.NET C#
Do
Loop While condition
do
{
} while (condition)

Loop Until

VB.NET C# (no specific 'loop until' construct)
Do
Loop Until condition
do
{
} while ( ! condition)

Do Until

VB.NET C# (no specific 'do until' construct)
Do Until condition
Loop
while ( ! condition)
{
}
VB.NET C#
Public Module Utility
    Public Sub UtilityMethod()
        ...
    End Sub
End Module

or:

Public NotInheritable Class Utility
    Private Sub New() 'prevent instantiation
    End Sub

    Public Shared Sub UtilityMethod()
        ...
    End Sub
End Class
public static class Utility
{
    public static void UtilityMethod()
    {
        ...
    }
}
VB.NET (2015 multiline string) C# (verbatim string)
Dim myVar = "first line
    second line"
var myVar = @"first line
    second line";

Named Type Object Initializer

VB.NET C#
Dim myVar = New Person() With
{
    .Name = s1,
    .Surname = s2
}
var myVar = new Person()
{
    Name = s1,
    Surname = s2
};

Anonymous Type Object Initializer

VB.NET C#
Dim myVar = New With
{
   .Name = x,
   .Surname = y
}
var myVar = new
{
   Name = x,
   Surname = y
};
VB.NET C#
Public Shared Operator *(ByVal X As SomeType, ByVal Y As SomeType) As Long
    '...
End Operator

Public Shared Narrowing Operator CType(ByVal X As SomeType) As SomeOtherType
    '...
End Operator

Public Shared Widening Operator CType(ByVal X As SomeOtherType) As SomeType
    '...
End Operator
public static long operator * (SomeType X, SomeType Y)
{
    //...
}

public static explicit operator SomeOtherType(SomeType X)
{
    //...
}

public static implicit operator SomeType(SomeOtherType X)
{
    //...
}
VB.NET C#
+, -, *, >, >=, <, <=, <<, >>
&    (string concatenation)
()    (indexing)
And
Or
AndAlso
OrElse
Not
Xor
Mod
x ^ y
=
Is
IsNot
<>
If(x, y, z)
If(x, y)
x / y    (where x and y are integers)
x / y    (where x and y are doubles)
x \ y    (where x and y are integers)
x \ y    (where x and y are doubles)
unchanged
+    (string concatenation)
[]
&
|
&&
||
! or ~    (depending on context)
^
%
Math.Pow(x, y)
= or ==    (depending on context)
==
!=
!=
x ? y : z
x ?? y
x / (double)y
x / y
x / y
Convert.ToInt32(x) / Convert.ToInt32(y)

Optional Parameters

VB.NET C#
Sub Method(p1 As Integer, Optional p2 As Integer = 0) public void Method(int p1, int p2 = 0)

Named Arguments

VB.NET C#
Method(p1 := 2, p2 := 3) Method(p1 : 2, p2 : 3)
VB.NET C#
Sub Method(ParamArray myParam As Object())
End Sub
void Method(params object[] myParam)
{
}

Property

VB.NET C#
Property MyProperty() As Integer
    Get
        Return field
    End Get
    Set (ByVal var As Integer)
        field = var
    End Set
End Property
public int MyProperty
{
    get
    {
        return field;
    }
    set
    {
        field = value;
    }
}

Indexer

VB.NET C#
Private field() As Integer

Public Default Property Item(ByVal index As Integer) As Integer
    Get
        Return field(index)
    End Get
    Set(ByVal value As Integer)
        field(index) = value
    End Set
End Property
private int[] field

public int this[int index]
{
    get
    {
        return field[index];
    }
    set
    {
        field[index] = value;
    }
}

Parameterized Property

VB.NET C# (no direct equivalent)
Public Property ParameterizedProperty(ByVal i As Integer) As Integer
    Get
        Return GetFoo(i)
    End Get
    Set(value As Integer)
        SetFoo(i, value)
    End Set
End Property
public int get_ParameterizedProperty(int i)
{
    return GetFoo(i);
}
public void set_ParameterizedProperty(int i, int value)
{
    SetFoo(i, value);
}
VB.NET C#
Select Case z
    Case 1
        CaseOneLogic()
    Case 2
        CaseTwoLogic()
    Case 3, 4
        CaseThreeAndFourLogic()
    Case Is = 5
        CaseFiveLogic()
    Case Else
        DefaultLogic()
End Select
switch (z)
{
    case 1:
        CaseOneLogic();
        break;
    case 2:
        CaseTwoLogic();
        break;
    case 3:
    case 4:
        CaseThreeAndFourLogic();
        break;
    case 5:
        CaseFiveLogic();
        break;
    default:
        DefaultLogic();
        break;
}
VB.NET C#
Public Function TupleReturningMethod1() As (first As String, middle As String, last As String)
    '... retrieve first, middle and last
    Return (first, middle, last)
End Function

'option to not assign names to tuple fields:
Public Function TupleReturningMethod2() As (String, String, String)
    '... retrieve first, middle and last
    Return (first, middle, last)
End Function

Public Sub CallTupleMethods()
    'assign the tuple to an implicitly-type variable:
    Dim names = TupleReturningMethod1()
    'can reference different parts of tuple via 'Item1', 'Item2', etc.
    Foo(names.Item1, names.Item3)
    'can reference different parts via names provided in tuple header:
    Foo(names.first, names.last)

    'assign the tuple to an explicitly-typed variable:
    Dim tuple As (first1 As String, middle1 As String, last1 As String) = TupleReturningMethod1()
End Sub
public (string first, string middle, string last) TupleReturningMethod1()
{
    //... retrieve first, middle and last
    return (first, middle, last);
}

//option to not assign names to tuple fields:
public (string, string, string) TupleReturningMethod2()
{
    //... retrieve first, middle and last
    return (first, middle, last);
}

public void CallTupleMethods()
{
    //assign the tuple to an implicitly-type variable:
    var names = TupleReturningMethod1();
    //can reference different parts of tuple via 'Item1', 'Item2', etc.
    Foo(names.Item1, names.Item3);
    //can reference different parts via names provided in tuple header:
    Foo(names.first, names.last);

    //assign the tuple to an explicitly-typed variable:
    (string first1, string middle1, string last1) tuple = TupleReturningMethod1();
}
VB.NET C#
x = TypeOf y Is z
v = GetType(w)
x = y is z;
v = typeof(w);
VB.NET C#
'Legacy:
Public Declare Function APIFunction Lib "kernel32"(ByRef x As String) As Integer

'Modern:
Imports System.Runtime.InteropServices

<DllImport("kernel32")>
Public Shared Function APIFunction(ByRef x As String) As Integer
End Function
using System.Runtime.InteropServices;

[DllImport("kernel32")]
public static extern int APIFunction(ref string x);
VB.NET C#
Public Sub LegacyErrorHandling()

    On Error GoTo ErrorHandler
    '... main logic

ErrorHandler:
    '... error handling code
End Sub
public void LegacyErrorHandling()
{
    try
    {
        //... main logic
    }
    catch
    {
        //... error handling code
    }
}
VB.NET C# (omitting null handling)
LCase(x)
UCase(x)
Left(x, 2)
Right(x, 2)
Trim(x)
LTrim(x)
RTrim(x)
Mid(x, 3)
InStr(x, y)
x.ToLower()
x.ToUpper()
x.Substring(0, 2)
x.Substring(x.Length - 2)
x.Trim(' ')
x.TrimStart(' ')
x.TrimEnd(' ')
x.Substring(2)
x.IndexOf(y) + 1
VB.NET C#
Dim myVar%
Dim myVar$
int myVar = 0;
string myVar = null;

Copyright © 1997 – 2017 Tangible Software Solutions Inc.