473,549 Members | 2,628 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Type conversion Syntax

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 developer.

x = someObject as MySpecificType;

x = (MySpecificType ) someObject;
Thanks.
Aug 5 '07 #1
8 3135
Smithers wrote:
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 developer.

x = someObject as MySpecificType;

x = (MySpecificType ) someObject;
Thanks.

One important difference is that the first one will give you a
conversion error if someObject cannot be converted to a MySpecificType
at compile time. The second one will always compile but will throw a
run-time error if someObject cannot be cast to a MySpecificType.

When you know that at compile-time that someObject is of type (or a type
derived from) MySpecificType then use the first syntax. If you don't
know until run-time whether someObject will be of type (or a type
derived from) MySpecificType type then use the second syntax.
--
-glenn-
Aug 5 '07 #2
Smithers wrote:
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 developer.

x = someObject as MySpecificType;
This will attemt to cast the reference, and if it's not possible, it
will put a null reference in the variable x.

Use this if you aren't certain what the actual type is, and check if the
reference is null to find out if the casting was possible or not.
x = (MySpecificType ) someObject;
This will attemt to cast the reference, and it it's not possible, it
will throw an exception.

Use this if you are certain what the actual type is.

--
Göran Andersson
_____
http://www.guffa.com
Aug 5 '07 #3
GlennDoten wrote:
Smithers wrote:
>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 developer.

x = someObject as MySpecificType;

x = (MySpecificType ) someObject;
Thanks.

One important difference is that the first one will give you a
conversion error if someObject cannot be converted to a MySpecificType
at compile time.
No, it won't.
The second one will always compile but will throw a
run-time error if someObject cannot be cast to a MySpecificType.

When you know that at compile-time that someObject is of type (or a type
derived from) MySpecificType then use the first syntax. If you don't
know until run-time whether someObject will be of type (or a type
derived from) MySpecificType type then use the second syntax.
That's completely backwards.

--
Göran Andersson
_____
http://www.guffa.com
Aug 5 '07 #4
Göran Andersson wrote:
GlennDoten wrote:
>Smithers wrote:
>>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 developer.

x = someObject as MySpecificType;

x = (MySpecificType ) someObject;
Thanks.

One important difference is that the first one will give you a
conversion error if someObject cannot be converted to a MySpecificType
at compile time.

No, it won't.
Göran, look at this code:

public class MySpecificType { }
public class MySpecificType2 : MySpecificType { }
public class FooTester
{
public void A()
{
Version v = new Version();
Random r = new Random();
Random r2 = (Random)v;
Random r3 = v as Random;

object o = new object();

MySpecificType x = o as MySpecificType;
MySpecificType y = (MySpecificType )o;

MySpecificType x2 = o as MySpecificType2 ;
MySpecificType y2 = (MySpecificType 2)o;
}
}

On the r2 line, C# gives this error message: "Cannot convert type
'System.Version ' to 'System.Random' via a built-in conversion".

On the r3 line, C# gives this error message: "Cannot convert type
'System.Version ' to 'System.Random' ".

I always thought that C# would let these lines compile and give a
run-time error, but the compiler's smarter than I thought (maybe it's
something new in C# 2.0). The x line compiles but gives this run-time
error: "Unable to cast object of type 'System.Object' to type
'Console_Playgr ound.MySpecific Type'".

I think we're both right, and that it depends on whether the compiler
can figure out the type compatibility fully at compile-time or not.
>The second one will always compile but will throw a run-time error if
someObject cannot be cast to a MySpecificType.
You're right; I'm wrong here. I did believe that "as" would always
compile until I tried the r3 line above (at your prompting).
>When you know that at compile-time that someObject is of type MySpecificType (or a
type derived from) MySpecificType then use the first syntax. If you
don't know until run-time whether someObject will be of type (or a
type derived from) MySpecificType type then use the second syntax.

That's completely backwards.
Not quite, I don't think. Although to be clearer I should have said this:

"then use[STRIKE "USE"] the first syntax [ADD "CAN BE USED"]". Though
typically I would use the cast syntax. And I use this pattern all the time:

MySpecificType x = o as MySpecificType;
if (x == null)
{
// x isn't of MySpecificType or doesn't it's type doesn't derive
// from MySpecificType.
}

