Hello,
I am somewhat lost in the implicit/expicit possible/impossible type casting
in C#...
I need to write a class, which among other things, must have wat to read a
numeric value type, and internally convert it so that it could be saved in
database as real number (float). I plan to provide property(set) interface
for reading the value.
I have counted 11 types that are "numeric" in nature. Maybe there are more,
I don't know:
SByte
Int16
Int32
Int64
Byte
UInt16
UInt32
UInt64
Decimal
Double
Single
Obviously, it makes sense to long for a single property, that takes object
type and then knows what to do with it. Alternative could be writing
separate 11 properties for all the numeric types, that sounds like good
waste of time and code.
What I am sort of looking for, is the most correct way to do the two
following things:
1. Validate if the input is numeric.
my present approaches are:
1.1. Check if the value is a mamber of any one of the types:
if (value is SByte || value is Int16 || value is Int32 ... ) { proceed }
1.2. Do it in another way:
switch(value.GetType()+"")
{
case "System.Int16":
case "System.Int32":
case "System.Int64":
case "System.UInt16":
case "System.UInt32":
case "System.UInt64":
.....
proceed
}
2. Once we discovered that value is number, must convert the value to Double
1.1. Use implicit conversion:
Possible only in case if I have different properties for different number
types
1.2. Use explicit conversion:
int i = 100;
object o = i;
double d = (double) o; // throws error "Specified cast not valid", although
double d = (double) i; works smoothly.
1.3 Use Convert.ToDouble(value)
Seems that this works quite well. But, perhaps that is not the "fastest"
way?
Thanks for help,
Pavils