using System;
class Conv
{
public static void Process(sbyte value)
{
Console.WriteLine("sbyte {0}", value);
}
public static void Process(short value)
{
Console.WriteLine("short {0}", value);
}
public static void Process(int value)
{
Console.WriteLine("int {0}", value);
}
}
public class ConversionsandMemberLookup
{
public static void Main()
{
int value1 = 2;
sbyte value2 = 1;
Conv.Process(value1);
Conv.Process(value2);
}
}
Month: February 2011
Conversions:Numeric Types:Checked Conversions
using System;
public class UNCheckedConversions
{
public static void Main()
{
uint value1 = 312;
byte value2;
value2 = unchecked((byte) value1); // never checked
value2 = (byte) value1; // checked if /checked
value2 = checked((byte) value1); // always checked
}
}
Numeric Types: Checked Conversions
using System;
public class CheckedConversions
{
public static void Main()
{
checked
{
uint value1 = 312;
byte value2 = (byte) value1;
Console.WriteLine("Value: {0}", value2);
}
}
}
Conversions: Numeric Types
public class NumericTypesConversion
{
public static void Main()
{
// all implicit
sbyte v = 55;
short v2 = v;
int v3 = v2;
long v4 = v3;
// explicit to "smaller" types
v3 = (int) v4;
v2 = (short) v3;
v = (sbyte) v2;
}
}
User-Defined Conversions: How It Works: Conversion Lookup
// This demo has compiling error
class S
{
}
class TBase
{
}
class T: TBase
{
public static implicit operator T(S s)
{
return(new T());
}
}
public class ConversionLookup1
{
public static void Main()
{
S myS = new S();
TBase tb = (TBase) myS;
}
}
Casting int float and byte
/*
* C# Programmers Pocket Consultant
* Author: Gregory S. MacBeth
* Email: gmacbeth@comporium.net
* Create Date: June 27, 2003
* Last Modified Date:
* Version: 1
*/
using System;
namespace Client.Chapter_1___Common_Type_System
{
public class Casting
{
static void Main(string[] args)
{
int MyInt = 12345;
long MyLong = MyInt;
short MyShort = (short)MyInt;
}
}
}
The use of the cast operator
/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
/*
Example2_3.cs shows the use of the cast operator,
and how information loss can occur when explicitly
converting a variable of one type to another
*/
public class Example2_3
{
public static void Main()
{
short myShort = 17000;
System.Console.WriteLine("myShort = " + myShort);
int myInt = myShort;
System.Console.WriteLine("myInt = " + myInt);
myShort = (short) (myInt * 2);
System.Console.WriteLine("myShort = " + myShort);
}
}

