VB.Net - Syntax


Static Variables

Also known as Static method variables or method level static variables
These are not supported in C#.
The equivalent in C# would be a private static variable to the class
VB.Net static local variables are not thread safe


Static variables are not used very often but they can be very useful when used in the correct way.
Variables do have a lifetime.
Indicates that the local variable is preserved between calls.
A static variable can be thought of as a local variable with memory.
A static variable is a local variable whose lifetime is the lifetime of the entire module and not the procedure where it is declared.
In fact static variables retain their values as long as the code module is active. There does not have to be any code running all the time.
Therefore a static variable has the scope of a local variable but the lifetime of a module level variable.
Makes a variable persistent even after the procedure has completed.
The next execution of the routine can access the previous value.
It is the lifetime of a variable that determines its existence, the scope determines its visibility.


Private Module Level Variables

You can obtain the same effect using a private module level variable instead of a static variable.
It is considered better programming practice to use static variables as this uses a more restictive scope.
This helps to prevent accidental changes being made to the variable in other portions of the code.


Simple Example

Using "static variables" lets you retain the value of a variable that may go in and out of scope during execution, yet remain valid.
A static variable has the scope of a local variable although the lifetime of a module level variable.

Public Sub Procedure_One() 
   Debug.Print Function_Two()
   Debug.Print Function_Two()
   Debug.Print Function_Two()
   Debug.Print Function_Two()
   Debug.Print Function_Two()
End Sub

Public Function Function_Two() As Integer
Static iValue As Integer

   iValue = iValue + 1
   Function_Two = iValue
End Function

It is possible that a variable can go in and out of scope and yet remain valid during that time (ie keep its value).
Once the lifetime of the variable expires the value is lost.
It is the lifetime that determines the existence of a variable and it's the scope that determines its visibility.
Indicate that the variable is initialised the first time and is then preserved between function / procedure calls.
A static variable is a local variable whose life time is the lifetime of the entire module, not just the procedure


Static Procedures and Functions

To make all local variables in a procedure or function static, place the static keyword at the beginning of the procedure or function heading (eg Static Sub or Static Function).


Private Static Sub Procedure_One() 
Dim slocalvariable As String

End Sub

With End Block

There is no direct equivalent to this in C#

oHttpWebRequest.Method = "GET"; 
oHttpWebRequest.TimeOut = 10000

You can use object initializers

MyClass myObject = new SuperHero(); 
myObject = new MyClass() {Name="Text", Value=3 }

With oHttpWebRequest 
.Method = "GET"
.TimeOut = 10000
End With


Dim myObject As MyClass; 
myObject = New MyClass;

With myObject
.Name = "Text"
.Value = 3
End With

Option Strict

This is switched off by default but actually appears as "(custom)"
The default is off which is to allow implicit type casting (or late binding).
When switched on it will prevent narrowing conversions without explicit casting.


Right click on your project and select "Properties"
Display the Compile tab
SS


This setting does not exist in C#, because implicit data type converson is not allowed.
This is a new setting in VB.NET and is switched off by default.
Ensures you do not perform any unsafe type conversions
With Option Strict On you cannot perform any narrowing conversions
(i.e. you cannot cast a variable from Long to Integer without explicitly using a conversion function)
Widening is always allowed.



Special reference should be made to the function CType()
This function allows us to temporarily convert a variable of one Reference type (usually object) into another Reference type.
When Option Strict is on this is the only way to convert a variable of type Object into a more specific data type.


All objects are early bound by default
Early binding means our code is checked at compile time (before run-time errors can occur) to determine whether a certain object has the correct properties and methods.
Intellisense is a direct consequence of early binding.


If Option Strict is On, when you pass in a Single with a decimal part (eg 3.45) you must append the letter F (3.45F) to indicate to the compiler that the value is a Single and not a Double.


Option Explicit

This setting does not exist in C#, because variables must always be declared
[include link ??]


The default is on and this is not included in your source code.
Determines if you have to declare all your variables before they are used.


