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

about casting

Hello!

Here I have two different way to use casting.
Is any of these any better then the other?
Or is it just a question of taste.

newCards.Add((Card)sourceCard.Clone());
newCards.Add(sourceCard.Clone() as Card);

//Tony
Jun 27 '08 #1
29 1813
Tony Johansson <jo*****************@telia.comwrote:
Here I have two different way to use casting.
Is any of these any better then the other?
Or is it just a question of taste.

newCards.Add((Card)sourceCard.Clone());
newCards.Add(sourceCard.Clone() as Card);
Using "as" doesn't throw an exception if the cast fails - it just
returns null instead.

Using a direct cast also allows for user-defined conversions etc.

I tend to use "as" for values I'm in doubt about - when I'm about to
test the result:

Object unknown = GetMeSomeData();
string text = unknown as string;
if (text != null)
{
...
}
I use direct casting when I really, really expect it to succeed - i.e.
when a failure indicates a problem which should be reported as an
exception:

Object shouldBeString = GetMeSomeText();
string text = (string) shouldBeString;

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Jun 27 '08 #2
One other note; "as" can only be used with reference types and
Nullable<T>, as it can't return null for a regular struct. You'd need
to use "is" and cast to achieve the same.

Marc
Jun 27 '08 #3
Tony,

I use "as" because it is much faster than the "(Card)" variety of casting.
Also, I think "(vehicle as Car).Color" looks a lot cleaner than "((Car)
vehicle).Color". That's my preference though - others might think "(Car)"
looks better. Let me preempt my fellow NGers by saying that you should only
optimize yada yada yada. I say, ya know what, I'm developing on mobile
devices running a 200MHz, I'm gonna use every little speed enhancement I can
get especially when it is for free.

Very important to note is that they are different as Jon pointed out, so
sometimes it makes sense to use one instead of the other.

Anyway, there you go.

Hilton

"Tony Johansson" <jo*****************@telia.comwrote in message
news:pk*************@newsb.telia.net...
Hello!

Here I have two different way to use casting.
Is any of these any better then the other?
Or is it just a question of taste.

newCards.Add((Card)sourceCard.Clone());
newCards.Add(sourceCard.Clone() as Card);

//Tony

Jun 27 '08 #4
Hilton,
Why is 'as' much faster that (Card), except in cases where (Card) might
throw an exception?
Otherwise, I think in both cases the CLR needs to walk the same level of
object type structures and so should be have the same running time.

Sujeet

"Hilton" wrote:
Tony,

I use "as" because it is much faster than the "(Card)" variety of casting.
Also, I think "(vehicle as Car).Color" looks a lot cleaner than "((Car)
vehicle).Color". That's my preference though - others might think "(Car)"
looks better. Let me preempt my fellow NGers by saying that you should only
optimize yada yada yada. I say, ya know what, I'm developing on mobile
devices running a 200MHz, I'm gonna use every little speed enhancement I can
get especially when it is for free.

Very important to note is that they are different as Jon pointed out, so
sometimes it makes sense to use one instead of the other.

Anyway, there you go.

Hilton

"Tony Johansson" <jo*****************@telia.comwrote in message
news:pk*************@newsb.telia.net...
Hello!

Here I have two different way to use casting.
Is any of these any better then the other?
Or is it just a question of taste.

newCards.Add((Card)sourceCard.Clone());
newCards.Add(sourceCard.Clone() as Card);

//Tony


Jun 27 '08 #5
Actually, I think the DirectCast version: (string) x is faster (by design)
as long as you don't get an exception because that version is meant to do
the cast without checking to see if the cast is doable first.

-Scott
"Sujeet" <Su****@discussions.microsoft.comwrote in message
news:63**********************************@microsof t.com...
Hilton,
Why is 'as' much faster that (Card), except in cases where (Card) might
throw an exception?
Otherwise, I think in both cases the CLR needs to walk the same level of
object type structures and so should be have the same running time.

Sujeet