Sorry if I wasn't clear about that.

Assuming that Smithers means this:

MySpecificType x = someObject as MySpecificType;
MySpecificType x = (MySpecificType ) someObject;

and also that Smithers means that someObject is is of type
MySepcificType or a class that derives from MySpecific type. However,
since what he posted is a little ambiguous (he doesn't specify what the
type of x is) I may well be reading his question differently than you
and/or what he means, and maybe the two assumptions I just mentioned
aren't what he intended, but that's the way I read he question. Maybe
Smithers will clarify for us.

The bottom line is the first variant (again, assuming these two
assumptions) is useful when you don't want an exception throw at
run-time and will check the variable to see if it is null or not, and
the second variant is useful when you pretty much now the type of the
variable being cast and if you don't know 100% you don't mind an
exception being thrown at run-time.

--
-glenn-
Aug 5 '07 #5
RE:
<< Maybe Smithers will clarify for us. >>

Gladly - and thanks for the good information so far. The big picture is that
I'm writing an application that is extensible via a plug-in architecture
(thus the use of Activator.Creat eInstance() and the subsequent need to
convert to a specific type).

Here is the relevant code. Notice Lines 7 and 8 provide the alternative
conversion syntax in question.

1 private List<CompanyNam eHere.CommonIns tallerTypes.Ins taller>
m_InstallerInst ances;
2 Type installerTypeRe ference = null;
3 System.Reflecti on.Assembly loadedAssembly =
System.Reflecti on.Assembly.Loa dFile(pathToAss embly);
4 installerTypeRe ference =
loadedAssembly. GetType(current Installer.Class Name);
5 if (installerTypeR eference != null)
6 {
7 installerInstan ce = (CompanyNameHer e.CommonInstall erTypes.Install er)
Activator.Creat eInstance(insta llerTypeReferen ce);
8 // installerInstan ce = Activator.Creat eInstance(insta llerTypeReferen ce)
as CompanyNameHere .CommonInstalle rTypes.Installe r;
9 m_InstallerInst ances.Add(insta llerInstance);
10 }
Thanks for the great dialog. It is very helpful. You can see I'm wanting to
understand this and not simply "get it to work".

-"Smithers"
Aug 5 '07 #6
Smithers wrote:
RE:
<< Maybe Smithers will clarify for us. >>

Gladly - and thanks for the good information so far. The big picture is that
I'm writing an application that is extensible via a plug-in architecture
(thus the use of Activator.Creat eInstance() and the subsequent need to
convert to a specific type).

Here is the relevant code. Notice Lines 7 and 8 provide the alternative
conversion syntax in question.

1 private List<CompanyNam eHere.CommonIns tallerTypes.Ins taller>
m_InstallerInst ances;
2 Type installerTypeRe ference = null;
3 System.Reflecti on.Assembly loadedAssembly =
System.Reflecti on.Assembly.Loa dFile(pathToAss embly);
4 installerTypeRe ference =
loadedAssembly. GetType(current Installer.Class Name);
5 if (installerTypeR eference != null)
6 {
7 installerInstan ce = (CompanyNameHer e.CommonInstall erTypes.Install er)
Activator.Creat eInstance(insta llerTypeReferen ce);
8 // installerInstan ce = Activator.Creat eInstance(insta llerTypeReferen ce)
as CompanyNameHere .CommonInstalle rTypes.Installe r;
9 m_InstallerInst ances.Add(insta llerInstance);
10 }
Both will work. You might use casting--as in line 7--if you were sure
that the ClassName variable always specified the name of a type that is
of type Installer, or a type that derives from type Installer. But even
if the type specified by ClassName were not such a type the code would
still work, it would just throw an exception when line 7 executes. This
may be perfectly acceptable behavior so long as your callers know to
trap for this potential exception and recover accordingly.

Line 8 would work just as well, but typically you would use it if you
had a corresponding line 8a that did something like this:

if (installInstanc e == null) { /* Handle the incorrect type. */ }

But without such a check then it doesn't matter whether you use a cast
(which will throw an exception if the wrong type is created) or whether
you use the "as" keyword (which will not throw an exception but will
return a null if a wrong type is created).