C# requires all variables to be declared and there is no way of turning this off.
In C# all variables must be declared before they are used.


Explicit Declaration / Option Explicit

VBA is not a "strictly typed" programming language so you can get away with not explicitly declaring the data type of your variables.
This is very bad practice and leads to code that is slow and unreadable.
There is an option though that can force you to explicitly declare the data type of each variable and this should be switched on.
Check your (Tools > Options)(Editor tab, "Require Explict Declaration") and make sure it is checked.
Selecting this check box will automatically add the statement Option Explicit to any new modules (not existing ones).


Option Explicit 

When this statement is used you must explicitly declare all your variables before using them.
This ensures that a program will not run if it contains any variables that have not been explicitly declared.


You declare variables by using the "Dim" keyword.
Local variables are the most efficient because VBA frees up the memory when the procedure or function executes


Any variables that are not specifically declared are assigned as a "Variant" data type. VBA automatically converts the data to the proper type when it is used.


The variant data type generally wastes memory although there is another reason why all your variables should be explicitly declared.
This is related to preventing typing errors.
If you accidently misspell a variable name (which can happen) a new variable will not be created if your variables have all been explicitly declared.
This can lead to some nasty Run-time errors and unpredictable results.


Variables should always be declared explicitly as it ensures that spelling mistakes are picked up and ensures that memory is used efficiently.
The "Variant" data type uses a minimum of 16 bytes and is very slow. Using a list of comma-separated variables does not work.
You do not have to explicitly declare your variables, you can let Visual Basic do this for you.
Any variables that are created automatically have the "Variant" data type and can contain any type of data.
VBA automatically converts the data to the proper type when it is used.
You should explicitly initialise the variables and not rely on the system defaults.
You code will run a lot slower since a variant data type uses up more memory.


Option Infer

This is switched on by default.
This is used extensively with LINQ statements
This enables the user of local type inference when declaring variables.
When this is On, you can declare local variables without explicitly stating their data type.


New to VB in Visual Studio 2008
The default is on.
If you have Option Explicit switched off then whether a variable has the old behaviour or new is determined by this setting ???


Turning Option Infer On allows old VB6 code full of variants to compile and run.
To set Option Infer in a file type type Option Infer On at the top of the file, before any source code
If this value conflicts with the setting in the IDE then the value in the file has precedence.
The compiler infers the data type for a variable when it is initialised.


Option Compare

By default this option is set to binary
This setting does not exist in C#, because all string comparisons are case sensitive.
By default in VB string comparisons are not case sensitive


String

You cannot assign a string expression to a Char variable, instead you must explicitly ask for a conversion from String to Char using the new CChar conversion function

Dim myChar As Char 
myChar = CChar(Mid("Sometext",3,1))

You can also use the Chr function to convert a Unicode code to a character

myChar = Chr(65) 


Project Settings

Right click on your project and select "Properties"
Display the Compile tab
SS


Is Operator

The Is operator checks if the run-time type of an expression result is compatible with a given type.

Dim oDataGridViewCell As System.Windows.Forms.DataGridViewCell 
oDataGridViewCell = Me.dgrDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex)

If (TypeOf oDataGridViewCell Is System.Windows.Forms.DataGridViewCheckBoxCell) Then

This is frequently used in conjunction with the TypeOf Operator.


TypeOf Operator

The TypeOf operator is used for checking if an object is of a particular type.
The way to check if an object is of a particular type is to use the TypeOf operator
This is frequently used in conjunction with the Is Operator.

If (TypeOf myobject Is Dog) Then 
End If

result = TypeOf x Is Integer

There is no equivalent in C#.
There is a typeof Operator in C# but it has a different meaning - which is extremely confusing.
This operator is available in VBA


TypeName

This function returns a string containing the name of the data type that is stored in a variable.

Dim sMyType As String 
Dim sStringVar As String
Dim iIntegerVar As Integer