"Hilton" wrote:
>Tony,

I use "as" because it is much faster than the "(Card)" variety of
casting.
Also, I think "(vehicle as Car).Color" looks a lot cleaner than "((Car)
vehicle).Color". That's my preference though - others might think
"(Car)"
looks better. Let me preempt my fellow NGers by saying that you should
only
optimize yada yada yada. I say, ya know what, I'm developing on mobile
devices running a 200MHz, I'm gonna use every little speed enhancement I
can
get especially when it is for free.

Very important to note is that they are different as Jon pointed out, so
sometimes it makes sense to use one instead of the other.

Anyway, there you go.

Hilton

"Tony Johansson" <jo*****************@telia.comwrote in message
news:pk*************@newsb.telia.net...
Hello!

Here I have two different way to use casting.
Is any of these any better then the other?
Or is it just a question of taste.

newCards.Add((Card)sourceCard.Clone());
newCards.Add(sourceCard.Clone() as Card);

//Tony



Jun 27 '08 #6
On Jun 12, 2:44 am, "Hilton" <nos...@nospam.comwrote:
I use "as" because it is much faster than the "(Card)" variety of casting.
No it's not. At least, it's not on the desktop CLR.

It's faster to use "as" and then a comparison with null than it is to
use "is" and then a direct cast, but if you're just casting then
they're about the same - with casting coming out slightly on top in
one microbenchmark I've just run:

using System;
using System.Diagnostics;

public class Test
{
static void Main(string[] args)
{
object o = "hello";
int iterations = int.Parse(args[0]);
int total = 0;
Stopwatch sw = Stopwatch.StartNew();
for (int i=0; i < iterations; i++)
{
total += Cast(o).Length;
}
sw.Stop();
Console.WriteLine(total);
Console.WriteLine(sw.ElapsedMilliseconds);
}

static string Cast(object o)
{
return (string)o;
}

static string As(object o)
{
return o as string;
}
}

Change the call appropriately to test the different methods, and then
change the calling code to have the cast/as directly in the loop:

Running with 2,000,000,000 iterations, 3 runs each
As: 9595, 9567m 9565
Cast: 7180, 7199, 7216
As inline: 6355, 6393, 6595
Cast inline: 4777, 4807, 4812

Normal caveats about microbenchmarks apply, but I'd be interested to
see the results of you running the above tests on the CF. It certainly
looks to me like "as" is marginally slower, and certainly far from
"much faster".
Also, I think "(vehicle as Car).Color" looks a lot cleaner than "((Car)
vehicle).Color". That's my preference though - others might think "(Car)"
looks better. Let me preempt my fellow NGers by saying that you should only
optimize yada yada yada. I say, ya know what, I'm developing on mobile
devices running a 200MHz, I'm gonna use every little speed enhancement I can
get especially when it is for free.
Except it's not for free anyway - it means you get a
NullReferenceException instead of an InvalidCastException if
anything's wrong, and that's if you're lucky and use the referece
immediately. Using "as" when you really expect a cast to work can
obscure the origin of a bug.
Very important to note is that they are different as Jon pointed out, so
sometimes it makes sense to use one instead of the other.
One thing I didn't mention about the difference between the two is
nulls. If you cast and end up with null, you know that the source was
null. If you use "as" and end up with null, it's either because the
original reference was null *or* because it referred to an object of
the wrong type.

Jon
Jun 27 '08 #7
On Jun 12, 4:19 am, "Scott M." <s...@nospam.nospamwrote:
Actually, I think the DirectCast version: (string) x is faster (by design)
as long as you don't get an exception because that version is meant to do
the cast without checking to see if the cast is doable first.
No, it's still got to do the cast to see whether or not you *do* get
an exception. As it happens it seems like it's marginally faster on
the current desktop CLR - I think it may have been the other way round
at some point. The important part is that both of them actually need
to do the same expensive bit of work: check whether a cast is valid.
What happens after that is relatively cheap (in the success case).

