[.net] c# typecasting

Started by
7 comments, last by DrGUI 18 years, 3 months ago
Hello everyone, I have finally come to a bit of a problem with c#, how do I typecast? I was using c++ for a while but I figured it would be wise to change with the times and move to c#. Thanks in Advance. Regards, Mike
Advertisement
(Type)SomeObject
Also, look at the keyword "as"
Alright so it seems there are two ways. just to be clear, (float)this.width / 2 * 3 would work?
Yes, you can use C-style casts: (float)myInt; or the as keyword: myInt as float.

I can't remember exactly (check MSDN, it's your friend!) and don't have a reference handy, but casting one way throws exceptions for invalid casts and casting the other way returns a null for invalid casts. I believe the as keyword gives you a null on an invalid cast and is only applicable to classes/structs (not intrinsic types like int, float), but I may be wrong, so check MSDN...
He's right:

Car c = (Vehicle)thingy;Car c = thingy as object;


These are both legal. However, in case of an invalid cast, the first throws an exception while the second sets 'c' to null.

The latter can indeed only be applied to reference values, which are classes and structs.
That's why this:

float a = b as int;


is illegal.
Quote:Original post by atoi
Alright so it seems there are two ways. just to be clear, (float)this.width / 2 * 3 would work?


That will convert the Width to float before doing any other operation. Dividing or multiplying by 2.0f or 3.0f will accomplish the same result.

Toolmaker

A simple cast throws an exception when it fails:
try{    NewType castedVariable = (NewType)someVariable;}catch{    // Error casting variable}


The is keyword lets you check if it can be cast to the given type:
if(someVariable is NewType){    // It can be cast}else{    // Nopers}


I prefer the as operator. It returns null if it can't be cast, or the new casted object if it can:
NewType someVariable = oldVariable as NewType;if(someVariable == null){    // Nopers}else{    // Yay!}


As mentioned earlier, they need to be objects as opposed to values or structs.
Rob Loach [Website] [Projects] [Contact]
I think I also read somewhere that 'as' is a bit faster than '()' casting. I suppose it makes sense since 'as' uses the IL instruction 'isinst' while '()' casting uses the 'castclass' instruction. But as everyone says, micro-optimisation is not good until you've profiled so it's just good practise really.

Happy New Year!

This topic is closed to new replies.

Advertisement