sMyType = Microsoft.VisualBasic.Information.TypeName(sStringVar) ' Returns "String".
sMyType = Microsoft.VisualBasic.Information.TypeName(iIntegerVar) ' Returns "Integer".

The equivalent in C# is to use the object.GetType() method.
This function is available in VBA


GetType Operator

This has nothing to do with the .NET framework and was originally part of Visual Basic 6.0.
The GetType operator requires that you pass the data type in.
Do not confuse this with the .NET Framework object.GetType() method.

Dim t As Type = GetType(String) 

The equivalent in C# is to use the typeof Operator.
This operator is not available in VBA.



CType

This is a type of explicit conversion
If this conversion is not possible then an exception is thrown.
When you use Option Strict On any data type conversions must be explicit.

Dim iNumber As Integer = CType(12.5, Integer) 
Dim iNumber As Integer = CType("12.5", Integer)

The second argument is the name of the target class and is not enclosed in quotes.
Can be used on any valid expression.
If the argument cannot be cast directly to the target type in the case of the above conversion from a double to an integer.
CType will attempt to convert it even if it means losing the fractional part of the number.


If the argument cannot be converted to the target type in the case of a string to a number.

Dim iNumber As Integer = CType("sometext", Integer) 

Then the CType operator will throw an InvalidCastException error.


This is compiled inline, which means that the conversion code is part of the evaluation.
In somes cases there is no call to something else for evaluation, which makes execution faster.
If a narrowing conversion fails an OverflowException error is generated.


The following line will not compile

Dim myInteger As Integer 
myInteger = myDouble

You must use

myInteger = CType(myDouble, Integer) 

Never declare a new object when it is declared, (eg Dim object as New Connection).
Always declare the object and then set the object before you actually need it.
Always remember to set it to NOTHING (eg set object = Nothing) when you have finished with it.
When using the IsMissing function the variable must always be declared as variant.


If you have any problems with the Int() or Cint() type conversion functions then use the Str() function to return a string representation of the number first, before converting.


This is the same as using (Brackets)
This function is not available in VBA.



DirectCast

This is a type of explicit conversion
If this conversion is not possible then an exception is thrown.
This is another way to convert between different data types.
The DirectCast works in a similar way to the CType operator but has a few imporatant differences:
It only works with arguments that are reference type. If you pass a Value type then a compilation error will occur.
It cannot perform widening conversions from Short to Integer.
It cannot perform widening conversions from Single to Double.
This method is slightly faster that CType so you should use CType when you need to cast rather than convert a value.


DirectCast requires an inheritance or implementation relationship between the data types of the two arguments.
This means that one type must inherit from or implement the other.
This is a cast operator that has the same syntax as CType and is useful in certain narrowing situations
The DirectCast gives you the CLR supported conversions rather than using any of the other conversion functions.
DirectCast(objObject, Integer) will generate an exception if objObject doesn't contain an integer.
CType(objObject, Integer) will work if objObject is a Long, Double, String etc
Using DirectCast instead of CType can make the conversion that little bit faster and should only be used when you know exactly what you are converting.


Dim arArray As New ArrayList() 
Dim i as Integer
arArray.Add(100)
i = DirectCast(arArray(0), Integer)

DirectCast is twice as fast for value types (integers, etc) and marginally faster for reference types.
There is no boxing in DirectCast
DirectCast only works if the specified type and the run-time type of the expression are the same.
If the argument cannot be converted to the target type it will throw an InvalidCastException error.
This is the same as using (Brackets)
This operator is not available in VBA.



TryCast

This is a type of explicit conversion
If this conversion is not possible a Nothing value is returned.
This is a type of conversion operator that does not throw an exception.


Dim myText As String
myText = TryCast(myNumber, String)


If you try to do a coversion with DirectCast or CType and it fails an InvalidCastException is thrown.
Instead of generating an exception this operator return Nothing
This operator can only be used with reference types
This operator is not available in VBA



Large Integers

Integer 
Long

Small Integers

Short 
SByte