Jon
Jun 27 '08 #8
Jon Skeet wrote:
Normal caveats about microbenchmarks apply, but I'd be interested to
see the results of you running the above tests on the CF. It certainly
looks to me like "as" is marginally slower, and certainly far from
"much faster".
I remember doing this test after seeing an article in CodeProject and my
results definitely showed that "as" was much faster - see the CodeProject
article: http://69.10.233.10/KB/cs/csharpcasts.aspx

To verify before I posted my earlier post today, I ran some code on my
desktop. The two inner loops looked like:

{
Blob b = (Blob) o;
}

and

{
Blob b = o as Blob;
}

....and the second version was indeed *much* faster than the first, so I was
confident posting that it was much faster. Only when I went back and
thought about it, I realized that the compiler could safely remove "o as
Blob", but *not* "(Blob) o" - right? So, I was, in effect, testing compiler
optimization which I am glad to say is alive and well. OK, perhaps I had
originally tested in on CF 1. So I wrote a quick app, ran it on my X51 and
the two versions ran in exactly the same time (give or take). The
CodeProject guy never posted any code, perhaps he made the same "compiler
optimization" error as I did.

Interestingly though, the two are very different beasts, used in different
circumstances, and definitely help to self-document if used correctly. The
cool thing though is that C# has both of these tools.

OK, I was wrong - sorry about that and thanks to Jon for correcting me.

Hilton
Jun 27 '08 #9
On Jun 12, 8:26 am, "Hilton" <nos...@nospam.comwrote:
Jon Skeet wrote:
Normal caveats about microbenchmarks apply, but I'd be interested to
see the results of you running the above tests on the CF. It certainly
looks to me like "as" is marginally slower, and certainly far from
"much faster".

I remember doing this test after seeing an article in CodeProject and my
results definitely showed that "as" was much faster - see the CodeProject
article:http://69.10.233.10/KB/cs/csharpcasts.aspx
<snip>

Interestingly, there's a post there saying that the performance of
direct casting was significantly improved for .NET 2.0 - so that's
probably where the confusion comes from.

Now, for your particular case it's worth investigating whether that's
also true on the CF - or rather, for the particular version of the CF
you're using. I wouldn't be surprised if the performance
characteristics were quite different there.

<snip>
Interestingly though, the two are very different beasts, used in different
circumstances, and definitely help to self-document if used correctly. The
cool thing though is that C# has both of these tools.
Yes, it's definitely nice to have both. I do wonder whether "as" might
not be better as a slightly different language construct though -
something to do:

Foo x = y as Foo;
if (x != null)
{
...
}

in one block, e.g.:

when (Foo x = y)
{
...
}

I'm not sure though. (And I certainly wouldn't want to introduce it
now - just an idea of what might have been nice at 1.0.)

Jon
Jun 27 '08 #10
Jon Skeet wrote:
Interestingly, there's a post there saying that the performance of
direct casting was significantly improved for .NET 2.0 - so that's
probably where the confusion comes from.
Here are the CF numbers:

Running 1.0.4292.0:

33:13 <--start time
33:39 <--after () cast, before "as"
34:05 <--end time

i.e. both took 26 seconds
Running 2.0.7045.0:

35:04
35:11
35:18

i.e. both took 7 seconds - nice!

My app runs a lot zippier on CF2 than CF1. I don't recall noticing a huge
increase from 2.0 to 3.5, I'd need to do some timing, but 1.0 to 2.0 was
very noticable. Thank you Microsoft.

Hilton
Jun 27 '08 #11
On Jun 12, 10:16 am, "Tony Johansson" <johansson.anders...@telia.com>
wrote:
Here you are talking about CF what is that?
The Compact Framework - a version of .NET used for mobile devices like
PDAs.

(There's also the .NET Micro Edition, but I don't know how widely used
that is.)

