Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typecasting in C#

Tags:

What is type casting, what's the use of it? How does it work?

like image 544
MAC Avatar asked Aug 27 '09 07:08

MAC


People also ask

What is typecasting in C?

Type Casting is basically a process in C in which we change a variable belonging to one data type to another one. In type casting, the compiler automatically changes one data type to another one depending on what we want the program to do.

What is typecasting and its types?

Type casting is when you assign a value of one primitive data type to another type. In Java, there are two types of casting: Widening Casting (automatically) - converting a smaller type to a larger type size. byte -> short -> char -> int -> long -> float -> double.

What is an example of typecasting?

An example of typecasting is converting an integer to a string. This might be done in order to compare two numbers, when one number is saved as a string and the other is an integer. For example, a mail program might compare the first part of a street address with an integer.


1 Answers

Casting is usually a matter of telling the compiler that although it only knows that a value is of some general type, you know it's actually of a more specific type. For example:

object x = "hello";

...

// I know that x really refers to a string
string y = (string) x;

There are various conversion operators. The (typename) expression form can do three different things:

  • An unboxing conversion (e.g. from a boxed integer to int)
  • A user-defined conversion (e.g. casting XAttribute to string)
  • A reference conversion within a type hierarchy (e.g. casting object to string)

All of these may fail at execution time, in which case an exception will be thrown.

The as operator, on the other hand, never throws an exception - instead, the result of the conversion is null if it fails:

object x = new object();
string y = x as string; // Now y is null because x isn't a string

It can be used for unboxing to a nullable value type:

object x = 10; // Boxed int
float? y = x as float?; // Now y has a null value because x isn't a boxed float

There are also implicit conversions, e.g. from int to long:

int x = 10;
long y = x; // Implicit conversion

Does that cover everything you were interested in?

like image 95
Jon Skeet Avatar answered Sep 25 '22 08:09

Jon Skeet