Unsigned Integers

UShort 
UInteger
ULong

And

If (oMyObject Is Nothing) And (bUpdate = False) Then 
End If

AndAlso

Performs short-circuiting logical.
A logical operation is said to be short-circuiting if the compiled code can bypass the evaluation of one expression depending on the result of another expression.
This means if the first expression is False the expression returns False and does not evaluated the second expression.


If (oMyObject Is Nothing) AndAlso (oMyObject.Property = True) Then 
End If

ExpressionReturnedNotes
True AndAlso TrueTrue 
True AndAlso FalseFalse 
False AndAlso TrueFalseTrue is not evaluated
False AndAlso FalseFalseFalse is not evaluated
Not (True AndAlso True)False 
Not (True AndAlso False)True 
Not (False AndAlso True)True 
Not (False AndAlso False)True 

Or

If (oMyObject Is Nothing) Or (sFullName = "Steven") Then 
End If

OrElse

Performs short-circuiting inclusive logical.
A logical operation is said to be short-circuiting if the compiled code can bypass the evaluation of one expression depending on the result of another expression.
This means if the first expression is True the expression returns False and does not evaluated the second expression.


If (oMyObject Is Nothing) OrElse (sFullName = "Steven") Then 
End If

ExpressionReturnedNotes
True OrElse TrueTrueTrue is not evaluated
True OrElse FalseTrueFalse is not evaluated
False OrElse TrueTrue 
False OrElse FalseFalse 
Not (True OrElse True)False 
Not (True OrElse False)False 
Not (False OrElse True)False 
Not (False OrElse False)True 

Not



Xor

Performs short-circuiting inclusive logical.
A logical operation is said to be short-circuiting if the compiled code can bypass the evaluation of one expression depending on the result of another expression.
This means


If (oMyObject Is Nothing) Xor (sFullName = "Steven") Then 
End If

ExpressionReturnedNotes
True Xor TrueTrue 
True Xor False  
False Xor True  
False Xor False  
Not (True Xor True)  
Not (True Xor False)  
Not (False Xor True)  
Not (False Xor False)  

Modulus

Mod (eg 10 Mod 5)


Like

There is no C# equialent, you have to use regular expressions.



If

If (bValue = True) Then 
   sVariable1 = "text";
End If

You can put everything on one line, but this makes it much harder to read.

If (bValue = True) Then sVariable1 = "text"; 
If (bValue = True) Then _
   sVariable1 = "text";

If - Else

If (bValue = True) Then 
   sVariable1 = "text";
Else
   sVariable2 = "text";
End If

You can leave out the curly brackets when there is only one statement to execute.
This makes it much harder to read and means you are limited to just one statement.

if (bValue == true) 
   sVariable1 = "text";
else
   sVariable2 = "text";

If - ElseIf - Else

Very important to remember that "else if" is 2 words in C# but "ElseIf" is 1 word in VB.Net.

If (iValue < 10) Then 

ElseIf (iValue < 20)

Else

End If

If (OR)

If ( a > b ) Or ( c < d ) Then 
End If

If (OR conditional)

You can use the "OrElse" if you do not want the second expression evaluated when the first expression is not true

If ( a > b ) OrElse ( c < d ) Then 
End If

If (AND)

If ( a > b ) And ( c < d ) Then 
End If

If (AND conditional)

You can use the "OrElse" if you do not want the second expression evaluated when the first expression is not true

If ( a > b ) AndElse ( c < d ) Then 
End If

If Nested

If (bValue = False) Then 
   If (iValue < 10) Then
   End If
End If

Immediate IF

Dim breturn As Boolean 
breturn = Microsoft.VisualBasic.Interaction.IIf(inumber<10, svariable1="some", svariable2="text")

IF Operator

This uses short-circuit evaluation to return one of two values.
This operator can be called with three arguments

If(argument1, argument2, argument3) 

The first argument must evaluate to a boolean.
When this operator has three arguments it works exactly the same as the Immediate IF
This operator can be called with two arguments.

