Monday, July 27, 2009

What is explict cast in programming (im learning C#)?

Simple but detailed gets best answer ;)

What is explict cast in programming (im learning C#)?
Its when you force a cast conversion. Like so:





int x, y, z;





(double) z = (double)(x / y);





The variables x, y and z are declared integers. So the expression x/y will perform integer division and will not give accurate results. So you can force it by explicitly casting one variable as a double and that forces a conversion from int to double.
Reply:an explict cast is assigning a variable object to a specific type. For instance everything derives from object but you probably don't want to make every variable an object in your program. Therefore, you explicity cast you variable objects to things like int or string instead of object. To do this in code you can do the following example.





object o = 1;


int i = (int)o;





the second line is the casting of an object to an int.





I hope this simple example helps.
Reply:Its when you explicitly change the type of a value.





double a = 3.7;


int b = (double)a;


int c = a;





You'll probably get a warning on the third like because you are losing precision in the implicit conversion.





The type can also be converted when passing as a function parameter like if you passed a double where an int was expected.





For pointers, you can implicitly cast a derived pointer to a base class pointer, but not the other way around.





class Shape { ... }


class Box : public Shape { ... }


void func1( Shape * p );


void func2( Box * p );


Shape *pS = new Box(); // implicit cast from Box * to Shape *


Box *pB = new Box();


func1( pS );


func2( pS ); // error - can't convert Shape * to Box *


func2( (Box *)pS ); // explicit cast works


func1( pB );


func2( pB );
Reply:Explicit casting is when the programmer performs the cast. This is in contrast to implicit casting where the compiler will do the casting itself (e.g. when you try to divide an int by a double --%26gt; the int gets promoted to a double).





Anyways an explicit cast would look like so:


int i = 7;


double result = (double)i/2;





Here the int i is promoted to a double. If you would not have promoted to a double 7/2 using int arithmetic would yield 3. When casting i to a double it becomes 7.0, therefore using floating point arithmetic the 2 would be promoted to a double as well and your answer would be 7.0/2.0 = 3.5.


No comments:

Post a Comment