I have a program that asks the user for an integer (as large as they'd like). It then reads that in and does a lot of calculations with it. What I want to do is cast the input to the "best" type before using it (byte, short, int, long, or BigInteger).
What I'm looking to do is this
if(number < 256)
{
byte numberToWorkWith = (byte)number;
}
else if(number < 65536)
{
ushort numberToWorkWith = (ushort)number
}
else if ...
then I want to be able to do all of my calculations/etc with numberToWorkWith. The problem is that after I'm out of the if/else if/ else statement, I lose access to numberToWorkWith.
Here is what I've considered (and why they haven't yet worked)
- Declaring a var type numberToWorkWith (which doesn't work because I have to initialize it at declaration)
- Declaring
dynamic numberToWorkWith;
above, then putting something likenumberToWorkWith = (byte)number;
in the loop (but I need to lock in that type. The program changes the type again later on and causes an error). Creating a method like below
private static void WorkWithNumber(Type passedType) { passedType numberToWorkWith = (passedType)number; }
which gives me an error because I can't used passedType as a type (although I'm not sure why)
There is a long block of code that I execute on numberToWorkWith no matter what type it is, so I'd very much rather not copy the code 5 times to put it in each of the if/else if/else statements. I feel like solution 3 (creating a method and passing a type) might have potential ...
Thoughts? Suggestions?
Thank you in advance!!