Jon
Jun 27 '08 #12
The Compact Framework - a version of .NET used for mobile devices like
PDAs.
(There's also the .NET Micro Edition, but I don't know how widely used
that is.)
And the Silverlight framework; to be honest I haven't done enough
digging to know if this re-uses any of the others, or is just a
completely different architecture, but it is yet another .NET host ;-p

[out of interest, if anybody else knows... ?]

Marc
Jun 27 '08 #13
Jon,
>
Using a direct cast also allows for user-defined conversions etc.
Are you sure of this, I thought that it was the opposite

(As that is the way the DirectCast in VB for Net is working oposite the
CType (Convert or Cast Type), which are in my idea a little bit equivalent
to this. The DirectCast should be sometimes slightly quicker, those things I
never measure)

Cor
Jun 27 '08 #14
Using a direct cast also allows for user-defined conversions etc.
>
Are you sure of this, I thought that it was the opposite
cast will use defined implicit/explicit operators; "as" doesn't - you
get this instead:

"Cannot convert type 'Bar' to 'Foo' via a reference conversion, boxing
conversion, unboxing conversion, wrapping conversion, or null type
conversion"

In the ECMA spec, sections 14.6.6 and 14.9.11

Marc
Jun 27 '08 #15
On Jun 12, 12:02 pm, "Cor Ligthert [MVP]" <notmyfirstn...@planet.nl>
wrote:
Using a direct cast also allows for user-defined conversions etc.

Are you sure of this, I thought that it was the opposite
Absolutely positive. Here's proof:
XElement has an explicit user-defined conversion operator to string.

using System.Xml.Linq;

public class Test
{
static void Main()
{
XElement element = new XElement("name", "text");

// Direct cast is fine
string text = (string) element;

// Doesn't compile - no reference conversion, boxing conversion,
// unboxing conversion, wrapping conversion or null type
conversion
// available
string text2 = element as XElement;
}
}

Jon
Jun 27 '08 #16
Can you explain in more detail? The whole point of doing DirectCast-ing is
that it is faster than not doing it.
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:19**********************************@59g2000h sb.googlegroups.com...
On Jun 12, 4:19 am, "Scott M." <s...@nospam.nospamwrote:
>Actually, I think the DirectCast version: (string) x is faster (by
design)
as long as you don't get an exception because that version is meant to do
the cast without checking to see if the cast is doable first.

No, it's still got to do the cast to see whether or not you *do* get
an exception. As it happens it seems like it's marginally faster on
the current desktop CLR - I think it may have been the other way round
at some point. The important part is that both of them actually need
to do the same expensive bit of work: check whether a cast is valid.
What happens after that is relatively cheap (in the success case).

Jon

Jun 27 '08 #17
On Jun 12, 2:46 pm, "Scott M." <s...@nospam.nospamwrote:
Can you explain in more detail? The whole point of doing DirectCast-ing is
that it is faster than not doing it.
Perhaps we are talking about different things here, given your use of
capitalization. When I talk about a direct cast, I mean using:

string x = (string) y;

instead of

string x = y as string;

Are you talking about something different?

The "whole point" of a direct cast is:
1) Potentially do conversions / unboxing
2) Convert an expression of one type into another, potentially by
creating a new value but more often using an explicit reference
conversion which returns the same reference, but with a different
expression type.

"Not doing it" usually isn't an option here - the option is usually to
use "as" instead of the direct cast. Assuming it's not compile-time
verifiable, the conversion *has* to be checked at execution time
otherwise you lose type safety.

Could you give an example program where you believe some checking is
skipped?

Jon
Jun 27 '08 #18
Perhaps my confusion is that I am applying what I know about VB .NET to C#.

I've understood that using VB's DirectCast vs. its CType is preferrable for
performance when you know that the cast is "do-able".

Am I wrong in thinking that VB's DirectCast is the same as C#'s (type)
variable; and VB's CType is the same as C#'s type variable = variable as
type;?

"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:b3**********************************@l42g2000 hsc.googlegroups.com...
On Jun 12, 2:46 pm, "Scott M." <s...@nospam.nospamwrote:
>Can you explain in more detail? The whole point of doing DirectCast-ing
is
that it is faster than not doing it.

