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.5 Converting between types<br />
A cast does not involve processing ‐ data is simply interpreted in a different way.<br />
For example if we cast the character ʹ5ʹ <strong>to</strong> an integer we get the ASCII code for 5<br />
(which is 53).<br />
A conversion usually involves some processing.<br />
2.5.1 Converting <strong>to</strong> a string<br />
We often need <strong>to</strong> convert <strong>to</strong> a string.<br />
2.5.1.1 ToString()<br />
The method ToString() can be used for any object. We may optionally control the<br />
format with a format string.<br />
Examples of ToString on an integer<br />
//No surprises here – it gives "3"<br />
3.ToString();<br />
//The stand currency format is used "£3.00" for the UK<br />
3.ToString("c");<br />
//Uses three digits both sides of the . "003.000"<br />
3.ToString("000.000");<br />
//Daisy chains a string method " 3"<br />
3.ToString().PadLeft(5)<br />
duction <strong>to</strong> .NET<br />
<strong>Intro</strong><br />
2.5.1.2 String.Format()<br />
The Format method of the String class may be used <strong>to</strong> construct strings with variable<br />
components.<br />
Examples of use:<br />
Examples of String.Format<br />
// {0} is a place holder "3 men went <strong>to</strong> mow"<br />
String.Format("{0} men went <strong>to</strong> mow.",3)<br />
//"The time is now 23/06/04 12:30"<br />
String.Format("The time now is {0}.", DateTime.Now)<br />
//The place holder {1} crops up with different formats<br />
String.Format("I paid {0:c} on {1:%d} of {1:%MMM}.",<br />
3,DateTime.Now));<br />
In a string format {0} indicates the first parameter, {1} is the next…<br />
Following this indica<strong>to</strong>r we can specify the format <strong>to</strong> be used after a :<br />
In the example above :c indicates currency ‐ £3.00.<br />
Agilent .NET Course: C# Basics 5