So which one you use depends on how you want this code to behave.
Personally, I use a cast when creating a "late-bound" object like this
because I know that the type name specified in the ClassName variable is
going to specify a proper type, and if it doesn't I'll catch that bug
during testing. Though you can't always make that assumption, in which
case I'd probably still just wrap a "try" around the cast. Another
pattern I use for this type of code is to replace your line 7 with
something like this:

object instance = Activator.Creat eInstance(insta llerTypeReferen ce);
Debug.Assert(in stance is Installer);
installerInstan ce = (Installer)inst ance;

Make sense?
Thanks for the great dialog. It is very helpful. You can see I'm wanting to
understand this and not simply "get it to work".
Same thing here!

--
-glenn-
Aug 5 '07 #7
Yes - it all makes sense... exactly the sort of perspective I was looking
for. Thank you very much.

-"Smithers"


"GlennDoten " <gd****@gmail.c omwrote in message
news:%2******** ********@TK2MSF TNGP04.phx.gbl. ..
Smithers wrote:
>RE:
<< Maybe Smithers will clarify for us. >>

Gladly - and thanks for the good information so far. The big picture is
that I'm writing an application that is extensible via a plug-in
architecture (thus the use of Activator.Creat eInstance() and the
subsequent need to convert to a specific type).

Here is the relevant code. Notice Lines 7 and 8 provide the alternative
conversion syntax in question.

1 private List<CompanyNam eHere.CommonIns tallerTypes.Ins taller>
m_InstallerIns tances;
2 Type installerTypeRe ference = null;
3 System.Reflecti on.Assembly loadedAssembly =
System.Reflect ion.Assembly.Lo adFile(pathToAs sembly);
4 installerTypeRe ference =
loadedAssembly .GetType(curren tInstaller.Clas sName);
5 if (installerTypeR eference != null)
6 {
7 installerInstan ce =
(CompanyNameHe re.CommonInstal lerTypes.Instal ler)
Activator.Crea teInstance(inst allerTypeRefere nce);
8 // installerInstan ce =
Activator.Crea teInstance(inst allerTypeRefere nce) as
CompanyNameHer e.CommonInstall erTypes.Install er;
9 m_InstallerInst ances.Add(insta llerInstance);
10 }

Both will work. You might use casting--as in line 7--if you were sure that
the ClassName variable always specified the name of a type that is of type
Installer, or a type that derives from type Installer. But even if the
type specified by ClassName were not such a type the code would still
work, it would just throw an exception when line 7 executes. This may be
perfectly acceptable behavior so long as your callers know to trap for
this potential exception and recover accordingly.

Line 8 would work just as well, but typically you would use it if you had
a corresponding line 8a that did something like this:

if (installInstanc e == null) { /* Handle the incorrect type. */ }

But without such a check then it doesn't matter whether you use a cast
(which will throw an exception if the wrong type is created) or whether
you use the "as" keyword (which will not throw an exception but will
return a null if a wrong type is created).

So which one you use depends on how you want this code to behave.
Personally, I use a cast when creating a "late-bound" object like this
because I know that the type name specified in the ClassName variable is
going to specify a proper type, and if it doesn't I'll catch that bug
during testing. Though you can't always make that assumption, in which
case I'd probably still just wrap a "try" around the cast. Another pattern
I use for this type of code is to replace your line 7 with something like
this:

object instance = Activator.Creat eInstance(insta llerTypeReferen ce);
Debug.Assert(in stance is Installer);
installerInstan ce = (Installer)inst ance;

Make sense?
>Thanks for the great dialog. It is very helpful. You can see I'm wanting
to understand this and not simply "get it to work".

Same thing here!

--
-glenn-

Aug 5 '07 #8
This is still not quite right.

the as operator is a reference converter. This means it will convert an
object reference from one type to another based on the rules of polymorphism.
e.g
Imagin you have this object hierachy:
System.Object
MyClassA
MyClassB
MyClassC
MyClassD

So as MyClassA is at the same level as MyClassB this will fail as you cant
point to an instance of MyClassA with a reference of type MyClassB

MyClassA inst = new MyClassA();
MyClassB inst2 = isnt as MyClassB();

This However will work as the rules of polymorphism allow this
Object inst = new MyClassC();
MyClassB inst2 = isnt as MyClassB();
MyClassC inst3 = isnt2 as MyClassC();