If(argument1, argument2) 

The first argument is always returned unless it evaluates to Nothing, in which case the second argument is returned.


Select Case - End Case

Select Case Temp 
   Case "red"
      r += 1
   Case "green"
       r = r + 1
   Case "blue"
   Case Else : 'same line
End Select

For - Next

For icount = 1 to 20  'the variable is automatically declared  

Next icount

For icount As Integer = 1 to 20 'the variable is declared on the same line

Next icount

Dim icount As Integer 'the variable is declared earlier
For icount = 1 to 20

Next icount

For icount As Integer = 20 to 1 Step -1

Next icount

For icount As Integer = 2 To 10
   If (icount = 6) Then
       Continue For
   End If
Next

For - Each

Dim objRow As System.Windows.Forms.DataGridViewRow 
For Each objRow In objDataGridView.Rows

Next objRow


Do - While - Loop

Do While (inumber < 5) 
   inumber = inumber + 1
   Exit While
Loop

Do While (inumber < 5)
   If (True) Then
      Continue While
   End If
Loop


Do - Until - Loop

Do Until (inumber = 5) 
   inumber = inumber + 1
Loop

While - End - While

While 
   Exit While
End While

VB includes an additional While-End While loop. This loop is identical to the Do-While loop.


Do - Loop - While

Do 

Loop While (inumber = 5)


Do - Loop - Until

Do 

Loop Until (inumber = 5)


Classes - Overloading

Public Class MyClass 
   Public Sub New(ByVal myVar1 As String,
                  ByVal myVar2 As String)
      Me.New(myVar1)
   End Sub

   Public Sub New(ByVal myVar1 As String)
   End Sub
End Class

Public Class MyClass 
   Private _internal1 As String
   Private _internal2 As String
   Private _internal3 As String

   Public Sub New(param1 As String)
      Me._internal1 = param1
   End Sub

   Public Sub New(param1 As String, param2 As String)
      Me.New(param1)
      Me._internal2 = param2
   End Sub

   Public Sub New(param1 As String, param2 As String, param3 As String)
      Me.New(param1, param2)
      Me._internal3 = param3
   End Sub
End Class

Me

The Me keyword provides a way to refer to the specific instance of a class or structure in which the code is currently executing.
Me behaves like either an object variable or a structure variable referring to the current instance.
Using Me is particularly useful for passing information about the currently executing instance of a class or structure to a procedure in another class, structure, or module.


MyBase

The MyBase keyword behaves like an object variable referring to the base class of the current instance of a class.
MyBase is commonly used to access base class members that are overridden or shadowed in a derived class.
MyBase.New is used to explicitly call a base class constructor from a derived class constructor.


MyClass

The MyClass keyword behaves like an object variable referring to the current instance of a class as originally implemented.
MyClass is similar to Me, but all method calls on it are treated as if the method were NotOverridable.


Class_Initialize

The Class_Initialize event is no longer supported. Use 'Sub New' to initialize a class.


Events

Event Handlers in VB have very specific names.
If the name is not spelt correctly then the subroutine is not called.
These events and event handlers can only be defined at design time (not at run time).
You must specify the classname when you declare the object variable.
You cannot handle shared events as these are not tied to class instances but the class itself.


Handles

The handles clause declares that a procedure handles a specified event

Public Class MyClass 
   Event MyEvent
End Class

Public MyDerivedClass Inherits MyClass
   Sub TestEvent() Handles MyBase.MyEvent
   End Sub
End Sub

WithEvents

In VB.Net the WithEvents keyword
You can declare an object variable using the keyword WithEvents to allow the events from that class to be captured.

WithEvents objButton As System.Windows.Forms.Button 

You must create an instance of this class first.

objMyButton = New System.Windows.Forms.Button 

You can then declare a procedure with the Handles keyword to associate this with a particular event.

Public Sub MyButtonClick(byVal sender As Object, _ 
                           ByVal s As System.EventArgs) Handles objMyButton.Click
