473,703 Members | 3,036 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

casting vs. using the "Convert" methods?


Hi everyone,

A basic one here, I think. I haven't found the pattern yet, but
sometimes when I cast a variable to another type using the "C" style cast
operator the compiler refuses to play along. It says it's an invalid cast.
However, if I use the Convert.ToInt32 () method (for example) things will
work. At least, that's how it appears to me.

Could someone explain when to use old-style parenthesized casts vs. the
Convert() methods?
Nov 16 '05 #1
7 30782
For the most part, casting says "This object of type A is really an
object of type B-derived-from-A"
Convert.To*() functions say This object isn't a type B, but there exists
a way to convert to type B"

string a = "1234";
object b = a;
string c = (string) b; // succeeds because b really
is a string.
// int d = (int) b; // fails because b is not an int.
int e = Convert.ToInt32 (b); // Succeeds because b can be converted
into an int.

"Jim Bancroft" <as******@nowhe re.com> wrote in message
news:#w******** ******@tk2msftn gp13.phx.gbl...

Hi everyone,

A basic one here, I think. I haven't found the pattern yet, but
sometimes when I cast a variable to another type using the "C" style cast
operator the compiler refuses to play along. It says it's an invalid cast. However, if I use the Convert.ToInt32 () method (for example) things will
work. At least, that's how it appears to me.

Could someone explain when to use old-style parenthesized casts vs. the Convert() methods?

Nov 16 '05 #2
Jim Bancroft wrote:
Hi everyone,

A basic one here, I think. I haven't found the pattern yet, but
sometimes when I cast a variable to another type using the "C" style cast
operator the compiler refuses to play along. It says it's an invalid cast.
However, if I use the Convert.ToInt32 () method (for example) things will
work. At least, that's how it appears to me.

Could someone explain when to use old-style parenthesized casts vs. the
Convert() methods?


Basically, a cast does not really convert anything but only tells the
compiler to treat something as something "similar" - it just gets a
different internal type label, seen from the compiler's standpoint.
Converting data usually actually changes the underlying data structure,
casting does not do this.

Alexander
Nov 16 '05 #3
Not true. The truth is a bit more complex than that. .NET provides
three methods of getting from point A to point B, as it were.

First, there is the implicit cast. This is the cast that doesn't
require you to do anything more than an assignment:

int i = 5;
double d = i;

These are also called "widening conversions" and .NET allows you to
perform them without any cast operator because you could never lose any
information doing it: the possible range of valid values of a double
encompasses the range of valid values for an int and then some, so
you're never going to do this assignment and then discover to your
horror that the runtime dropped a few digits off your int value. For
reference types, the rule behind an implicit cast is that the cast
could never throw an InvalidCastExce ption: it is clear to the compiler
that the cast is always valid.

