I could use something like this to check...
private static readonly int IntMaxValue = int.Parse(int.MaxValue.ToString());
private static bool IsChecked()
{
try {
var i = (IntMaxValue + 1);
return false;
}
catch (OverflowException) {
return true;
}
}
... but that's a lot of overhead in a tight loop, throwing and catching just to detect it. Is there a lighter way to do this?
EDIT for more context...
struct NarrowChar
{
private readonly Byte b;
public static implicit operator NarrowChar(Char c) => new NarrowChar(c);
public NarrowChar(Char c)
{
if (c > Byte.MaxValue)
if (IsCheckedContext())
throw new OverflowException();
else
b = 0; // since ideally I don't want to have a non-sensical value
b = (Byte)c;
}
}
If the answer is just 'no', don't be afraid to simply say that :)