cast object to int c# code example
Example 1: c# how to convert string to int
var myInt = int.Parse("123");
var successfullyParsed = int.TryParse("123", out convertedInt);
Example 2: c# convert string to int
int number;
bool result = int.TryParse("12345", out number);
if(result)
{
}
else
{
}
Example 3: 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}";
}