Perhaps we are talking about different things here, given your use of
capitalization. When I talk about a direct cast, I mean using:

string x = (string) y;

instead of

string x = y as string;

Are you talking about something different?

The "whole point" of a direct cast is:
1) Potentially do conversions / unboxing
2) Convert an expression of one type into another, potentially by
creating a new value but more often using an explicit reference
conversion which returns the same reference, but with a different
expression type.

"Not doing it" usually isn't an option here - the option is usually to
use "as" instead of the direct cast. Assuming it's not compile-time
verifiable, the conversion *has* to be checked at execution time
otherwise you lose type safety.

Could you give an example program where you believe some checking is
skipped?

Jon

Jun 27 '08 #19
On Jun 12, 3:53 pm, "Scott M." <s...@nospam.nospamwrote:
Perhaps my confusion is that I am applying what I know about VB .NET to C#.
I suspect so.
I've understood that using VB's DirectCast vs. its CType is preferrable for
performance when you know that the cast is "do-able".
It may well be faster than CType, but that doesn't mean it's removing
all execution-time checking. In fact, the MSDN page for VB's
DirectCast specifically states:

<quote>
But the lack of a compiler error does not guarantee a successful
conversion. If the desired conversion is narrowing, it could fail at
run time. If this happens, the runtime throws an InvalidCastException
error.
</quote>

In other words, there *is* still a check at execution time - and there
has to be, really, to maintain type safety.
Am I wrong in thinking that VB's DirectCast is the same as C#'s (type)
variable; and VB's CType is the same as C#'s type variable = variable as
type;?
I don't think it's as simple as that. I may well be wrong, but will
CType do things like converting strings to integers by parsing them?
If so, there's no direct equivalent in C#.

Looking at MSDN, it looks to me like C# casting, e.g. string x =
(string) y is *mostly* the equivalent of VB's DirectCast, and the C#
"as" operator is *mostly* the equivalent of VB's TryCast.

However, cast expressions in C# are also used to perform unboxing and
to invoke user-defined operators. I don't know which constructs in VB
are used for those purposes.

Jon
Jun 27 '08 #20
(string) element

Jon,

Probably just the terminology as I thought to see

(string) X, is in my ide more or less the same like CType(X,string)
while I see
X as string, the same as DirectCast(X, string)

You use the terminonlogy direct cast for (string)X , while I use for direct
cast for: cast but exclude any indirect conversion.

Strange is maybe that I use in VB seldom CType but try to do always
DirectCast, while in C# I seldom use "as", maybe I should use the latter
more. (Can be that it is because there are in VB standard so many more
optimized conversion functions).

Cor
"Jon Skeet [C# MVP]" <sk***@pobox.comschreef in bericht
news:54**********************************@y38g2000 hsy.googlegroups.com...
On Jun 12, 12:02 pm, "Cor Ligthert [MVP]" <notmyfirstn...@planet.nl>
wrote:
Using a direct cast also allows for user-defined conversions etc.

Are you sure of this, I thought that it was the opposite

Absolutely positive. Here's proof:
XElement has an explicit user-defined conversion operator to string.

using System.Xml.Linq;

public class Test
{
static void Main()
{
XElement element = new XElement("name", "text");

// Direct cast is fine
string text = (string) element;

// Doesn't compile - no reference conversion, boxing conversion,
// unboxing conversion, wrapping conversion or null type
conversion
// available
string text2 = element as XElement;
}
}

Jon
Jun 27 '08 #21
On Jun 13, 6:06 am, "Cor Ligthert[MVP]" <notmyfirstn...@planet.nl>
wrote:
Probably just the terminology as I thought to see