You can make new implicit cast operators for your own types (which
means that you can make implicit casts that break all of the rules, if
you're stupid about it). The basic rule of thumb is that an implicit
cast can never include the possibility of losing information in the
transition.

Note that the underlying representation _did_ change in this
conversion: a double is represented completely differently from an int.

The second kind of conversion is an explicit cast. An explicit cast is
required wherever there is the possibility of losing information, or
there is a possibility that the cast might not be valid and thus throw
an InvalidCastExce ption:

double d = 1.5;
int i = (int)d;

Here you are obviously going to lose information: i will be 1 after the
cast, so the 0.5 gets lost. This is also known as a "narrowing"
conversion, and the compiler requires that you include an explicit cast
(int) to indicate that yes, you know that information may be lost, but
you don't care.

Similarly, with reference types the compiler requires explicit casts in
situations in which the cast may not be valid at run time, as a signal
that yes, you know there's a risk, but you know what you're doing.

The third kind of conversion is one that involves such a radical change
in representation that the designers didn't provide even an explicit
cast: they make you call a method in order to do the conversion:

string s = "15";
int i = Convert.ToInt32 (s);

Note that there is nothing that absolutely requires a method call here.
Implicit and explicit casts are method calls too (that's how you make
your own). The designers could quite easily have created an explicit
cast operator that converted a string to an int. The requirement that
you call a method is a stylistic choice rather than a fundamental
requirement of the language.

The stylistic reasoning goes something like this: String-to-int is a
complicated conversion with lots of opportunity for things going
horribly wrong:

string s = "The quick brown fox";
int i = Convert.ToInt32 (s);

As such, the method call gives you documentation to read, and a broad
hint that this is something more than just a quick cast.

When designing your own types (particularly your own value types), you
may decide to create cast operators and conversion functions. The lines
dividing "implicit cast", "explicit cast", and "conversion function"
territory are a bit blurry, so different people may make different
decisions as to what should be what. Just try to keep in mind
information loss, and potential for exceptions and invalid data, and
that should help you decide.

Nov 16 '05 #4
Bruce Wood wrote:
Not true. The truth is a bit more complex than that. .NET provides
three methods of getting from point A to point B, as it were.
When I was talking of casting I was of course only talking about casting
in terms of objects and not of primitive types.

Note that the underlying representation _did_ change in this
conversion: a double is represented completely differently from an int.
Well, because it was a conversion and not a cast.

Note that there is nothing that absolutely requires a method call here.
The designers could quite easily have created an explicit
cast operator that converted a string to an int. The requirement that
you call a method is a stylistic choice rather than a fundamental
requirement of the language.
As proven by PHP.
Implicit and explicit casts are method calls too (that's how you make
your own).


I have to say I am not extremely well familiar with C# internals but I
doubt it calls a method for a simple cast. Casting an instance from
object to string will probably only tell the compiler not to report the
typical incompatible types message - along with additional checks for
possible unsupported casting exceptions.
Nov 16 '05 #5
I have to say I am not extremely well familiar with C# internals but I
doubt it calls a method for a simple cast. Casting an instance from
object to string will probably only tell the compiler not to report the
typical incompatible types message - along with additional checks for
possible unsupported casting exceptions.
Hmmm... I'm not sure about the C# compiler, and even less sure about
the JIT compiler (remember the C# 'compiler' actually translates source
code into MSIL !), but if you had to design the compiler, wouldn't you
simply make it instantiate an 'anonymous' instance of the class that
the object needs to be converted to and use that instance from that
point on (till end of scope, evidently) ?

I got a feeling it might be more complicated to tell the compiler not
to report errors than to make an instance of the casted-to class and
use that (this second alternative sounds safer to me too, on top of
that).

F.O.R.

Nov 16 '05 #6
Olorin wrote:

Hmmm... I'm not sure about the C# compiler, and even less sure about
the JIT compiler (remember the C# 'compiler' actually translates source
code into MSIL !), but if you had to design the compiler, wouldn't you
simply make it instantiate an 'anonymous' instance of the class that
the object needs to be converted to and use that instance from that
point on (till end of scope, evidently) ?

I got a feeling it might be more complicated to tell the compiler not
to report errors than to make an instance of the casted-to class and
use that (this second alternative sounds safer to me too, on top of
that).

F.O.R.


This might be very well possible, as I said I do not really know how it
is internally handled.

The only thing I would wonder about, would be that by instantiating a
second instance with absolutely the indentical instance data (not only
member values but also all instance states like locks, ....) it might
cause some confusion. I'd see it as easier to simply perform a check
whether the assigned class is compatible with the cast and do it if
everything is okay.
Nov 16 '05 #7
>> Not true. The truth is a bit more complex than that. .NET provides
three methods of getting from point A to point B, as it were.
When I was talking of casting I was of course only talking about casting in terms of objects and not of primitive types.
Sorry. I misunderstood, as the OP was giving examples of primitive type
casts. My reply was more directed at the OP than at your post.
I have to say I am not extremely well familiar with C# internals but I doubt it calls a method for a simple cast. Casting an instance from
object to string will probably only tell the compiler not to report the typical incompatible types message - along with additional checks for possible unsupported casting exceptions.


What you say is true for casts up and down the reference type
hierarchy, but not for other kinds of "casts" (which are really
conversions, as you pointed out, but which use the cast notation and
therefore are rightly referred to as "casts").

Casting a reference type to one of its parent types (up the class
hierarchy) or to a child type (down the class hierarchy) does not
involve anonymous instances or any copying at all. It simply, as you
mentioned, copies the reference to a variable of another type. Both
variables continue to point at the same object instance, and will
usually interpret all method calls and property references the same
(unless a method or property is declared "new").

When I was talking about casting to a string (or from a string), I was
not referring to a simple cast down the inheritance hierarchy like
this:

Object o = "abcdef";
string s = (string)o;

which in fact does nothing more than copy the reference to "abcdef"
from o to s, along with the necessary run-time type compatibility
checking. I was, instead, referring to a cast like this:

MyClass mc = new MyClass();
string s = (string)mc;

which in C# is possible if you declare an explicit or implicit cast
operator that casts from MyClass to a string. That "cast" is, in fact,
a call to the static method you declare that performs the conversion.
(If the cast operator is implicit then you can express the second line
like this:

string s = mc;

with no complaint from the compiler. Only explicit casts _require_ the
(string) cast notation.)

Of course, when dealing with built-in primitive types and casts up and
down the class hierarchy the compiler doesn't bother calling a method.
A method call is required only for casts that you define yourself.

Nov 16 '05 #8

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

Similar topics

5
2782
by: Michael Stevens | last post by:
Probably the wrong wording but since I'm not a scripter I won't claim to know what I'm talking about. I got this script from www.htmlgoodies.com <script language="JavaScript"> <!-- window.open ('photos01.html','photogallery',config='height=550, width=750,toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no');
13
1908
by: dee | last post by:
Hi My code complies the following line: Session("passed") = 1 but puts wiggly error line under the second Session("passed") in the following expression: Session("passed") = Session("passed") + 1 Why? Thanks Dee.
10
15460
by: David Garamond | last post by:
The Postgres manual says: The AT TIME ZONE construct allows conversions of time stamps to different time zones. I'd guess most people would think what's meant here is something like "unit conversion", and that the timestamp value stays the same (much like 2 feet becomes 24 inches when it's being "converted"). But: # SELECT NOW() = NOW() AT TIME ZONE 'UTC';
2
1503
by: Matt Brown - identify | last post by:
Hello, I decided to not spend the rest of my life figuring out docking and, instead, use the cDockingHandler class offered on Veign.com (http:// www.veign.com/vrc_codeview.asp?type=app&id=149). The problem is that it is a class for vb6, and uses some methods, functions and properties that are no longer supported in vb .net. I attempted to convert it yesterday and got stuck.
6
24310
by: arti | last post by:
I dont want to use Convert(Char(9),date,106) function to show date in dd/MM/yyyy format. It changes the datatype of my column to char & I cant perform other date operations on it without changing it back to datetime. Is there any T-sql way of doing it?
6
4263
by: Ken Fine | last post by:
This is a basic question. What is the difference between casting and using the Convert.ToXXX methods, from the standpoint of the compiler, in terms of performance, and in other ways? e.g. this.ContentID = (int)ci.Conid; vs. this.ContentID = Convert.ToInt32(ci.Conid); I tend to use the latter form because it seems more descriptive to me, but it would be good to know what's best practice. I'm guessing those methods
29
11094
by: candy_init | last post by:
Hi all, I just came across the following program: #include <stdio.h> int main() { float a = 12.5; printf("%d\n", a); printf("%d\n", *(int *)&a); return 0;
0
8759
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9252
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9017
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
7872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6588
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5922
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4433
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4687
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2070
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.