. N E T C o n v e r t C l a s s
By Michael McIntyre
Visual Basic .NET includes the keywords CBool, CByte, CChar, CShort, CInt, CLng, CSng, CDbl, CDec, CDate, CObj, CType, and CStr; each of which is used to convert a data type to another data type.
Example: CBool
CBool(“True”)
The Microsoft®.Net class library provides an alternative, the Convert class, which includes a complete set of methods for supported conversions. It provides a language-neutral and generic way to perform conversions and is available to all languages that target the common language runtime.
Example: Convert.ToBoolean
Console.WriteLine(Convert.ToBoolean(“True”))
Result: True
The Convert class provides an alternative to the VB.NET conversion keywords. There is nothing wrong with using the VB.NET intrinsic language conversion keywords instead of the .Net Framework Convert class methods. This article points out some of the differences and provides some resource links you can use to learn where, when, and why you may choose the Convert class over the VB.NET conversion keywords.
More Conversions
Not all the conversions that are possible with the .Net Framework’s Convert class are possible using the VB.NET conversion keywords. The Convert class includes many additional conversions. Here are a few, there are many more.
ChangeType - Returns an Object with a specified type and whose value is equivalent to a specified object.
FromBase64CharArray - Converts the specified subset of an array of Unicode characters consisting of base 64 digits to an equivalent array of 8-bit unsigned integers.
GetTypeCode - Returns the TypeCode for the specified object.
IsDBNull - Returns an indication whether the specified object is of type DBNull.
ToSByte - Converts a specified value to an 8-bit signed integer.
ToUInt64 - Converts a specified value to a 64-bit unsigned integer.
Easier to Use
You may find the Convert class is easier to use because remembering one word - Convert – is easier than remembering the 12+ VB.NET conversion keywords mentioned in the first paragraph of this article. By remembering the word Convert you can let Intellisense help you find the conversion method you need.
VB.NET Conversion Keyword Examples
CBool(“True”)
CSng(12.345)
CString(1045)
Convert Class Equivalents
Convert.ToBoolean(“True”)
Convert.ToSingle(12.345)
Convert.ToString(1045)
To learn more about the Convert class click here – > .Net Convert Class
To learn more about when to use the Convert class click here – > Converting with System.Convert