Complete set: Intro to C - Bill Buchanan
Complete set: Intro to C - Bill Buchanan
Complete set: Intro to C - Bill Buchanan
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
2.4 Casting Objects<br />
Sometimes we need <strong>to</strong> cast objects.<br />
We may cast up or down the object hierarchy.<br />
Casting down is dangerous and may result in a run time error.<br />
Examples of casting Objects<br />
Object sr0 = new StreamReader("file.txt");<br />
Object ht0 = new Hashtable();<br />
// Following fails at compile time<br />
// StreamReader f1 = sr0;<br />
StreamReader f2 = (StreamReader)sr0;<br />
// Following generates run time error<br />
StreamReader f3 = (StreamReader)ht0;<br />
2.4.1 Self-test<br />
For each of the following decide if the line will work OK or fail at design time or fail<br />
at run time.<br />
Which of these will compile and run<br />
int i0 = 3.1;<br />
string s0 = 'x';<br />
char c0 = 'c';<br />
string s1 = "x" + 'y';<br />
char c1 = (char) "a";<br />
float f0 = 3;<br />
Compile Error<br />
duction <strong>to</strong> .NET<br />
<strong>Intro</strong><br />
float f1 = "3.1";<br />
DateTime v0 = DateTime.Now;<br />
Object v1 = DateTime.Now;<br />
Object v2 = new Object();<br />
DateTime v3 = (DateTime) new Object();<br />
DateTime v4 = new Object();<br />
OK<br />
OK<br />
Agilent .NET Course: C# Basics 4