Skip to Main Content
C# Cookbook, 2nd Edition
book

C# Cookbook, 2nd Edition

by Jay Hilyard, Stephen Teilhet
January 2006
Intermediate to advanced content levelIntermediate to advanced
1184 pages
43h 23m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook, 2nd Edition
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Converting Between Simple Types in a Language-Agnostic Manner
|
133
finalValue = (int)initialValue;
Console.WriteLine(finalValue.ToString( ));
initialValue = (float)13.5;
finalValue = (int)initialValue;
Console.WriteLine(finalValue.ToString( ));
initialValue = (float)13.501;
finalValue = (int)initialValue;
Console.WriteLine(finalValue.ToString( ));
This code outputs the following:
13
13
13
Notice that the resulting value was not rounded. Instead, the C# casting operator
simply truncates the fractional portion of the number.
Consistently casting numeric types in any language can be done through the static
methods on the
Convert class. The previous C# code can be converted to use the
ToInt32 method:
// C# Code:
finalValue = Convert.ToInt32((float)13.449);
Console.WriteLine(finalValue.ToString( ));
finalValue = Convert.ToInt32((float)13.5);
Console.WriteLine(finalValue.ToString( ));
finalValue = Convert.ToInt32((float)13.501);
Console.WriteLine(finalValue.ToString( ));
This code outputs the following:
13
14
14
Discussion
All conversions performed using methods on the Convert class are considered to be
in a checked context in C#. VB.NET does not have the concept of a checked or
unchecked context, so all conversions are considered to be in a checked context—an
unchecked context cannot be created in VB.NET.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard
Head First C#, 4th Edition

Head First C#, 4th Edition

Andrew Stellman, Jennifer Greene

Publisher Resources

ISBN: 0596100639Supplemental ContentCatalog PageErrata