End Sub

You cannot create arrays of WithEvents object variables.


RaiseEvent

In VB.Net he RaiseEvent statement can be used to raise an event previously declared with the Event keyword.
This is the only way to cause an event to actually happen form within a class.

RaiseEvent EventName("Argument") 

This will generate an error if the event has not been declared in the same class.


AddHandler

In VB.Net the AddHandler statement
The AddHandler statement is used to associate an event handler with an event at run time.
The AddHandler statement has the following syntax:

AddHandler object.Event, New EventHandler(AddressOf eventhandler) 

The first argument is the object and the name of the event (for example a control).
The second argument is an expression that evaluates to an EventHandler delegate.


You must create an instance of the class first.

Dim objButton As System.Windows.Forms.Button 
objButton = New System.Windows.Forms.Button

AddHandler objButton.Click, New EventHandler(AddressOf MyButtonClick)

Public Sub MyButtonClick( _
                ByVal sender As Object, _
                ByVal s As System.EventArgs) _
                Handles objMyButton.Click
End Sub

VB.NET lets you dynamically associate event handlers by creating a delegate for you when you call the Addhandler statement.
If you want to handle shared events or events from a class you must use AddHandler.


AddHandler Button1_Click, AddressOf myEventHandler 

Private Sub myEventHandler()
End Sub


RemoveHandler

RemoveHandler object.eventName, AddressOf delegateInstance 

RemoveHandler Button1_Click, AddressOf myEventHandler 


AddressOf

In VB.Net the AddressOf operator can implicitly create the delegate object for you but this is not recommended.
It is possible to declare an event handler without explicitly creating the EventHandler object.
is this anything to do with multi-threaded ?

AddHandler object.Event, AddressOf Method1 
AddHandler objButton.Click, AddressOf MyButtonClick

Private Sub Method1
   Me.Invoke (New System.Action(AddressOf Method2))
End Sub

You can actually use the AddressOf operator to assign a subroutine to the delegate variable without creating the delegate object explicitly.

