Author : MD TAREQ HASSAN | Updated : 2021/03/22
Implicit Casting
// Implicit Casting
int x = 5
long y = x; // implicitly converted, no data is lost
Derived d = new Derived();
Base b = d; // Always OK.
Explicit Casting
// Explicit Casting
double x = 1234.56;
int y = (int) x ; // y = 1234, data lost by explicitly casting
Animal x = new Animal();
Cat y = (Cat) x;
is and as operator
// To avoid exception: use `is` & `as` operator
if (myObject is Foo)
{
// casting
}
var x = "Hassan";
var y = x as object;
Convert Class
// Convert Class
var intString = "123"
var intVal = Convert.ToInt32(intString);
TryParse
// TryParse
var intAsString = "10";
Int32.TryParse(intAsString, out intVal);