473,407 Members | 2,306 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,407 software developers and data experts.

C-style casts versus using the as operator

Hello,

I would like to ask the following question concerning the C# as operator.
I would like to know whether the difference between using a C-style cast
such as

double x = 0;
float y = (double) x;

and using the as operator is simply that as works on references rather
than on primitive data types. So using the as operator in C# should be
roughly equivalent to casting a pointer type to another in C. I would
like to know though, does anything in particular happen when a concersion
from one reference type to another takes place in C# using the as keyword?
In particular, how does the as keyword work under the hood?

Thanks,

Neil
Nov 16 '05 #1
3 2286
and using the as operator is simply that as works on references rather
than on primitive data types.


No, you can use C-style casts on reference types too.

The difference is that the as operator returns null if the cast fails,
whereas the () cast throws an InvalidCastException.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 16 '05 #2

- e as T : yields e as type T if (E is T), null otherwise
- (T)e : yields e as type T if (E is T), exception otherwise

So, you should use "(T)e" where you want immediate failure if E is not
of type t, and "e as T" when you want some behaviour on e, even if it is
not of type T

Example:

class Foo: IComparable {
int i;
public int CompareTo(Object arg0) {
Foo other = arg0 as Foo;
if ( other == null )
return 1;
else
return i - other.i;
}
public override bool Equals(Object arg0) {
Foo other = (Foo)arg0;
return i == other.i;
}
}

please dont do:

public void foo(Object o) {
Foo foo = o as Foo;
if ( foo == null )
throw new ArgumentException("must be instance of Foo", "o");

or, worse:

public void foo(Object o) {
Foo foo = o as Foo;
...
foo.f(x); // throws NullReference if o is not a Foo

Since:

public void foo(Object o) {
Foo foo = (Foo)o;

Gives a much more precise error-path
and using the as operator is simply that as works on references rather
than on primitive data types. So using the as operator in C# should be
roughly equivalent to casting a pointer type to another in C.
No, its like casting pointers with dynamic_cast in _C++_. In C, casts
have no runtime-meaning, they do in C++ (with RTTI...):

C++ C#

dynamic_cast<T>(e) ~ (T)e
dynamic_cast<T*>(e) ~ e as T
I would
like to know though, does anything in particular happen when a concersion
from one reference type to another takes place in C# using the as keyword?
Nah,
In particular, how does the as keyword work under the hood?


Nothing happens, you can psuedo-code "as" yourself:

public static T as(Object o) {
if ( o is T )
return (T)o;
else
return null;
}

--
Helge
Nov 16 '05 #3
<snip stuff that is already adequatly explained>
In particular, how does the as keyword work under the hood?


Assuming a straight A to B cast, the primary difference between the two is
the instruction that is used. 'as' and 'is' uses the instruction isinst,
which pushes either the cast value or null onto the stack, while the () cast
uses castclass which throws an exception if the cast fails.

From a language perspective, as is a slightly simpler operator. The ()
casting operator can also perform user defined, implicit value conversions,
and unboxing conversions which gives it more flexibilty(and potentially more
ambiguity).
Nov 16 '05 #4

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

Similar topics

5
by: Roger Leigh | last post by:
I've written a simple container template class to contain a single value. This emits a signal when the value is changed (it's used as a notifier of changes), and listeners can connect to its...
2
by: Tony Johansson | last post by:
Hello Experts! I have one class template here called Handle and one concrete class called Point. At the bottom is the main program and the class template definitions for Handle. This program...
0
by: Robert Potthast | last post by:
Hello, I want to make my garbage collector more safe. To make it more safe I need to know if an object has been allocated on the stack or on the heap using the operator new. My garbage collector...
3
by: Adam Monsen | last post by:
The following code uses the % operator to print possibly unitialized data attributes: ------------------------8<------------------------ class J: name = '' value = '' def __str__(self): vals =...
24
by: Bangalore | last post by:
Hi all, I have a problem in accessing elements using overloaded operator . Consider, const int SIZE=10; int FALSE=0; class Array { private: int x; public:
17
by: Martin | last post by:
Below is some sample code to illustrate two warnings I get using a Hitachi compiler. When I use the GCC compiler I get a clean compile. I'd be grateful if someone could explain what the warnings...
2
by: Bharath | last post by:
Hello All, Can you please let me know if we can do pointer arthrmetic using operator overloading? If not, can you please explain why it's not supported by compiler? I tried below e.g. which was...
5
patjones
by: patjones | last post by:
Hi: I have a table in my Access database, "tblWC", which contains a field called "fldTrackingStatus". Furthermore, I have a report "rptTrackingReport" which is based on tblWC (using an SQL query...
5
by: jewel87 | last post by:
Hello, I am working on a program which uses a dynamic array of Employee class objects, the array is defined in EmployeeList class. When i am calling a function from my form to enter or display...
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...
0
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...
0
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...
0
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,...

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.