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.