473,394 Members | 1,703 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,394 software developers and data experts.

C# Conversion Differences

Why will this fail:

(short) txtQty.Text

and this succeed?

Convert.ToInt16(txtQty.Text)
Nov 4 '06 #1
5 1525
Scott M. <No****@NoSpam.comwrote:
Why will this fail:

(short) txtQty.Text
That's trying to do a *cast* from a string to a short - and no such
*language* conversion is available.
and this succeed?

Convert.ToInt16(txtQty.Text)
That's calling a *method* (rather than casting) which takes a string
and returns a short.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 4 '06 #2
Scott M. wrote:
Why will this fail:

(short) txtQty.Text

and this succeed?

Convert.ToInt16(txtQty.Text)
Two completely different things.

The second work because Convert.ToInt16 has an
overload that takes a string.

The first fails because you can not cast from
a string to a short.

Arne
Nov 4 '06 #3

Scott M. wrote:
Why will this fail:

(short) txtQty.Text

and this succeed?

Convert.ToInt16(txtQty.Text)
Perhaps you misunderstand what a cast is (usually). Conceptually there
are several kinds of casts in C#. Unfortunately they all use the same
syntax, so it can be confusing. The kinds of casts that I can think of
off the top of my head are:

1. Unboxing casts: you have a value type (such as int) wrapped up to
look like an Object. When you say

int x = (int)obj;

you're trying to unwrap the boxed value and get the integer back again.
This kind of cast is very restrictive: you have to specify the type in
the box and nothing else.

2. Value type coercions: you have one value, such as an int, and you
want to fit it into another value type, such as a short. When you say

short s = (short)x;

you're telling the compiler to convert one numeric type to another, and
you don't care about any lost precision.

3. Conversions down the inheritance hierarchy. If you have a class
Derived that is derived from class Base, and you have:

Base b = new Derived(...);
Derived d = (Derived)b;

what you are saying to the compiler is, "The variable b contains a
reference to a Derived object (or something else farther down the
inheritance hierarchy). Trust me. I know."

4. Finally, you can write casts yourself, which can do anything you
like. In C# 2.0 and before, you can do this only for your own types,
but in C# 3.0 I believe that you can use extension methods to add casts
for existing types.

The lesson in all of this is that except for the cast mentioned in #4,
most of the casts in C# don't do anything radical. Conservativsm is the
watchword. Unlike languages like VB.NET, C# avoids seemingly-simple
statements that end up doing complex conversions.

Converting a string to a short is complex. At the very least, it can
result in format exceptions: what if the string doesn't contain a valid
representation of a number? What if the user is in Denmark? Egypt?
China? How does this affect number formatting and how does it affect
how the machine should interpret the string? It's not as simple as just
reading the string and pumping out a number.

For that reason, C# supplies a function to do the conversion. The fact
that you have to call a function is a hint that this isn't as simple as
it looks. Notice, in this case, that the method has three overloads: a
string, a string and a format provider, and a string and an int
representing the base representation.

Nov 4 '06 #4
Scott,

Because you are a long time VB.Net user and contributor to the non C# dotNet
newsgroups is it in my idea easy trying to explain this from the equalities
with that language and C#.

In C# you have as in VB.Net beside the "convert" and "parse" functions the
same as in VB.Net the CType and DirectCast.

The "as" keyword in C# gives the same results as the DirectCast in VB.Net.
http://msdn2.microsoft.com/en-us/lib...bt(VS.80).aspx

The construction between () you show gives in C# the same results as the
CType in VB.Net.
(Searching for a link for this one is not easy) but you know it I assume
from VB.Net. A as you most probably know is this construction not forever a
direct cast, it can be a convert if the types have user defined conversions,
the same as the CType in VB.Net)

I assume that you are well known with the "parse" and "convert" methods,
knowing how long you are active outside the C# newsgroup.

Just to give you an idea in another way.

Cor

"Scott M." <No****@NoSpam.comschreef in bericht
news:OA**************@TK2MSFTNGP02.phx.gbl...
Why will this fail:

(short) txtQty.Text

and this succeed?

Convert.ToInt16(txtQty.Text)

Nov 5 '06 #5
Thanks everyone.
"Scott M." <No****@NoSpam.comwrote in message
news:OA**************@TK2MSFTNGP02.phx.gbl...
Why will this fail:

(short) txtQty.Text

and this succeed?

Convert.ToInt16(txtQty.Text)

Nov 5 '06 #6

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

Similar topics

8
by: Gregory Casamento | last post by:
I am currently looking for a way to convert HTML to PDF in Java. I cannot: 1) use anything which is MS-Windows specific. 2) Use an external server which processes the HTML -> PDF. Keeping...
2
by: seia0106 | last post by:
Hello I am writing a function to read a binary file. Here is a part of code #include <fstream> .. .. BYTE *pData; long lDataLen; pms->GetPointer(&pData); lDataLen = pms->GetSize(); // Read...
5
by: Dan | last post by:
Hi Gurus I got a very basic question to ask: When a .NET exe (MSIL) is first run, the JIT-compiler will converts the IL into native codes so that it can executes on the current machine. my...
2
by: Peter Mather | last post by:
Hi, I have struck problems when trying to convert an Access97 database to Access 2000. I get a compile Error when I start the database in Access 2000.. The message is Can't find project or...
8
by: Perception | last post by:
Hello all, If I have a C-like data structure such that struct Data { int a; //16-bit value char; //3 ASCII characters int b; //32-bit value int c; //24-bit value }
4
by: hday1 | last post by:
What is the difference between these two lines of code. Feet = Double.Parse(FeetTextBox.Text) Feet = CDbl(FeetTextBox.Text) Thanks, Hilton
47
by: rawCoder | last post by:
Hi, Just wanted to know if there is any speed difference between VB conversion Keywords like CInt, Clng, CStr, CDbl, CBool etc. ..NETs Convert.To<...> methods. And which is better to be...
5
by: Martin Jørgensen | last post by:
Hi, I'm using this alloc_mem-function (by Michael Mair): - - - - - - - - - - - - - - - - - - - - - - - - void *alloc_mem (size_t num_elems, size_t elem_size, char *filename, int line,...
8
by: Smithers | last post by:
Are there any important differences between the following two ways to convert to a type?... where 'important differences' means something more profound than a simple syntax preference of the...
43
by: John | last post by:
Hi This .net is driving me crazy!! In VB6 I had a type which contained a couple of multi-dimentional arrays which i used to create and read records: Type AAA : Array1(10,10,2) as Integer
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.