casting c# code example

Example 1: c# type conversion

// --------------------- TYPE CONVERSION --------------------- //

// Implicit conversion
float varFloat = 12.7f;
double varDouble = varFloat;   // converts float => double


// Explicit conversion (casting)
double varDouble = 2.3;
int varInt = (int) varDouble;        // converts double => int


// Type convertion: number to string
int varInt = 19;
string varString = varInt.ToString();    // converts int => string


// Type convertion: string to number
string varString = "89";   
int varInt = int.Parse(varString);         // converts string => int
double varDouble = double.Parse(varString);  // converts string => double
//OR
int varInt = Convert.ToInt32(varString);
double varDouble = Convert.ToDouble(varString);

Example 2: casting in c#

Console.WriteLine(Convert.ToString(myInt));    // convert int to string
Console.WriteLine(Convert.ToDouble(myInt));    // convert int to double
Console.WriteLine(Convert.ToInt32(myDouble));  // convert double to int
Console.WriteLine(Convert.ToString(myBool));   // convert bool to string

Example 3: how to make a cast in c#

//If you want to make your own cast for your struct or class you
//can overload an operator. Note that you can't make a cast 
//if your your target class is in inheritence with yours.

// This is if you want to manually type out (MyType)b. This is recommened
// if your cast can fail.
public static explicit operator MyType(byte[] b)
{
  MyType m = new MyType();
  m = MagicToConvertByteToMytype(b);
  return m;
}

// This is if you want to do it automatically. 
// This is recommened if your cast is defananlty safe.
public static implicit operator byte[](MyType m)
{
  return m.ToBytes();
}

Example 4: how to make a cast in c#

// if we have:
float f = 12.0f;
// and we want to put the value of f into 
int x;
// we can cast f to int like this:
x = (int)f //(int) is the cast