473,385 Members | 1,531 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Number type conversion

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
Apr 28 '06 #1
5 2280
Pavils,

There is no IsNumeric or something like that method or property anywhere but
you can use Type.IsPrimitive that will return true for all primitive types
which are all numerics (except Decimal) + Char. so you can save some typing.
BTW VB has some function called IsNumeric, so if you don't use VB you can
use the reflector tool to see how it's implemented. It does more than you
need though.

Converter class can convert only types the implement IConvertible interface,
which are all primtive types.

I don't know why you worry so much about performance, but I needed to do
something like this and what I did was
TypeConverter conv = TypeDescriptor.GetConverter(...)
if(conv != null && conv.CanConvertTo(typeof(double))
{
double dblVal = (double)conv.CovertTo(..., typeof(double));
}

I believe it is slower than Converter.ToDouble, but it works with all
primitive types and doesn't throw exceptions if the conversion is not
possible.

--
HTH
Stoitcho Goutsev (100)

"Pavils Jurjans" <pa****@mailbox.riga.lv> wrote in message
news:uV**************@TK2MSFTNGP02.phx.gbl...
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

Apr 28 '06 #2
Let's take a step back.

Where are these numbers coming from? Does a line that reads them look
like this:
int N = ReadFieldInt("Num");
or are they all like this:
object obj = ReadField("Num");

And if the latter, is ReadField() taking different types and forcing
them all into an object?

The reason I ask these questions is:
a) Doing the type identification at run-time is a slow & fragile
process.
b) Doing it at compile-time is fast & safer.
c) It's a virtual certainty that you already know what the data type
is. (for example, if they are being read from a database, the database
clearly knows what type they are. And if you are reading a particular
field, you know if that fields is a string or a number.)

Apr 28 '06 #3
Hello, James,
Let's take a step back.

Where are these numbers coming from? Does a line that reads them look
like this:
int N = ReadFieldInt("Num");
or are they all like this:
object obj = ReadField("Num");

And if the latter, is ReadField() taking different types and forcing
them all into an object?

The reason I ask these questions is:
a) Doing the type identification at run-time is a slow & fragile
process.
b) Doing it at compile-time is fast & safer.
c) It's a virtual certainty that you already know what the data type
is. (for example, if they are being read from a database, the database
clearly knows what type they are. And if you are reading a particular
field, you know if that fields is a string or a number.)


I understand you point - in my case, I am writing a solution that indeed
saved the data in the database in real type, and it is the type that is
returned in the property {get}, but I want to make interface more friendly
for the user of the class, and provide the property {set} with code that is
ready to accept all possible numeric types - so that the user of the class
doesn't have to bother about fat type-casting and converting code.

Regards,

Pavils
May 1 '06 #4
I have no idea why you are messing with this - if you declare your
property as double then all the other types will be implicitly
converted (except decimal).

I would have thought Int64 and Uint64 would require an explicit
conversion since you potentially have loss of precision but apparently
not.

May 1 '06 #5
How 'bout, instead of a property with a setter, an overloaded set
method:

void Set(Int32 v) {......}
void Set(float f) {.....}

etc.

May 1 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
by: atse | last post by:
Hi, How can I know the number of columns of the .csv files? I want to import them to the database. Thanks. Atse
6
by: John Bentley | last post by:
John Bentley writes at this level: If we think about our savings accounts then division never comes in (as far as I can see). We deposit and withdraw exact amounts most of the time. Occasionaly...
7
by: astro | last post by:
Anyone have suggestions on where to troubleshoot this error? Background: -Access 2k v. 9.0.6926 sp3 - front and backend on production server (wiindows 2k) -accessed via Citrix -front-end is...
7
by: vikky | last post by:
hi all, Out of sheer curosity, I decided to initialize an integer with a number bigger than INT_MAX, however I still am not able to justify its output. Here is the program : #include<stdio.h> ...
37
by: Gregc. | last post by:
G'day I'm trying to work out the number of years since 1970, here is my code: include <stdio.h> #include <time.h> const int SEC_IN_MIN = 60; const int SEC_IN_HOUR = SEC_IN_MIN * 60;
4
by: dba_222 | last post by:
Dear Experts, Ok, I hate to ask such a seemingly dumb question, but I've already spent far too much time on this. More that I would care to admit. In Sql server, how do I simply change a...
1
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - Why does 1+1 equal 11? or How do I convert a string to a number?...
2
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - Why does 1+1 equal 11? or How do I convert a string to a number?...
23
by: neha_chhatre | last post by:
which is the best format specifier(data type) if i have to work with decimal number. also please tell me the syntax for truncating a decimal number please reply as soon as possible
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.