(string) X, is in my ide more or less the same like CType(X,string)
while I see X as string, the same as DirectCast(X, string)
As I wrote to Scott, (string) X is the equivalent of DirectCast in
many situations, but that doesn't cover everything. "as" is more like
TryCast in VB.
You use the terminonlogy direct cast for (string)X , while I use for direct
cast for: cast but exclude any indirect conversion.
But in C# there's just the one syntax which does the three, and that's
what we've been talking about as a "direct cast" just to distinguish
it from using "as". There's no cast operator which does the same
conversions as "as" but throwing an exception if it fails. However,
the decision it use the direct cast syntax doesn't mean that the
nature of the conversion is decided at execution time - the compiler
works out what it's going to do, and emits the appropriate code.
Strange is maybe that I use in VB seldom CType but try to do always
DirectCast, while in C# I seldom use "as", maybe I should use the latter
more.
I doubt it - only if you're testing whether or not a conversion will
work and then acting on that.
(Can be that it is because there are in VB standard so many more
optimized conversion functions).
What exactly do you mean? Any time there's a conversion available as
either an inheritance-style conversion or a user-defined conversion
operator, C# will happily use those and they're likely to be
optimised. For less obvious conversions (such as string to int, which
involves parsing, cultures etc) you just call the appropriate method -
I can't see how VB would be more "optimized" there.

Jon
Jun 27 '08 #22
Jon,
snip
What exactly do you mean? Any time there's a conversion available as
either an inheritance-style conversion or a user-defined conversion
operator, C# will happily use those and they're likely to be
optimised.
snip

And it does not need to do any instructions to find the best way, amazing!

:-)

Cor
Jun 27 '08 #23
On Jun 13, 7:18 am, "Cor Ligthert [MVP]" <notmyfirstn...@planet.nl>
wrote:
snipWhat exactly do you mean? Any time there's a conversion available as
either an inheritance-style conversion or a user-defined conversion
operator, C# will happily use those and they're likely to be
optimised.

snip

And it does not need to do any instructions to find the best way, amazing!
I don't see what's surprising here. You can't write a user-defined
operator to perform a conversion which is alreay available, so there's
no ambiguity there. If you *are* writing a user-defined conversion
operator, you're likely to do that in a sensible way.

It's not that the compiler is optimising anything here - it's just
using one piece of syntax for three different things (unboxing, user-
defined conversion, inheritance-style casting). It can easily work out
which to do at compile time. What are you surprised by?

Jon
Jun 27 '08 #24
Your answer

:-)

Last reply Jon, feel free to make a last, but I won't reply in this thread
anymore.

Cor
"Jon Skeet [C# MVP]" <sk***@pobox.comschreef in bericht
news:61**********************************@34g2000h sf.googlegroups.com...
On Jun 13, 7:18 am, "Cor Ligthert [MVP]" <notmyfirstn...@planet.nl>
wrote:
>snipWhat exactly do you mean? Any time there's a conversion available
as
either an inheritance-style conversion or a user-defined conversion
operator, C# will happily use those and they're likely to be
optimised.

snip

And it does not need to do any instructions to find the best way,
amazing!

I don't see what's surprising here. You can't write a user-defined
operator to perform a conversion which is alreay available, so there's
no ambiguity there. If you *are* writing a user-defined conversion
operator, you're likely to do that in a sensible way.

It's not that the compiler is optimising anything here - it's just
using one piece of syntax for three different things (unboxing, user-
defined conversion, inheritance-style casting). It can easily work out
which to do at compile time. What are you surprised by?

Jon

Jun 27 '08 #25
(string) X, is in my ide more or less the same like CType(X,string)
while I see
X as string, the same as DirectCast(X, string)
I would interpret that in reverse:

I would think (string) x is more equivelent to DirectCast(x, String)

and

x as string is more like CType(x, String)

-Scott
Jun 27 '08 #26
On 2008-06-13, Scott M. <sm**@nospam.nospamwrote:
>(string) X, is in my ide more or less the same like CType(X,string)
while I see
X as string, the same as DirectCast(X, string)

I would interpret that in reverse:

