cast object to int c# code example

Example 1: c# how to convert string to int

var myInt = int.Parse("123"); // this one throw exception if the argument is not a number
var successfullyParsed = int.TryParse("123", out convertedInt); //this returns true if the convertion has been successfully done (integer is stored in "convertedInt"), otherwise false.

Example 2: c# convert string to int

int number;
bool result = int.TryParse("12345", out number);
if(result)
                {
                    // Do whatever.
                }
                else
                {
                    // Failed to parse.
                }

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}";
}