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;

FromTo
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

Important

There is no implicit datatype conversion in VB.NET it must be explicit using the ToString method.


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