Casting and Type Conversions

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 11

CASTING

AND
TYPE CONVERSIONS
CASTING AND TYPE CONVERSIONS
• Because C# is statically-typed at compile time, after a variable is declared, it cannot be
declared again or used to store values of another type unless that type is convertible to the
variable's type.
• For example,

int i;
i = "Hello"; // Error: "Cannot implicitly
convert type 'string' to 'int'"
CASTING AND TYPE CONVERSIONS
• However, we might sometimes need to copy a value into a variable or method parameter of
another type.
• For example, we might have an integer variable that you need to pass to a method whose
parameter is typed as double.
• Or we might need to assign a class variable to a variable of a derived type.
• These kinds of operations are called type conversions.
CASTING AND TYPE CONVERSIONS
In C#, we can perform the following kinds of conversions:
•Implicit conversions: No special syntax is required because the conversion is type safe and no
data will be lost. Examples include conversions from smaller to larger integral types, and
conversions from derived classes to base classes.

•Explicit conversions (casts): Explicit conversions require a cast operator. Casting is required
when information might be lost in the conversion, or when the conversion might not succeed
for other reasons. Typical examples include numeric conversion to a type that has less
precision or a smaller range, and conversion of a base-class instance to a derived class.

•Conversions with helper classes: To convert between non-compatible types, such as


integers and strings and byte arrays, we can use Parse methods of the built-in numeric types,
such as Int32.Parse.
IMPLICIT CONVERSIONS
• For built-in numeric types, an implicit conversion can be made when the value to be stored
can fit into the variable without being truncated or rounded off.
• For example,
// Implicit conversion. num long can
// hold any value an int can hold, and more!
int num = 21474836;
long bigNum = num;

• For reference types, an implicit conversion always exists from a class to any one of its direct
or indirect base classes. No special syntax is necessary because a derived class always
contains all the members of a base class.
Derived d = new Derived();
Base b = d; // Always OK.
EXPLICIT CONVERSIONS
• However, if a conversion cannot be made
without a risk of losing information, the class Test
{ static void Main()
compiler requires that you perform an explicit {
conversion, which is called a cast. double x = 1234.7;
• int a;
A cast is a way of explicitly informing the // Cast double to int.
compiler that you intend to make the a = (int)x;
conversion and that you are aware that data System.Console.WriteLine(a);
loss might occur. }
}
• To perform a cast, specify the type that you // Output: 1234
are casting to in parentheses in front of the
value or variable to be converted.
EXPLICIT CONVERSIONS
• For reference types, an explicit cast is required if you need to convert from a base type to
a derived type:

// Create a new derived type.


Giraffe g = new Giraffe();
// Implicit conversion to base type is safe.
Animal a = g;
// Explicit conversion is required to cast back
// to derived type. Note: This will compile but will
// throw an exception at run time if the right-side
// object is not in fact a Giraffe.
Giraffe g2 = (Giraffe) a;
TYPE CONVERSION EXCEPTIONS AT RUN TIME
• In some reference type conversions, the compiler cannot determine whether a
cast will be valid. It is possible for a cast operation that compiles correctly to fail at
run time.
CAST BY USING AS AND IS OPERATORS

Look at the example given below:


Circle c = new Circle(32);
object o = c;
int i = (int)o; // it compiles okay but throws an exception at runtime
CAST BY USING AS AND IS OPERATORS
• Because objects are polymorphic.
• However, to attempt a simple cast in these cases creates the risk of throwing
an InvalidCastException. That is why C# provides the is and as operators.
• You can use these operators to test whether a cast will succeed without
causing an exception to be thrown.
• In general, the as operator is more efficient because it actually returns the cast
value if the cast can be made successfully.
• The is operator returns only a Boolean value. It can therefore be used when
you just want to determine an object's type but do not have to actually cast it.
CAST BY USING AS AND IS OPERATORS
• is Operator
• The "is" operator is used to check whether the run-time type of an object is compatible with a given
type or not. In other words, we use the "is" operator to verify that the type of an object is what we
expect it to be.

• as Operator
• The "as" operator is used to perform conversions between compatible types. Actually, the "as"
operator returns the cast value if the cast can be made successfully.

You might also like