Public Delegate Sub MyDelegate(ByVal sArgument As String 
Dim objMyDelegate = AddressOf DebugMsg

Public Delegate Function MyDelegate2(ByVal Name As Object) As String 

Built-in Functions

Built-in functions that can be called directly in VBA will need to be prefixed with the correct namespace
VB.Net does not use arbitrary statement blocks. Instead, certain keywords that have a specialized terminating statement are used instead of the statement blocks.
In C# braces ({}) are used to delimit a statement block; otherwise, a single statement is assumed.


Statements in VB.Net are terminated by the end of the line.
You can use the colon (:) to put multiple statements in a line, and you can use the line continuation (_) character to make a statement span several lines.
Statements in Visual C# .NET are terminated by the semicolon (;).
You can use multiple statements per line, and statements can span multiple lines.


Code is automatically reformatted and realigned in VB but not in C# where you have to press (Ctrl + K), D


// C# Code 
<>
// VB.Net
!=

// C# Code 
Inherits
// VB.Net
: (colon)

// C# Code 
MyBase.New(nothing)
// VB.Net
: base (String.Empty)

// C# Code 
< System.Serializable() >
// VB.Net
[ System.Serializable ]

// C# Code 
GetType(this)
// VB.Net
this.GetType()


C# has "default namespace"
VB has "root namespace"


VBA Interoperability with Visual Studio Tools for the Office System (3.0)

link - learn.microsoft.com/en-us/previous-versions/office/developer/office-2007/bb931201(v=office.12) 

Chapter 4: Moving from VBA to VSTO and Visual Basic

link - learn.microsoft.com/en-us/previous-versions/office/developer/office-2007/dd627739(v=office.12) 

Chapter 12: Migrating VBA Solutions to VSTO

link - learn.microsoft.com/en-us/previous-versions/office/developer/office-2007/dd627738(v=office.12) 

Structure replaces Type

Structures can be used in arrays in the same way as custom types are in VBA.
All data types expose the Equals() method which is especially useful when using a structure because you can compare two structures without having to compare the individual fields.


There are quite a lot of differences but the main one is the syntax


Delegates

Sub DelegateMethod1(ByVal sMessage As String) 
    System.Console.WriteLine(sMessage);
End Sub

Sub DelegateMethod2(ByVal sMessage As String)
    System.Console.WriteLine(sMessage);
End Sub

Public Delegate Sub Del_MyDelegate(ByVal sMessage As String)

Dim delMyDelegate As Del_MyDelegate1
delMyDelegate = New Del_MyDelegate(AddressOf DelegateMethod1)

Shared Delegates

Public Delegate Function Del_AskQuestion(ByVal sMessage As String) As Boolean 

Sub Main()
   Dim delAskQuestion As Del_AskQuestion

   delAskQuestion = New Del_AskQuestion(AddressOf MessageType.AskYesNo)

   If delAskQuestion.Invoke("Do you want to save this file ?") = True Then

   End If
End Sub

This class contains a shared function that returns True if the user answers Yes to the question.

Public Class MessageType 

   Public Shared Function AskYesNo(ByVal sMessage As String) As Boolean
      Dim answer As objMsgBoxResult

      objanswer = MsgBox(sMessage, MsgBoxStyle.YesNo Or MsgBoxStyle.Question)

      AskYesNo = (objanswer = MsgBoxResult.Yes)
   End Function
End Class

VB.Net Highlights

Not case sensitive
Statements are terminated by the end of the line
Has a Line Continuation character "_"
Adjusts the capitalisation of keywords for consistency
Reformats code by logically aligning statements
Adds missing end quotes to strings
Supplying parentheses to function calls and methods
Adds parentheses when declaring subroutines.
Has implicit type conversion
Has With-EndWith capability making your code less verbose
Can use late binding
Provides more Intellisense / code completion options
Can use optional parameters
String concatenation is done using "&"


Strings & Characters


// C# Code 
\r\n
System.Environment.NewLine

// VB.Net
Microsoft.VisualBasic.Constants.vbNewline
Microsoft.VisualBasic.ControlChars.Newline
Microsoft.VisualBasic.Constants.vbCrLf
Microsoft.VisualBasic.ControlChars.CrLf

// C# Code 
\r

// VB.Net
Microsoft.VisualBasic.Constants.vbCr
Microsoft.VisualBasic.ControlChars.Cr

// C# Code 
\n

// VB.Net
Microsoft.VisualBasic.Constants.vbLf
Microsoft.VisualBasic.ControlChars.Lf

// C# Code 
\t

// VB.Net
Microsoft.VisualBasic.Constants.vbTab
Microsoft.VisualBasic.ControlChars.Tab

// C# Code 
@""""

// VB.Net
""""


Microsoft.VisualBasic

This namespace does contain a lot of the old VB 6.0 runtime functions which you should try and avoid using in a .NET solution.

Microsoft.VisualBasic.Compatibility 

When you upgrade a Visual Basic 6.0 project to VB.Net there are a number of items that are impossible to convert across to the Microsoft.VisualBasic namespace.
In this situation this additional namespace has to be used.
These items mimic the Visual Basic 6.0 behaviour while remaining compliant with the Common Language Specification
Whereever possible the upgrade tool within Visual Studio will try and move the code directly to methods in the Microsoft.VisualBasic namespace or System namespace


You should always try and use components from the System namespace if you can but if you really want to you can use he old Visual Basc 6.0 components.
For example the DirListBox, DriveListBox and FileListBox components can all be found in the Microsoft.VisualBasic.Compatibility namespace

Microsoft.VisualBasic.Information 
Microsoft.VisualBasic.CompilerServices
Microsoft.VisualBasic.Conversion
Microsoft.VisualBasic.Interaction


© 2026 Better Solutions Limited. All Rights Reserved. © 2026 Better Solutions Limited TopPrevNext