Strings & Characters

Single or Double Quote

Strings can only use double quotes.
Single quotes can only be used with individual/single characters.

string myString = "All strings must be in double quotes"; 
char myChar = 's';


The System.Char data type is a value data type.
A char represents a single UNICODE character and occuppies two bytes.
The value of a char object is a 16-bit numerical value.
A character literal is specified within single quotes.

System.Char myChar = 'A';  


The System.String data type is a reference data type.
This is a read-only collections of char objects.
The length property returns the number of char objects that it contains.
A string literal is specified within double quotes

System.String myString = "some text"; 
string myString2 = "some text";


All Strings should be initialised when they are declared.
If string variables are not initialised they are given the value null by default.

System.String myString1; 
System.String myString1 = null;
string myString2;
string myString2 = null;


All strings should be initialised before they are used.
The empty string is an instance of the System.String object that contains zero characters.

System.String myString1 = System.String.Empty; 
string myString2 = string.Empty;

Empty vs ""

Since .NET 2.0 the following two lines are equivalent.

System.String myString1 = ""; 
System.String myString2 = System.String.Empty;


You should only assign the keyword null to a string when you want to represent an unassigned object.
The null keyword is the default value when a String variables has not been initialised.
Any attempt to call a method on a null string will generate a NullReferenceException.

Checking for Null

There are a couple of ways you can check for a null value.
System.String myString = null;

if (myString == null) { } 
if (System.String.IsNullOrEmpty(myString)) { } // added in .NET 3.5
if (System.String.IsNullOrWhiteSpace(myString)) { } // added in .NET 4.0


VB.Net and VBA Migration

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopNext