473,545 Members | 2,776 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Ge tType()+"")
{
case "System.Int 16":
case "System.Int 32":
case "System.Int 64":
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.ToDoubl e(value)
Seems that this works quite well. But, perhaps that is not the "fastest"
way?

Thanks for help,

Pavils
Apr 28 '06 #1
5 2292
Pavils,

There is no IsNumeric or something like that method or property anywhere but
you can use Type.IsPrimitiv e 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.CanConvert To(typeof(doubl e))
{
double dblVal = (double)conv.Co vertTo(..., typeof(double)) ;
}

I believe it is slower than Converter.ToDou ble, 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******** ******@TK2MSFTN GP02.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.Ge tType()+"")
{
case "System.Int 16":
case "System.Int 32":
case "System.Int 64":
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.ToDoubl e(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("N um");
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("N um");
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
2785
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
8275
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 we get an interest payment. Unless the bank is cruel to its developers the interest figure will be able to be exactly represented by a computer,...
7
7232
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 mde, backend is mdb -only occurs on the production server -only occurs with mde verson - i've tested the problem with the mdb version of the...
7
6121
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> int main(void) { int t=0xFFFFFFFFFFFFFFFFDABC;
37
2259
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
118786
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 character into a number?????? In Oracle, it is:
1
442
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - Why does 1+1 equal 11? or How do I convert a string to a number? ----------------------------------------------------------------------- Javascript variables are loosely typed: the conversion between a string and a number happens automatically. Since plus...
2
2201
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - Why does 1+1 equal 11? or How do I convert a string to a number? ----------------------------------------------------------------------- Javascript variables are loosely typed: the conversion between a string and a number happens automatically. Since plus...
23
9752
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
0
7432
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7689
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7456
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7786
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5359
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5076
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3490
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1919
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1044
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.