I would think (string) x is more equivelent to DirectCast(x, String)

and

x as string is more like CType(x, String)

-Scott

DirectCast and as are close, in that they don't respect user defined
conversions, but as doesn't throw exceptions - it returns null. So, it is
probably closer to TryCast then DirectCast.

CType is closer to (string) x becasue both of those methods allow
for user defined conversions. In other words, there doesn't have to be a
"inheritance or implementation relationship" (from the docs) for the
cast to succeed.

--
Tom Shelton
Jun 27 '08 #27
On Jun 13, 5:09 pm, "Scott M." <s...@nospam.nospamwrote:
I would interpret that in reverse:

I would think (string) x is more equivelent to DirectCast(x, String)

and

x as string is more like CType(x, String)
But that's still wrong:
1) A cast expression in C# does more than DirectCast in VB (but less
than CType, I think)
2) x as string will never throw an exception, whereas CType can.

As I've said before, "as" is the same as TryCast as far as I can tell.

Jon
Jun 27 '08 #28
Yes, I get that Jon, but I'm not really thinking about exceptions here since
in VB, both DirectCast and CType can throw exceptions. I'm really talking
more in terms of performance when the cast is possible.
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:af**********************************@e53g2000 hsa.googlegroups.com...
On Jun 13, 5:09 pm, "Scott M." <s...@nospam.nospamwrote:
>I would interpret that in reverse:

I would think (string) x is more equivelent to DirectCast(x, String)

and

x as string is more like CType(x, String)

But that's still wrong:
1) A cast expression in C# does more than DirectCast in VB (but less
than CType, I think)
2) x as string will never throw an exception, whereas CType can.

As I've said before, "as" is the same as TryCast as far as I can tell.

Jon

Jun 27 '08 #29
Scott M. <sm**@nospam.nospamwrote:
Yes, I get that Jon, but I'm not really thinking about exceptions here since
in VB, both DirectCast and CType can throw exceptions. I'm really talking
more in terms of performance when the cast is possible.
If the cast is possible as an "inheritance-style" cast, both "as" and
direct casting are like DirectCast.

If a user-defined operator conversion is involved then direct casting
acts more like CType - but that's pretty rare, and the operator to call
is still decided at compile time.

I get the impression that CType is capable of deciding which conversion
to apply (like parsing a string to an integer) at exection time. That's
not the case with either direct casting or "as" in C#.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Jun 27 '08 #30

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

Similar topics

4
by: drowned | last post by:
I'm having a problem understanding why the code in this little program I've got is behaving the way it does... if anyone can explain it, I'd be grateful: #include <iostream> using namespace...
4
by: David Vestal | last post by:
I'm reading a 24-bit address from a char* named i_msg, and I expected these two snippets to be equivalent. They aren't; the first doesn't work. What gives? SNIPPET 1: unsigned long address;...
3
by: Alfonso Morra | last post by:
Hi, I have two func ptr prototypes declared as : typedef void (*VFP)(void) ; typedef int(MyCallback*)(enum_1, enum2, int, void*) ; I hav a struct as ff: typedef struct {
3
by: Barry Mossman | last post by:
Hi, I get the feeling that I am missing something with regards to casting. The CopyTo method allows me to copy the contents of a collection into an array. My collection is a MatchCollection...
6
by: Jim Bancroft | last post by:
Hi everyone, I'm having some trouble with the code below. I receive a compile-time error on the second line saying "; expected": private static void myTestFunction(long myLong) { ...
3
by: Dariusz Tomon | last post by:
Hi I'm trying to retrieve data from database (MS Sql serv) from field of BIT type. I'm trying like this: while (myReader.Read()) { Int16 cos = (Int16)myReader.GetSqlInt16(1);
3
by: Andy Chen | last post by:
Hi, I have a Hashtable, key is string and value is ArrayList. The problem is I cannot cast the value from object to ArrayList. like this: Hashtable ht = new Hashtable(); ArrayList al = new...
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
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: 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
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.