This however will fail:

Object inst = new MyClassC();
MyClassD inst3 = isnt2 as MyClassD();

as an instance of MyClassC cant be made more special.
As you can see the 'as' operator works solely on the reference and leaves
the actual instance untouched in all cases. so the reference returned is to
the same memory location as the original but it a different type.

Casting is a little different, the rules above will apply the same way for
casting

BUT

you can add implicit and explicit conversion functions to make casting work
for completly different types. Castign is used this wayto make a different
instance of a different class which is a conversion of the original.

This allows this to work

int a = 1;
double b = (double)a;

int and double are unrelated classes but have conversion functions to allow
you to convert one to the other. In the above case, the memory rerence of b
and a are different (I know this is the case as much to the stack based
nature of them but its the same with reference types and their members).

Hopefully this highlights the difference between the 2.

as = pointer conversion only
(cast) = automatic pointer conversion for reference types or object
conversion for all supporting types.
The other difference is 'as' doesnt throw an expcetion but returns a null if
it fails, therefore it only works for reference types. (casting) throws an
exception on failure and cant be used on value types too.

The compiler support for detecting improper conversions is just MS being
clever. If the compiler can detect a garunteed failure it will throw an
error. The same as writing int i = 10/0; throws a divide by zero exception.
Hope this helps to clarify

--
Ciaran O''Donnell
http://wannabedeveloper.spaces.live.com
"Göran Andersson" wrote:
Smithers wrote:
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 developer.

x = someObject as MySpecificType;

This will attemt to cast the reference, and if it's not possible, it
will put a null reference in the variable x.

Use this if you aren't certain what the actual type is, and check if the
reference is null to find out if the casting was possible or not.
x = (MySpecificType ) someObject;

This will attemt to cast the reference, and it it's not possible, it
will throw an exception.

Use this if you are certain what the actual type is.

--
Göran Andersson
_____
http://www.guffa.com
Aug 6 '07 #9

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

Similar topics

21
4498
by: Batista, Facundo | last post by:
Here I send it. Suggestions and all kinds of recomendations are more than welcomed. If it all goes ok, it'll be a PEP when I finish writing/modifying the code. Thank you. .. Facundo
19
1680
by: Randy Yates | last post by:
Consider the following code: #include "dsptypes.h" /* definitions */ #define VECTOR_LENGTH 64 /* local variables */
11
1699
by: Peter Oliphant | last post by:
I've been trying all morning to convert my 2003 project (managed) to 2005 (/clr since I have both managed and unmanaged code). I'm guessing I have tens of thousands of lines of code to change. Did a lot of converting '__gc' to 'ref', converting '*' to '^', converting 'new' to 'gcnew'. Of course this can't be done with a blanket replace, as my...
47
2830
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 used and why ? Thanx
3
7702
by: PeterK | last post by:
I am trying to set Public overridable CreditlimitS() as System.Data.SqlTypes.SqlMoney to Creditlimit as Double like CreditLimitS=creditlimit and get this error "Value of type double cannot be converted to System.Data.SqlTypes.SqlMoney " How do I get creditlimit into creditlimitS? There seems to be no conversion function. TIA
4
3628
by: Frank-René Schäfer | last post by:
-- A class needs to have N members according to N types mentioned in a typelist (possibly with one type occuring more than once). -- The classes should be generated **avoiding** multiple inheritance (avoiding prosperation of virtual func tables). -- At the same time, a class taking N types shall contain a virtual member function that calls a...
669
25615
by: Xah Lee | last post by:
in March, i posted a essay “What is Expressiveness in a Computer Language”, archived at: http://xahlee.org/perl-python/what_is_expresiveness.html I was informed then that there is a academic paper written on this subject. On the Expressive Power of Programming Languages, by Matthias Felleisen, 1990....
1
2011
by: zaeminkr | last post by:
I have a question about type conversion function for user defined type. I have two classes class DRect { private : double x0; double y0;
22
1649
by: Ruben | last post by:
Why would a method that is defined to return a reference such as with the operator overload of , operator, href& operator(int index){ return _array; } not cause a type mismatch compiler error? Ruben
0
7734
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. ...
0
7979
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7497
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...
0
7826
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6065
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...
0
5107
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...
1
1960
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1074
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
781
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...

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.