Converting
Widening conversion - This is one in which the conversion is to a data type that can accommodate every possible value.
A widening conversion can be implicit or explicit.
Narrowing conversion - This is one in which the conversion is to a data type that does not accommodate every possible value
A narrowing conversion is always explicit.
The following line will not compile
Dim myInteger As Integer
myInteger = myDouble
You must use
myInteger = Ctype(myDouble, Integer)
Implicit Conversion
Conversion is perfomed automatically.
Also known as coercion.
This includes arithmetic operation. Is invoked automatically when a value of one data type is assigned to a value of another.
No special syntax is required because the conversion is type safe and no data will be lost.
Examples include conversions from smaller to larger integral types
short myshort = 5;
int myint = myshort;
This is an example of a widening conversion.
For classes there is always an implicit conversion from a Derived class to a Base class.
A derived class always contains all the members of its base class.
public class Base {}
public class Derived : Base {}
Base B = new Derived();
C# will automatically convert an integer variable to a string when it is concatenated using the + operator.
Examples include converting from smaller to larger integral types and converting from a derived class to a base class.
For built-in numeric types an implicit conversion can be made when the value can fit into the variable without being truncated or rounded off
There are no implicit conversions to the char type
There are no implicit conversions between floating-point and decimal types
int value1 = 1234;
long value2 = value1;
From | To |
Sbyte | short , int, long, float, double, or decimal |
Byte - | short , ushort, int, uint, long, ulong, float, double, or decimal |
Short - | int , long, float, double, or decimal |
Ushort - | int , uint, long, ulong, float, double, or decimal |
Int - | long , float, double, or decimal |
Uint - | long , ulong, float, double, or decimal |
Long - | float , double, or decimal |
Char - | ushort , int, uint, long, ulong, float, double, or decimal |
Float - | double |
Ulong - | float , double, or decimal |
There is no implicit data type conversion in VB.Net it must be explicit using the ToString method.
Explicit Conversion
There are three ways of performing an explicit conversion in C#
0) Brackets - returns an instance of the type you are requesting or an exception. Also known as prefix casting or type cast operator.
1) As Operator - returns an instance of the type you are requesting or null.
2) System.Convert - returns an instance of the type you are requesting or an exception.
There are three ways of performing an explicit conversion in VB.NET
0) DirectCast
1) CType
2) TryCast - the equivalent of As
© 2023 Better Solutions Limited. All Rights Reserved. © 2023 Better Solutions Limited TopPrevNext