Categorized | Programming, Tutorial

C# code snippet for demonstration of data casting!

Posted on 06 September 2008

A handy C# code snippet to demonstrate ways of achieve data typecasting like int -> double, int-> and so on…

using System;


class CastDemo {
public static void Main()
{
double x, y;
byte b;
int i;
char ch;
uint u;
short s;
long l;

x = 10.0;
y = 3.0;
// cast an int into a double
i = (int) (x / y); // cast double to int, fractional component lost
Console.WriteLine(”Integer outcome of x / y: ” + i);
Console.WriteLine();

// cast an int into a byte, no data lost
i = 255;
b = (byte) i;
Console.WriteLine(”b after assigning 255: ” + b +
” — no data lost.”);

// cast an int into a byte, data lost
i = 257;
b = (byte) i;
Console.WriteLine(”b after assigning 257: ” + b +
” — data lost.”);
Console.WriteLine();

// cast a uint into a short, no data lost
u = 32000;
s = (short) u;
Console.WriteLine(”s after assigning 32000: ” + s +
” — no data lost.”);

// cast a uint into a short, data lost
u = 64000;
s = (short) u;
Console.WriteLine(”s after assigning 64000: ” + s +
” — data lost.”);
Console.WriteLine();

// cast a long into a uint, no data lost
l = 64000;
u = (uint) l;
Console.WriteLine(”u after assigning 64000: ” + u +
” — no data lost.”);


// cast a long into a uint, data lost
l = -12;
u = (uint) l;
Console.WriteLine(”u after assigning -12: ” + u +
” — data lost.”);
Console.WriteLine();

// cast an int into a char

b = 88; // ASCII code for X
ch = (char) b;
Console.WriteLine(”ch after assigning 88: ” + ch);
}
}

1 Star2 Stars3 Stars4 Stars5 Stars (5 votes, average: 4.8 out of 5)
Loading ... Loading ...

This post was authored by:

om - who has written 106 posts on Tech Pedia.

Om is a freelance writer cum software engineer! Works for a reputed IT company & provides freelancing writing & web-services to several clients in US, Europe, Asia and all over the world! Owns a website,blog &runs a private franchise business whose clients are in fortune 100 listing! For relevant work contact him to om.thoke86@gmail.com

Contact the author

Leave a Reply

Site Sponsors

  • programming freak: And by the way thanks for those useful codes, i am surprised a site like this has C codes? and...
  • programming freak: Keep posting some codes man, i would be glad to find some c/c++/java/html/unix codes, sql queries...
  • programming freak: Hey thanks, good one!
  • Nathaniel Baker: its all good information.. but you forgot one very very important thing…. FAT32 can not...
  • om: Yeah sure it is.. :)

Older Posts

Ads

  • Advertise Here

Topics