cast object to type c# code example
Example 1: c# type conversion
float varFloat = 12.7f;
double varDouble = varFloat;
double varDouble = 2.3;
int varInt = (int) varDouble;
int varInt = 19;
string varString = varInt.ToString();
string varString = "89";
int varInt = int.Parse(varString);
double varDouble = double.Parse(varString);
int varInt = Convert.ToInt32(varString);
double varDouble = Convert.ToDouble(varString);
Example 2: custom cast c#
using System;
public readonly struct Digit
{
private readonly byte digit;
public Digit(byte digit)
{
if (digit > 9)
{
throw new ArgumentOutOfRangeException(nameof(digit), "Digit cannot be greater than nine.");
}
this.digit = digit;
}
public static implicit operator byte(Digit d) => d.digit;
public static explicit operator Digit(byte b) => new Digit(b);
public override string ToString() => $"{digit}";
}