.NET Framework Standard Library Annotated Reference Volume 1
Contents | Index
MS NET_SP_7.375x9.25.qxd 10/14/03 5:18 PM Page 1
Microsoft .NET Development Series John Montgomery, Series Advisor Don Box, Series Advisor Martin Heller, Series Editor The Microsoft .NET Development Series is supported and developed by the leaders and experts of Microsoft development technologies including Microsoft architects and DevelopMentor instructors. The books in this series provide a core resource of information and understanding every developer needs in order to write effective applications and managed code. Learn from the leaders how to maximize your use of the .NET Framework and its programming languages.
Titles in the Series Brad Abrams, .NET Framework Standard Library Annotated Reference Volume 1, 0-32115489-4 Keith Ballinger, .NET Web Services: Architecture and Implementation, 0-321-11359-4 Don Box with Chris Sells, Essential .NET, Volume 1: The Common Language Runtime, 0-201-73411-7 Mahesh Chand, Graphics Programming with GDI+, 0-321-16077-0 Anders Hejlsberg, Scott Wiltamuth, Peter Golde, The C# Programming Language, 0321-15491-6 Alex Homer, Dave Sussman, Mark Fussell, A First Look at ADO.NET and System.Xml v. 2.0, 0-321-22839-1 Alex Homer, Dave Sussman, Rob Howard, A First Look at ASP.NET v. 2.0, 0-321-22896-0 James S. Miller and Susann Ragsdale, The Common Language Infrastructure Annotated Standard, 0-321-15493-2
www.awprofessional.com/msdotnetseries/
Fritz Onion, Essential ASP.NET with Examples in C#, 0-201-76040-1 Fritz Onion, Essential ASP.NET with Examples in Visual Basic .NET, 0-201-76039-8 Ted Pattison and Dr. Joe Hummel, Building Applications and Components with Visual Basic .NET, 0-201-73495-8 Chris Sells, Windows Forms Programming in C#, 0-321-11620-8 Chris Sells and Justin Gehtland, Windows Forms Programming in Visual Basic .NET, 0321-12519-3 Paul Vick, The Visual Basic .NET Programming Language, 0-321-16951-4 Damien Watkins, Mark Hammond, Brad Abrams, Programming in the .NET Environment, 0-201-77018-0 Shawn Wildermuth, Pragmatic ADO.NET: Data Access for the Internet World, 0-201-74568-2
.NET Framework Standard Library Annotated Reference Volume 1 Base Class Library and Extended Numerics Library Brad Abrams
Boston • San Francisco • New York • Toronto • Montreal London • Munich • Paris • Madrid Capetown • Sydney • Tokyo • Singapore • Mexico City
Contents | Index
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Addison-Wesley was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. The .NET logo is either a registered trademark or trademark of Microsoft Corporation in the United States and/or other countries and is used under license from Microsoft. The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. The publisher offers discounts on this book when ordered in quantity for special sales. For more information, please contact: U.S. Corporate and Government Sales (800) 382-3419
[email protected] For sales outside of the U.S., please contact: International Sales (317) 581-3793
[email protected] Visit Addison-Wesley on the Web: www.awprofessional.com Library of Congress Cataloging-in-Publication Data Abrams, Brad. .NET framework standard library annotated reference volume 1: base class library and extended numerics library / Brad Abrams. p. cm. ISBN 0-321-15489-4 (hardcover : alk. paper) 1. Microsoft .NET Framework. I. Title. QA76.76.M52A27 2004 005.2'768—dc22
2003024327
Copyright © 2004 by Microsoft Corporation All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. Published simultaneously in Canada. For information on obtaining permission for use of material from this work, please submit a written request to: Pearson Education, Inc. Rights and Contracts Department 75 Arlington Street, Suite 300 Boston, MA 02116 Fax: (617) 848-7047 ISBN 0-321-15489-4 Text printed on recycled paper
Contents | Index
To the two most important things in my life: My God and my family.
Contents | Index
Contents Foreword xiii Preface xvii
Part I Namespace Overviews 1 System 3 System.Collections 11 System.Diagnostics 14 System.Globalization 15 System.IO 17 System.Security 21 System.Text 25 System.Threading 27
Part II Class Libraries 31 System.ApplicationException 33 System.ArgumentException 38 System.ArgumentNullException 47 System.ArgumentOutOfRangeException 53 System.ArithmeticException 61 System.Array 65 System.Collections.ArrayList 191 System.ArrayTypeMismatchException 283 System.Text.ASCIIEncoding 288 System.AsyncCallback Delegate 309 System.Attribute 311 vii
Contents | Index
Contents
System.AttributeTargets Enum 369 System.AttributeUsageAttribute 376 System.Boolean Structure 383 System.Byte Structure 400 System.Char Structure 423 System.CharEnumerator 487 System.CLSCompliantAttribute 493 System.Security.CodeAccessPermission 496 System.Security.Permissions.CodeAccessSecurityAttribute System.Collections.Comparer 517 System.Diagnostics.ConditionalAttribute 523 System.Console 528 System.Convert 589
514
System.DateTime Structure 991 System.Globalization.DateTimeFormatInfo 1097 System.Globalization.DateTimeStyles Enum 1154 System.Decimal Structure 1162 System.Text.Decoder 1290 System.Delegate 1295 System.Collections.DictionaryEntry Structure 1337 System.IO.Directory 1340 System.IO.DirectoryNotFoundException 1394 System.DivideByZeroException 1399 System.Double Structure 1403 System.DuplicateWaitObjectException 1448 System.Text.Encoder 1453 System.Text.Encoding 1458 System.IO.EndOfStreamException 1497 System.Enum 1502 System.Environment 1550 System.Security.Permissions.EnvironmentPermission 1574 System.Security.Permissions.EnvironmentPermissionAccess Enum 1594 System.Security.Permissions.EnvironmentPermissionAttribute 1597 viii
Contents | Index
Contents
System.EventArgs 1604 System.EventHandler Delegate 1608 System.Exception 1610 System.ExecutionEngineException 1629 System.IO.File 1633 System.IO.FileAccess Enum 1693 System.Security.Permissions.FileIOPermission 1696 System.Security.Permissions.FileIOPermissionAccess Enum 1723 System.Security.Permissions.FileIOPermissionAttribute 1727 System.IO.FileLoadException 1737 System.IO.FileMode Enum 1748 System.IO.FileNotFoundException 1752 System.IO.FileShare Enum 1762 System.IO.FileStream 1766 System.FlagsAttribute 1831 System.FormatException 1834 System.GC 1839 System.Collections.Hashtable
1851
System.IAsyncResult Interface 1901 System.ICloneable Interface 1911 System.Collections.ICollection Interface 1915 System.IComparable Interface 1922 System.Collections.IComparer Interface 1927 System.Collections.IDictionary Interface 1931 System.Collections.IDictionaryEnumerator Interface 1946 System.IDisposable Interface 1950 System.Collections.IEnumerable Interface 1954 System.Collections.IEnumerator Interface 1957 System.IFormatProvider Interface 1964 System.IFormattable Interface 1967 System.Collections.IHashCodeProvider Interface 1978 System.Collections.IList Interface 1982 System.IndexOutOfRangeException 2004 ix
Contents | Index
Contents
System.Int16 Structure 2008 System.Int32 Structure 2038 System.Int64 Structure 2069 System.Threading.Interlocked 2100 System.InvalidCastException 2116 System.InvalidOperationException 2120 System.InvalidProgramException 2125 System.IO.IOException 2128 System.Security.IPermission Interface 2133 System.MarshalByRefObject 2145 System.Math 2150 System.IO.MemoryStream 2233 System.Threading.Monitor 2278 System.NotFiniteNumberException 2313 System.NotImplementedException 2320 System.NotSupportedException 2324 System.NullReferenceException 2329 System.Globalization.NumberFormatInfo 2334 System.Globalization.NumberStyles Enum 2388 System.Object 2399 System.ObjectDisposedException 2424 System.ObsoleteAttribute 2430 System.OutOfMemoryException 2439 System.OverflowException 2443 System.IO.Path 2447 System.IO.PathTooLongException 2476 System.Security.PermissionSet 2481 System.Security.Permissions.PermissionState Enum
2517
System.Random 2519 System.RankException 2532 System.SByte Structure 2537 System.Security.Permissions.SecurityAction Enum
2568
x
Contents | Index
Contents
System.Security.Permissions.SecurityAttribute 2583 System.Security.SecurityElement 2587 System.Security.SecurityException 2600 System.Security.Permissions.SecurityPermission 2611 System.Security.Permissions.SecurityPermissionAttribute 2628 System.Security.Permissions.SecurityPermissionFlag Enum 2638 System.IO.SeekOrigin Enum 2645 System.Single Structure 2648 System.StackOverflowException 2690 System.IO.Stream 2694 System.IO.StreamReader 2735 System.IO.StreamWriter 2774 System.String 2807 System.Text.StringBuilder 2955 System.IO.StringReader 3042 System.IO.StringWriter 3054 System.Threading.SynchronizationLockException 3069 System.SystemException 3074 System.IO.TextReader 3079 System.IO.TextWriter 3089 System.Threading.Thread 3128 System.Threading.ThreadAbortException 3192 System.Threading.ThreadPriority Enum 3195 System.Threading.ThreadStart Delegate 3199 System.Threading.ThreadState Enum 3201 System.Threading.ThreadStateException 3207 System.Threading.Timeout 3212 System.Threading.Timer 3214 System.Threading.TimerCallback Delegate 3234 System.TimeSpan Structure 3236 System.Type 3305 System.TypeInitializationException 3528 System.UInt16 Structure System.UInt32 Structure
3531 3562 xi
Contents | Index
Contents
System.UInt64 Structure 3593 System.UnauthorizedAccessException 3624 System.Globalization.UnicodeCategory Enum System.Text.UnicodeEncoding 3640 System.Text.UTF8Encoding 3667 System.ValueType 3697 System.Security.VerificationException System.Version 3709 System.Threading.WaitHandle
3629
3704
3739
Annotations Index 3763 Index 3765
xii
Contents | Index
Foreword When I began my standards “career” back in August 2000, “ECMA” and “ISO” meant as much to me as the sequence of letters in the daily newspaper jumble. I hadn’t a clue on how the standards process actually worked, from either a technical or a political perspective. Now, as I write this, I am chair of the ECMA committee that oversees the standardization of programming and scripting languages. In addition, I am convener of the task group within the committee that is responsible for the standardization of the CLI, on which, of course, the content of this book is based. In 2000, Microsoft publicly introduced its .NET vision. A key component of this vision is the .NET Framework, which includes a set of class libraries and a virtual machine (“runtime engine”) to execute next-generation applications. In September 2000, Microsoft, co-sponsored by Intel and Hewlett-Packard, formally submitted a core subset of the .NET Framework to ECMA International, a renowned international standards organization. The submission was entitled the Common Language Infrastructure, or CLI. The meeting was held in Bristol, England, with representatives from companies such as IBM and Sun Microsystems. Microsoft presented the CLI to ECMA’s Programming and Scripting Languages Technical Committee, or TC39. It was decided by unanimous consent that the CLI would be added to the program of work for TC39 and that a new task group, called the TG3, would be responsible for the standardization effort. One might ask what happened to TG1 and TG2. Before the submission of the CLI, the TC39 was responsible for the standardization of only ECMAScript. There were no task groups, per se. When the CLI was approved for work, ECMAScript was moved to a newly formed TG1. C#, which was submitted at the same time as the CLI, introduced the TG2. The TG3 was reserved for the CLI. There is now even a TG4 responsible for the standardization of the Eiffel programming language and a TG5 chartered to standardize a binding between ISO C++ and the CLI. There are two primary facets to the CLI standardization process within ECMA, the virtual machine and the class libraries. The virtual machine provides the environment necessary to execute applications written for the CLI. The class libraries provide the core infrastructure to enable developers to create libraries and applications for execution on top of the virtual machine. xiii
Contents | Index
Foreword
I am involved in both facets of the standardization process, but I have enjoyed the class library aspect the most. This is primarily because I have a better understanding of that level of the development stack than I do the lower layers, such as where the virtual machine would lie. And since Brad Abrams was the Microsoft lead in the class library standardization effort, my good relationship with him began. The set of class libraries submitted to ECMA International are, from a .NET Framework perspective, relatively small. However, they definitely provide the foundation upon which all other class libraries are built. The class library was segmented into what the standard calls “profiles.” The kernel profile consists of the base types that would be expected to exist in modern programming languages (as well as types to assist compilers for those languages). String and Int32 are examples of such types. The kernel profile must be implemented in order to claim conformance to the standard. The compact profile consists of the kernel profile, plus some types necessary to implement basic Web services-type applications while maintaining a small enough footprint to fit on standard compact, connected devices. Then there are some types that do not fit any profile, but can be implemented as part of any profile. These include types dealing with floating point numbers and multidimensional arrays. Brad’s book concentrates on the base types that are part of the kernel profile, as well as the extended numerics (e.g., floating point and decimal). For information on the concept behind the segmentation of the class libraries into profiles, see Partition IV of the ECMA Standard ECMA-335, also published as ISO/IEC 23271. The ECMA Standard can be downloaded— and freely copied—free of charge from http://www.ecma-international.org. The process by which we standardized the base types associated with kernel profile was systematic, and yet churned out some very interesting and heated discussion. There was an initial cursory review of all of the libraries in order to weed out any obvious errors and missing data. Then came the detailed reviews. We started with the type of all types, System.Object. This served as the model of the process we would use to do the rest of the detailed reviews. The task group members would work offline and formulate individual comments on the type. Then at the meeting we would go page by page, method by method, property by property to see if there were any comments. Brad, who managed the editing process at Microsoft, took the comments back and incorporated them. Finally, the task group would review the type again with the incorporated changes and consider it final. Of course, if the task group just reviewed one type per meeting, we would still be reviewing the class libraries. After System.Object, the base types were divided into relatively equal parts, and at each meeting the task group would review one of those parts. To expedite the process, a subgroup of people were assigned as primary reviewers for certain types. Thus, committee members weren’t overwhelmed by having to do detailed analysis and commentary on all types. If all we did at the meetings were editorial reviews of the types—fixing punctuation here and changing a word there—they would have been quite boring. (Actually, come to think of it, it would have been amazing if that were the case—no substantial changes were needed to the class libraries because they were already perfect!) I mentioned that some interesting and heated discussion occurred during the reviews of the class libraries. This was because they were, of course, not perfect, and thus illustrate the benefit and relevance xiv
Contents | Index
Foreword
of the standardization process. You will see many annotations in this book that are examples of cool discussion, so I won’t dive into it much here, but one instance definitely sticks out as a whopper. It was within the System.Decimal structure, where the original specification of the ToString() method did not preserve the scale (trailing zeros) during conversion (even though it maintained scale internally, it was not exposed through conversions back and forth from String). For example, given a decimal value of 134.320000, it can be noted that this has a scale of 6. Calling the ToString() method would produce a string with the characters 134.32, making a decimal value with a scale of 2. This was deemed the wrong thing to do. Now one must remember that the .NET Framework 1.0 had already been shipped to millions of customers. Even so, the change was made to the specification and, even more important, Microsoft staff agreed to this change even though it would break code. They knew, however, it was the right thing to do. Indeed, standardization can be quite interesting! The class library specifications were submitted to ECMA International, but not as the Microsoft Word or Adobe PDF documentation that one would expect. Instead they were submitted in XML format. This was done for various reasons, but the primary one was so that implementers could create documentation in any form they chose (HTML, Word, PDF, etc.) using well-known XSLT techniques and other mechanisms. It allowed for a lot of freedom in the documentation. Of course, no one (at least no one of sound mind) is going to read 10 MB of raw XML, let alone use it as the means to review the types. Thus a way to convert the XML to Word was needed. A managed code-based tool was developed by one of the task group members using XSLT and COM Interop to access the Word APIs (I am usually very humble, so I won’t mention the tool author by name, but… ☺). This turned out to be very valuable because it produced human-readable documentation. It also saved months of manual editing and formatting because the tool allowed edits to be made to the XML only, and then it would take care of the rest. The tool was also versatile. It did not just generate Word documents. For example, the type, method, and property signatures you see in this book—even those in the C# standard—are based on the running of the conversion tool. It was actually quite fun to develop. Not everyone was convinced of the benefits of the XML, and there was some controversy regarding the submission of the class libraries in that format (although ECMA had already developed another standard in this format); it even caused one delegation within ISO to vote against accepting the standard at first. After discussion, however, the XML format was accepted as an appropriate submission mechanism. The tool, and the results it produces, is published as ECMA TR/84, which is also freely available from the ECMA Web site. Some people may ask why the CLI was submitted for standardization in the first place. Yes, it’s true that the current standard CLI specification alone will not allow developers to implement a majority of real-world applications (e.g., I doubt Quake could be etched out of the standard library set). However, it is, in my mind, a near-perfect base to begin such an implementation. Also, the industry has accepted the standard. Intel’s Open Class Libraries (OCL), as well as other public projects, are based on what the standard has to offer (the licensing arrangements for the standard are very kind, which helps here, but I won’t get into that). It provides a cookbook for researchers to do work in the xv
Contents | Index
Foreword
area of managed runtime environments, knowing that this cookbook is based on a highquality and widely used commercial implementation. It also provides a foundation for future technologies to be added to the standard, which is already evident in the work happening to the next edition of the standard. The first edition of the standard was ratified by ECMA in December 2001, and approved by ISO in October 2002 (which became Edition 2 of the ECMA standard in December 2002 because minor edits were made during the ISO review process). Work on Edition 3 is occurring as I write this, and some interesting libraries are being considered in the area of generics and threading. The specification itself, while important in implementing the CLI class libraries, could be construed as very dry reading. It is, after all, primarily a cookbook specifying what must be included in a successful class library recipe. .NET Framework Standard Library Annotated Reference, Volume 1, adds some pizzazz to the standard. Annotations are not typically an official part of a standard, and rightly so, as a standard must be as clear and concise as possible, only providing necessary information for implementation. However, if I were a developer using the CLI class libraries (heck, even if I were an implementer of the libraries), this book would be my primary tool. Why? Because it provides you with all the information of the official standard, but also includes firsthand insight, examples, and occasionally a little humor by those who developed it. And those added extras could answer a lot of the “Why was this done that way?” questions that many developers have. Some quick praise for the author of this book, Brad Abrams: It is obvious that he is a content guru. In addition, it was his leadership in producing the specifications, accepting (most of the time ☺) and incorporating changes, and reproducing the results in a timely manner, that enabled this standard to be produced in the time frame it was. For me, the journey from alphabet soup to where we are today has been an interesting ride. I like to think my hard work during the process and my passion for what was being standardized led me to the ECMA positions I hold today. But if it weren’t for the dedication of people like Brad, who was instrumental in getting the first edition of the standard out the door, I am not sure there would be such positions in the first place. Step into the minds of the people who actually made the standard class libraries happen, and enjoy the book. Joel Marcey Intel Corporation Chair of TC39 Convener of TG31
1. The views expressed in this Foreword do not necessarily reflect the views of Intel Corporation, its affiliates, its subsidiaries, or its employees.
xvi
Contents | Index
Preface This book is intended for anyone building applications using the .NET Framework. It is meant to be a dictionary-style reference to the core types in the Framework. The .NET Framework is huge. The amount of time that would be required (and the physical constraints of binding a book) limits our ability to cover the entire .NET Framework in the depth it deserves. As a result, we have focused the scope of this book on the most important, widely used types in the Framework. Luckily, such a subset was already created in the standardization process of the Common Language Runtime and the C# Programming Language. This book covers the first half of that subset (Volume 2 will pick up the second half). In the printed portion of this volume you will find all the type-level information for these types. Both the type-level information and member-level information are available in electronic form on the CD. To make the standard more accessible, this book includes the following features: • • • • • •
Annotations from key folks involved in the design of the .NET Framework Namespace overviews Type descriptions Sample code to illustrate type uses A fully searchable CD that includes all source code, descriptions, annotations, and examples A fold-out poster containing a detailed inheritance diagram for all types covered in this volume.
These features not only bring the standard to life, but more importantly, they serve as a convenient, informative reference to the most used types in the .NET Framework.
The Standard At the Professional Developer’s Conference in October 2001, Microsoft, in partnership with HP and Intel, began the ECMA standardization process of three core parts of its new developer platform: the Common Language Infrastructure (CLI), the C# programming xvii
Contents | Index
Preface
language, and a subset of the .NET Framework that is included in the CLI and referenced in the C# specification. The CLI and the C# programming language are covered in other books in this series. Jim Miller’s The Common Language Infrastructure Annotated Standard covers the CLI, which includes the metadata file format, IL Instruction set, and the type system. The C# Programming Language by Anders Hejlsberg, Scott Wiltamuth, and Peter Golde covers the C# programming language specification. This book covers the first half of the .NET Framework as standardized in ECMA 335 and ISO 23271. The standards break the .NET Framework into seven different libraries to allow conformant implementations in resource-constrained environments. Those libraries are as follows: Base Class Library—A simple runtime library for modern programming languages. It serves as the standard for the runtime library for the language C#, as well as one of the CLI standard libraries. It provides types to represent the built-in data types of the CLI, simple file access, custom attributes, security attributes, string manipulation, formatting, streams, collections, and so forth. Extended Numerics Library—Provides the support for floating-point (System.Single, System.Double) and extended-precision (System.Decimal) data types. Like the Base Class Library, this library is directly referenced by the C# standard. Network Library—Provides simple networking services, including direct access to network ports and HTTP support. Reflection Library—Provides the ability to examine the structure of types, create instances of types, and invoke methods on types, all based on a description of the type. XML Library—Provides a simple “pull-style” parser for XML. It is designed for resource-constrained devices, yet provides a simple user model. Runtime Infrastructure Library—Provides the services needed by a compiler to target the CLI and the facilities needed to dynamically load types from a stream in the file format specified. For example, it provides System.BadImageFormatException, which is thrown when a stream that does not have the correct format is loaded. Extended Array Library—Provides support for non-vector arrays, that is, arrays that have more than one dimension and arrays that have non-zero lower bounds. This volume completely covers the Base Class Library and the Extended Numerics Library, as well as Microsoft-specific members on those types. It is our intention to cover the remaining libraries in future volumes.
xviii
Contents | Index
Preface
Namespace Overviews To facilitate reader understanding, we provide an overview of each namespace we cover that describes the functionality and the inheritance hierarchy of types defined in that namespace. At the end of the namespace overview section we include a complete inheritance hierarchy for all the types covered in this volume. In the diagrams we differentiate the various kinds of types that make up the framework as follows: •
For classes, we use a rectangle: Object
Example of a class
•
For interfaces, we use a rounded rectangle: IComparable
Example of an interface
•
Abstract types are indicated with an “A”: ValueType
Example of an abstract type
•
Enums are indicated with an “E”: AttributeTargets
Example of an enum
•
All other value types are indicated with a “V”: Boolean
Example of a value type
•
Types in the Extended Numerics Library and those that are not standardized are specifically called out. If not otherwise noted, a type belongs to the Base Class Library. Decimal
ExtendedNumerics
Example of a type in the Extended Numerics Library
xix
Contents | Index
Preface
Type Chapters Types are described in their own chapters, which are organized alphabetically by type name. Header The header contains the namespace name (1), the type name (2), and the library name from the ECMA\ISO Standard (3).
System.IO File
BCL
1
3 2
Type Hierarchy Under the header we include a diagram representing the full inheritance hierarchy for this type (1), subclasses of this type found in this volume (2), and any interfaces they implement (3). The type being described is shown with a gray background (4).
1
Object MarshalByRefObject
4 Stream
IDisposable
3 FileStream
2
MemoryStream
Example of type hierarchy for the Stream class.
Type Summary This section contains the C# declaration syntax for all members defined on this type. It is meant to provide a quick reference in a very familiar format to what is in the type. In this summary we highlight certain attributes of these members. CF
Indicates the member is not available in the .NET Compact Framework. If not included the member is available.
MS
Indicates that the member is not included in the ECMA\ISO standard.
1.1
Indicates that the member is new in V1.1 of the .NET Framework.
xx
Contents | Index
Preface
Most of these attributes are shown below. public sealed class Environment { // Properties CF public static string CommandLine { get; } MS CF public static string CurrentDirectory { set; get; } CF public static int ExitCode { set; get; } CF 1.1 public static bool HasShutdownStarted { get; } MS CF public static string MachineName { get; } CF public static string NewLine { get; } MS public static OperatingSystem OSVersion { get; } CF public static string StackTrace { get; } MS CF public static string SystemDirectory { get; } public static int TickCount { get; } MS CF public static string UserDomainName { get; } MS CF public static bool UserInteractive { get; } MS CF public static string UserName { get; } public static Version Version { get; } MS CF public static long WorkingSet { get; } // CF MS CF CF CF CF MS CF MS CF }
Methods public static public static public static public static public static public static public static
void Exit (int exitCode); string ExpandEnvironmentVariables (string name); string[] GetCommandLineArgs (); string GetEnvironmentVariable (string variable); IDictionary GetEnvironmentVariables (); string GetFolderPath (SpecialFolder folder); string[] GetLogicalDrives ();
Type Description This section contains a detailed description of how this type is to be used. For the most part this text is taken directly from the standard. Annotations Throughout this section we provide annotations from key members of the design team at Microsoft and members of the ECMA standardization committee. The comments in this section vary widely, and include notes on everything from common issues to the history of the class design or standardization process to areas where, in retrospect, the designers feel they could have done better.
xxi
Contents | Index
Preface
Here’s an example of an annotation from Anders Hejlsberg on the String class:
AH While it may seem obvious, one of the big advantages of .NET is that it defines a single representation for strings. During its evolution, the Windows platform has accrued quite a collection of string representations: ANSI strings, Unicode strings, null terminated strings, length prefixed strings, etc. Unifying all of those has made .NET a much simpler and safer place to program.
Each annotation is attributed to individuals by their initials. In this volume you will find annotations from: BA—Brad Abrams is a Lead Program Manager on the .NET Framework team at Microsoft, where he has been designing the Framework Class Libraries since 1997. Brad graduated with a B.A. in computer science from North Carolina State University. He is the primary author of the .NET Framework Design Guidelines, the Common Language Specification, and the class libraries for the ECMA\ISO CLI standard and C# language standard. KC—Krzysztof Cwalina is a program manager on the .NET Framework team at Microsoft. He graduated in 1999 with an M.A. in computer science from the University of Iowa, specializing in software engineering. He has participated in the design and implementation of the first release of the .NET Framework. He is also a member of a working group developing the .NET Framework Design Guidelines. KG—Kit George is a program manager on the Common Language Runtime team at Microsoft. He graduated in 1995 with a B.A. in psychology, philosophy, and mathematics from Victoria University of Wellington (New Zealand). Prior to joining Microsoft, he worked as a technical trainer, primarily in Visual Basic. He participated in the design and implementation of the first two releases of the framework for the last two years. BG—Brian Grunkemeyer has been a software design engineer on the .NET Framework team at Microsoft for more than five years. He graduated in 1998 with a B.S. in computer science (and a double major in cognitive science) from Carnegie Mellon University. He has implemented a large portion of the Framework Class Libraries and contributed to the details of many classes in the ECMA\ISO CLI standard. He is currently working on future versions of the .NET Framework, including areas such as generic collections and managed code reliability.
xxii
Contents | Index
Preface
AH—Anders Hejlsberg is a Distinguished Engineer in the Developer Division for Microsoft. He is the chief designer of the C# programming language and a key participant in the development of the Microsoft .NET Framework. Hejlsberg has also represented Microsoft in ECMA, where C# and the .NET Framework have been submitted by Microsoft for standardization. Before his work on C# and the .NET Framework, Hejlsberg was an architect for the Visual J++ development system and the Windows Foundation Classes. Before joining Microsoft, Hejlsberg was one of the first employees of Borland International Inc. As principal engineer, he was the original author of Turbo Pascal and later worked as the chief architect of the Delphi product line. Anders studied engineering at the Technical University of Denmark. YL—Yung-Shin Lin is a development lead on the Windows Globalization team at Microsoft. He participated in the design and implemented most of the functionality in the System.Globalization namespace. JM—Joel Marcey is a senior software engineer at Intel Corporation in Folsom, California. He has been with Intel for six years. He graduated in 1997 with a B.S. in computer engineering from North Carolina State University. He is currently doing research and development in the area of managed runtime execution environments. He is also a key member and technical contributor to the CLI standardization process within ECMA. He is the elected chair of ECMA TC39 and the elected convener of the TC39 TG3 for the 2003 calendar year. JR—Jeffrey Richter is a co-founder of Wintellect (www.Wintellect.com), a training, debugging, and consulting firm dedicated to helping companies build better software, faster. He is the author of Applied Microsoft .NET Framework Programming (Microsoft Press) and several Windows programming books. Jeffrey is also a contributing editor to MSDN Magazine, where he writes the .NET column. Jeff has been consulting with Microsoft’s .NET Framework team since October 1999 and has been involved in the standardization process of the CLI. Type Examples In this section we provide sample code illustrating use of the type. Some samples are from the standard, but we added many more to facilitate a deeper and quicker understanding of the use of the type. All the samples we provide are fully compilable programs (1) and include selected output (2).
xxiii
Contents | Index
Preface
Example using System; namespace Samples { public class ObjectSample { public static void Main() { Object o = new Object(); Console.WriteLine("Are they equal: {0}", o.Equals(new Object())); Console.WriteLine("Are they equal: {0}", o.Equals(o)); Console.WriteLine("GetHashcode yields {0}", o.GetHashCode()); 1 Console.WriteLine("GetHashcode yields {0}", new Object().GetHashCode()); Console.WriteLine("o.ToString(): {0}", o.ToString()); } } }
The output is Are they equal: False Are they equal: True GetHashcode yields 3 GetHashcode yields 5 o.ToString(): System.Object
2
All of these samples have been tested with V1.0 and V1.1 of the .NET Framework and the appropriate ones have been tested on the .NET Compact Framework. Complete source code for the samples is available at www.awprofessional.com/titles/ 0321154894 and on the CD that is included in the back of the book. Type Members The detailed descriptions of the members are included in the electronic version of the book on the CD. To facilitate easy look-ups, the member descriptions appear in the same order as the type summary sections. Each member contains some or all of the following fields: Syntax—C# declaration syntax is provided for familiar reference. ILASM syntax is provided for completeness. Summary—Short description of the member’s purpose. Parameters—Table of parameters accepted by this member and their meaning.
xxiv
Contents | Index
Preface
Description—A complete description of this member. Return Value—The value and range returned by this method. Property Value—The value of this property. Exceptions—Table of the common exceptions thrown by this member. Permissions—Table of the code access permissions demanded by this method. Example—An example using this member following the same pattern as the type samples.
Conventions Used in This Book Courier is used for all source code blocks, including syntax declarations, class names, and member names.
Additional Features In addition to including the content from the ISO CLI standard, this book includes a number of other features: •
•
•
For every type covered in the book we include all the members as defined in V1.1 of the .NET Framework. Many members were left out of the ECMA standard to streamline platform work because types in the signature were not in the standard or because of scheduling reasons. As this book is primarily targeted at developers using the .NET Framework, we elected to include all the members of the types we cover, not just those that are standardized. Nearly every type contains annotations from key members of the design team at Microsoft and members of the ECMA standards group. These annotations bring rationale, history, and other interesting notes about the types covered. We added more than 1,000 samples to the book. Nearly every member has a working sample with output included. All of the samples can be found on the CD.
Acknowledgments Many people contributed to making this book possible. We would like to thank: Martin Heller, editor, for his technical guidance as well has coordinating a myriad of details involved in creating the book. Stephane Thomas from Addison-Wesley for her constant support and for keeping us on schedule. David Platt for producing the excellent namespace overviews provided here. Damien Watkins for writing (and re-writing) hundreds of samples. Tamara Abrams for her painstaking review and copy edit of the entire work. xxv
Contents | Index
Preface
Joel Marcey for providing technical support in working with the Xml doc format used in the ECMA standard and for providing thoughtful and lighthearted annotations. Jeffrey Richter for advisory services and for providing insightful annotations. Yung-Shin Lin, Anders Hejlsberg, Brian Grunkemeyer, Kit George, and Krzysztof Cwalina for providing additional annotations. The contributing members of ECMA TC-39 TG1 and TG2 for formalizing the CLI and C# Standards on which this book is based. Susan Radke-Sproull, my manager here at Microsoft, for allowing me the time to contribute this work. Tyrrell Albaugh and Reuben Kantor, the real unsung heroes of this project, who put up with countless changes through the project. Their efforts resulted in a much better book. Brad Abrams Lead Program Manager, .NET Framework Team Microsoft Corporation February 2004
xxvi
Contents | Index
PART I Namespace Overviews
1
Contents | Index
System
System
The System namespace is the root of all namespaces in the .NET Framework, containing all other namespaces as subordinates. It also contains the types that we felt to be the most fundamental and frequently used.
Basic Variable Types The class Object is the root of the inheritance hierarchy in the .NET Framework. Every class in the .NET Framework ultimately derives from this class. If you define a class without specifying any other inheritance, Object is the implied base class. It provides the most basic methods and properties that all objects need to support, such as returning an identifying string, returning a Type object (think of it as a class descriptor) to use for runtime discovery of the object’s contents, and providing a location for a garbage collection finalizer. The .NET Framework provides two kinds of types, value types and reference types. Instances of value types are allocated on the stack or inline inside an object, which incurs a lower overhead than using the managed heap. Value types are most often used for small, lightweight variables accessed primarily for a single data value, while still allowing them to be treated as objects in the inheritance hierarchy (for example, having methods). All value types must derive from the abstract base class ValueType. Table 1 lists the value types in the System namespace. TABLE 1
Name
Represents
Boolean
Boolean value (true or false).
Byte
8-bit unsigned integer.
Char
UTF-16 code point.
DateTime
An instant in time, typically expressed as a date and time of day.
Decimal
Decimal number.
Double
Double-precision floating-point number.
Enum
Base class for enumerations.
Int16
16-bit signed integer.
Int32
32-bit signed integer.
3
Contents | Index
System
System
TABLE 1 (continued)
Name
Represents
Int64
64-bit signed integer.
SByte
8-bit signed integer.
Single
Single-precision floating-point number.
TimeSpan
Time interval.
UInt16
16-bit unsigned integer.
UInt32
32-bit unsigned integer.
UInt64
64-bit unsigned integer.
All objects that are not value types are by definition reference types. Creating an instance of a reference type allocates the new object from the managed heap and returns a reference to it, hence the name. Most objects are reference types. The class String is a reference type that represents an immutable series of characters. The class CharEnumerator supports iterating over a String and reading its individual characters. The System namespace also contains the abstract base class Array, which represents a fixed-size, ordered series of objects accessed by index. It contains methods for creating, manipulating, and searching for elements within the array. Programmers will generally not use this class directly. Instead, their programming language will provide an abstraction of it.
Attributes The .NET Framework makes extensive use of attributes, descriptive pieces of read-only information that a programmer can place in an object’s metadata. Attributes can be read by any interested piece of code that has the required level of permission. Many attributes are provided and used by the system. Others are defined by programmers and used for their own purposes. All attributes derive from the abstract base class System.Attribute. The attributes in Table 2 were felt to be common enough to occupy the System namespace. Many other subordinate namespaces also define more specialized attributes.
4
Contents | Index
System
TABLE 2
Meaning
AttributeUsageAttribute
Used in the definition of other attribute classes, specifying the target types to which the other attribute class can be applied (assembly, class, method, some combination, etc.). Uses AttributeTargets enumeration.
CLSCompliantAttribute
Indicates whether a program element is compliant with the Common Language Specification (CLS).
FlagsAttribute
Indicates that an enumeration can be treated as a bit field; that is, a set of flags.
ObsoleteAttribute
Marks the program elements that are no longer in use.
System
Attributes
Utility Objects The class Console provides functions for performing input and output to a console window. It’s useful for debugging and development, and any functionality for which a full Windows interface is overkill. The class Convert provides static methods for converting a variable of one base type into another base type, such as Int32 to Double. The class GC provides a connection to the garbage collector in the automatic memory management system. It contains methods such as Collect, which forces an immediate garbage collection. The utility class Environment provides access to environment variables, and other environment properties such as machine name. The class MarshalByRefObject is the abstract base class for objects that communicate across application domain boundaries by exchanging messages using a proxy. Classes must inherit from MarshalByRefObject when the type is used across application domain boundaries, and the state of the object must not be copied because the members of the object are not usable outside the application domain where they were created. The class Math provides access to mathematical operations such as trigonometric and logarithmic functions. The class Random provides methods that generate a sequence of random numbers, starting from a specified seed. You should use specialized cryptographic functionality (in the System.Security.Cryptography namespace) for random number generation for cryptographic purposes. The class Type is the basis for all reflection operations. Think of it as a class descriptor. The class Version represents a dotted quad version number (major, minor, build, revision). It is used in the utility functions that specify versioning behavior of assemblies.
5
Contents | Index
System
Interfaces
System
The System namespace defines a number of interfaces. An interface is a set of pure virtual function definitions, which a class can choose to implement. You define an interface to enforce a common design pattern among classes that are not hierarchically related. For example, the IDisposable interface contains the method Dispose, used for deterministic finalization. This provides a way to force an object to perform its cleanup code immediately instead of when the garbage collector feels like getting around to it. Any class anywhere in any inheritance hierarchy might reasonably need this behavior. However, most classes won’t need this behavior, so it wouldn’t make sense to put it in the System.Object base class and force all objects to implement it whether they needed it or not. Instead, a class that needs this behavior implements the interface, ensuring that it follows the same syntactic rules as all other objects that do so, without disturbing its inheritance relationships with its base classes. The interfaces in Table 3 were felt to be common enough to occupy the System namespace. Many other subordinate namespaces also define more specialized interfaces. TABLE 3
Interface
Meaning
IAsyncResult
Represents the status of an asynchronous operation.
ICloneable
Supports cloning, which creates a new instance of a class with the same value as an existing instance.
IComparable
Defines a generalized comparison method that a value type or class implements to create a type-specific comparison method.
IDisposable
Defines a method to release allocated unmanaged resources.
IFormatProvider
Provides a mechanism for retrieving an object to control formatting.
IFormattable
Provides functionality to format the value of an object into a string representation.
Delegates The .NET Framework supports callbacks from one object to another by means of the class Delegate. A Delegate represents a pointer to an individual object method or to a static class method. You generally will not use the Delegate class directly, but instead will use the wrapper provided by your programming language. The .NET Framework event system uses delegates. The object wanting to receive the event provides the sender with a delegate, and the sender calls the function on the delegate to signal the event. The .NET Framework supports asynchronous method invocation for any method on any object. The caller can either poll for completion, or pass a delegate of the AsyncCallback class to be notified of completion by an asynchronous callback. 6
Contents | Index
System
Exceptions
System
In order to provide a common, rich, easily programmed and difficult to ignore way of signaling and handling errors, the .NET Framework supports structured exception handling. A caller places an exception handler on the stack at the point at which he wants to catch the error, using the try–catch syntax of his programming language. A called function wanting to signal an error creates an object of class System.Exception (or one derived from it) containing information about the error and throws it. The CLR searches up the call stack until it finds a handler for the type of exception that was thrown, at which time the stack is unwound and control transferred to the catch block, which contains the error-handling code. The class System.Exception is the base class from which all exception objects derive. It contains such basic information as a message provided by the thrower and the stack trace at which the exception took place. The class System.SystemException derives from it, and all system-provided exceptions derive from that. This allows a programmer to differentiate between system-provided and programmer-built exceptions. The system-provided exceptions in Table 4 were felt to be common enough to occupy the base System namespace. Many more specialized exception classes live in subordinate namespaces. TABLE 4
Exception
Meaning
ApplicationException
A non-fatal application error occurred.
ArgumentException
One of the arguments provided to a method is not valid.
ArgumentNullException
A null reference is passed to a member that does not accept it as a valid argument.
ArgumentOutOfRangeException
The value of an argument is outside the allowable range of values as defined by the invoked member.
ArithmeticException
Error in an arithmetic, casting, or conversion operation.
ArrayTypeMismatchException
An attempt is made to store an element of the wrong type within an array.
DivideByZeroException
An attempt was made to divide an integral or decimal value by zero.
DuplicateWaitObjectException
An object appears more than once in an array of synchronization objects.
ExecutionEngineException
An internal error occurred in the execution engine of the common language runtime.
7
Contents | Index
System
System
TABLE 4 (continued)
Exception
Meaning
FormatException
The format of an argument does not meet the parameter specifications of the invoked method.
IndexOutOfRangeException
An attempt is made to access an element of an array with an index that is outside the bounds of the array.
InvalidCastException
Invalid casting or explicit conversion.
InvalidOperationException
A method call is invalid for the object’s current state.
InvalidProgramException
A program contains invalid Microsoft intermediate language (MSIL) or metadata. Generally this indicates a bug in a compiler.
NotFiniteNumberException
A floating-point value is positive infinity, negative infinity, or Not-a-Number (NaN).
NotSupportedException
An invoked method is not supported or not supported in the current mode of operation.
NullReferenceException
An attempt to dereference a null object reference.
ObjectDisposedException
An operation is performed on a disposed object.
OutOfMemoryException
There is not enough memory to continue the execution of a program.
OverflowException
An arithmetic, casting, or conversion operation in a checked context results in an overflow.
RankException
An array with the wrong number of dimensions is passed to a method.
StackOverflowException
The execution stack overflows by having too many pending method calls.
TypeInitializationException
A wrapper around the exception thrown by the type initializer.
UnauthorizedAccessException
The operating system denies access because of an I/O error or a specific type of security error.
8
Contents | Index
System
Diagram Object Exception
System.Runtime.Serialization.ISerializable
NotStandardized
System
ApplicationException SystemException ArgumentException ArgumentNullException ArgumentOutOfRangeException DuplicateWaitObjectException ArithmeticException DivideByZeroException OverflowException NotFiniteNumberException
ExtendedNumerics
ArrayTypeMismatchException ExecutionEngineException FormatException IndexOutOfRangeException InvalidCastException InvalidOperationException ObjectDisposedException InvalidProgramException NotImplementedException NotSupportedException NullReferenceException OutOfMemoryException RankException StackOverflowException
ICloneable
TypeInitializationException
System.Collections.IList
UnauthorizedAccessException
System.Collections.ICollection
Array
System.Collections.IEnumerable
Delegate
ICloneable
MulticastDelegate
NotStandardized
System.Runtime.Serialization.ISerializable
NotStandardized
AsyncCallback EventHandler Attribute AttributeUsageAttribute
9
Contents | Index
System
CLSCompliantAttribute FlagsAttribute IComparable
System
ObsoleteAttribute
IFormattable
ValueType Enum
IConvertible
NotStandardized
AttributeTargets IComparable Boolean IConvertible
NotStandardized
Byte IComparable Char IConvertible
NotStandardized
DateTime Int16 Int32 Int64 IComparable
SByte TimeSpan
IComparable
IFormattable
UInt16
IConvertible
NotStandardized
UInt32 UInt64 Decimal
ExtendedNumerics
Double
ExtendedNumerics
Single
ExtendedNumerics
System.Collections.IEnumerator CharEnumerator ICloneable Console Convert Environment EventArgs GC
IComparable
MarshalByRefObject
ICloneable
Random
System.Collections.IEnumerable
String
IConvertible
IAsyncResult
ICloneable
System.Reflection.MemberInfo
Reflection
Type
IComparable
NotStandardized
System.Refection.ICustomAttributeProvider System.Refection.IReflect
NotStandardized
IDisposable
NotStandardized
IFormatProvider Version Math
ICloneable ExtendedNumerics
IComparable
IFormattable
10
Contents | Index
System.Collections System.Collections
Organizing collections of objects is a vital but boring task that operating system designers have historically left to language implementers. Naturally, every language’s and every vendor’s implementation of collections varied drastically, making it essentially impossible for different applications to exchange, say, an array of objects without having intimate knowledge of each other’s internal workings. With the System.Collections namespace, Microsoft has brought the common implementation philosophy to the mundane task of organizing collections of objects. Rather than depend on individual languages to implement such common concepts as arrays and hash tables, Microsoft decided to bring them into the .NET Framework, thereby standardizing them for all applications. This namespace contains classes that are used to organize collections of objects, and also the interfaces that you can use to write your own collection classes while still retaining a common interface to callers. The two main classes of collection are ArrayList and Hashtable. Each is dynamically sizable and can hold any type of object, even mixing contained object types within the same collection object. They differ in their organization strategies. The ArrayList is an ordered, numerically indexed collection of objects. When you place an object into an ArrayList or fetch an object from it, you specify which element location to put it in or fetch it from (“Put this object in slot 2,” “Get the object from slot 5”). Think of it as a set of pigeonholes. It differs from the basic array class System.Array by being dynamically sizable. The architects felt that the basic fixed-size array was fundamental enough to join the most basic types in the System namespace. A Hashtable is an unordered collection in which objects are identified by keys. When you place an object in a Hashtable, you specify the key that you want used to identify it. When you fetch an object from a Hashtable, you provide the key and the Hashtable returns the object that the key identifies. The key is most often a string, but it can be any type of object. As you examine the individual member functions, you will notice that the collection classes share many common methods. For example, the ArrayList and Hashtable classes each contain the method GetEnumerator. These common behaviors ease the tasks of implementers and consumers alike. The collection classes obtain this commonality of behavior by implementing standardized interfaces. You probably want to do the same with your derived classes. The standardized interfaces, and their usages in the collection classes, are shown in Table 5. Note that a number of the interfaces are not implemented directly on the collection classes that I’ve listed. For example, the IEnumerator interface is not implemented directly on ArrayList or Hashtable object, but instead is returned by the IEnumerable interface, which is. Also note that the collection classes listed implement interfaces from other namespaces, such as System.ICloneable.
11
Contents | Index
System.Collections
System.Collections
TABLE 5
Interface
Description
ICollection
Defines size, enumerators and synchronization methods for all collections.
IComparer
Exposes a method that compares two objects.
IDictionary
Represents a collection of keyand-value pairs.
IDictionaryEnumerator
Enumerates the elements of a dictionary.
IEnumerable
Exposes the enumerator, which supports a simple iteration over a collection.
IEnumerator
Supports a simple iteration over a collection.
IHashCodeProvider
Supplies a hash code for an object, using a custom hash function.
IList
Represents a collection of objects that can be individually accessed by index.
ArrayList
HashTable
Y
Y
Y
Y
Y
Y
12
Contents | Index
System.Collections
Diagram
System.Collections
IList ICollection IEnumerable
System.Object ArrayList
System.ICloneable
Comparer
IComparer
System.ValueType IDictionary DictionaryEntry ICollection Hashtable IEnumerable System.ICloneable System.Runtime.Serialization.ISerializable
NotStandardized
System.Runtime.Serialization.IDeserializationCallback
NotStandardized
IEnumerable ICollection IDictionary IList
IComparer
IEnumerator IDictionaryEnumerator
IHashCodeProvider
13
Contents | Index
System.Diagnostics
System.Diagnostics The System.Diagnostics namespace was designed to contain classes that allow a program to do profiling, performance monitoring, and error logging. However, these sorts of features depend critically on the implementation of a particular operating system. Since the Standard describes objects that should be common to all operating systems, and diagnostic objects by their very nature can’t be, it contains only one class. The operating system for which you actually write code will probably provide many more classes in this namespace, but these will vary widely from one operating system to another. The common class is called ConditionalAttribute, which derives from System.Attribute. As with all attributes, it represents a read-only piece of metadata with which a programmer marks a piece of code. When this attribute appears on a method, it tells the compiler that it can omit calls to the method unless a compilation variable is defined at the site of the call. The property ConditionString specifies the name of the variable and the value that it must have. It’s an easy way to implement features such as tracing in a debugging executable while having them automatically disappear from the release executable generated from the same code base.
Diagram System.Object System.Attribute ConditionalAttribute
14
Contents | Index
System.Globalization System.Globalization
The global reach of the Internet, which essentially connects every intelligent box in the universe to every other intelligent box in the universe, means that essentially any application can be used by a native speaker of essentially any human language. Presenting numbers and dates in the manner that each user expects and immediately understands is not a matter of cultural sensitivity. It is a critical piece of communication necessary to avoid expensive errors. When you buy your non-refundable airline ticket online, does the departure date of 6-5-02 represent May 6 or June 5? The System.Globalization namespace in the .NET Framework contains classes that provide prefabricated functionality allowing a programmer to write programs that adjust to the language of its user, particularly in the area of formatting dates and numbers. The class DateTimeFormatInfo provides methods and properties that assist with the formatting of DateTime objects in accordance with a particular culture (a language and optionally a country, such as English and optionally US or Canada). For example, the methods Parse and ParseExact convert input strings into DateTime objects. You fetch the DateTimeFormatInfo for the calling thread’s current culture via the static property CurrentInfo, or you can create them directly via the constructor. The DateTimeFormatInfo class implements the interface System.IFormatProvider, which returns the proper date format pattern according to the culture for use in string formatting. You pass the DateTimeFormatInfo to the method DateTime.ToString when you want to format a date. The enumeration DateTimeStyles customizes how the DateTime.Parse and DateTime.ParseExact methods parse a string, for example, specifying whether whitespace is or isn’t allowed in the input string. The class NumberFormatInfo provides methods and properties that assist with the formatting of numeric values according to culture. For example, the property CurrencySymbol returns the currency symbol in the culture associated with a particular NumberFormatInfo object instance. You fetch the NumberFormatInfo for the calling thread’s current culture via the static property CurrentInfo, or you can create them directly via the class constructor. The NumberFormatInfo class implements the interface System.IFormatProvider, which returns the proper number format pattern according to the culture for use in string formatting. You pass the NumberFormatInfo to the method ToString when you want to format a number. The enumeration NumberStyles customizes how the Parse methods of individual numeric types (for example, Int32.Parse) parse a string, for example, whether or not to allow an exponent. The enumeration UnicodeCategory contains values that denote the various categories of Unicode characters that exist, for example, uppercase letter or lowercase letter. It is the return type of the method System.Char.GetUnicodeCategory.
15
Contents | Index
System.Globalization
System.Globalization
Diagram System.Object System.ICloneable DateTimeFormatInfo System.IFormatProvider System.ValueType System.Enum
System.IComparable
DateTimeStyles
System.IFormattable
NumberStyles
System.IConvertible
NotStandardized
UnicodeCategory System.ICloneable NumberFormatInfo System.IFormatProvider
16
Contents | Index
System.IO
System.IO
The modern operating system as we know it was first developed to provide applications with prefabricated I/O operations on the (at the time) newfangled things called disks. Providing programmers with a logically contiguous stream of bytes called a “file”, regardless of the underlying hardware, was an enormous advance and saved programmers a great deal of time. The extra system overhead was a small price to pay. The System.IO namespace contains classes that provide low-level file system I/O operations. The cornerstone of the I/O system is the abstract base class Stream, which represents a logically contiguous sequence of bytes. All actual I/O operations use classes that derive from Stream. This base class defines abstract methods for common stream operations, such as Read, Write, and Seek, which an implementer overrides to provide functionality in the derived class. All Stream-derived classes will thus contain the same access methods and parameters regardless of the storage medium to which the Stream mediates access. The base class itself does not provide or specify any particular storage medium backing to the stream. It is up to the implementer of the derived class to marry the Streambased functions to a particular storage medium. Table 6 lists the classes in this namespace derived from Stream. TABLE 6
Class
Meaning
FileStream
Stream whose backing is a file.
MemoryStream
Stream whose backing store is memory.
You usually create a Stream-based object directly from its own constructor. Alternatively, the File class allows you to create a FileStream from a File. Once you have a stream, you generally want to read from it or write to it. If the stream contains binary data, you can do this directly from the Stream object’s methods. However, if the stream contains text, reading directly from the Stream object would force you to deal manually with the various character encodings that the stream’s contents might use, a waste of valuable developer time. To make this task easier, the .NET Framework provides the abstract base classes TextReader and TextWriter. These classes enforce a common programmatic interface for reading and writing text on their descendants, taking into account character encodings and other features of textual data such as newline characters. The TextReader and TextWriter classes do not provide or specify a backing medium, in the same manner as StreamReader and StreamWriter.
17
Contents | Index
System.IO
System.IO
The classes StreamReader and StreamWriter provide an implementation of the TextReader and TextWriter that works with any class derived from Stream. You associate a StreamReader or StreamWriter with a stream by passing the stream in the StreamReader or StreamWriter constructor. You can also directly instantiate a StreamReader or StreamWriter directly from a file’s path name. The classes StringReader and StringWriter provide an implementation of the TextReader and TextWriter on variables of class System.String. Several other namespaces contain other classes that derive from TextReader and TextWriter, implementing their philosophy on other types of media. Files live in directories, and directories are organized hierarchically. The class Directory contains static methods (those which do not require an individual directory instance) for creating, moving, and searching among file system directories. You identify the directory on which you want to operate by passing its path string. In the same manner, the class File provides static methods for creating, destroying, copying, and opening files. You identify the file on which you want to operate by passing its path string. The utility class Path performs handy operations on path strings, such as extracting a file name or an extension. It’s handy. It is quite common for file system operations to fail, for example, when you try to open a file that doesn’t exist. As with all parts of the .NET Framework, file system objects signal failed operations by throwing exceptions. The System.IO namespace contains a number of different exception classes that are listed in Table 7, which signal specific types of file system-related failure. Note that objects in the System.IO namespace are not limited to throwing the exceptions that live in this namespace. TABLE 7
Exception
Meaning
DirectoryNotFoundException
Exception thrown when part of a file or directory cannot be found.
EndOfStreamException
Exception thrown when reading is attempted past the end of a stream.
FileLoadException
Exception thrown when a file is found but cannot be loaded.
FileNotFoundException
Exception thrown when an attempt to access a file that does not exist on disk fails.
IOException
Exception thrown when an I/O error occurs.
PathTooLongException
Exception thrown when a pathname or filename is longer than the system-defined maximum length.
18
Contents | Index
System.IO
This namespace also contains several enumerations that are used for making choices among discrete sets of properties used in various functions. Table 8 lists the enumerations.
System.IO
TABLE 8
Enumeration
Meaning
FileAccess
Constants signifying file access permission, such as read, write, or read/write.
FileMode
Constants signifying how the operating system should open a file, such as append, open, create, etc.
SeekOrigin
Constants signifying reference points in streams for seeking, such as begin, current, and end.
19
Contents | Index
System.IO
Diagram System.Object
System.IO
Directory System.Exception
System.Runtime.Serialization.ISerializable
NotStandardized
System.SystemException IOException DirectoryNotFoundException EndOfStreamException FileLoadException FileNotFoundException PathTooLongException File System.ValueType System.Enum FileAccess
System.IComparable System.IFormattable System.IConvertible
NotStandardized
FileMode FileShare SeekOrigin System.MarshalByRefObject Stream
System.IDisposable
FileStream MemoryStream TextReader
System.IDisposable
StreamReader StringReader TextWriter
System.IDisposable
StreamWriter StringWriter Path
20
Contents | Index
System.Security System.Security
Code that runs in modern operating systems comes from many different sources. Some assemblies might be installed from a shrink-wrapped CD-ROM, others downloaded from local intranets or the global Internet, still others may come in the form of e-mail documents. Many runtime systems prior to the .NET Framework ran all code on an allor-nothing privilege level, allowing an administrator no choices except to let installed code do anything it wanted or not to install it at all. However, it is essentially impossible for a human user to correctly determine in every case which pieces of code are worthy of this high level of trust and which are not. The .NET Framework therefore provides the Code Access Security mechanism, which allows administrators to restrict the operations that individual assemblies may perform on protected resources. This allows an operating system to run assemblies with different levels of trust. For example, an administrator might configure the system so that Assembly A is allowed to read and write a certain file, but Assembly B is only allowed to read it and Assembly C can’t interact with the file system in any manner. These privileges can be based on individual code modules, or on such properties as a code module’s author or the location from which it came. The System.Security namespace contains classes that allow a programmer to interact with the code access security system. Each secured operation that can be granted or denied to a program is represented by an object called a permission, many of which live in the System.Security.Permissions namespace. Because each type of protected resource requires its own type of description such as, for example, the location of a file or the name of an environment variable, each type of protected resource permission is represented by its own class of object. The abstract base class CodeAccessPermission is the base for all permissions and implements the IPermission interface. This interface contains such methods as Demand, which tells the CLR to walk the call stack and ensure that all callers of an object contain the specified permission, throwing an exception if any of them don’t. The PermissionSet class is a collection that can contain any number of permission objects (that is, objects derived from CodeAccessPermission). The PermissionSet contains methods that allow you to demand or deny permissions as a group instead of individually. It also contains methods to calculate its union and intersection with other PermissionSet objects. Security descriptors often need to serialize themselves into and out of XML for storage in administrative files. This happens in the case of declarative security, as described in the System.Security.Permissions namespace. The class SecurityElement is a helper class developed to make this process easier. It’s a lightweight XML element that contains a collection of attributes. As with all .NET Framework methods, security operations throw exceptions when they fail. The class SecurityException signals a permission failure, such as trying to open a
21
Contents | Index
System.Security
System.Security
file for which your application does not have permission. It tells you which permission caused the exception, and the permission’s state at the time the exception was thrown. The CLR performs verification of code as part of its just-in-time compilation. The verification process ensures that objects are accessed in a type-safe manner, for example, accessing objects only at the specified offsets of public members, instead of any arbitrary numeric offset that could lead to a security violation. The CLR throws the VerificationException if the code fails the type safety check.
Diagram IStackWalk
NotStandardized
ISecurityEncodable
System.Object CodeAccessPermission
NotStandardized
IPermission NotStandardized
PermissionSet
IDictionary ISecurityEncodable
SecurityElement
IStackWalk
System.Exception
System.Collections.ICollection
System.SystemException
NotStandardized
System.Runtime.Serialization.IDeserializationCallback
SecurityException
NotStandardized
System.Collections.IEnumerable
VerificationException System.Runtime.Serialization.ISerializable
NotStandardized
IPermission
System.Security.Permissions A permission is an object that specifies security rules for access to a protected resource. Permissions come in two flavors, programmatic and declarative. In the former case, the permission class (e.g., EnvironmentPermission), derives from CodeAccessPermission. You write code that creates these objects, sets their properties, and calls their methods in the usual way. You will need this technique when your security operations can vary dynamically at runtime. Alternatively, many programmers like to specify their permissions declaratively by marking their code with attributes. The attributes tell the CLR which security permissions the code needs to do its job, in the same way that calling methods on a permission object would do. When a caller attempts to access the marked code, the CLR checks if the caller has the permissions that the code requires and throws an exception if it doesn’t. This allows security permission failures (say, your caller doesn’t have permission to use the file system) to be detected when code is first loaded instead of later in the runtime session (say, after the user
22
Contents | Index
System.Security
System.Security
has done a lot of work and needs to save it in a file). Specifying security requirements declaratively also allows an administrator using a viewer program to see which permissions your code requires, so she can either (a) grant them ahead of time and avoid the fuss, or (b) refuse to grant them and understand why the code, or at least certain portions of it, won’t work. Specifying permissions declaratively is usually easier than doing it programmatically provided that you know your permission needs at development time. The class SecurityAttribute (deriving from System.Attribute) contains a member variable called Action, which contains a member of the SecurityAction enumeration. This specifies the type of action to be taken (demand a permission, deny a permission) that the attribute specifies. The attribute CodeAccessSecurityAttribute derives from SecurityAttribute, and is the abstract base class for all code access security attributes. The permission classes, their corresponding attribute classes, and the protected resources to which they control access are listed in Table 9. TABLE 9
Permission
Attribute
Controls Access to
EnvironmentPermission
EnvironmentPermissionAttribute
System and user environment variables
FileIOPermission
FileIOPermission Attribute
Files and folders
SecurityPermission
SecurityPermissionAttribute
Miscellaneous operations listed in SecurityPermissionFlag enumeration
A permission object can contain its own fine-grained subdivisions of permissions. For example, a FileIOPermission object does not have to grant permission to do anything to any file anywhere in the system, and generally will not. Each permission class has its own enumeration specifying the sub-privileges that a piece of code may ask for, as listed in Table 10. In addition to the fine-grained permission states listed above, the PermissionState enumeration contains the values “None” and “Unrestricted,” which can be used in any of the permissions.
23
Contents | Index
System.Security
System.Security
TABLE 10
Enumeration
Meaning
EnvironmentPermissionAccess
Type of access requested, such as Read or Write.
FileIOPermissionAccess
Type of file access requested, such as Read or Write or Append.
SecurityPermissionFlag
Miscellaneous security permissions, such as skipping type safety verification or accessing unmanaged code. Often powerful, use with caution.
Diagram System.Object System.Attribute SecurityAttribute CodeAccessSecurityAttribute EnvironmentPermissionAttribute FileIOPermissionAttribute
System.Security.IPermission
SecurityPermissionAttribute
System.Security.ISecurityEncodable
System.Security.CodeAccessPermission
System.Security.IStackWalk
NotStandardized
NotStandardized
EnvironmentPermission FileIOPermission
IUnrestrictedPermission
NotStandardized
SecurityPermission System.ValueType System.Enum EnvironmentPermissionAccess
System.IComparable System.IFormattable System.IConvertible
NotStandardized
FileIOPermissionAccess PermissionState SecurityAction SecurityPermissionFlag
24
Contents | Index
System.Text System.Text
The character set used within a text string is an important design decision in any development project. Within the .NET Framework it’s quite simple, as all text strings use the same Unicode character set. However, your programs will often need to use other character sets when you exchange strings or files with other non-.NET Framework systems and programs. The namespace System.Text contains classes that assist you in converting from one character set to another. An encoding is an object that converts text to or from a particular character set. The abstract base class Encoding defines a common set of methods and properties that all classes deriving from it must implement, thereby providing a common programmatic interface for all character set conversions. For example, the method GetBytes converts characters from Unicode into the character set of the derived class. The classes ASCIIEncoding, UnicodeEncoding, and UTF8Encoding derive from Encoding, converting characters to and from the character sets as listed in Table 11. TABLE 11
Class
Character Set
ASCIIEncoding
7-bit ASCII characters.
UnicodeEncoding
Unicode character set, 16 bits per character.
UTF8Encoding
Unicode character set, 8 or 16 bits per character depending on character.
Each encoding contains internal objects that implement the abstract base class Encoder and Decoder, which perform the actual conversion respectively out of and into the encoding’s character set. For large or repetitive conversions, it is sometimes more efficient to fetch these objects from the encoding and deal with them directly rather than going through the additional layer of the encoding. A StringBuilder is a mutable (changeable) string. Adding characters to a standard System.String object creates a new instance of a string. Adding characters to a StringBuilder modifies the existing StringBuilder without creating a new one. This can yield a large performance gain in certain cases, such as adding a small amount of new data to a large existing string.
25
Contents | Index
System.Text
Diagram System.Object
System.Text
Encoding ASCIIEncoding UnicodeEncoding UTF8Encoding Decoder Encoder StringBuilder
26
Contents | Index
System.Threading System.Threading
Modern operating systems handle many independent programs at once, and the programs themselves often contain many independent tasks. Logically segregating these tasks for efficient development, and sharing the computer’s processor(s) among them for efficient operation, is such an important concept that the functionality for doing it comes built into the modern operating system. Programmers divide their program’s functionality into threads. A thread is an object within a process that executes code, and a process is a virtual address space. You can think of a process as a garage and a thread as an engine within the garage. Every process gets created with one thread. A programmer may explicitly create more threads in order to accomplish the program’s work, for example, one thread to handle a user interface and another to handle background printing. Some CLR operations, such as garbage collection or asynchronous method invocation, may cause the operating system to create and use additional threads behind the scenes. So your programs live in a multithreaded environment whether they think about it or not. The operating system preemptively multitasks the threads of all applications. The OS maintains a list of all the threads in the entire computer that are ready, willing, and able to run. Every 10 milliseconds or so (an interval known as the timeslice), the OS performs an interrupt and checks to see which thread should have the CPU. Each thread has a priority, and the scheduler picks the highest priority thread in the computer-wide ready list to run. If several threads share the highest priority level, the scheduler alternates them in a roundrobin fashion. If the machine contains more than one CPU, each CPU is assigned a thread from the ready list, working from the highest priority downward. The register values of the currently running thread are saved in memory (“swapped out”), and those of the incoming thread placed into the CPU (“swapped in”), which then starts running the incoming thread at the point where it was swapped out the last time. A thread doesn’t know when it is swapped in or out. As far as it knows, it’s simply executing to completion at a speed over which it has no control. Not all threads in the system are in the ready state, squabbling with each other over CPU cycles; in fact most of them usually aren’t. One of the most useful features of threads is that they can be made to wait, without consuming CPU cycles, for various external events to happen. For example, a Windows Forms application’s main thread is generally waiting to receive a message from the operating system announcing that the user has clicked the mouse or pressed a key. A thread in this waiting state is said to be blocked. Think of this thread as a car waiting at a stoplight. It’s more efficient than that, however, as the thread doesn’t have its own engine, so it’s not wasting gas sitting there idling. Other threads can use the CPU while the blocked thread waits. When the block clears, the thread goes back into the ready list to compete for CPU time with the rest of the threads. The class Thread represents a thread in the .NET Framework. The methods on this object allow a programmer to start a thread’s operation, suspend it, resume it, abort it, or set its priority. Creating a new object of this class creates a new thread within the caller’s process. 27
Contents | Index
System.Threading
System.Threading
You must pass its constructor a delegate that implements that ThreadStart design pattern. This delegate contains the code that the thread will execute when it starts to run. The Timer class uses a background thread to provide callbacks to your program at specified intervals. You create an object of this class, passing its constructor a delegate that implements the TimerCallback design pattern. The timer will call the delegate’s code on a thread from the pool at the specified interval. As with all parts of the .NET Framework, threading operations throw exceptions when they encounter errors. The namespace includes classes for signaling these exceptions. Table 12 lists these classes. TABLE 12
Exception
Meaning
ThreadAbortException
Thrown when a call is made to the Abort method.
ThreadStateException
Thrown when a Thread is in an invalid ThreadState for a method call made on it.
Using threads looks relatively simple, but this appearance is deceptive. The operating system swaps running threads in and out of the CPU without regard to where a thread is in the course of its work. Writing good multithreaded code is primarily about dealing with the interactions of the various threads swapping in and out at times you can’t control. The main problem in multithreaded code arises when one thread modifies data that another thread is using. Think of two children sharing one set of watercolor paints, or two programmers working on the same file. Consider the code snippet N = N + 1. Most programmers can’t imagine anything simpler, easier, and safer. And indeed, every thread has its own stack, so if N is a stack (automatic) variable or a function parameter, each thread that executes the code has its own copy and we have no problem. But if two threads try to share the same copy of N, we’re looking at a nasty, hard-to-find bug waiting to happen. They will occasionally mix each other up and produce the wrong result. Such a mix-up can occur if N is a global variable (or a shared class variable, which is just a politically correct form of global) and two threads access it simultaneously. It can also occur if N is an object member variable and two threads access the same object simultaneously. How could such a simple piece of code as N = N + 1 possibly screw up? Look at Figure 1, which shows the assembler instructions to which the source line compiles: move the contents of the variable’s memory location to a processor register, increment the value in the register, and move the result back to the variable’s memory location.
28
Contents | Index
System.Threading
AX, [N] AX, 1 [N], AX
; move variable memory location to CPU register ; add 1 to contents of register ; move contents of register back to memory location
System.Threading
mov add mov
Figure 1: Assembler listing of simple variable increment
The problem happens if threads get swapped at the wrong time. Suppose the memory location of the variable N contains the value 4. Suppose Thread A executes the first two statements—moves 4 into the AX register, adds 1 to it to get 5—but further suppose that it reaches this code near the end of its timeslice, so it gets swapped out before it can execute the last statement, which would have stored the result. This isn’t immediately a problem. The operating system retains the values of Thread A’s registers in its own memory along with other administrative information about Thread A, so it doesn’t get lost. But now suppose that Thread B gets swapped in and starts executing the same code—it fetches 4 from memory (because Thread A hasn’t had time to store its result), adds 1, and moves 5 back to memory. At some future time, Thread B exhausts its timeslice and the operating system swaps in Thread A, restoring the value of 5 to register AX. Thread A picks up where it left off, and moves 5 into the memory location. The variable N now contains an incorrect value of 5, whereas if Thread A had been allowed to complete its operation before Thread B ran, N would contain the correct value of 6. We lost one of our increments because thread swapping happened at the wrong moment. This is the most difficult, frustrating kind of bug to track down that I’ve ever encountered because, as you can see, it is devilishly hard to reproduce. It only happens when the threads get swapped in and out at exactly the wrong moments, and any instrumentation you add to detect it will likely change that timing. If Thread A had finished its operation before getting swapped out, or hadn’t started it, or Thread B executed some other code during its timeslice, we wouldn’t have encountered this problem. This is the kind of bug that causes programmers to smash their keyboards and take up goat herding. We need to ensure that Thread B doesn’t mess with any operations that Thread A has started but hasn’t yet finished. We need to make any access to shared resources atomic with respect to threads. We do this by using the synchronization objects provided by the .NET Framework. The most common way of doing this generically is by using the class Monitor, which provides methods that ensure that only one thread can execute a block of code at a time. You can use this class directly if you want, but more commonly your programming language will wrap this class up in a language construct where you don’t see it directly. The lock statement in C# uses this class internally. The first thread to enter the monitored region is granted ownership of it. Subsequent threads attempting to enter the region will block until the first thread leaves it. The Monitor throws an exception of class SynchronizationLockException if someone tries to bypass it. A faster alternative for very simple operations is to use the class Interlocked, which contains static methods for incrementing, decrementing, or exchanging two values. These methods are thread-safe but incur a lower overhead cost than does the use of a Monitor object.
29
Contents | Index
System.Threading
System.Threading
A programmer may want to develop other synchronization objects to provide different waiting and blocking behavior than the mutual exclusion offered by the Monitor or Interlocked classes. The .NET Framework contains the class WaitHandle in order to provide a common design pattern for developing these types of objects. For example, Microsoft’s implementation of the .NET Framework contains the class Mutex, which derives from WaitHandle and provides Monitor-like behavior across different processes. WaitHandle contains methods that cause the calling thread to block, with an optional timeout, until the synchronization object’s conditions for unblocking are met. The calling thread can wait on one synchronization object, or any or all of a collection of them.
Diagram System.Object Interlocked Monitor System.Runtime.Serialization.ISerializable
System.Exception
NotStandardized
System.SystemException SynchronizationLockException ThreadAbortException ThreadStateException Thread System.IComparable
System.ValueType System.Enum
System.IFormattable
ThreadPriority
System.IConvertible
NotStandardized
ThreadState System.ICloneable System.Delegate System.Runtime.Serialization.ISerializable System.MulticastDelegate
NotStandardized
NotStandardized
ThreadStart TimerCallback Timeout System.MarshalByRefObject Timer
System.IDisposable
WaitHandle
System.IDisposable
30
Contents | Index
PART II Class Libraries
31
Contents | Index
System ApplicationException
BCL
Object Exception
ISerializable
NotStandardized
A B
ApplicationException
C
Summary
D
System.ApplicationException is the base class for all exceptions defined by applications.
E F
Type Summary public class ApplicationException : Exception { // Constructors public ApplicationException (); public ApplicationException (string message); public ApplicationException (string message, Exception innerException); MS CF protected ApplicationException (SerializationInfo info, StreamingContext context); }
G H I J K L M N
KC Designing exception hierarchies is tricky. Well-designed exception hierarchies are wide, not very deep, and contain only those exceptions for which there is a programmating scenario for catching. We added ApplicationException thinking it would add value by grouping exceptions declared outside of the .NET Framework, but there is no scenario for catching ApplicationException and it only adds unnecessary depth to the hierarchy.
O P Q R S
JR You should not define new exception classes derived from Application-
T
Exception; use Exception instead. In addition, you should not write code that catches ApplicationException.
U V W
Description
X
This class represents application-defined errors detected during the execution of an application. It is provided as means to differentiate between exceptions defined by applications versus exceptions defined by the system. [Note: For more information on exceptions defined by the system, see System.SystemException.] [Note: System.ApplicationException does not provide information as to the cause of the exception. In most scenarios, instances of this class should not be thrown. In
Y Z
33
Contents | Index
ApplicationException
System
ApplicationException Class
cases where this class is instantiated, a human-readable message describing the error should be passed to the constructor.] A
Example
B
The following example demonstrates catching an exception type that derives from ApplicationException. There is, however, no valid scenerio for catching an ApplicationException type.
C D
using System; using System.Reflection;
E F
namespace Samples { public class ApplicationExceptionSample { public static void Main() { try { Type t = typeof(string); MethodInfo m = t.GetMethod("EndsWith"); string s = "Hello world!"; object[] arguments = {"world!", "!"}; Console.WriteLine(m.Invoke(s, arguments)); } catch(ApplicationException e) { Console.WriteLine("Exception: {0}", e); } } } }
G H I J K L M N O P Q R S
The output is
T U
Exception: System.Reflection.TargetParameterCountException: Parameter count mismatch. at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess) at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean verifyAccess) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) at Samples.ApplicationExceptionSample.Main() in C:\Books\BCL\Samples\System\ ApplicationException\ApplicationException.cs:line 16
V W X Y Z
34
Contents | Index
System
ApplicationException ApplicationException() Constructor
ApplicationException() Constructor [ILASM]
public rtspecialname specialname instance void .ctor() [C#]
A
public ApplicationException()
B C
Summary
D
Constructs and initializes a new instance of the System.ApplicationException class.
E
Description
F
This constructor initializes the System.ApplicationException.Message property of the new instance to a system-supplied message that describes the error, such as “An application error has occurred.” This message takes into account the current system culture. The System.ApplicationException.InnerException property is initialized to null.
G H I J K
ApplicationException(System.String) Constructor
L
[ILASM]
M
public rtspecialname specialname instance void .ctor(string message)
N
[C#]
public ApplicationException(string message)
O P
Summary
Q
Constructs and initializes a new instance of the System.ApplicationException class.
R
Parameters
S
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
T U V W X Y Z
35
Contents | Index
ApplicationException
System
ApplicationException() Constructor
Description This constructor initializes the System.ApplicationException.Message property of the new instance using message. If message is null, the System.ApplicationException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.ApplicationException.InnerException property is initialized to null.
A B C D E
ApplicationException(System.String, System.Exception) Constructor
F
[ILASM]
G
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
H
[C#]
public ApplicationException(string message, Exception innerException)
I J
Summary
K
Constructs and initializes a new instance of the System.ApplicationException class.
L M
Parameters
N O
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
An instance of System.Exception that is the cause of the current Exception. If innerException is non-null, then the current Exception was raised in a catch block handling innerException.
P Q R S T U V
Description
W
This constructor initializes the System.ApplicationException.Message property of the new instance using message, and the System.ApplicationException.InnerException property using innerException. If message is null, the System.ApplicationException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
X Y Z
36
Contents | Index
System
ApplicationException ApplicationException() Constructor
ApplicationException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor [ILASM]
A
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
B
[C#]
C
protected ApplicationException(SerializationInfo info, StreamingContext context)
D E
Summary
F
Initializes a new instance of the System.ApplicationException class with serialized data.
G H
Parameters
I
Parameter
Description
info
The object that holds the serialized object data.
context
The contextual information about the source or destination.
J K L M N
Description
O
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
P Q R S T U V W X Y Z
37
Contents | Index
System ArgumentException
BCL
Object
A
Exception
B
ISerializable
NotStandardized
SystemException ArgumentException
C D
ArgumentNullException
E
ArgumentOutOfRangeException DuplicateWaitObjectException
F G
Summary
H
Represents the error that occurs when an argument passed to a method is invalid.
I
Type Summary
J
public class ArgumentException : SystemException, ISerializable { // Constructors public ArgumentException (); public ArgumentException (string message); public ArgumentException (string message, string paramName); CF public ArgumentException (string message, string paramName, Exception innerException); public ArgumentException (string message, Exception innerException); MS CF protected ArgumentException (SerializationInfo info, StreamingContext context);
K L M N O P Q R S T
// Properties MS CF public override string Message { get; } CF public virtual string ParamName { get; }
U V
// Methods MS CF public override void GetObjectData (SerializationInfo info, StreamingContext context); }
W X Y
Description
Z
System.ArgumentException is thrown when a method is invoked and at least one of the passed arguments does not meet the method’s parameter specification.
38
Contents | Index
System
ArgumentException ArgumentException() Constructor
[Note: The Base Class Library includes three derived types: When appropriate, use these types instead of System.ArgumentException.]
Example
A
using System;
B C
namespace Samples { public class ArgumentExceptionSample { public static void Main() { try { string s = "one"; s.CompareTo(1); } catch(ArgumentException e) { Console.WriteLine("Exception: {0}", e); } } } }
D E F G H I J K L M N
The output is
O P
Exception: System.ArgumentException: Object must be of type String. at System.String.CompareTo(Object value) at Samples.ArgumentExceptionSample.Main() in C:\Books\BCL\Samples\System\ ArgumentException\ArgumentException.cs:line 12
Q R S T
ArgumentException() Constructor
U
[ILASM]
public rtspecialname specialname instance void .ctor()
V
[C#]
W
public ArgumentException()
X
Summary
Y
Constructs and initializes a new instance of the System.ArgumentException class.
Z
39
Contents | Index
ArgumentException
System
ArgumentException() Constructor
Description This constructor initializes the System.ArgumentException.Message property of the new instance to a system-supplied message that describes the error, such as “An invalid argument was specified.” This message takes into account the current system culture. The System.ArgumentException.InnerException property is initialized to null.
A B C D E
ArgumentException(System.String) Constructor
F
[ILASM]
public rtspecialname specialname instance void .ctor(string message)
G
[C#]
public ArgumentException(string message)
H I
Summary
J
Constructs and initializes a new instance of the System.ArgumentException class.
K
Parameters
L M
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
N O P Q R
Description
S
This constructor initializes the System.ArgumentException.Message property of the new instance using message. If message is null, the System.ArgumentException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.ArgumentException.InnerException and System.ArgumentException.ParamName properties are initialized to null.
T U V W X
ArgumentException(System.String, System.String) Constructor
Y
[ILASM]
Z
public rtspecialname specialname instance void .ctor(string message, string paramName) [C#]
public ArgumentException(string message, string paramName)
40
Contents | Index
System
ArgumentException ArgumentException() Constructor
Summary Constructs and initializes a new instance of the System.ArgumentException class. A
Parameters
B
Parameter
Description
C
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
D
message
paramName
A System.String that contains the name of the parameter that caused the exception.
E F G H
Description
I
This constructor initializes the System.ArgumentException.Message property of the new instance using message, and the System.ArgumentException.ParamName property using paramName. If message is null, the System.ArgumentException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.ArgumentException.InnerException property is initialized to null.
J K L M N O
ArgumentException(System.String, System.String, System.Exception) Constructor
P
[ILASM]
Q
public rtspecialname specialname instance void .ctor(string message, string paramName, class System.Exception innerException)
R
[C#]
S
public ArgumentException(string message, string paramName, Exception innerException)
T U
Summary
V
Constructs and initializes a new instance of the System.ArgumentException class.
W X Y Z
41
Contents | Index
ArgumentException
System
ArgumentException() Constructor
Parameters Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
paramName
A System.String that contains the name of the parameter that caused the current exception.
innerException
An instance of System.Exception that is the cause of the current Exception. If innerException is non-null, then the current Exception was raised in a catch block handling innerException.
A B C D E F G H I
Description
J
This constructor initializes the System.ArgumentException.Message property of the new instance using message, the System.ArgumentException.ParamName property using paramName, and the System.ArgumentException.InnerException property using innerException. If message is null, the System.ArgumentException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
K L M N O P Q
ArgumentException(System.String, System.Exception) Constructor
R
[ILASM]
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
S T
[C#]
public ArgumentException(string message, Exception innerException)
U V
Summary
W
Constructs and initializes a new instance of the System.ArgumentException class.
X Y Z
42
Contents | Index
System
ArgumentException ArgumentException() Constructor
Parameters Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
A B C D
An instance of System.Exception that is the cause of the current Exception. If innerException is non-null, then the current Exception was raised in a catch block handling innerException.
E F G
Description
H
This constructor initializes the System.ArgumentException.Message property of the new instance using message, and the System.ArgumentException.InnerException property using innerException. If message is null, the System.ArgumentException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.ArgumentException.ParamName property is initialized to null. [Note: For information on inner exceptions, see System.Exception.InnerException.]
I J K L M N
ArgumentException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
O
[ILASM]
Q
family rtspecialname specialname instance void .ctor(class System.Runtime. Serialization.SerializationInfo info, valuetype System.Runtime.Serialization. StreamingContext context)
R
P
S
[C#]
T
protected ArgumentException(SerializationInfo info, StreamingContext context)
U
Summary
V
Initializes a new instance of the System.ArgumentException class with serialized data.
W X Y Z
43
Contents | Index
ArgumentException
System
Message Property
Parameters Parameter
Description
info
The object that holds the serialized object data.
context
The contextual information about the source or destination.
A B C D E
Description
F
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
G H I
ArgumentException.Message Property
J
[ILASM]
K
.property string Message { public hidebysig virtual specialname string get_Message() }
L
[C#]
public override string Message { get; }
M N
Summary
O
Gets the error message and the parameter name, or only the error message if no parameter name is set.
P Q
Property Value
R
A text string describing the details of the exception. The value of this property takes one of two forms:
S T U
Condition
Value
The paramName is a null reference or of zero length.
The message string passed to the constructor.
The paramName is not a null reference and it has a length greater than zero.
The message string appended with the name of the invalid parameter.
V W X Y Z
44
Contents | Index
System
ArgumentException GetObjectData() Method
Description This property overrides System.Exception.Message. The error message should be localized. A B
ArgumentException.ParamName Property
C
[ILASM]
D
.property string ParamName { public hidebysig virtual specialname string get_ParamName() }
E
[C#]
F
public virtual string ParamName { get; }
G
Summary
H
Gets the name of the parameter that caused the current Exception.
I
Property Value
J
A System.String that contains the name of the parameter that caused the current Exception, or null if no value was specified to the constructor for the current instance.
K L M
Behaviors
N
The System.ArgumentException.ParamName property returns the same value as was passed into the constructor.
O P
How and When to Override
Q
Override the System.ArgumentException.ParamName property to customize the content or format of the parameter name.
R S T
ArgumentException.GetObjectData(System.Runtime.Serialization. SerializationInfo, System.Runtime.Serialization.StreamingContext) Method
U
[ILASM]
W
V
.method public hidebysig virtual void GetObjectData(class System.Runtime. Serialization.SerializationInfo info, valuetype System.Runtime.Serialization. StreamingContext context)
X Y
[C#]
Z
public override void GetObjectData(SerializationInfo info, StreamingContext context)
45
Contents | Index
ArgumentException
System
GetObjectData() Method
Summary Sets the System.Runtime.Serialization.SerializationInfo object with the parameter name and additional exception information. A
Parameters
B C
Parameter
Description
E
info
The object that holds the serialized object data.
F
context
The contextual information about the source or destination.
D
G H
Description
I
System.ArgumentException.GetObjectData sets a System.Runtime.Serialization.SerializationInfo with all the exception object data targeted for serialization. During deserialization, the exception object is reconstituted from the System.Runtime.Serialization.SerializationInfo transmitted over the stream. For more information, see System.Runtime.Serialization.SerializationInfo.
J K L M N O P Q R S T U V W X Y Z
46
Contents | Index
System ArgumentNullException
BCL
Object Exception
ISerializable
A
NotStandardized
B
SystemException ArgumentException
C
ArgumentNullException
D E
Summary
F
Represents the error that occurs when an argument passed to a method is invalid because it is null.
G H
Type Summary
I
public class ArgumentNullException : ArgumentException { // Constructors public ArgumentNullException (); public ArgumentNullException (string paramName); public ArgumentNullException (string paramName, string message); MS CF protected ArgumentNullException (SerializationInfo info, StreamingContext context); }
J K L M N O P Q
BA This class goes down in the API design hall of shame. ArgumentNullException does not follow the exception constructor pattern given in the Design Guidelines Specification, which says the constructor overloads should include at least:
R S T
public XxxException (); public XxxException (string message); public XxxException (string message, Exception inner);
U V
The rationale for violating this guideline was that the parameter name would be much more commonly specified than the message text. However, because nearly every
W X
continued
Y Z
47
Contents | Index
ArgumentNullException
System
ArgumentNullException Class
other exception in the system does follow the pattern, the usual result is that the force of habit wins out. Developers commonly make this mistake: A throw new ArgumentNullException (“must pass an employee name”);
B
Rather than:
C D
throw new ArgumentNullException (“Name”, “must pass an employee name”);
E
This mistake means that we end up with an error message such as this one:
F Unhandled Exception: System.ArgumentNullException: Value cannot be null. Parameter name: “must pass employee name”
G H
Lesson learned: Just follow the pattern.
I
JR In addition to Brad’s comments, a properly designed exception class should also allow for serializability. Specifically, this means that the class should have the System.SerializableAttribute applied to it and the class should implement the ISerializable interface with its GetObjectData method and special constructor. These two methods should serialize/deserialize any fields in the class and be sure to call the base class methods so that any fields in the base class are also serialized/ deserialized. If the exception class is sealed, the constructor can be marked private; otherwise, mark the constructor as protected. Since GetObjectData is an interface method, mark it as public.
J K L M N O P Q
Description
R
[Note: System.ArgumentNullException is thrown when a method is invoked and at least one of the passed arguments is null and should never be null. System.ArgumentNullException behaves identically to System.ArgumentException. It is provided so that application code can differentiate between exceptions caused by null arguments and exceptions caused by non-null arguments. For errors caused by non-null arguments, see System.ArgumentOutOfRangeException.]
S T U V W X Y Z
48
Contents | Index
System
ArgumentNullException ArgumentNullException() Constructor
Example using System; namespace Samples { class ArgumentNullExceptionSample { public static void Main() { String[] strings = null; String separator = " "; try { String s = String.Join(separator, strings); } catch(ArgumentNullException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M
The output is
N Exception: System.ArgumentNullException: Value cannot be null. Parameter name: value at System.String.Join(String separator, String[] value) at Samples.ArgumentNullExceptionSample.Main() in C:\Books\BCL\Samples\System\ ArgumentNullException\ArgumentNullException.cs:line 13
O P Q R
ArgumentNullException() Constructor
S
[ILASM]
T
public rtspecialname specialname instance void .ctor()
U
[C#]
V
public ArgumentNullException()
W
Summary
X
Constructs and initializes a new instance of the System.ArgumentNullException class.
Y Z
49
Contents | Index
ArgumentNullException
System
ArgumentNullException() Constructor
Description This constructor initializes the System.ArgumentNullException.Message property of the new instance to a system-supplied message that describes the error, such as “Argument cannot be null.” This message takes into account the current system culture. The System.ArgumentNullException.ParamName property is initialized to null.
A B C D
ArgumentNullException(System.String) Constructor
E
[ILASM]
F
public rtspecialname specialname instance void .ctor(string paramName) [C#]
G
public ArgumentNullException(string paramName)
H
Summary
I
Constructs and initializes a new instance of the System.ArgumentNullException class.
J K
Parameters
L M
Parameter
Description
paramName
A System.String that contains the name of the parameter that caused the exception. The content of paramName is intended to be understood by humans.
N O P Q
Description
R
This constructor initializes the System.ArgumentNullException.ParamName property of the new instance using paramName. The System.ArgumentNullException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments.
S T U V W
ArgumentNullException(System.String, System.String) Constructor
X
[ILASM]
Y
public rtspecialname specialname instance void .ctor(string paramName, string message) [C#]
Z
public ArgumentNullException(string paramName, string message)
50
Contents | Index
System
ArgumentNullException ArgumentNullException() Constructor
Summary Constructs and initializes a new instance of the System.ArgumentNullException class. A
Parameters
B C
Parameter
Description
paramName
A System.String that contains the name of the parameter that caused the exception. The content of paramName is intended to be understood by humans.
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
D E F G H I
Description
J
This constructor initializes the System.ArgumentNullException.ParamName property of the new instance using paramName, and the System.ArgumentNullException.Message property using message. If message is null, the System.ArgumentNullException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments.
K L M N O
ArgumentNullException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
Q
[ILASM]
R
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
S
P
T
[C#]
U
protected ArgumentNullException(SerializationInfo info, StreamingContext context)
V
Summary
W
Initializes a new instance of the System.ArgumentNullException class with serialized data.
X Y Z
51
Contents | Index
ArgumentNullException
System
ArgumentNullException() Constructor
Parameters Parameter
Description
info
The object that holds the serialized object data.
context
The contextual information about the source or destination.
A B C D E
Description
F
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
G H I J K L M N O P Q R S T U V W X Y Z
52
Contents | Index
System ArgumentOutOfRangeException
BCL
Object Exception
ISerializable
A
NotStandardized
B
SystemException
C
ArgumentException ArgumentOutOfRangeException
D E
Summary
F
Represents the error that occurs when an argument passed to a method is invalid because it is outside the allowable range of values as specified by the method.
G H
Type Summary
I
public class ArgumentOutOfRangeException : ArgumentException, ISerializable { // Constructors public ArgumentOutOfRangeException (); public ArgumentOutOfRangeException (string paramName); CF public ArgumentOutOfRangeException (string paramName, object actualValue, string message); CF public ArgumentOutOfRangeException (string paramName, string message); MS CF protected ArgumentOutOfRangeException (SerializationInfo info, StreamingContext context);
J K L M N O P Q
// Properties CF public virtual object ActualValue { get; } MS CF public override string Message { get; }
R S
// Methods MS CF public override void GetObjectData (SerializationInfo info, StreamingContext context); }
T U V W
BA Please see my comments in ArgumentNullException.
X Y
Description
Z
[Note: System.ArgumentOutOfRangeException is thrown when a method is invoked and at least one of the arguments passed to the method is not null and does not contain a valid
53
Contents | Index
ArgumentOutOfRangeException
System
ArgumentOutOfRangeException() Constructor
value. System.ArgumentOutOfRangeException behaves identically to System.ArgumentException. It is provided so that application code can differentiate between exceptions caused by invalid arguments that are not null, and exceptions caused by null arguments. For errors caused by null arguments, see System.ArgumentNullException.]
A B
Example
C
using System;
D namespace Samples { class ArgumentOutOfRangeExceptionSample { public static void Main() { int[] array1 = {42, 42}; int[] array2 = {0, 0}; try { Array.Copy(array1, array2, -1); } catch(ArgumentOutOfRangeException e) { Console.WriteLine(e); } } } }
E F G H I J K L M N O P
The output is
Q R
System.ArgumentOutOfRangeException: Non-negative number required. Parameter name: length at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length) at System.Array.Copy(Array sourceArray, Array destinationArray, Int32 length) at Samples.ArgumentOutOfRangeExceptionSample.Main() in C:\Books\BCL\Samples\ System\ArgumentOutOfRangeException\ArgumentOutOfRangeException.cs:line 13
S T U V W X
ArgumentOutOfRangeException() Constructor
Y
[ILASM]
public rtspecialname specialname instance void .ctor()
Z
[C#]
public ArgumentOutOfRangeException()
54
Contents | Index
System
ArgumentOutOfRangeException ArgumentOutOfRangeException() Constructor
Summary Constructs and initializes a new instance of the System.ArgumentOutOfRangeException class. A
Description
B
This constructor initializes the System.ArgumentOutOfRangeException.Message property of the new instance to a system-supplied message that describes the error, such as “Non-negative number required.” This message takes into account the current system culture. The System.ArgumentOutOfRangeException.ParamName and System.ArgumentOutOfRangeException.ActualValue properties are initialized to null.
C D E F G
ArgumentOutOfRangeException(System.String) Constructor
H
[ILASM]
I
public rtspecialname specialname instance void .ctor(string paramName)
J
[C#]
K
public ArgumentOutOfRangeException(string paramName)
L
Summary
M
Constructs and initializes a new instance of the System.ArgumentOutOfRangeException class.
N O
Parameters
P
Parameter
Description
paramName
A System.String that contains the name of the parameter that caused the current exception. The content of paramName is intended to be understood by humans.
Q R S T U
Description
V
This constructor initializes the System.ArgumentOutOfRangeException.ParamName property of the new instance using paramName. The System.ArgumentOutOfRangeException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.ArgumentOutOfRangeException.ActualValue property is initialized to null.
W X Y Z
55
Contents | Index
ArgumentOutOfRangeException
System
ArgumentOutOfRangeException() Constructor
ArgumentOutOfRangeException(System.String, System.Object, System.String) Constructor [ILASM]
A
public rtspecialname specialname instance void .ctor(string paramName, object actualValue, string message)
B
[C#]
C
public ArgumentOutOfRangeException(string paramName, object actualValue, string message)
D E
Summary
F
Constructs and initializes a new instance of the System.ArgumentOutOfRangeException class.
G H
Parameters
I J
Parameter
Description
paramName
A System.String that contains the name of the parameter that caused the current exception. The content of paramName is intended to be understood by humans.
actualValue
The value of the argument that caused the current exception.
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
K L M N O P Q R
Description
S
This constructor initializes the System.ArgumentOutOfRangeException.ParamName property of the new instance using paramName, the System.ArgumentOutOfRangeException.ActualValue property using actualValue, and the System.ArgumentOutOfRangeException.Message property using message. If message is null, the System.ArgumentOutOfRangeException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: The actualValue parameter contains the invalid argument that was passed to the method. Use the System.ArgumentOutOfRangeException.ParamName property to retrieve the name of the parameter used to pass actualValue.]
T U V W X Y Z
56
Contents | Index
System
ArgumentOutOfRangeException ArgumentOutOfRangeException() Constructor
ArgumentOutOfRangeException(System.String, System.String) Constructor [ILASM]
public rtspecialname specialname instance void .ctor(string paramName, string message)
A
[C#]
B
public ArgumentOutOfRangeException(string paramName, string message)
C
Summary
D
Constructs and initializes a new instance of the System.ArgumentOutOfRangeException class.
E F
Parameters
G
Parameter
Description
paramName
A System.String that contains the name of the parameter that caused the current exception. The content of paramName is intended to be understood by humans.
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
H I J K L M N
Description This constructor initializes the System.ArgumentOutOfRangeException.ParamName property of the new instance using paramName, and the System.ArgumentOutOfRangeException.Message property using message. If message is null, the System.ArgumentOutOfRangeException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.ArgumentOutOfRangeException.ActualValue property is initialized to null.
O
ArgumentOutOfRangeException(System.Runtime.Serialization. SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
U
P Q R S T
V W X
[ILASM] family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context) [C#] protected ArgumentOutOfRangeException(SerializationInfo info, StreamingContext context)
Y Z
57
Contents | Index
ArgumentOutOfRangeException
System
ActualValue Property
Summary Initializes a new instance of the System.ArgumentOutOfRangeException class with serialized data. A
Parameters
B C
Parameter
Description
E
info
The object that holds the serialized object data.
F
context
The contextual information about the source or destination.
D
G H
Description
I
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
J K L
ArgumentOutOfRangeException.ActualValue Property
M
[ILASM]
.property object ActualValue { public hidebysig virtual specialname object get_ActualValue() }
N O
[C#]
public virtual object ActualValue { get; }
P Q
Summary
R
Gets the value of the parameter that caused the current exception.
S T
Property Value
U
A System.Object that contains the value of the parameter that caused the current exception, or null if no value was specified to the constructor for the current instance.
V W
Behaviors
X
The System.ArgumentOutOfRangeException.ActualValue property returns the same value as was passed into the constructor.
Y Z
How and When to Override Override the System.ArgumentOutOfRangeException.ActualValue property to customize the content or format of the value. 58
Contents | Index
System
ArgumentOutOfRangeException Message Property
Usage Use this property to retrieve the invalid argument. A
ArgumentOutOfRangeException.Message Property
B
[ILASM]
C
.property string Message { public hidebysig virtual specialname string get_Message() }
D
[C#]
E
public override string Message { get; }
F
Summary
G
Gets the error message and the string representation of the invalid argument value, or only the error message if the argument value is null.
H
Property Value
J
The text message for this exception. The value of this property takes one of two forms, as follows.
K
I
L M
Condition
Value
The actualValue is null.
The message string passed to the constructor.
The actualValue is not null.
The message string appended with the string representation of the invalid argument value.
N O P Q R S
Description
T
This property overrides System.ArgumentException.Message. The error message should describe the expected values of the parameter that causes this exception. The error message should be localized.
U V W X Y Z
59
Contents | Index
ArgumentOutOfRangeException
System
GetObjectData() Method
ArgumentOutOfRangeException.GetObjectData(System.Runtime. Serialization.SerializationInfo, System.Runtime.Serialization. StreamingContext) Method A [ILASM]
B C
.method public hidebysig virtual void GetObjectData(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
D
[C#]
E
public override void GetObjectData(SerializationInfo info, StreamingContext context)
F G
Summary
H
Sets the System.Runtime.Serialization.SerializationInfo object with the invalid argument value and additional exception information.
I
Parameters
J K
Parameter
Description
M
info
The object that holds the serialized object data.
N
context
The contextual information about the source or destination.
L
O P
Description
Q
System.ArgumentOutOfRangeException.GetObjectData sets a System.Runtime.Serialization.SerializationInfo with all the exception object data targeted for serialization. During deserialization, the exception object is reconstituted from the System.Runtime.Serialization.SerializationInfo transmitted over the stream. For more information, see System.Runtime.Serialization.SerializationInfo.
R S T U V W
Exceptions
X Y Z
Exception
Condition
System.ArgumentNullException
The info object is null.
60
Contents | Index
System ArithmeticException
BCL
Object Exception
ISerializable
NotStandardized
A B
SystemException ArithmeticException
C
DivideByZeroException
D
OverflowException NotFiniteNumberException
E ExtendedNumerics
F G
Summary
H
Represents an error caused by an arithmetic operation.
I
Type Summary
J
public class ArithmeticException : SystemException { // Constructors public ArithmeticException (); public ArithmeticException (string message); public ArithmeticException (string message, Exception innerException); MS CF protected ArithmeticException (SerializationInfo info, StreamingContext context); }
K L M N O P Q
Description
R
[Note: The Base Class Library includes two types derived from System.ArithmeticException: When appropriate, use these types instead of System.ArithmeticException. ]
S T
Example
U
using System;
V namespace Samples { class ArithmeticExceptionSample { public static void Main() { try { Math.Sign(Double.NaN);
W X Y Z
61
Contents | Index
ArithmeticException
System
ArithmeticException() Constructor
} catch(ArithmeticException e) { Console.WriteLine("Exception: {0}", e); }
A }
B }
C
}
D
The output is
E Exception: System.ArithmeticException: Function does not accept floating point Not-a-Number values. at System.Math.Sign(Double value) at Samples.ArithmeticExceptionSample.Main() in C:\Books\BCL\Samples\System\ ArithmeticException\ArithmeticException.cs:line 11
F G H I J
ArithmeticException() Constructor
K [ILASM]
L
public rtspecialname specialname instance void .ctor() [C#]
M
public ArithmeticException()
N
Summary
O
Constructs and initializes a new instance of the System.ArithmeticException class.
P Q
Description
R
This constructor initializes the System.ArithmeticException.Message property of the new instance to a system-supplied message that describes the error, such as “The arithmetic operation is not allowed.” This message takes into account the current system culture. The System.ArithmeticException.InnerException property is initialized to null.
S T U V W
ArithmeticException(System.String) Constructor
X
[ILASM]
Y
public rtspecialname specialname instance void .ctor(string message) [C#]
Z
public ArithmeticException(string message)
62
Contents | Index
System
ArithmeticException ArithmeticException() Constructor
Summary Constructs and initializes a new instance of the System.ArithmeticException class. A
Parameters
B
Parameter
Description
C
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
D
message
E F G
Description
H
This constructor initializes the System.ArithmeticException.Message property of the new instance using message. If message is null, the System.ArithmeticException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.ArithmeticException.InnerException property is initialized to null.
I J K L M
ArithmeticException(System.String, System.Exception) Constructor
N
[ILASM]
O
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
P
[C#]
public ArithmeticException(string message, Exception innerException)
Q
Summary
R
Constructs and initializes a new instance of the System.ArithmeticException class.
S T
Parameters
U
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
V W X Y Z
63
Contents | Index
ArithmeticException
System
ArithmeticException() Constructor
Description This constructor initializes the System.ArithmeticException.Message property of the new instance using message, and the System.Exception.InnerException property using innerException. If message is null, the System.ArithmeticException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
A B C D E
ArithmeticException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
F G
[ILASM]
H
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
I J
[C#]
protected ArithmeticException(SerializationInfo info, StreamingContext context)
K L
Summary
M
Initializes a new instance of the System.ArithmeticException class with serialized data.
N O
Parameters
P Q
Parameter
Description
R
info
The object that holds the serialized object data.
context
The contextual information about the source or destination.
S T U
Description
V
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
W X Y Z
64
Contents | Index
System Array
BCL
ICloneable Object IList
A
ICollection
B
IEnumerable
C
Array
D
Summary
E
Serves as the base class for arrays. Provides methods for creating, copying, manipulating, searching, and sorting arrays.
F G
Type Summary
H
public abstract class Array : ICloneable, IList, ICollection, IEnumerable { // Constructors protected Array();
I J K L
// MS MS MS
Properties public virtual bool IsFixedSize { get; } public virtual bool IsReadOnly { get; } public virtual bool IsSynchronized { get; } public int Length { get; } CF 1.1 public long LongLength { get; } public int Rank { get; } MS public virtual object SyncRoot { get; }
M N O P Q
// Methods CF public static int BinarySearch (Array array, int index, int length, object value); public static int BinarySearch (Array array, int index, int length, object value, IComparer comparer); public static int BinarySearch (Array array, object value); CF public static int BinarySearch (Array array, object value, IComparer comparer); public static void Clear (Array array, int index, int length);
R S T U V W X Y Z
65
Contents | Index
Array
System
Array Class
A B MS CF 1.1
C D E CF
F G
MS CF 1.1
H I MS CF 1.1
J K
CF
L M
CF
N O P Q
CF
R S
MS CF 1.1
T MS MS CF 1.1
U V W
CF CF
X Y Z
MS CF 1.1 MS CF 1.1
public virtual object Clone (); public static void Copy (Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length); public static void Copy (Array sourceArray, long sourceIndex, Array destinationArray, long destinationIndex, long length); public static void Copy (Array sourceArray, Array destinationArray, int length); public static void Copy (Array sourceArray, Array destinationArray, long length); public virtual void CopyTo (Array array, int index); public virtual void CopyTo (Array array, long index); public static Array CreateInstance (Type elementType, int length); public static Array CreateInstance (Type elementType, int length1, int length2); public static Array CreateInstance (Type elementType, int length1, int length2, int length3); public static Array CreateInstance (Type elementType, params int[] lengths); public static Array CreateInstance (Type elementType, int[] lengths, int[] lowerBounds); public static Array CreateInstance (Type elementType, params long[] lengths); public virtual IEnumerator GetEnumerator (); public int GetLength (int dimension); public long GetLongLength (int dimension); public int GetLowerBound (int dimension); public int GetUpperBound (int dimension); public object GetValue (int index); public object GetValue (int index1, int index2); public object GetValue (int index1, int index2, int index3); public object GetValue (params int[] indices); public object GetValue (long index); public object GetValue (long index1, long index2);
66
Contents | Index
System
Array Array Class
MS CF 1.1 public object GetValue (long index1, long index2, long index3); MS CF 1.1 public object GetValue (params long[] indices); CF public static int IndexOf (Array array, object value); CF public static int IndexOf (Array array, object value, int startIndex); public static int IndexOf (Array array, object value, int startIndex, int count); public void Initialize (); CF public static int LastIndexOf (Array array, object value); CF public static int LastIndexOf (Array array, object value, int startIndex); public static int LastIndexOf (Array array, object value, int startIndex, int count); CF public static void Reverse (Array array); public static void Reverse (Array array, int index, int length); public void SetValue (object value, int index); CF public void SetValue (object value, int index1, int index2); CF public void SetValue (object value, int index1, int index2, int index3); public void SetValue (object value, params int[] indices); MS CF 1.1 public void SetValue (object value, long index); MS CF 1.1 public void SetValue (object value, long index1, long index2); MS CF 1.1 public void SetValue (object value, long index1, long index2, long index3); MS CF 1.1 public void SetValue (object value, params long[] indices); public static void Sort (Array array); CF public static void Sort (Array array, int index, int length); public static void Sort (Array array, int index, int length, IComparer comparer); CF public static void Sort (Array keys, Array items);
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
67
Contents | Index
Array
System
Array Class
CF public static void Sort (Array keys, Array items, int index, int length); public static void Sort (Array keys, Array items, int index, int length, IComparer comparer); CF public static void Sort (Array keys, Array items, IComparer comparer); CF public static void Sort (Array array, IComparer comparer);
A B C D
// CF CF CF CF CF CF CF CF CF
E F G H I J
Explicit Interface Members int IList.Add(object value); void IList.Clear(); bool IList.Contains(object value); int IList.IndexOf(object value); void IList.Insert(int index, object value); void IList.Remove(object value); void IList.RemoveAt(int index); int ICollection.Count { get; }; object IList.this [int index] {get; set;}
}
K L
BA Notice the heavy use of 32-bit integer values for indices in this class. In the standardization process we spent hours discussing how this class moves to the 64-bit world. There were arguments that suggested we will rarely need arrays bigger than 2,147,483,647 values (this is the largest integer value). In the end we decided to offer a LongLength property which returns the length as a 64-bit value. We decided it was prudent to wait and add all the other support for 64-bit indices once there was a demonstrable customer requirement.
M N O P Q R
Notice that we used signed values for the indices in the Array class. Some people may feel this is an odd choice as the negative values are always invalid for indices. There are two reasons for this. First, the Common Language Specification lacks support for unsigned 32-bit integrals, which means some languages would not be able to consume these members. Second, unsigned numbers are just harder to work with. Many domains naturally return values as signed numbers, so using unsigned indices here would lead to uglier code with more casts.
S T U V W X
Notice that the Array class implements the IList interface. We did that to support databinding and other generic mechanisms such as the “foreach” language construct in C#.
Y Z
continued
68
Contents | Index
System
Array Array Class
Accessing elements through the IList interface on an array is significantly more expensive than accessing elements directly, because the JIT can, for example, recognize code patterns and host bounds checks. Luckily, the C# compiler generates special case code for arrays that the JIT is able to recognize and optimize. For example, look at the code the C# compiler generates for this:
A B C
int [] arr = new int[] {1,2,3,4}; foreach (int i in arr) { Console.WriteLine (i) }
D E F
Rather than going through the enumerator the C# compiler generates code as if you had written:
G H
int [] arr = new int[] {1,2,3,4}; for (int i = 0; i < arr.Length; i++){ Console.WriteLine (i) }
I J K
Notice that we used explicit method implementation to hide many of the methods from the IList interface that do not make much sense on Array. This keeps the Array class clean but still allows arrays to be plugged into generic services such as databinding.
L M N
JM In the original submission of this class for standardization, the Clear() method was not specified as precisely as it is now. Before it was specified as just zeroing out an array. But for Booleans and reference types it needs to be false and null, respectively. The change was indeed made during the standardization process.
O
BG Looking forward, as we add generic collections into the picture, one might imagine making all array instances implement a generic IList
interface (i.e., Int32[] would implement IList). This would facilitate writing generic algorithms without requiring an STL-style iterator. A clever CLI implementation might potentially avoid performance hits when accessing an array through this generic interface, with sufficient complexity in the JIT.
R
P Q
S T U V W
Providing a base class for all arrays is one of our subtler but more notable advances. Most notably it allows all arrays to implement the IList interface, meaning that you can write one method that consumes a collection and also works with arrays, because our arrays are collections. Note that this duality allows us and our users to write APIs
X Y Z
continued
69
Contents | Index
Array
System
Array Class
that accept any collection instead of just an enumerator. This gives developers more flexibility than STL’s iterator-centric approach. A
Array::Copy is a very interesting method, supporting all the conversions that we can prove will always work (i.e., upcasting, downcasting particular instances, boxing, unboxing, and primitive widening). Most people do not realize how useful this method can be when dealing with arrays of various primitive types.
B C D
JR The CreateInstance method can be used for all kinds of interesting things. I have used it to create a method that can redimension any kind of array. Here is a simple example showing how to redimension a single-dimension array:
E F G
static Array Redim(Array origArray, Int32 desiredSize) { Type t = origArray.GetType().GetElementType(); Array newArray = Array.CreateInstance(t, desiredSize); Array.Copy(origArray, 0, newArray, 0, Math.Min(origArray.Length, desiredSize)); return newArray; }
H I J K L
I’ve also used CreateInstance to create arrays whose lower bounds are not 0: // I want a two-dimensional array [1995..2004][1..4]
M N
Int32[] lowerBounds = { 1995, 1 }; Int32[] lengths = { 10, 4 }; Decimal[,] quarterlyRevenue = (Decimal[,]) Array.CreateInstance(typeof(Decimal), lengths, lowerBounds); ... Console.WriteLine(“The quarterly revenue for the 2nd quarter of 1998 is: “ + quarterlyRevenue[1998][2]);
O P Q R S T
You can pass an IComparable object to Array’s Sort and BinarySearch methods. If your object’s CompareTo method throws an exception (any exception), Sort and BinarySearch catch the exception and throw an InvalidOperationException. This is not ideal; the exception thrown should not have been caught and allowed to propagate the call stack.
U V W X Y Z
70
Contents | Index
System
Array Array Class
Description This class is intended to be used as a base class by language implementations that support arrays. Only the system can derive from this type: derived classes of System.Array are not to be created by the developer. [Note: An array is a collection of identically typed data elements that are accessed and referenced by sets of integral indices. The rank of an array is the number of dimensions in the array. Each dimension has its own set of indices. An array with a rank greater than one can have a different lower bound and a different number of elements for each dimension. Multidimensional arrays (i.e., arrays with a rank greater than one) are processed in rowmajor order. The lower bound of a dimension is the starting index of that dimension. The length of an array is the total number of elements contained in all of its dimensions. A vector is a one-dimensional array with a lower bound of “0”. If the implementer creates a derived class of System.Array, expected System.Array behavior cannot be guaranteed. For information on array-like objects with increased functionality, see the System.Collections.IList interface. For more information regarding the use of arrays versus the use of collections, see Partition V of the CLI Specification.] Every specific System.Array type has three instance methods defined on it. While some programming languages allow direct access to these methods, they are primarily intended to be called by the output of compilers based on language syntax that deals with arrays. •
•
•
A B C D E F G H I J K L M
Get: Takes as many System.Int32 arguments as the array has dimensions and returns the value stored at the given index. It throws a System.IndexOutOfRangeException exception for invalid indices. Set: Takes as many System.Int32 arguments as the array has dimensions, plus one additional argument (the last argument), which has the same type as an array element. It stores the final value in the specified index of the array. It throws a System.IndexOutOfRangeException exception for invalid indices. Address: Takes as many System.Int32 arguments as the array has dimensions and returns the address of the element at the given index. It throws a System.IndexOutOfRangeException exception for invalid indices.
N O P Q R S T U
In addition, every specific System.Array type has a constructor on it that takes as many positive System.Int32 arguments as the array has dimensions. The arguments specify the number of elements in each dimension, and a lower bound of 0. Thus, a twodimensional array of System.Int32 objects would have a constructor that could be called with (2, 4) as its arguments to create an array of eight zeros with the first dimension indexed with 0 and 1 and the second dimension indexed with 0, 1, 2, and 3. For all specific array types except vectors (i.e., those permitted to have non-zero lower bounds and those with more than one dimension) there is an additional constructor. It takes twice as many arguments as the array has dimensions. The arguments are considered in pairs,
V W X Y Z
71
Contents | Index
Array
System
Array Class
with the first of the pair specifying the lower bound for that dimension and the second specifying the total number of elements in that dimension. Thus, a two-dimensional array of System.Int32 objects would also have a constructor that could be called with (–1, 2, 1, 3) as its arguments, specifying an array of 6 zeros, with the first dimension indexed by −1 and 0, and the second dimension indexed by 1, 2, and 3.
A B C
Example
D
using System; using System.Collections;
E
namespace Samples { public class ArraySample { public class MyReverseComparer: IComparer { public int Compare(Object a, Object b) { return -((IComparable)a).CompareTo(b); } } public static void Main() { string[] strings = {"one", "two", "three"}; Console.WriteLine("Array elements: "); Display(strings); Array.Reverse(strings); Display(strings); Array.Sort(strings); Display(strings); Array.Sort(strings, new MyReverseComparer()); Display(strings); } public static void Display(Array a) { foreach(object o in a) Console.Write("{0} ", o); Console.WriteLine(); } } }
F G H I J K L M N O P Q R S T U V W X
The output is
Y
Array elements: one two three three two one one three two two three one
Z
72
Contents | Index
System
Array IsReadOnly Property
Array() Constructor [ILASM]
family specialname instance void .ctor() [C#]
A
protected Array()
B C
Summary
D
Constructs a new instance of the System.Array class.
E F
Array.IsFixedSize Property
G
[ILASM]
H
.property bool IsFixedSize { public hidebysig virtual specialname bool get_IsFixedSize() }
I
[C#]
J
public virtual bool IsFixedSize { get; }
K
Summary
L
Gets a value indicating whether the System.Array has a fixed size.
M
Property Value
N
This property is always true for all arrays.
O P
Description
Q
System.Array implements the System.Array.IsFixedSize property because it is required by the System.Collections.IList interface. An array with a fixed size does not allow the addition or removal of elements after the array is created, but it allows the modification of existing elements.
R S T U
Array.IsReadOnly Property
V
[ILASM]
W
.property bool IsReadOnly { public hidebysig virtual specialname bool get_IsReadOnly() }
X
[C#]
Y
public virtual bool IsReadOnly { get; }
Z
73
Contents | Index
Array
System
IsSynchronized Property
Summary Gets a value indicating whether the System.Array is read-only. A
Property Value
B
This property is always false for all arrays.
C
Description
D
System.Array implements the System.Array.IsReadOnly property because it is required by the System.Collections.IList interface. If you require a read-only collection, use a System.Collections class that implements the System.Collections.IList interface. An array that is read-only does not allow the addition, removal, or modification of elements after the array is created.
E F G H I J
Array.IsSynchronized Property
K [ILASM]
L
.property bool IsSynchronized { public hidebysig virtual specialname bool get_IsSynchronized() }
M
[C#]
N
public virtual bool IsSynchronized { get; }
O
Summary
P
Gets a value indicating whether access to the System.Array is synchronized (thread-safe).
Q R
Property Value
S
This property is always false for all arrays.
T
Description
U
System.Array implements the System.Array.IsSynchronized property because it is required by the System.Collections.ICollection interface. .NET Framework classes based on System.Array provide their own synchronized version of the collection using the System.Array.SyncRoot property. Classes that use arrays can also implement their own synchronization using the System.Array.SyncRoot property. The synchronizing code must perform operations on the SyncRoot of the collection, not directly on the collection. This ensures proper operation of collections that are derived from other objects. Specifically, it maintains proper synchronization with other threads that might be simultaneously modifying the
V W X Y Z
74
Contents | Index
System
Array Length Property
collection. Note that some implementations of System.Array.SyncRoot might return the System.Array itself. Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads. The following code example shows how to lock a collection during the entire enumeration by using the System.Array.SyncRoot:
A B C D E
Array myCollection = new int[]; lock( myCollection.SyncRoot ) { foreach ( Object item in myCollection ) { // Insert your code here. } }
F G H I J K
Array.Length Property
L
[ILASM]
.property int32 Length { public hidebysig specialname instance int32 get_Length() }
M
[C#]
N
public int Length { get; }
O
Summary
P
Gets the total number of elements in all the dimensions of the current instance.
Q
Example
R
using System;
S
namespace Samples { public class ArrayLength { public static void Main() { string[] strings = {"brad", "tamara", "boston"}; Console.WriteLine("Length: {0}", strings.Length); } } }
T U V W X Y Z
75
Contents | Index
Array
System
LongLength Property
The output is Length: 3
A B
Array.LongLength Property
C
[ILASM]
D
.property int32 Length { public hidebysig specialname instance int32 get_LongLength() }
E
[C#]
public long LongLength {get;}
F G
Summary
H
Gets the total number of elements in all the dimensions of the current instance.
I
Description
J
[Note: For additional information, see System.Array.Length.]
K L M
Array.Rank Property
N
[ILASM]
.property int32 Rank { public hidebysig specialname instance int32 get_Rank() }
O
[C#]
P
public int Rank { get; }
Q
Summary
R
Gets the rank (number of dimensions) of the current instance.
S
Example
T
using System;
U namespace Samples { public class ArrayRank { public static void Main() { string[] strings = {"brad", "tamara", "boston"}; Console.WriteLine("Rank: {0}", strings.Rank); } } }
V W X Y Z
76
Contents | Index
System
Array SyncRoot Property
The output is Rank: 1
A B
Array.SyncRoot Property
C [ILASM]
D
.property object SyncRoot { public hidebysig virtual specialname object get_SyncRoot() }
E
[C#]
public virtual object SyncRoot { get; }
F G
Summary
H
Gets an object that can be used to synchronize access to the System.Array.
I
Description
J
This property implements the System.Collections.ICollection interface. .NET Framework classes based on System.Array provide their own synchronized version of the collection using the System.Array.SyncRoot property. Classes that use arrays can also implement their own synchronization using the System.Array.SyncRoot property. The synchronizing code must perform operations on the SyncRoot of the collection, not directly on the collection. This ensures proper operation of collections that are derived from other objects. Specifically, it maintains proper synchronization with other threads that might be simultaneously modifying the collection. Note that some implementations of System.Array.SyncRoot might return the System.Array itself. Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads. The following code example shows how to lock a collection during the entire enumeration by using the System.Array.SyncRoot:
K L M N O P Q R S T U V
Array myCollection = new int[]; lock( myCollection.SyncRoot ) { foreach ( Object item in myCollection ) { // Insert your code here. } }
W X Y Z
77
Contents | Index
Array
System
BinarySearch() Method
Array.BinarySearch(System.Array, System.Int32, System.Int32, System.Object) Method [ILASM]
A
.method public hidebysig static int32 BinarySearch(class System.Array array, int32 index, int32 length, object value)
B
[C#]
C
public static int BinarySearch(Array array, int index, int length, object value)
D E
Summary
F
Searches the specified section of the specified one-dimensional System.Array for the specified value.
G
Parameters
H I
Parameter
Description
array
A System.Array to search.
index
A System.Int32 that contains the index at which searching starts.
length
A System.Int32 that contains the number of elements to search, beginning with index.
value
A System.Object for which to search, or a null reference. [Note: A null reference will be considered to compare less than any non-null object, or equal to another null reference.]
J K L M N O P Q R
Return Value
S
A System.Int32 with one of the following values based on the result of the search operation.
T U V
Return Value
Description
The index of value in the array.
value was found.
The bitwise complement of the index of the first element that is larger than value.
value was not found, and at least one array element in the range of index to index + length – 1 was greater than value.
The bitwise complement of (index + length).
value was not found, and value was greater than all array elements in the range of index to index + length – 1.
W X Y Z
78
Contents | Index
System
Array BinarySearch() Method
[Note: If value is not found, the caller can take the bitwise complement of the return value to determine the index of the array where value would be found in the range of index to index + length – 1 if array is already sorted.] A
Description
B
This version of System.Array.BinarySearch is equivalent to System.Array.BinarySearch(array, array.GetLowerBound(0), array.Length, value, null). value is compared to each element of array using the System.IComparable interface of the element being compared — or of value if the element being compared does not implement the interface — until an element with a value greater than or equal to value is found. If value does not implement the System.IComparable interface and is compared to an element that does not implement the System.IComparable interface, a System.ArgumentException exception is thrown. If array is not already sorted, correct results are not guaranteed. [Note: A null reference can be compared with any type; therefore, comparisons with a null reference do not generate exceptions.]
C D E F G H I J K
Exceptions
L
Exception
Condition
System.ArgumentNullException
array is null.
System.RankException
array has more than one dimension.
M N O P
index < array.GetLowerBound(0). System.ArgumentOutOfRangeException
Q
-orR
length < 0.
S
index and length do not specify a valid range in array (i.e., index + length > array.GetLowerBound(0) + array.Length).
T U
-orSystem.ArgumentException
V
Either value or at least one element of array does not implement the System.IComparable interface.
W
-or-
X
value is not assignment-compatible with at least one element of array.
Y
-or-
Z
array.UpperBound == System.Int32.MaxValue.
79
Contents | Index
Array
System
BinarySearch() Method
Example using System; namespace Samples { class ArrayBinarySearch { public static void Main() { int[] ints = {0, 2, 4, 6, 8 }; Console.WriteLine( "The indices and elements of the array are: "); for(int i = 0; i < ints.Length; i++ ) Console.Write("[{0}]: {1, -5}", i, ints[i]); Console.WriteLine(); SearchFor(ints, 3); SearchFor(ints, 6); SearchFor(ints, 9); } public static void SearchFor(Array a, Object o) { int i = Array.BinarySearch(a, 0, a.Length, o); Console.WriteLine(); if(i > 0 ) { Console.WriteLine( "Object: {0}, was found at: {1}", o, i ); } else if(~i == a.Length ) { Console.WriteLine("Object: {0}, was not found", o); Console.WriteLine( "No object in the array had a greater value."); } else { Console.WriteLine("Object: {0}, was not found", o); Console.WriteLine( "The next larger object is at index: {0}.", ~i ); } } } }
A B C D E F G H I J K L M N O P Q R S T U V W X Y
The output is
Z
The indices and elements of the array are: [0]: 0 [1]: 2 [2]: 4 [3]: 6 [4]: 8
80
Contents | Index
System
Array BinarySearch() Method
Object: 3, was not found The next larger object is at index: 2. Object: 6, was found at: 3
A
Object: 9, was not found No object in the array had a greater value.
B C D
Array.BinarySearch(System.Array, System.Int32, System.Int32, System.Object, System.Collections.IComparer) Method
E F
[ILASM]
G
.method public hidebysig static int32 BinarySearch(class System.Array array, int32 index, int32 length, object value, class System.Collections.IComparer comparer)
H
[C#]
public static int BinarySearch(Array array, int index, int length, object value, IComparer comparer)
I
Summary
K
Searches the specified section of the specified one-dimensional System.Array for the specified value, using the specified System.Collections.IComparer implementation.
L
J
M N
Parameters
O
Parameter
Description
array
A System.Array to search.
index
A System.Int32 that contains the index at which searching starts.
length
A System.Int32 that contains the number of elements to search, beginning with index.
value
A System.Object for which to search, or a null reference. [Note: A null reference will be considered to compare less than any non-null object, or equal to another null reference.]
comparer
The System.Collections.IComparer implementation to use when comparing elements. Specify a null reference to use the System.IComparable implementation of each element.
P Q R S T U V W X Y Z
81
Contents | Index
Array
System
BinarySearch() Method
Return Value A System.Int32 with one of the following values based on the result of the search operation. A B C D
Return Value
Description
The index of value in the array.
value was found.
The bitwise complement of the index of the first element that is larger than value.
value was not found, and at least one array element in the range of index to index + length – 1 was greater than value.
The bitwise complement of (index + length).
value was not found, and value was greater than all array elements in the range of index to index + length – 1.
E F G H I J
[Note: If value is not found, the caller can take the bitwise complement of the return value to determine the index of array where value would be found in the range of index to index + length – 1 if array is already sorted.]
K L M N
Description
O
value is compared to each element of array using comparer until an element with a value greater than or equal to value is found. If comparer is null, the System.IComparable interface of the element being compared—or of value if the element being compared does not implement the interface—is used. If value does not implement the System.IComparable interface and is compared to an element that does not implement the System.IComparable interface, a System.ArgumentException exception is thrown. If array is not already sorted, correct results are not guaranteed. [Note: A null reference can be compared with any type; therefore, comparisons with a null reference do not generate exceptions.]
P Q R S T U V W X Y Z
82
Contents | Index
System
Array BinarySearch() Method
Exceptions Exception
Condition
System.ArgumentNullException
array is null.
System.RankException
array has more than one dimension.
C
index < array.GetLowerBound(0).
D
-or-
E
length < 0.
F
index and length do not specify a valid range in array (i.e., index + length > array.GetLowerBound(0) + array.Length).
G H
-or-
I
comparer is null, and both value and at least one element of array do not implement the System.IComparable interface.
J K
-or-
L
comparer is null, and value is not of the same type as the elements of array.
M
-or-
N
array.UpperBound == System.Int32.MaxValue.
O
A
System.ArgumentOutOfRangeException
System.ArgumentException
B
P
Example
Q
using System; using System.Collections;
R S
namespace Samples { class ArrayBinarySearch { public class MyComparer: IComparer { public int Compare(Object a, Object b) { return ((IComparable)a).CompareTo(b); } } public static void Main() { int[] ints = { 0, 2, 4, 6, 8 }; Console.WriteLine(
T U V W X Y Z
83
Contents | Index
Array
System
BinarySearch() Method
"The indices and elements of the array are: "); for(int i = 0; i < ints.Length; i++ ) Console.Write("[{0}]: {1, -5}", i, ints[i]); Console.WriteLine(); SearchFor(ints, 3); SearchFor(ints, 6); SearchFor(ints, 9);
A B
} public static void SearchFor(Array a, Object o) { int i = Array.BinarySearch( a, 0, a.Length, o, new MyComparer()); Console.WriteLine(); if(i > 0 ) { Console.WriteLine( "Object: {0}, was found at: {1}", o, i ); } else if(~i == a.Length ) { Console.WriteLine("Object: {0}, was not found", o); Console.WriteLine( "No object in the array had a greater value."); } else { Console.WriteLine("Object: {0}, was not found", o); Console.WriteLine( "The next larger object is at index: {0}.", ~i ); } }
C D E F G H I J K L M N O P
} }
Q
The output is
R S
The indices and elements of the array are: [0]: 0 [1]: 2 [2]: 4 [3]: 6 [4]: 8
T U
Object: 3, was not found The next larger object is at index: 2.
V W
Object: 6, was found at: 3
X
Object: 9, was not found No object in the array had a greater value.
Y Z
84
Contents | Index
System
Array BinarySearch() Method
Array.BinarySearch(System.Array, System.Object) Method [ILASM]
.method public hidebysig static int32 BinarySearch(class System.Array array, object value)
A
[C#]
B
public static int BinarySearch(Array array, object value)
C
Summary
D
Searches the specified one-dimensional System.Array for the specified object.
E F
Parameters
G H
Parameter
Description
array
A System.Array to search for an object.
value
A System.Object for which to search, or a null reference. [Note: A null reference will be considered to compare less than any non-null object, or equal to another null reference.]
I J K L M
Return Value
N
A System.Int32 with one of the following values based on the result of the search operation.
O P
Return Value
Description
The index of value in the array.
value was found.
The bitwise complement of the index of the first element that is larger than value.
value was not found and the value of at least one element of array was greater than value.
The bitwise complement of (array.GetLowerBound(0) + array.Length).
value was not found, and value was greater than the value of all array elements.
Q R S T U V W X
[Note: If value is not found, the caller can take the bitwise complement of the return value to determine the index where value would be found in array if it is sorted already.]
Y Z
85
Contents | Index
Array
System
BinarySearch() Method
Description This version of System.Array.BinarySearch is equivalent to System.Array.BinarySearch(array, array.GetLowerBound(0), array.Length, value, null). value is compared to each element of array using the System.IComparable interface of the element being compared — or of value if the element being compared does not implement the interface — until an element with a value greater than or equal to value is found. If value does not implement the System.IComparable interface and is compared to an element that does not implement the System.IComparable interface, a System.ArgumentException exception is thrown. If array is not already sorted, correct results are not guaranteed. [Note: A null reference can be compared with any type; therefore, comparisons with a null reference do not generate exceptions.]
A B C D E F G H
Exceptions
I J
Exception
K
Condition Both value and at least one element of array do not implement the System.IComparable interface.
L
-or-
M System.ArgumentException
N
value is not assignment-compatible with at least one element of array.
O
-or-
P
array.UpperBound == System.Int32.MaxValue.
Q R
System.ArgumentNullException
array is null.
System.RankException
array has more than one dimension.
S T
Example
U
using System;
V namespace Samples { class ArrayBinarySearch { public static void Main() { int[] ints = { 0, 2, 4, 6, 8 }; Console.WriteLine( "The indices and elements of the array are: ");
W X Y Z
86
Contents | Index
System
Array BinarySearch() Method
for(int i = 0; i < ints.Length; i++ ) Console.Write("[{0}]: {1, -5}", i, ints[i]); Console.WriteLine(); SearchFor(ints, 3); SearchFor(ints, 6); SearchFor(ints, 9);
A B
} public static void SearchFor(Array a, Object o) { int i = Array.BinarySearch(a, o); Console.WriteLine(); if(i > 0 ) { Console.WriteLine( "Object: {0}, was found at: {1}", o, i ); } else if(~i == a.Length ) { Console.WriteLine("Object: {0}, was not found", o); Console.WriteLine( "No object in the array had a greater value."); } else { Console.WriteLine("Object: {0}, was not found", o); Console.WriteLine( "The next larger object is at index: {0}.", ~i ); } }
C D E F G H I J K L M N O P
}
Q
}
R
The output is
S The indices and elements of the array are: [0]: 0 [1]: 2 [2]: 4 [3]: 6 [4]: 8
T U
Object: 3, was not found The next larger object is at index: 2.
V W
Object: 6, was found at: 3
X Object: 9, was not found No object in the array had a greater value.
Y Z
87
Contents | Index
Array
System
BinarySearch() Method
Array.BinarySearch(System.Array, System.Object, System.Collections.IComparer) Method [ILASM]
A
.method public hidebysig static int32 BinarySearch(class System.Array array, object value, class System.Collections.IComparer comparer)
B
[C#]
C
public static int BinarySearch(Array array, object value, IComparer comparer)
D E
Summary
F
Searches the specified one-dimensional System.Array for the specified value, using the specified System.Collections.IComparer implementation.
G
Parameters
H I
Parameter
Description
array
A System.Array to search.
value
A System.Object for which to search, or a null reference. [Note: A null reference will be considered to compare less than any non-null object, or equal to another null reference.]
comparer
The System.Collections.IComparer implementation to use when comparing elements. Specify a null reference to use the System.IComparable implementation of each element.
J K L M N O P Q
Return Value
R
A System.Int32 with one of the following values based on the result of the search operation.
S T U
Return Value
Description
V
The index of value in the array.
value was found.
The bitwise complement of the index of the first element that is larger than value.
value was not found, and at least one array element was greater than value.
The bitwise complement of (array.GetLowerBound(0) + array.Length).
value was not found, and value was greater than all array elements.
W X Y Z
88
Contents | Index
System
Array BinarySearch() Method
[Note: If value is not found, the caller can take the bitwise complement of the return value to determine the index where value would be found in array if it is already sorted.]
Description
A
This version of System.Array.BinarySearch is equivalent to System.Array.BinarySearch(array, array.GetLowerBound(0), array.Length, value, comparer). value is compared to each element of array using comparer until an element with a value greater than or equal to value is found. If comparer is null, the System.IComparable interface of the element being compared — or of value if the element being compared does not implement the interface — is used. If value does not implement the System.IComparable interface and is compared to an element that does not implement the System.IComparable interface, a System.ArgumentException exception is thrown. If array is not already sorted, correct results are not guaranteed. [Note: A null reference can be compared with any type; therefore, comparisons with a null reference do not generate exceptions.]
B C D E F G H I J
Exceptions Exception
K L
Condition
M
comparer is null, and both value and at least one element of array do not implement the System.IComparable interface.
N O
-orSystem.ArgumentException
P
comparer is null, and value is not assignment-compatible with at least one element of array.
Q
-or-
R
array.UpperBound == System.Int32.MaxValue.
S
System.ArgumentNullException
array is null.
T
System.RankException
array has more than one dimension.
U V W X Y Z
89
Contents | Index
Array
System
BinarySearch() Method
Example using System; using System.Collections;
A
namespace Samples { class ArrayBinarySearch { public class MyComparer: IComparer { public int Compare(Object a, Object b) { return ((IComparable)a).CompareTo(b); } } public static void Main() { int[] ints = { 0, 2, 4, 6, 8 }; Console.WriteLine( "The indices and elements of the array are: "); for(int i = 0; i < ints.Length; i++ ) Console.Write("[{0}]: {1, -5}", i, ints[i]); Console.WriteLine(); SearchFor(ints, 3); SearchFor(ints, 6); SearchFor(ints, 9); } public static void SearchFor(Array a, Object o) { int i = Array.BinarySearch(a, o, new MyComparer()); Console.WriteLine(); if(i > 0 ) { Console.WriteLine( "Object: {0}, was found at: {1}", o, i ); } else if(~i == a.Length ) { Console.WriteLine("Object: {0}, was not found", o); Console.WriteLine( "No object in the array had a greater value."); } else { Console.WriteLine("Object: {0}, was not found", o); Console.WriteLine( "The next larger object is at index: {0}.", ~i ); } } } }
B C D E F G H I J K L M N O P Q R S T U V W X Y Z
90
Contents | Index
System
Array Clear() Method
The output is The indices and elements of the array are: [0]: 0 [1]: 2 [2]: 4 [3]: 6 [4]: 8
A B
Object: 3, was not found The next larger object is at index: 2.
C Object: 6, was found at: 3
D
Object: 9, was not found No object in the array had a greater value.
E F G
Array.Clear(System.Array, System.Int32, System.Int32) Method
H
[ILASM]
I
.method public hidebysig static void Clear(class System.Array array, int32 index, int32 length)
J
[C#]
K
public static void Clear(Array array, int index, int length)
L
Summary
M
Sets the specified range of elements in the specified System.Array to zero, false, or to a null reference, depending on the element type.
N O P
Parameters
Q
Parameter
Description
array
The System.Array to clear.
index
A System.Int32 that contains the index at which clearing starts.
length
A System.Int32 that contains the number of elements to clear, beginning with index.
R S T U V W
Description
X
Reference-type elements will be set to null. Value-type elements will be set to zero, except for System.Boolean elements, which will be set to false.
Y Z
91
Contents | Index
Array
System
Clear() Method
Exceptions Exception
Condition
System.ArgumentNullException
array is null.
A B
index < array.GetLowerBound(0).
C
length < 0.
D
System.ArgumentOutOfRangeException
E F
index and length do not specify a valid range in array (i.e., index + length > array.GetLowerBound(0) + array.Length ).
G H
Example
I
using System;
J
namespace Samples { class ArrayClear { public static void Main() { int[] ints = { 0, 2, 4, 6, 8 }; DisplayArray(ints); Array.Clear(ints, 2, 2); DisplayArray(ints); } public static void DisplayArray(int[] a) { Console.WriteLine( "The indices and elements of the array are: "); for(int i = 0; i < a.Length; i++ ) Console.Write("[{0}]: {1, -5}", i, a[i]); Console.WriteLine(); } } }
K L M N O P Q R S T U V W
The output is
X The indices and elements [0]: 0 [1]: 2 [2]: The indices and elements [0]: 0 [1]: 2 [2]:
Y Z
of the array are: 4 [3]: 6 [4]: 8 of the array are: 0 [3]: 0 [4]: 8
92
Contents | Index
System
Array Clone() Method
Array.Clone() Method [ILASM]
.method public hidebysig virtual object Clone() [C#]
A
public virtual object Clone()
B C
Summary
D
Returns a System.Object that is a copy of the current instance.
E
Description
F
[Note: This method is implemented to support the System.ICloneable interface.]
G
Behaviors
H
Each of the elements of the current instance is copied to the clone. If the elements are reference types, the references are copied. If the elements are value types, the values are copied. The clone is of the same type as the current instance.
I J K
Example
L
using System;
M
namespace Samples { class ArrayClone { public static void Main() { string[] strings1 = {"one", "two", "three"}; string[] strings2 = (string[]) strings1.Clone(); DisplayArrays(strings1, strings2); Array.Clear(strings1, 0, strings1.Length); DisplayArrays(strings1, strings2); } private static void DisplayArrays(string[] a, string[]b) { Console.WriteLine("First array elements: "); foreach(string s in a) Console.Write("{0} ", s); Console.WriteLine(); Console.WriteLine("Second array elements: "); foreach(string s in b) Console.Write("{0} ", s); Console.WriteLine(); } } }
N O P Q R S T U V W X Y Z
93
Contents | Index
Array
System
Copy() Method
The output is First array elements: one two three Second array elements: one two three First array elements:
A B C
Second array elements: one two three
D E F
Array.Copy(System.Array, System.Int32, System.Array, System.Int32, System.Int32) Method
G H
[ILASM]
I
.method public hidebysig static void Copy(class System.Array sourceArray, int32 sourceIndex, class System.Array destinationArray, int32 destinationIndex, int32 length)
J K
[C#]
L
public static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
M N
Summary
O
Copies the specified number of elements from a source array starting at the specified source index to a destination array starting at the specified destination index.
P
Parameters
Q R
Parameter
Description
T
sourceArray
The System.Array that contains the data to copy.
U
sourceIndex
A System.Int32 that contains the index in sourceArray from which copying begins.
destinationArray
The System.Array that receives the data.
destinationIndex
A System.Int32 that contains the index in destinationArray at which storing begins.
length
A System.Int32 that contains the number of elements to copy.
S
V W X Y Z
94
Contents | Index
System
Array Copy() Method
Description If sourceArray and destinationArray are of different types, System.Array.Copy performs widening conversions on the elements of sourceArray as necessary before storing the information in destinationArray. Value types will be boxed when being converted to a System.Object. If the necessary conversion is a narrowing conversion, a System.ArrayTypeMismatchException exception is thrown. [Note: For information regarding valid conversions performed by this method, see System.Convert.] If an exception is thrown while copying, the state of destinationArray is undefined. If sourceArray and destinationArray are the same array, System.Array.Copy copies the source elements safely to their destination as if the copy were done through an intermediate array.
A B C D E F G
Exceptions Exception
H I
Condition
J System.ArgumentNullException
sourceArray or destinationArray is null.
System.RankException
sourceArray and destinationArray have different ranks.
K L M
The elements in both arrays are built-in types, and converting from the type of the elements of sourceArray into the type of the elements in destinationArray requires a narrowing conversion. System.ArrayTypeMismatchException
N O
-or-
P
Both arrays are built-in types, and one array is a value-type array and the other an array of interface type not implemented by that value type.
Q
-or-
S
Both arrays are user-defined value types and are not of the same type.
T
R
U System.InvalidCastException
At least one element in sourceArray is assignment-incompatible with the type of destinationArray.
V W X Y Z
95
Contents | Index
Array
System
Copy() Method
Exception
Condition sourceIndex < sourceArray.GetLowerBound(0).
A
-or-
B
System.ArgumentOutOfRangeException
C
destinationIndex < destinationArray.GetLowerBound(0). -or-
D
length < 0.
E F
System.ArgumentException
G
(sourceIndex + length ) > (sourceArray.GetLowerBound(0) + sourceArray.Length). (destinationIndex + length ) > (destinationArray.GetLowerBound(0) + destinationArray.Length).
H I
Example
J
using System;
K namespace Samples { class ArrayCopy { public static void Main() { int[] ints = { 0, 10, 20, 30, 40, 50 }; Console.Write("Array elements: "); foreach(int i in ints) Console.Write("{0,3}", i ); Console.WriteLine(); Array.Copy(ints, 2, ints, 0, 4 ); Console.Write("Array elements: "); foreach(int i in ints) Console.Write("{0,3}", i ); Console.WriteLine(); } } }
L M N O P Q R S T U V W
The output is
X Y
Array elements: Array elements:
Z
0 10 20 30 40 50 20 30 40 50 40 50
96
Contents | Index
System
Array Copy() Method
Array.Copy(System.Array, System.Int64, System.Array, System.Int64, System.Int64) Method [ILASM]
A
.method public hidebysig static void Copy(class System.Array sourceArray, int64 sourceIndex, class System.Array destinationArray, int64 destinationIndex, int64 length)
B C
[C#]
public static void Copy(Array sourceArray, long sourceIndex, Array destinationArray, long destinationIndex, long length)
D E
Summary
F
Copies a range of elements from a System.Array starting at the specified source index and pastes them to another System.Array starting at the specified destination index. The length and the indexes are specified as 64-bit integers.
G H I
Parameters
J K
Parameter
Description
sourceArray
The System.Array that contains the data to copy.
M
sourceIndex
A 64-bit integer that represents the index in the sourceArray at which copying begins.
N
destinationArray
The System.Array that receives the data.
destinationIndex
A 64-bit integer that represents the index in the destinationArray at which storing begins.
length
A 64-bit integer that represents the number of elements to copy.
L
O P Q R S T
Description
U
The sourceArray and destinationArray parameters must have the same number of dimensions. When copying between multidimensional arrays, the array behaves like a long one-dimensional array, where the rows (or columns) are conceptually laid end to end. For example, if an array has three rows (or columns) with four elements each, copying six elements from the beginning of the array would copy all four elements of the first row (or column) and the first two elements of the second row (or column). To start copying from the second element of the third row (or column), sourceIndex must be the upper bound of the first row (or column) plus the length of the second row (or column) plus two.
V W X Y Z
97
Contents | Index
Array
System
Copy() Method
If sourceArray and destinationArray overlap, this method behaves as if the original values of sourceArray were preserved in a temporary location before destinationArray is overwritten. This method is equivalent to the standard C/C++ function memmove, not memcpy. The arrays can be reference-type arrays or value-type arrays. Type downcasting is performed, as required.
A B C
•
D E F
•
G H I
•
J K L M
When copying from a reference-type array to a value-type array, each element is unboxed and then copied. When copying from a value-type array to a reference-type array, each element is boxed and then copied. When copying from a reference-type or value-type array to a System.Object array, a System.Object is created to hold each value or reference and then copied. When copying from a System.Object array to a reference-type or value-type array and the assignment is not possible, a System.InvalidCastException is thrown. If sourceArray and destinationArray are both reference-type arrays or are both arrays of type System.Object, a shallow copy is performed. A shallow copy of a System.Array is a new System.Array containing references to the same elements as the original System.Array. The elements themselves or anything referenced by the elements are not copied. In contrast, a deep copy of a System.Array copies the elements and everything directly or indirectly referenced by the elements.
A System.ArrayTypeMismatchException is thrown if the arrays are of incompatible types. Type compatibility is defined as follows:
N O P
• •
Q R S
•
T U V W
•
X
A type is compatible with itself. A value type is compatible with System.Object and with an interface type implemented by that value type. A value type is considered connected to an interface only if it implements that interface directly. Disconnected types are not compatible. Two intrinsic (predefined) value types are compatible if copying from the source type to the destination type is a widening conversion. A widening conversion never loses information, whereas a narrowing conversion can lose information. For example, converting a 32-bit signed integer to a 64-bit signed integer is a widening conversion, and converting a 64-bit signed integer to a 32-bit signed integer is a narrowing conversion. For more information about conversions, see System.Convert. A nonintrinsic (user-defined) value type is compatible only with itself.
If every element in sourceArray requires a downcast (for example, from a base class to a derived class or from an interface to an object) and one or more elements cannot be cast to the corresponding type in destinationArray, a System.InvalidCastException is thrown.
Y Z
98
Contents | Index
System
Array Copy() Method
If this method throws an exception while copying, the state of destinationArray is undefined. A
Exceptions
B
Exception
Condition
System.ArgumentNullException
sourceArray is null. -ordestinationArray is null.
System.RankException
sourceArray and destinationArray have different ranks.
System.ArrayTypeMismatchException
sourceArray and destinationArray are of incompatible types.
System.InvalidCastException
At least one element in sourceArray cannot be cast to the type of destinationArray.
System.ArgumentOutOfRangeException
sourceIndex is less than the lower bound of the first dimension of sourceArray. -ordestinationIndex is less than the lower bound of the first dimension of destinationArray. -orlength is less than zero.
C D E F G
System.ArgumentException
H I J K L M N O
length is greater than the number of elements from sourceIndex to the end of sourceArray. -orlength is greater than the number of elements from destinationIndex to the end of destinationArray.
P Q R S T
Array.Copy(System.Array, System.Array, System.Int32) Method
U
[ILASM]
V
.method public hidebysig static void Copy(class System.Array sourceArray, class System.Array destinationArray, int32 length)
W
[C#]
X
public static void Copy(Array sourceArray, Array destinationArray, int length)
Y Z
99
Contents | Index
Array
System
Copy() Method
Summary Copies the specified number of elements from the specified source array to the specified destination array. A
Parameters
B C
Parameter
Description
E
sourceArray
A System.Array that contains the data to copy.
F
destinationArray
A System.Array that receives the data.
length
A System.Int32 designating the number of elements to copy, starting with the first element and proceeding in order.
D
G H I
Description
J
This version of System.Array.Copy is equivalent to System.Array.Copy (sourceArray, sourceArray.GetLowerBound(0), destinationArray, destinationArray.GetLowerBound(0), length). If sourceArray and destinationArray are of different types, System.Array.Copy performs widening conversions on the elements of sourceArray as necessary before storing the information in destinationArray. Value types will be boxed when being converted to a System.Object. If the necessary conversion is a narrowing conversion, a System.ArrayTypeMismatchException exception is thrown. [Note: For information regarding valid conversions performed by this method, see System.Convert.] If an exception is thrown while copying, the state of destinationArray is undefined. If sourceArray and destinationArray are the same array, System.Array.Copy copies the source elements safely to their destination, as if the copy were done through an intermediate array.
K L M N O P Q R S T U V W X Y Z
100
Contents | Index
System
Array Copy() Method
Exceptions Exception
Condition
System.ArgumentNullException
sourceArray or destinationArray is null.
System.RankException
sourceArray and destinationArray have different ranks.
C D
System.ArrayTypeMismatchException
The elements in both arrays are built-in types, and converting from the type of the elements of sourceArray into the type of the elements in destinationArray requires a narrowing conversion. -orBoth arrays are built-in types, and one array is a value-type array and the other an array of interface type not implemented by that value type. -orBoth arrays are user-defined value types and are not of the same type.
A
System.InvalidCastException
At least one of the elements in sourceArray is not assignmentcompatible with the type of destinationArray.
System.ArgumentOutOfRangeException
length < 0.
System.ArgumentException
length > sourceArray.Length. -orlength > destinationArray.Length.
B
E F G H I J K L M N O P Q
Example
R
using System;
S namespace Samples { public class ArrayCopy { public static void Main() { int[] ints = new int[]{1, 3, 5}; double[] doubles = new double[3]; Array.Copy(ints, doubles, 2); Console.WriteLine("First array elements: " ); foreach(int i in ints) Console.Write("{0,3}", i); Console.WriteLine(); Console.WriteLine("Copied array elements: " );
T U V W X Y Z
101
Contents | Index
Array
System
Copy() Method
foreach(double d in doubles) Console.Write("{0,3}", d); } }
A
}
B
The output is
C
First array elements: 1 3 5 Copied array elements: 1 3 0
D E F G H
Array.Copy(System.Array, System.Array, System.Int64) Method
I
[ILASM]
J
.method public hidebysig static void Copy(class System.Array sourceArray, class System.Array destinationArray, int64 length)
K
[C#]
public static void Copy(Array sourceArray, Array destinationArray, long length)
L M
Summary
N
Copies a range of elements from a System.Array starting at the first element and pastes them into another System.Array starting at the first element. The length is specified as a 64-bit integer.
O P
Parameters
Q R
Parameter
Description
T
sourceArray
The System.Array that contains the data to copy.
U
destinationArray
The System.Array that receives the data.
V
length
A 64-bit integer that represents the number of elements to copy.
S
W X
Description
Y
The sourceArray and destinationArray parameters must have the same number of dimensions. When copying between multidimensional arrays, the array behaves like a long onedimensional array, where the rows (or columns) are conceptually laid end to end. For example, if an array has three rows (or columns) with four elements each, copying six ele-
Z
102
Contents | Index
System
Array Copy() Method
ments from the beginning of the array would copy all four elements of the first row (or column) and the first two elements of the second row (or column). If sourceArray and destinationArray overlap, this method behaves as if the original values of sourceArray were preserved in a temporary location before destinationArray is overwritten. This method is equivalent to the standard C/C++ function memmove, not memcpy. The arrays can be reference-type arrays or value-type arrays. Type downcasting is performed, as required. •
•
•
A B C D E
When copying from a reference-type array to a value-type array, each element is unboxed and then copied. When copying from a value-type array to a reference-type array, each element is boxed and then copied. When copying from a reference-type or value-type array to a System.Object array, a System.Object is created to hold each value or reference and then copied. When copying from a System.Object array to a reference-type or value-type array and the assignment is not possible, a System.InvalidCastException is thrown. If sourceArray and destinationArray are both reference-type arrays or are both arrays of type System.Object, a shallow copy is performed. A shallow copy of a System.Array is a new System.Array containing references to the same elements as the original System.Array. The elements themselves or anything referenced by the elements are not copied. In contrast, a deep copy of a System.Array copies the elements and everything directly or indirectly referenced by the elements.
F G H I J K L M N O
A System.ArrayTypeMismatchException is thrown if the arrays are of incompatible types. Type compatibility is defined as follows:
P Q
• •
•
•
A type is compatible with itself. A value type is compatible with System.Object and with an interface type implemented by that value type. A value type is considered connected to an interface only if it implements that interface directly. Disconnected types are not compatible. Two intrinsic (predefined) value types are compatible if copying from the source type to the destination type is a widening conversion. A widening conversion never loses information, whereas a narrowing conversion can lose information. For example, converting a 32-bit signed integer to a 64-bit signed integer is a widening conversion, and converting a 64-bit signed integer to a 32-bit signed integer is a narrowing conversion. For more information about conversions, see System.Convert. A nonintrinsic (user-defined) value type is compatible only with itself.
R S T U V W X Y Z
103
Contents | Index
Array
System
CopyTo() Method
If every element in sourceArray requires a downcast (for example, from a base class to a derived class or from an interface to an object) and one or more elements cannot be cast to the corresponding type in destinationArray, a System.InvalidCastException is thrown. If this method throws an exception while copying, the state of destinationArray is undefined.
A B C
Exceptions
D
Exception
E F
Condition sourceArray is null.
System.ArgumentNullException
G
-ordestinationArray is null.
H I J K L M N O
System.RankException
sourceArray and destinationArray have different ranks.
System.ArrayTypeMismatchException
sourceArray and destinationArray are of incompatible types.
System.InvalidCastException
At least one element in sourceArray cannot be cast to the type of destinationArray.
System.ArgumentOutOfRangeException
length is less than zero. length is greater than the number of elements in sourceArray.
P
System.ArgumentException
Q
-orlength is greater than the number of elements in destinationArray.
R S T
Array.CopyTo(System.Array, System.Int32) Method
U
[ILASM]
V
.method public hidebysig virtual void CopyTo(class System.Array array, int32 index)
W
[C#]
public virtual void CopyTo(Array array, int index)
X Y
Summary
Z
Copies all the elements of the current instance to the specified one-dimensional array starting at the specified subscript in the destination array.
104
Contents | Index
System
Array CopyTo() Method
Parameters Parameter
Description
array
A one-dimensional System.Array that is the destination of the elements copied from the current instance.
index
A System.Int32 that contains the relative zero-based index in array at which copying begins.
A B C D E
Description
F
index is an array index at which copying begins. [Note: This method is implemented to support the System.Collections.ICollection interface. If implementing System.Collections.ICollection is not explicitly required, use System.Array.Copy to avoid an extra indirection. If the index of array is zero-based, this value is the same as the actual index at which copying begins. If the lower bound of array is not zero, the value of index is added to the lower bound of array to get the actual index at which copying begins. For example, if the lower bound of array is 2 and the value of index is 1, the copying actually starts at index 3. If this method throws an exception while copying, the state of array is undefined.]
G H I J K L M N
Exceptions
O
Exception
Condition
System.ArgumentNullException
array is null.
System.RankException
The current instance has more than one dimension.
S
System.ArgumentOutOfRangeException
index < 0.
T
System.ArgumentException
array has more than one dimension. -orindex is greater than or equal to array.Length. -orThe number of elements in the current instance is greater than the available space from index to the end of array.
W
The type of the current instance cannot be cast automatically to the type of array.
Z
P Q R
U
System.ArrayTypeMismatchException
V
X Y
105
Contents | Index
Array
System
CopyTo() Method
Example using System; namespace Samples { public class ArrayCopyTo { public static void Main() { object[] objects1 = {"one", "two", "three"}; object[] objects2 = {0, 1, 2, 3, 4, 5}; Console.WriteLine("First array elements:"); foreach(object o in objects1) Console.Write("{0} ", o); Console.WriteLine(); Console.WriteLine("Second array elements:"); foreach(object o in objects2) Console.Write("{0} ", o); Console.WriteLine(); objects1.CopyTo(objects2, 1); Console.WriteLine("Second array elements:"); foreach(object o in objects2) Console.Write("{0} ", o); } } }
A B C D E F G H I J K L M N
The output is
O
First array elements: one two three Second array elements: 0 1 2 3 4 5 Second array elements: 0 one two three 4 5
P Q R S T
Array.CopyTo(System.Array, System.Int64) Method
U [ILASM]
V
.method public hidebysig virtual void CopyTo(class System.Array array, int64 index)
W
[C#]
X
public virtual void CopyTo(Array array, long index)
Y
Summary
Z
Copies all the elements of the current one-dimensional System.Array to the specified one-dimensional System.Array starting at the specified destination System.Array index. The index is specified as a 64-bit integer. 106
Contents | Index
System
Array CopyTo() Method
Parameters Parameter
Description
array
The one-dimensional System.Array that is the destination of the elements copied from the current System.Array.
index
A 64-bit integer that represents the index in array at which copying begins.
A B C D E
Description
F
This method supports the System.Collections.ICollection interface. If implementing System.Collections.ICollection is not explicitly required, use System.Array.Copy to avoid an extra indirection. If this method throws an exception while copying, the state of array is undefined.
G H I J
Exceptions
K
Exception
Condition
System.ArgumentNullException
array is null.
System.ArgumentOutOfRangeException
index is less than the lower bound of array.
L M N O P
The source System.Array is multidimensional.
Q
-or-
R
array is multidimensional. System.ArgumentException
System.ArrayTypeMismatchException
S
-orindex is equal to or greater than the length of array.
T
-or-
U
The number of elements in the source System.Array is greater than the available space from index to the end of the destination array.
V W X
The type of the source System.Array cannot be cast automatically to the type of the destination array.
Y Z
107
Contents | Index
Array
System
CreateInstance() Method
Array.CreateInstance(System.Type, System.Int32) Method [ILASM]
A
.method public hidebysig static class System.Array CreateInstance(class System.Type elementType, int32 length)
B
[C#]
public static Array CreateInstance(Type elementType, int length)
C D
Summary
E
Constructs a zero-based, one-dimensional array with the specified number of elements of the specified type.
F G
Parameters
H I J
Parameter
Description
elementType
The System.Type of the elements contained in the new System.Array instance.
length
A System.Int32 that contains the number of elements contained in the new System.Array instance.
K L M N
Description
O
Reference-type elements will be set to null. Value-type elements will be set to zero, except for System.Boolean elements, which will be set to false. [Note: Unlike most classes, System.Array provides the System.Array.CreateInstance method, instead of public constructors, to allow for late bound access.]
P Q R S
Exceptions
T U
Exception
Condition
V
System.ArgumentNullException
elementType is null.
System.ArgumentException
elementType is not a valid System.Type.
System.ArgumentOutOfRangeException
length < 0.
W X Y Z
108
Contents | Index
System
Array CreateInstance() Method
Example using System; namespace Samples { public class ArrayCreateInstance { public static void Main() { Array a = Array.CreateInstance(typeof(int),5); for(int i= a.GetLowerBound(0); i<= a.GetUpperBound(0); i++) a.SetValue(i*3,i); Console.Write("Array elements:"); foreach(int i in a) Console.Write("{0} ",i); } } }
A B C D E F G H I J
The output is
K L
Array elements:0 3 6 9 12
M N
Array.CreateInstance(System.Type, System.Int32, System.Int32) Method
O [ILASM]
P
.method public hidebysig static class System.Array CreateInstance(class System.Type elementType, int32 length1, int32 length2) [C#]
Q
public static Array CreateInstance(Type elementType, int length1, int length2)
R S
Summary
T
Creates a zero-based, two-dimensional array of the specified System.Type and dimension lengths.
U V W X Y Z
109
Contents | Index
Array
System
CreateInstance() Method
Parameters Parameter
Description
elementType
The System.Type of the elements contained in the new System.Array instance.
length1
A System.Int32 that contains the number of elements contained in the first dimension of the new System.Array instance.
length2
A System.Int32 that contains the number of elements contained in the second dimension of the new System.Array instance.
A B C D E F G H
Return Value
I
A new zero-indexed, two-dimensional System.Array instance of elementType objects with the size length1 for the first dimension and length2 for the second.
J K
Description
L
Reference-type elements will be set to null. Value-type elements will be set to zero, except for System.Boolean elements, which will be set to false. [Note: Unlike most classes, System.Array provides the System.Array.CreateInstance method, instead of public constructors, to allow for late bound access.] This member must be implemented if the Extended Array Library is present in the implementation.
M N O P
Exceptions
Q R
Exception
Condition
System.ArgumentNullException
elementType is null.
System.ArgumentException
elementType is not a valid System.Type.
System.ArgumentOutOfRangeException
-or-
S T U
length1 < 0.
V W
length2 < 0.
X Y Z
110
Contents | Index
System
Array CreateInstance() Method
Example using System; namespace Samples { public class ArrayCreateInstance { public static void Main() { Array a = Array.CreateInstance(typeof(int), 5, 3); for(int i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i++ ) { for(int j = a.GetLowerBound(1); j <= a.GetUpperBound(1); j++) { a.SetValue((10*i + j), i, j ); } } Console.WriteLine("The elements of the array are:"); for(int i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i++) { for(int j = a.GetLowerBound(1); j <= a.GetUpperBound(1); j++) { Console.Write("{0, 2} ", a.GetValue(i, j)); } Console.WriteLine(); } } } }
A B C D E F G H I J K L M N O P Q R S
The output is
T U
The elements of the array are: 0 1 2 10 11 12 20 21 22 30 31 32 40 41 42
V W X Y Z
111
Contents | Index
Array
System
CreateInstance() Method
Array.CreateInstance(System.Type, System.Int32, System.Int32, System.Int32) Method [ILASM]
A
.method public hidebysig static class System.Array CreateInstance(class System.Type elementType, int32 length1, int32 length2, int32 length3)
B
[C#]
C
public static Array CreateInstance(Type elementType, int length1, int length2, int length3)
D E
Summary
F
Creates a zero-based, three-dimensional array of the specified System.Type and dimension lengths.
G H
Parameters
I J
Parameter
Description
elementType
The System.Type of the elements contained in the new System.Array instance.
length1
A System.Int32 that contains the number of elements contained in the first dimension of the new System.Array instance.
length2
A System.Int32 that contains the number of elements contained in the second dimension of the new System.Array instance.
length3
A System.Int32 that contains the number of elements contained in the third dimension of the new System.Array instance.
K L M N O P Q R S
Return Value
T
A new zero-based, three-dimensional System.Array instance of elementType objects with the size length1 for the first dimension, length2 for the second, and length3 for the third.
U V
Description
W
Reference-type elements will be set to null. Value-type elements will be set to zero, except for System.Boolean elements, which will be set to false. [Note: Unlike most classes, System.Array provides the System.Array.CreateInstance method, instead of public constructors, to allow for late bound access.] This member must be implemented if the Extended Array Library is present in the implementation.
X Y Z
112
Contents | Index
System
Array CreateInstance() Method
Exceptions Exception
Condition
System.ArgumentNullException
elementType is null.
System.ArgumentException
elementType is not a valid System.Type.
C
length1 < 0.
D
-or-
E
length2 < 0.
F
A
System.ArgumentOutOfRangeException
B
-or-
G
length3 < 0.
H I
Example
J
using System;
K namespace Samples { public class ArrayCreateInstance { public static void Main() { int i, j, k; Array a = Array.CreateInstance(typeof(int), 2, 4, 3); for(i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i++) { for(j = a.GetLowerBound(1); j <= a.GetUpperBound(1); j++) { for(k = a.GetLowerBound(2); k <= a.GetUpperBound(2); k++) { a.SetValue((100*i + 10*j + k), i, j, k ); } } } Console.WriteLine("The elements of the array are:"); for(i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i++) { for(j = a.GetLowerBound(1); j <= a.GetUpperBound(1); j++)
L M N O P Q R S T U V W X Y Z
113
Contents | Index
Array
System
CreateInstance() Method
{ for(k = a.GetLowerBound(2); k <= a.GetUpperBound(2); k++ ) { Console.Write("{0, 3} ", a.GetValue(i, j, k)); } Console.WriteLine();
A B C
} Console.WriteLine();
D
} }
E }
F
}
G
The output is
H The elements of the array are: 0 1 2 10 11 12 20 21 22 30 31 32
I J K L
100 110 120 130
M N
101 111 121 131
102 112 122 132
O P
Array.CreateInstance(System.Type, System.Int32[]) Method
Q [ILASM]
R
.method public hidebysig static class System.Array CreateInstance(class System.Type elementType, class System.Int32[] lengths)
S
[C#]
T
public static Array CreateInstance(Type elementType, params int[] lengths)
U
Summary
V
Creates a zero-based, multidimensional array of the specified System.Type and dimension lengths.
W X Y Z
114
Contents | Index
System
Array CreateInstance() Method
Parameters Parameter
Description
elementType
The System.Type of the elements contained in the new System.Array instance.
lengths
A one-dimensional array of System.Int32 objects that contains the size of each dimension of the new System.Array instance.
A B C D E
Return Value
F
A new zero-based, multidimensional System.Array instance of the specified System.Type with the specified length for each dimension. The System.Array.Rank of the new instance is equal to lengths.Length.
G H
Description
J
The number of elements in lengths is required to equal the number of dimensions in the new System.Array instance. Each element of lengths specifies the length of the corresponding dimension in the new instance. Reference-type elements will be set to null. Value-type elements will be set to zero, except for System.Boolean elements, which will be set to false. [Note: Unlike most classes, System.Array provides the System.Array.CreateInstance method, instead of public constructors, to allow for late bound access.] This member must be implemented if the Extended Array Library is present in the implementation.
K
I
L M N O P Q
Exceptions
R
Exception
Condition
System.ArgumentNullException
elementType or lengths is null.
S T U
elementType is not a valid System.Type. System.ArgumentException
V
-or-
W
lengths.Length = 0.
X System.ArgumentOutOfRangeException
A value in lengths is less than zero.
Y Z
115
Contents | Index
Array
System
CreateInstance() Method
Example using System; namespace Samples { public class ArrayCreateInstance { public static void Main() { int[] ints = {2, 4, 5}; Array a = Array.CreateInstance(typeof(int), ints); for(int i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i++) { for(int j = a.GetLowerBound(1); j <= a.GetUpperBound(1); j++) { for(int k = a.GetLowerBound(2); k <= a.GetUpperBound(2); k++) { a.SetValue((100*i + 10*j + k), i, j, k ); } } } Console.WriteLine("The elements of the array are:"); for(int i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i++) { for(int j = a.GetLowerBound(1); j <= a.GetUpperBound(1); j++) { for(int k = a.GetLowerBound(2); k <= a.GetUpperBound(2); k++ ) { Console.Write("{0, 3} ", a.GetValue(i, j, k)); } Console.WriteLine(); } Console.WriteLine(); } } } }
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
116
Contents | Index
System
Array CreateInstance() Method
The output is The elements of the array are: 0 1 2 3 4 10 11 12 13 14 20 21 22 23 24 30 31 32 33 34
A B C
100 110 120 130
101 111 121 131
102 112 122 132
103 113 123 133
104 114 124 134
D E F G
Array.CreateInstance(System.Type, System.Int32[], System.Int32[]) Method
H
[ILASM]
I
.method public hidebysig static class System.Array CreateInstance(class System.Type elementType, class System.Int32[] lengths, class System.Int32[] lowerBounds)
J K
[C#]
L
public static Array CreateInstance(Type elementType, int[] lengths, int[] lowerBounds)
M
Summary
N
Creates a multidimensional array of the specified System.Type and dimension lengths, with the specified lower bounds.
O P Q
Parameters
R
Parameter
Description
elementType
The System.Type of the elements contained in the new System.Array instance.
lengths
A one-dimensional array of System.Int32 objects that contains the size of each dimension of the new System.Array instance.
lowerBounds
A one-dimensional array of System.Int32 objects that contains the lower bound of each dimension of the new System.Array instance.
S T U V W X Y Z
117
Contents | Index
Array
System
CreateInstance() Method
Description The lengths and lowerBounds are required to have the same number of elements. The number of elements in lengths equals the number of dimensions in the new System.Array instance. Each element of lengths specifies the length of the corresponding dimension in the new System.Array instance. Each element of lowerBounds specifies the lower bound of the corresponding dimension in the new System.Array instance. Reference-type elements will be set to null. Value-type elements will be set to zero, except for System.Boolean elements, which will be set to false. [Note: Unlike most classes, System.Array provides the System.Array.CreateInstance method, instead of public constructors, to allow for late bound access.] This member must be implemented if the Extended Array Library is present in the implementation.
A B C D E F G H I
Exceptions
J K
Exception
Condition
L
System.ArgumentNullException
elementType, lengths, or lowerBounds is null.
M
elementType is not a valid System.Type.
N
-or-
O
System.ArgumentException
lengths.Length = 0.
P
-or-
Q
lengths and lowerBounds do not contain the same number of elements.
R System.ArgumentOutOfRangeException
S
A value in lengths is less than zero.
T U
Example
V
using System;
W
namespace Samples { public class ArrayCreateInstance { public static void Main() { int[] indexArray = {4, 2, 3}; int[] lowboundArray = {3, 2, 1};
X Y Z
118
Contents | Index
System
Array CreateInstance() Method
Array a = Array.CreateInstance( typeof(int), indexArray, lowboundArray); for(int i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i++ ) { for(int j = a.GetLowerBound(1); j <= a.GetUpperBound(1); j++) { for(int k = a.GetLowerBound(2); k <= a.GetUpperBound(2); k++ ) { a.SetValue((100*i + 10*j + k), i, j, k ); } } } Console.WriteLine("The elements of the array are:"); for(int i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i++) { for(int j = a.GetLowerBound(1); j <= a.GetUpperBound(1); j++) { for(int k = a.GetLowerBound(2); k <= a.GetUpperBound(2); k++ ) { Console.Write("{0, 3} ", a.GetValue(i, j, k)); } Console.WriteLine(); } Console.WriteLine(); }
A B C D E F G H I J K L M N O P Q
} }
R
}
S
The output is
T U
The elements of the array are: 321 322 323 331 332 333
V W
421 422 423 431 432 433
X Y
521 522 523 531 532 533
Z
621 622 623 631 632 633
119
Contents | Index
Array
System
CreateInstance() Method
Array.CreateInstance(System.Type, System.Int64[]) Method [ILASM]
A
.method public hidebysig static class System.Array CreateInstance(class System.Type elementType, class System.Int64[] lengths)
B
[C#]
public static Array CreateInstance(Type elementType, params long[] lengths)
C D
Summary
E
Creates a multidimensional System.Array of the specified System.Type and dimension lengths, with zero-based indexing. The dimension lengths are specified in an array of 64-bit integers.
F G
Parameters
H I
Parameter
Description
elementType
The System.Type of the System.Array to create.
lengths
An array of 64-bit integers that represent the size of each dimension of the System.Array to create.
J K L M N
Description
O
Unlike most classes, System.Array provides the System.Array.CreateInstance method, instead of public constructors, to allow for late bound access. The number of elements in the lengths array must equal the number of dimensions in the new System.Array. Each element of the lengths array must specify the length of the corresponding dimension in the new System.Array. Reference-type elements are initialized to null. Value-type elements are initialized to zero.
P Q R S T U V W X Y Z
120
Contents | Index
System
Array GetEnumerator() Method
Exceptions Exception
Condition A
elementType is null. System.ArgumentNullException
B
-or-
C
lengths is null.
D
elementType is not a valid System.Type. System.ArgumentException
E
-orF
The lengths array contains less than one element.
G System.NotSupportedException System.ArgumentOutOfRangeException
elementType is not supported.
H I
Any value in lengths is less than zero.
J K
Array.GetEnumerator() Method
L
[ILASM]
M
.method public hidebysig virtual class System.Collections.IEnumerator GetEnumerator()
N
[C#]
O
public virtual IEnumerator GetEnumerator()
P
Summary
Q
Returns a System.Collections.IEnumerator for the current instance.
R S
Description
T
A System.Collections.IEnumerator grants read-access to the elements of a System.Array. [Note: This method is implemented to support the System.Collections.IEnumerator interface. For more information regarding the use of an enumerator, see System.Collections.IEnumerator.]
U V W X
Behaviors
Y
Initially, the enumerator is positioned before the first element of the current instance. System.Collections.IEnumerator.Reset returns the enumerator to this position. Therefore, after an enumerator is created or after a System.Collections.IEnumera-
Z
121
Contents | Index
Array
System
GetEnumerator() Method
tor.Reset, System.Collections.IEnumerator.MoveNext is required to be called to advance the enumerator to the first element of the collection before reading the value of System.Collections.IEnumerator.Current. The enumerator is in an invalid state if it is positioned before the first element or after the last element of the current instance. Whenever the enumerator is in an invalid state, a call to System.Collections.IEnumerator.Current is required to throw a System.InvalidOperationException. System.Collections.IEnumerator.Current returns the same object until either System.Collections.IEnumerator.MoveNext or System.Collections.IEnumerator.Reset is called. Once the enumerator of the current instance is moved immediately past the last element of the current instance, subsequent calls to System.Collections.IEnumerator.MoveNext return false and the enumerator remains positioned immediately past the last element.
A B C D E F G H I
Default
J
Multidimensional arrays will be processed in row-major form. [Note: For some multidimensional System.Array objects, it may be desirable for an enumerator to process them in column-major form.]
K L M
How and When to Override
N
Override this method to provide read-access to the current instance.
O P
Usage
Q
Use this method to iterate over the elements of the current instance.
R
Example
S
using System; using System.Collections;
T U
namespace Samples { public class ArrayGetEnumerator { public static void Main() { string[,] strings = {{"1","one"}, {"2", "two"}, {"3", "three"}}; Console.WriteLine("Array elements:" ); IEnumerator e = strings.GetEnumerator(); while(e.MoveNext())
V W X Y Z
122
Contents | Index
System
Array GetLength() Method
Console.Write("{0} ", e.Current); Console.WriteLine(); } }
A
}
B
The output is
C
Array elements: 1 one 2 two 3 three
D E F
Array.GetLength(System.Int32) Method
G
[ILASM]
H
.method public hidebysig instance int32 GetLength(int32 dimension)
I
[C#]
public int GetLength(int dimension)
J
Summary
K
Gets a 32-bit integer that represents the number of elements in the specified dimension of the System.Array.
L M N
Parameters
O
Parameter
Description
P
dimension
A zero-based dimension of the System.Array whose length needs to be determined.
Q R S
Description
T
An example of System.Array.GetLength is GetLength(0), which returns the number of elements in the first dimension of the System.Array.
U V
Exceptions Exception
W X
Condition
Y
dimension is less than zero. System.IndexOutOfRangeException
Z
-ordimension is equal to or greater than System.Array.Rank.
123
Contents | Index
Array
System
GetLongLength() Method
Array.GetLongLength(System.Int32) Method [ILASM]
.method public hidebysig instance int64 GetLongLength(int32 dimension)
A
[C#]
public long GetLongLength(int dimension)
B C
Summary
D
Gets a 64-bit integer that represents the number of elements in the specified dimension of the System.Array.
E F
Parameters
G H
Parameter
Description
dimension
A zero-based dimension of the System.Array whose length needs to be determined.
I J K L
Description
M
An example of System.Array.GetLength is GetLength(0), which returns the number of elements in the first dimension of the System.Array.
N O
Exceptions
P
Exception
Q R
Condition dimension is less than zero.
System.IndexOutOfRangeException
S
-ordimension is equal to or greater than System.Array.Rank.
T U V
Array.GetLowerBound(System.Int32) Method
W
[ILASM]
X
.method public hidebysig instance int32 GetLowerBound(int32 dimension)
Y
[C#]
public int GetLowerBound(int dimension)
Z
124
Contents | Index
System
Array GetLowerBound() Method
Summary Returns the lower bound of the specified dimension in the current instance. A
Parameters
B
Parameter
Description
C
dimension
A System.Int32 that contains the zero-based dimension of the current instance whose lower bound is to be determined.
D E F
Description
G
[Note: For example, System.Array.GetLowerBound(0) returns the lower bound of the first dimension of the current instance, and System.Array.GetLowerBound(System.Array.Rank–1) returns the lower bound of the last dimension of the current instance.] This member must be implemented if the Runtime Infrastructure Library is present in the implementation.
H I J K L
Exceptions
M
Exception
System.IndexOutOfRangeException
Condition
N
dimension < 0.
O
-or-
P
dimension is equal to or greater than the System.Array.Rank property of the current instance.
Q R S
Example
T
using System;
U namespace Samples { public class ArrayGetLowerBound { public static void Main() { string[] strings = new string[42]; Console.WriteLine("Single Dimension Lower Bound {0}", strings.GetLowerBound(0)); int[] indexArray = {4, 2, 3}; int[] lowboundArray = {3, 2, 1};
V W X Y Z
125
Contents | Index
Array
System
GetUpperBound() Method
Array a = Array.CreateInstance( typeof(int), indexArray, lowboundArray); Console.WriteLine("Dimension 0 Lower Bound {0}", a.GetLowerBound(0)); Console.WriteLine("Dimension 1 Lower Bound {0}", a.GetLowerBound(1)); Console.WriteLine("Dimension 2 Lower Bound {0}", a.GetLowerBound(2));
A B C }
D
} }
E
The output is
F G
Single Dimension Lower Bound 0 Dimension 0 Lower Bound 3 Dimension 1 Lower Bound 2 Dimension 2 Lower Bound 1
H I J K
Array.GetUpperBound(System.Int32) Method
L [ILASM]
M
.method public hidebysig instance int32 GetUpperBound(int32 dimension) [C#]
N
public int GetUpperBound(int dimension)
O
Summary
P
Returns the upper bound of the specified dimension in the current instance.
Q R
Parameters
S T U
Parameter
Description
dimension
A System.Int32 that contains the zero-based dimension of the current instance whose upper bound is to be determined.
V W
Description
X
[Note: For example, System.Array.GetUpperBound(0) returns the upper bound of the first dimension of the current instance, and System.Array.GetUpperBound(System.Array.Rank–1) returns the upper bound of the last dimension of the current instance.] This member must be implemented if the Runtime Infrastructure Library is present in the implementation.
Y Z
126
Contents | Index
System
Array GetUpperBound() Method
Exceptions Exception
Condition A
dimension < 0. System.IndexOutOfRangeException
B
-orC
dimension is equal to or greater than the System.Array.Rank property of the current instance.
D E
Example
F
using System;
G
namespace Samples { public class ArrayGetUpperBound { public static void Main() { string[] strings = new string[42]; Console.WriteLine("Single Dimension Upper Bound {0}", strings.GetUpperBound(0)); int[] indexArray = {4, 2, 3}; int[] lowboundArray = {3, 2, 1}; Array a = Array.CreateInstance( typeof(int), indexArray, lowboundArray); Console.WriteLine("Dimension 0 Upper Bound {0}", a.GetUpperBound(0)); Console.WriteLine("Dimension 1 Upper Bound {0}", a.GetUpperBound(1)); Console.WriteLine("Dimension 2 Upper Bound {0}", a.GetUpperBound(2)); } } }
H I J K L M N O P Q R S T U V
The output is
W Single Dimension Upper Bound 41 Dimension 0 Upper Bound 6 Dimension 1 Upper Bound 3 Dimension 2 Upper Bound 3
X Y Z
127
Contents | Index
Array
System
GetValue() Method
Array.GetValue(System.Int32) Method [ILASM]
.method public hidebysig instance object GetValue(int32 index)
A
[C#]
public object GetValue(int index)
B C
Summary
D
Gets the value at the specified position in the current one-dimensional instance.
E
Parameters
F G
Parameter
Description
index
A System.Int32 that contains the position of the value to get from the current instance.
H I J K
Description
L
[Note: Use the System.Array.GetLowerBound and System.Array.GetUpperBound methods to determine whether index is out of bounds.]
M N
Exceptions
O P
Exception
Condition
System.ArgumentException
The current instance has more than one dimension.
System.IndexOutOfRangeException
index is outside the range of valid indices for the current instance.
Q R S T U
Example
V
using System;
W namespace Samples { public class ArrayGetValue { public static void Main() { String[] strings = {"one", "two", "three", "four"};
X Y Z
128
Contents | Index
System
Array GetValue() Method
Console.Write("Array elements: " ); for(int i = 0; i < strings.Length; i++) Console.Write("{0} {1}, ", strings.GetValue(i), strings[i]);
A
} }
B
}
C
The output is
D E
Array elements: one one, two two, three three, four four,
F G
Array.GetValue(System.Int32, System.Int32) Method
H
[ILASM]
I
.method public hidebysig instance object GetValue(int32 index1, int32 index2) [C#]
J
public object GetValue(int index1, int index2)
K
Summary
L
Gets the value at the specified position in the current two-dimensional instance.
M
Parameters
N
Parameter
Description
index1
A System.Int32 that contains the first-dimension index of the element in the current instance to get.
index2
A System.Int32 that contains the second-dimension index of the element in the current instance to get.
O P Q R S T
Description
U
[Note: Use the System.Array.GetLowerBound and System.Array.GetUpperBound methods to determine whether any of the indices are out of bounds.]
V W X Y Z
129
Contents | Index
Array
System
GetValue() Method
Exceptions Exception
Condition
System.ArgumentException
The current instance does not have exactly two dimensions.
System.IndexOutOfRangeException
At least one of index1 or index2 is outside the range of valid indexes for the corresponding dimension of the current instance.
A B C D E F
Example
G
using System;
H
namespace Samples { public class ArrayGetValue { public static void Main() { String[,] strings = {{"one", "two", "three"}, {"four", "five", "six"}}; Console.WriteLine("Value at strings.GetValue(1, 1) is: {0}", strings.GetValue(1, 1)); Console.WriteLine("Value at strings[1, 1] is: {0}", strings[1, 1]); } } }
I J K L M N O P Q R
The output is
S
Value at strings.GetValue(1, 1) is: five Value at strings[1, 1] is: five
T U V
Array.GetValue(System.Int32, System.Int32, System.Int32) Method
W
[ILASM]
X
.method public hidebysig instance object GetValue(int32 index1, int32 index2, int32 index3)
Y
[C#]
Z
public object GetValue(int index1, int index2, int index3)
130
Contents | Index
System
Array GetValue() Method
Summary Gets the value at the specified position in the current three-dimensional instance. A
Parameters
B
Parameter
Description
C
A System.Int32 that contains the first-dimension index of the element in the current instance to get.
D
index1
index2
A System.Int32 that contains the second-dimension index of the element in the current instance to get.
F
index3
A System.Int32 that contains the third-dimension index of the element in the current instance to get.
E
G H I J
Description
K
[Note: Use the System.Array.GetLowerBound and System.Array.GetUpperBound methods to determine whether any of the indices are out of bounds.] This member must be implemented if the Extended Array Library is present in the implementation.
L M N
Exceptions
O
Exception
Condition
P
System.ArgumentException
The current instance does not have exactly three dimensions.
Q
At least one of index1 or index2 or index3 is outside the range of valid indexes for the corresponding dimension of the current instance.
R
System.IndexOutOfRangeException
S T U
Example
V
using System;
W namespace Samples { public class ArrayGetValue { public static void Main() { int[] indexArray = {4, 2, 3}; int[] lowboundArray = {3, 2, 1};
X Y Z
131
Contents | Index
Array
System
GetValue() Method
Array a = Array.CreateInstance( typeof(int), indexArray, lowboundArray); for(int i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i++ ) { for(int j = a.GetLowerBound(1); j <= a.GetUpperBound(1); j++) { for(int k = a.GetLowerBound(2); k <= a.GetUpperBound(2); k++ ) { a.SetValue((100*i + 10*j + k), i, j, k ); } } } Console.WriteLine("Value at 3, 2, 2 is: {0}", a.GetValue(3, 2, 2));
A B C D E F G H }
I
} }
J K
The output is
L
Value at 3, 2, 2 is: 322
M N
Array.GetValue(System.Int32[]) Method
O [ILASM]
P
.method public hidebysig instance object GetValue(class System.Int32[] indices) [C#]
Q
public object GetValue(params int[] indices)
R
Summary
S
Gets the value at the specified position in the current multidimensional instance.
T
Parameters
U V
Parameter
Description
indices
A one-dimensional array of System.Int32 objects that contains the indices that specify the position of the element in the current instance whose value to get.
W X Y Z
132
Contents | Index
System
Array GetValue() Method
Description The number of elements in indices is required to be equal to the number of dimensions in the current instance. All elements in indices collectively specify the position of the desired element in the current instance. [Note: Use the System.Array.GetLowerBound and System.Array.GetUpperBound methods to determine whether any of the values in indices are out of bounds.] This member must be implemented if the Extended Array Library is present in the implementation.
A B C D
Exceptions
E
Exception
Condition
System.ArgumentNullException
indices is null.
System.ArgumentException
The number of dimensions in the current instance is not equal to the number of elements in indices.
System.IndexOutOfRangeException
At least one element in indices is outside the range of valid indices for the corresponding dimension of the current instance.
F G H I J K L M
Example
N
using System;
O
namespace Samples { public class ArrayGetValue { public static void Main() { int[] indexArray = {4, 2, 3}; int[] lowboundArray = {3, 2, 1}; Array a = Array.CreateInstance( typeof(int), indexArray, lowboundArray); for(int i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i++ ) { for(int j = a.GetLowerBound(1); j <= a.GetUpperBound(1); j++) { for(int k = a.GetLowerBound(2); k <= a.GetUpperBound(2); k++ ) { a.SetValue((100*i + 10*j + k), i, j, k ); } }
P Q R S T U V W X Y Z
133
Contents | Index
Array
System
GetValue() Method
} Console.WriteLine("Value at 3, 2, 2 is: {0}", a.GetValue(new int[]{3, 2, 2})); }
A
} }
B
The output is
C D
Value at 3, 2, 2 is: 322
E F
Array.GetValue(System.Int64) Method
G [ILASM]
H
.method public hidebysig instance object GetValue(int64 index) [C#]
I
public object GetValue(long index)
J K
Summary
L
Gets the value at the specified position in the one-dimensional System.Array. The index is specified as a 64-bit integer.
M
Parameters
N O P Q
Parameter
Description
index
A 64-bit integer that represents the position of the System.Array element to get.
R S
Description
T
The System.Array.GetLowerBound and System.Array.GetUpperBound methods can determine whether the value of index is out of bounds.
U
Exceptions
V W
Exception
Condition
System.ArgumentException
The current System.Array does not have exactly one dimension.
System.IndexOutOfRangeException
index is outside the range of valid indexes for the current System.Array.
X Y Z
134
Contents | Index
System
Array GetValue() Method
Array.GetValue(System.Int64, System.Int64) Method [ILASM]
.method public hidebysig instance object GetValue(int64 index1, int64 index2) [C#]
A
public object GetValue(long index1, long index2)
B
Summary
C
Gets the value at the specified position in the two-dimensional System.Array. The indexes are specified as 64-bit integers.
D E F
Parameters
G
Parameter
Description
H
index1
A 64-bit integer that represents the first-dimension index of the System.Array element to get.
I
index2
A 64-bit integer that represents the second-dimension index of the System.Array element to get.
K
J
L M
Description
N
The System.Array.GetLowerBound and System.Array.GetUpperBound methods can determine whether any of the indexes is out of bounds.
O P
Exceptions
Q
Exception
Condition
System.ArgumentException
The current System.Array does not have exactly two dimensions.
System.IndexOutOfRangeException
Either index1 or index2 is outside the range of valid indexes for the corresponding dimension of the current System.Array.
R S T U V W X Y Z
135
Contents | Index
Array
System
GetValue() Method
Array.GetValue(System.Int64, System.Int64, System.Int64) Method [ILASM]
A
.method public hidebysig instance object GetValue(int64 index1, int64 index2, int64 index3)
B
[C#]
public object GetValue(long index1, long index2, long index3)
C D
Summary
E
Gets the value at the specified position in the three-dimensional System.Array. The indexes are specified as 64-bit integers.
F G
Parameters
H I J
Parameter
Description
index1
A 64-bit integer that represents the first-dimension index of the System.Array element to get.
index2
A 64-bit integer that represents the second-dimension index of the System.Array element to get.
index3
A 64-bit integer that represents the third-dimension index of the System.Array element to get.
K L M N O P
Description
Q
The System.Array.GetLowerBound and System.Array.GetUpperBound methods can determine whether any of the indexes is out of bounds.
R S
Exceptions
T U
Exception
Condition
System.ArgumentException
The current System.Array does not have exactly three dimensions.
System.IndexOutOfRangeException
index1 or index2 or index3 is outside the range of valid indexes for the corresponding dimension of the current System.Array.
V W X Y Z
136
Contents | Index
System
Array GetValue() Method
Array.GetValue(System.Int64[]) Method [ILASM]
.method public hidebysig instance object GetValue(class System.Int64[] indices) [C#]
A
public object GetValue(params long[] indices)
B C
Summary
D
Gets the value at the specified position in the multidimensional System.Array. The indexes are specified as an array of 64-bit integers.
E F
Parameters
G H
Parameter
Description
indices
A one-dimensional array of 64-bit integers that represent the indexes specifying the position of the System.Array element to get.
I J K
Description
L
The number of elements in indices must equal the number of dimensions in the System.Array. All elements in the indices array must collectively specify the position of the desired element in the multidimensional System.Array. The System.Array.GetLowerBound and System.Array.GetUpperBound methods can determine whether any of the indexes is out of bounds.
M N O P Q
Exceptions
R
Exception
Condition
System.ArgumentNullException
indices is null.
System.ArgumentException
The number of dimensions in the current System.Array is not equal to the number of elements in indices.
S T
System.IndexOutOfRangeException
U V W X
Any element in indices is outside the range of valid indexes for the corresponding dimension of the current System.Array.
Y Z
137
Contents | Index
Array
System
IndexOf() Method
Array.IndexOf(System.Array, System.Object) Method [ILASM]
A
.method public hidebysig static int32 IndexOf(class System.Array array, object value)
B
[C#]
public static int IndexOf(Array array, object value)
C D
Summary
E
Searches the specified one-dimensional System.Array, returning the index of the first occurrence of the specified System.Object.
F G
Parameters
H I J K
Parameter
Description
array
A one-dimensional System.Array to search.
value
A System.Object to locate in array.
L M
Return Value
N
A System.Int32 containing the index of the first occurrence of value in array, if found; otherwise, array.GetLowerBound(0)–1. [Note: For a vector, if value is not found, the return value will be –1. This provides the caller with a standard code for a failed search.]
O P Q
Description
R
This version of System.Array.IndexOf is equivalent to System.Array.IndexOf(array, value, array.GetLowerBound(0), array.Length). The elements will be compared using the semantics of the System.Object.Equals method. For user-defined types, System.Object.Equals is actually called.
S T U
Exceptions
V W
Exception
Condition
Y
System.ArgumentNullException
array is null.
Z
System.RankException
array has more than one dimension.
X
138
Contents | Index
System
Array IndexOf() Method
Example using System; namespace Samples { public class ArrayIndexOf { public static void Main() { int[] ints = { 0, 0, 1, 2, 0, 1 }; Console.Write("Array elements: "); foreach(int i in ints) Console.Write("{0,5}", i); Console.WriteLine(); foreach(int i in new int []{0, 1, 2, 3, 4}) Console.WriteLine( "First occurrence of {0} is at {1}", i, Array.IndexOf(ints, i)); } } }
A B C D E F G H I J K L
The output is
M Array First First First First First
elements: occurrence occurrence occurrence occurrence occurrence
of of of of of
0 0 1 2 3 4
is is is is is
0 at at at at at
1
2
0
1
N
0 2 3 -1 -1
O P Q R
Array.IndexOf(System.Array, System.Object, System.Int32) Method
S
[ILASM]
T
.method public hidebysig static int32 IndexOf(class System.Array array, object value, int32 startIndex)
U
[C#]
V
public static int IndexOf(Array array, object value, int startIndex)
W
Summary
X
Searches the specified one-dimensional System.Array, returning the index of the first occurrence of the specified System.Object between the specified index and the last element.
Y Z
139
Contents | Index
Array
System
IndexOf() Method
Parameters Parameter
Description
array
A one-dimensional System.Array to search.
C
value
A System.Object to locate in array.
D
startIndex
A System.Int32 that contains the index at which searching starts.
A B
E F
Return Value
G
A System.Int32 containing the index of the first occurrence of value in array, within the range startIndex through the last element of array, if found; otherwise, array.GetLowerBound(0)–1. [Note: For a vector, if value is not found, the return value will be –1. This provides the caller with a standard code for the failed search.]
H I J K
Description
L
This version of System.Array.IndexOf is equivalent to System.Array.IndexOf (array, value, startIndex, (array.Length – startIndex + array.GetLowerBound(0))). The elements will be compared using the semantics of the System.Object.Equals method. For user-defined types, System.Object.Equals is actually called.
M N O
Exceptions
P Q
Exception
Condition
System.ArgumentNullException
array is null.
System.ArgumentOutOfRangeException
startIndex is outside the range of valid indexes for array.
System.RankException
array has more than one dimension.
R S T U V W
Example
X
using System;
Y namespace Samples { public class ArrayIndexOf {
Z
140
Contents | Index
System
Array IndexOf() Method
public static void Main() { string[] strings = {"one", "two", "three", "four"}; foreach(string s in new string[] {"one", "two", "six"}) Console.WriteLine("{0} is at index: {1}", s, Array.IndexOf(strings, s, 1)); }
A B C
}
D
}
E
The output is
F
one is at index: -1 two is at index: 1 six is at index: -1
G H I J
Array.IndexOf(System.Array, System.Object, System.Int32, System.Int32) Method
K
[ILASM]
L
.method public hidebysig static int32 IndexOf(class System.Array array, object value, int32 startIndex, int32 count)
M
[C#]
N
public static int IndexOf(Array array, object value, int startIndex, int count)
O
Summary
P
Searches the specified one-dimensional System.Array, returning the index of the first occurrence of the specified System.Object in the specified range.
Q R S
Parameters
T
Parameter
Description
array
A one-dimensional System.Array to search.
value
A System.Object to locate in array.
startIndex
A System.Int32 that contains the index at which searching starts.
count
A System.Int32 that contains the number of elements to search, beginning with startIndex.
U V W X Y Z
141
Contents | Index
Array
System
IndexOf() Method
Return Value A System.Int32 containing the index of the first occurrence of value in array, within the range startIndex through startIndex + count – 1, if found; otherwise, array.GetLowerBound(0)–1. [Note: For a vector, if value is not found, the return value will be –1. This provides the caller with a standard code for the failed search.]
A B C
Description
D
The elements will be compared using the semantics of the System.Object.Equals method. For user-defined types, System.Object.Equals is actually called.
E F
Exceptions
G H
Exception
Condition
I
System.ArgumentNullException
array is null.
System.ArgumentOutOfRangeException
startIndex is outside the range of valid indices for array. -orcount < 0. -orThe sum of count and startIndex does not specify a valid range in array (i.e., count + startIndex > array.GetLowerBound(0) + array.Length).
System.RankException
array has more than one dimension.
J K L M N O P Q
Example
R
using System;
S namespace Samples { public class ArrayIndexOf { public static void Main() { string[] strings = {"one", "two", "three", "four"}; foreach(string s in new string[] {"one", "two", "four"}) Console.WriteLine("{0} is at index: {1}", s, Array.IndexOf(strings, s, 1, 2)); } } }
T U V W X Y Z
142
Contents | Index
System
Array Initialize() Method
The output is one is at index: -1 two is at index: 1 four is at index: -1
A B C
Array.Initialize() Method
D
[ILASM]
.method public hidebysig instance void Initialize()
E
[C#]
F
public void Initialize()
G
Summary
H
Initializes every element of the current instance of value-type objects by calling the default constructor of that value type.
I J
Description
K
This method cannot be used on reference-type arrays. If the current instance is not a valuetype System.Array or if the value type does not have a default constructor, the current instance is not modified. The current instance can have any lower bound and any number of dimensions. [Note: This method can be used only on value types that have constructors.] This member must be implemented if the Runtime Infrastructure Library is present in the implementation.
L M N O
Example
P
The following example demonstrates the System.Array.Initialize method. The value type Point, written in Managed C++, has a default constructor.
Q
A value type called Point.
S
R
T
#using <mscorlib.dll>
U namespace Samples { __value public class Point { public: public: int x, y; Point() { x = y = 42; } }; }
V W X Y Z
143
Contents | Index
Array
System
LastIndexOf() Method
A C# program that uses the Point type. using System;
A
namespace Samples { public class ArrayInitialize { public static void Main() { Point[] points = new Point[1]; Console.WriteLine(points[0].x); points.Initialize(); Console.WriteLine(points[0].x); } } }
B C D E F G H I
The output is
J K
0 42
L M N
Array.LastIndexOf(System.Array, System.Object) Method
O
[ILASM]
P
.method public hidebysig static int32 LastIndexOf(class System.Array array, object value)
Q
[C#]
public static int LastIndexOf(Array array, object value)
R S
Summary
T
Searches the specified one-dimensional System.Array, returning the index of the last occurrence of the specified System.Object.
U V
Parameters
W X Y
Parameter
Description
array
A one-dimensional System.Array to search.
value
A System.Object to locate in array.
Z
144
Contents | Index
System
Array LastIndexOf() Method
Return Value A System.Int32 containing the index of the last occurrence in array of value, if found; otherwise, array.GetLowerBound(0)–1. [Note: For a vector, if value is not found, the return value will be –1. This provides the caller with a standard code for the failed search.]
A B
Description
C
This version of System.Array.LastIndexOf is equivalent to System.Array.LastIndexOf(array, value,(array.GetLowerBound(0)+ array.Length–1), array.Length). The elements will be compared using the semantics of the System.Object.Equals method. For user-defined types, System.Object.Equals is actually called.
D E F G
Exceptions
H
Exception
Condition
I
System.ArgumentNullException
array is null.
J
System.RankException
array has more than one dimension.
K L M
Example
N
using System;
O namespace Samples { public class ArrayLastIndexOf { public static void Main() { int[] ints = { 0, 1, 2, 0, 1 }; Console.Write("Array elements: "); foreach(int i in ints) Console.Write("{0,5}", i); Console.WriteLine(); foreach(int i in new int[]{0, 1, 2, 3}) Console.WriteLine( "{0} last occurs at {1}", i, Array.LastIndexOf(ints, i)); } } }
P Q R S T U V W X Y Z
145
Contents | Index
Array
System
LastIndexOf() Method
The output is Array elements: 0 last occurs at 1 last occurs at 2 last occurs at 3 last occurs at
A B
0
1
2
0
1
3 4 2 -1
C D E
Array.LastIndexOf(System.Array, System.Object, System.Int32) Method
F
[ILASM]
G
.method public hidebysig static int32 LastIndexOf(class System.Array array, object value, int32 startIndex) [C#]
H
public static int LastIndexOf(Array array, object value, int startIndex)
I
Summary
J
Searches the specified one-dimensional System.Array, returning the index of the last occurrence of the specified System.Object between the specified index and the first element.
K L M
Parameters
N O
Parameter
Description
array
A one-dimensional System.Array to search.
R
value
A System.Object to locate in array.
S
startIndex
A System.Int32 that contains the index at which searching starts.
P Q
T U
Return Value
V
A System.Int32 containing the index of the last occurrence of value in the range startIndex through the lower bound of array, if found; otherwise, array.GetLowerBound(0)–1. [Note: For a vector, if value is not found, the return value will be –1. This provides the caller with a standard code for the failed search.]
W X Y
Description
Z
This version of System.Array.LastIndexOf is equivalent to System.Array.LastIndexOf(array, value, startIndex,startIndex+1–array.GetLowerBound(0)). 146
Contents | Index
System
Array LastIndexOf() Method
The elements will be compared using the semantics of the System.Object.Equals method. For user-defined types, System.Object.Equals is actually called. A
Exceptions
B
Exception
Condition
System.ArgumentNullException
array is null.
System.ArgumentOutOfRangeException
startIndex is outside the range of valid indices for array.
System.RankException
array has more than one dimension.
C D E F G H I
Example
J
using System;
K
namespace Samples { public class ArrayLastIndexOf { public static void Main() { int[] ints = {0, 1, 1, 2, 2, 1, 0}; foreach(int i in new int[]{0, 1, 2, 3}) Console.WriteLine("{0} last occurs at : {1}", i, Array.LastIndexOf(ints, i, 2)); } } }
L M N O P Q R S
The output is 0 1 2 3
last last last last
occurs occurs occurs occurs
at at at at
T : : : :
U
0 2 -1 -1
V W X Y Z
147
Contents | Index
Array
System
LastIndexOf() Method
Array.LastIndexOf(System.Array, System.Object, System.Int32, System.Int32) Method [ILASM]
A
.method public hidebysig static int32 LastIndexOf(class System.Array array, object value, int32 startIndex, int32 count)
B
[C#]
C
public static int LastIndexOf(Array array, object value, int startIndex, int count)
D E
Summary
F
Searches the specified one-dimensional System.Array, returning the index of the last occurrence of the specified System.Object in the specified range.
G
Parameters
H I
Parameter
Description
K
array
A one-dimensional System.Array to search.
L
value
A System.Object to locate in array.
startIndex
A System.Int32 that contains the index at which searching starts.
count
A System.Int32 that contains the number of elements to search, beginning with startIndex.
J
M N O P Q
Return Value
R
A System.Int32 containing the index of the last occurrence of value in array, within the range startIndex through startIndex – count+1, if found; otherwise, array.GetLowerBound(0)–1. [Note: For a vector, if value is not found, the return value will be –1. This provides the caller with a standard code for the failed search.]
S T U V
Description
W
The elements will be compared using the semantics of the System.Object.Equals method. For user-defined types, System.Object.Equals is actually called.
X Y Z
148
Contents | Index
System
Array LastIndexOf() Method
Exceptions Exception
Condition
System.ArgumentNullException
array is null.
A B
startIndex is outside the range of valid indices for array.
C D
-orSystem.ArgumentOutOfRangeException
count < 0.
E
-or-
F
count and startIndex do not specify a valid range in array.
G H
System.RankException
array has more than one dimension.
I J
Example
K
using System;
L
namespace Samples { public class ArrayLastIndexOf { public static void Main() { int[] ints = {0, 1, 1, 2, 2, 1, 0}; foreach(int i in new int[]{0, 1, 2, 3}) Console.WriteLine("{0} last occurs at : {1}", i, Array.LastIndexOf(ints, i, 5, 4)); } } }
M N O P Q R S T U
The output is
V 0 1 2 3
last last last last
occurs occurs occurs occurs
at at at at
: : : :
-1 5 4 -1
W X Y Z
149
Contents | Index
Array
System
Reverse() Method
Array.Reverse(System.Array) Method [ILASM]
.method public hidebysig static void Reverse(class System.Array array)
A
[C#]
public static void Reverse(Array array)
B C
Summary
D
Reverses the sequence of the elements in the specified one-dimensional System.Array.
E
Parameters
F G
Parameter
Description
array
The one-dimensional System.Array to reverse.
H I J K
Description
L
This version of System.Array.Reverse is equivalent to System.Array.Reverse(array, array.GetLowerBound(0), array.Length).
M N
Exceptions
O
Exception
Condition
Q
System.ArgumentNullException
array is null.
R
System.RankException
array has more than one dimension.
P
S T
Example
U
using System;
V
namespace Samples { public class ArrayReverse { public static void Main() { string[] strings = {"one", "two", "three"}; Console.Write("Array elements: "); foreach(string s in strings) Console.Write("{0} ", s);
W X Y Z
150
Contents | Index
System
Array Reverse() Method
Console.WriteLine(); Array.Reverse(strings); Console.Write("Array elements: "); foreach(string s in strings) Console.Write("{0} ", s);
A
}
B
} }
C
The output is
D E
Array elements: one two three Array elements: three two one
F G
Array.Reverse(System.Array, System.Int32, System.Int32) Method
H I
[ILASM]
.method public hidebysig static void Reverse(class System.Array array, int32 index, int32 length)
J
[C#]
K
public static void Reverse(Array array, int index, int length)
L
Summary
M
Reverses the sequence of the elements in the specified range of the specified one-dimensional System.Array.
N O P
Parameters
Q
Parameter
Description
array
The one-dimensional System.Array to reverse.
index
A System.Int32 that contains the index at which reversing starts.
length
A System.Int32 that contains the number of elements to reverse.
R S T U V W X Y Z
151
Contents | Index
Array
System
Reverse() Method
Exceptions Exception
Condition
B
System.ArgumentNullException
array is null.
C
System.RankException
array is multidimensional.
A
D
System.ArgumentOutOfRangeException
E F
System.ArgumentException
G
index < array.GetLowerBound(0). length < 0. index and length do not specify a valid range in array (i.e., index + length > array.GetLowerBound(0) + array.Length).
H I
Example
J
using System;
K namespace Samples { public class ArrayReverse { public static void Main() { string[] strings = {"one", "two", "three", "four"}; Console.Write("Array elements: "); foreach(string s in strings) Console.Write("{0} ", s); Console.WriteLine(); Array.Reverse(strings, 1, 2); Console.Write("Array elements: "); foreach(string s in strings) Console.Write("{0} ", s); } } }
L M N O P Q R S T U V W
The output is
X Array elements: one two three four Array elements: one three two four
Y Z
152
Contents | Index
System
Array SetValue() Method
Array.SetValue(System.Object, System.Int32) Method [ILASM]
.method public hidebysig instance void SetValue(object value, int32 index) [C#]
A
public void SetValue(object value, int index)
B
Summary
C
Sets the value of the element at the specified position in the current one-dimensional instance.
D E F
Parameters
G
Parameter
Description
value
A System.Object that contains the new value for the specified element.
index
A System.Int32 that contains the index of the element whose value is to be set.
H I J K L
Description
M
[Note: Use the System.Array.GetLowerBound and System.Array.GetUpperBound methods to determine whether index is out of bounds. For more information regarding valid conversions that will be performed by this method, see System.Convert.]
N O P
Exceptions Exception
Q R
Condition
S
The current instance has more than one dimension. System.ArgumentException
System.IndexOutOfRangeException
T
-orvalue is not assignment-compatible with the element type of the current instance.
U
index is outside the range of valid indices for the current instance.
W
V
X Y Z
153
Contents | Index
Array
System
SetValue() Method
Example using System; namespace Samples { public class ArraySetValue { public static void Main() { String[] strings = {"one", "two", "three"}; Console.Write("Array elements: "); foreach(string s in strings) Console.Write("{0} ", s); Console.WriteLine(); strings.SetValue("four", 0); strings.SetValue("five", 1); Console.Write("Array elements: "); foreach(string s in strings) Console.Write("{0} ", s); } } }
A B C D E F G H I J K L
The output is
M N
Array elements: one two three Array elements: four five three
O P Q
Array.SetValue(System.Object, System.Int32, System.Int32) Method
R
[ILASM]
S
.method public hidebysig instance void SetValue(object value, int32 index1, int32 index2) [C#]
T
public void SetValue(object value, int index1, int index2)
U V
Summary
W
Sets the value of the element at the specified position in the current two-dimensional instance.
X Y Z
154
Contents | Index
System
Array SetValue() Method
Parameters Parameter
Description
value
A System.Object that contains the new value for the specified element.
index1
A System.Int32 that contains the first-dimension index of the element in the current instance to set.
index2
A System.Int32 that contains the second-dimension index of the element in the current instance to set.
A B C D E F G
Description
H
[Note: For more information regarding valid conversions that will be performed by this method, see System.Convert. Use the System.Array.GetLowerBound and System.Array.GetUpperBound methods to determine whether any of the indices are out of bounds.] This member must be implemented if the Extended Array Library is present in the implementation.
I J K L
Exceptions Exception
M N
Condition
O
The current instance does not have exactly two dimensions. System.ArgumentException
System.IndexOutOfRange Exception
P
-or-
Q
value is not assignment-compatible with the element type of the current instance.
R S
At least one of index1 or index2 is outside the range of valid indices for the corresponding dimension of the current instance.
T U
Example
V
using System;
W
namespace Samples { public class ArraySetValue { public static void Main() { String[,] strings = {{"one", "two", "three"},
X Y Z
155
Contents | Index
Array
System
SetValue() Method
{"four", "5", "six"}}; Console.WriteLine("The value at 1, 1 is: {0}", strings.GetValue(1,1)); strings.SetValue("five", 1, 1); Console.WriteLine("The value at 1, 1 is: {0}", strings.GetValue(1,1));
A B }
C
} }
D
The output is
E F
The value at 1, 1 is: 5 The value at 1, 1 is: five
G H
Array.SetValue(System.Object, System.Int32, System.Int32, System.Int32) Method
I J
[ILASM]
K
.method public hidebysig instance void SetValue(object value, int32 index1, int32 index2, int32 index3)
L
[C#]
M
public void SetValue(object value, int index1, int index2, int index3)
N O
Summary
P
Sets the value of the element at the specified position in the current three-dimensional instance.
Q
Parameters
R S
Parameter
Description
value
A System.Object that contains the new value for the specified element.
index1
A System.Int32 that contains the first-dimension index of the element in the current instance to set.
index2
A System.Int32 that contains the second-dimension index of the element in the current instance to set.
index3
A System.Int32 that contains the third-dimension index of the element in the current instance to set.
T U V W X Y Z
156
Contents | Index
System
Array SetValue() Method
Description [Note: For more information regarding valid conversions that will be performed by this method, see System.Convert. Use the System.Array.GetLowerBound and System.Array.GetUpperBound methods to determine whether any of the indices are out of bounds.] This member must be implemented if the Extended Array Library is present in the implementation.
A B C D
Exceptions
E
Exception
System.ArgumentException
Condition
F
The current instance does not have exactly three dimensions.
G
-or-
H
value is not assignment-compatible with the element type of the current instance.
I J
System.IndexOutOfRangeException
At least one of index1, index2, or index3 is outside the range of valid indices for the corresponding dimension of the current instance.
K L M
Example
N
using System;
O
namespace Samples { public class ArraySetValue { public static void Main() { int[] indexArray = {4, 2, 3}; int[] lowboundArray = {3, 2, 1}; Array a = Array.CreateInstance( typeof(int), indexArray, lowboundArray); for(int i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i++ ) { for(int j = a.GetLowerBound(1); j <= a.GetUpperBound(1); j++) { for(int k = a.GetLowerBound(2); k <= a.GetUpperBound(2); k++ ) { a.SetValue((100*i + 10*j + k), i, j, k );
P Q R S T U V W X Y Z
157
Contents | Index
Array
System
SetValue() Method
} } } Console.WriteLine("Value at 3, 2, 2 is: {0}", a.GetValue(3, 2, 2));
A }
B }
C
}
D
The output is
E Value at 3, 2, 2 is: 322
F G H
Array.SetValue(System.Object, System.Int32[]) Method
I
[ILASM]
J
.method public hidebysig instance void SetValue(object value, class System.Int32[] indices)
K
[C#]
public void SetValue(object value, params int[] indices)
L M
Summary
N
Sets the value of the element at the specified position in the current multidimensional instance.
O P
Parameters
Q R S
Parameter
Description
value
A System.Object that contains the new value for the specified element.
indices
A one-dimensional array of System.Int32 objects that contains the indices that specify the position of the element in the current instance to set.
T U V W
Description
X
The number of elements in indices is required to be equal to the number of dimensions in the current instance. All elements in indices collectively specify the position of the desired element in the current instance. [Note: For more information regarding valid conversions that will be performed by this method, see System.Convert. Use the System.Array.GetLowerBound and System.Array.GetUpperBound methods to determine whether any of the values in
Y Z
158
Contents | Index
System
Array SetValue() Method
indices is out of bounds.] This member must be implemented if the Extended Array Library is present in the implementation. A
Exceptions
B
Exception
Condition
System.ArgumentNullException
indices is null.
C D E
The number of dimensions in the current instance is not equal to the number of elements in indices. System.ArgumentException
F
-or-
G
value is not assignment-compatible with the element type of the current instance. System.IndexOutOfRangeException
H I
At least one element in indices is outside the range of valid indices for the corresponding dimension of the current instance.
J K L
Example
M
using System;
N namespace Samples { public class ArraySetValue { public static void Main() { int[] indexArray = {4, 2, 3}; int[] lowboundArray = {3, 2, 1}; int[] position = new int[3]; Array a = Array.CreateInstance( typeof(int), indexArray, lowboundArray); for(int i = a.GetLowerBound(0); i <= a.GetUpperBound(0); i++ ) { for(int j = a.GetLowerBound(1); j <= a.GetUpperBound(1); j++) { for(int k = a.GetLowerBound(2); k <= a.GetUpperBound(2); k++ ) { position[0] = i; position[1] = j; position[2] = k;
O P Q R S T U V W X Y Z
159
Contents | Index
Array
System
SetValue() Method
a.SetValue((100*i + 10*j + k), position); } } } Console.WriteLine("Value at 3, 2, 2 is: {0}", a.GetValue(new int[]{3, 2, 2}));
A B
} }
C }
D
The output is
E
Value at 3, 2, 2 is: 322
F G H
Array.SetValue(System.Object, System.Int64) Method
I
[ILASM]
.method public hidebysig instance void SetValue(object value, int64 index)
J
[C#]
public void SetValue(object value, long index)
K L
Summary
M
Sets a value to the element at the specified position in the one-dimensional System.Array. The index is specified as a 64-bit integer.
N O
Parameters
P Q
Parameter
Description
value
The new value for the specified element.
index
A 64-bit integer that represents the position of the System.Array element to set.
R S T U V
Description
W
The System.Array.GetLowerBound and System.Array.GetUpperBound methods can determine whether the value of index is out of bounds. For more information about conversions, see System.Convert.
X Y Z
160
Contents | Index
System
Array SetValue() Method
Exceptions Exception
Condition A
System.ArgumentException
System.IndexOutOfRangeException
The current System.Array does not have exactly one dimension.
B
-or-
C
value does not contain a type that can be widened, using the standard widening conversions, to the element type of the current System.Array.
D E F
index is outside the range of valid indices for the current System.Array.
G H I
Array.SetValue(System.Object, System.Int64, System.Int64) Method
J
[ILASM]
K
.method public hidebysig instance void SetValue(object value, int64 index1, int64 index2)
L
[C#]
M
public void SetValue(object value, long index1, long index2)
N
Summary
O
Sets a value to the element at the specified position in the two-dimensional System.Array. The indexes are specified as 64-bit integers.
P Q
Parameters Parameter
R S
Description
T
value
The new value for the specified element.
U
index1
A 64-bit integer that represents the first-dimension index of the System.Array element to set.
V
index2
A 64-bit integer that represents the second-dimension index of the System.Array element to set.
W X Y Z
161
Contents | Index
Array
System
SetValue() Method
Description The System.Array.GetLowerBound and System.Array.GetUpperBound methods can determine whether any of the indexes is out of bounds. For more information about conversions, see System.Convert.
A B
Exceptions
C D
Exception
Condition
E
The current System.Array does not have exactly two dimensions.
F G
System.ArgumentException
-or-
System.IndexOutOfRangeException
Either index1 or index2 is outside the range of valid indices for the corresponding dimension of the current System.Array.
H I J
value does not contain a type that can be widened, using the standard widening conversions, to the element type of the current System.Array.
K L
Array.SetValue(System.Object, System.Int64, System.Int64, System.Int64) Method
M N
[ILASM]
.method public hidebysig instance void SetValue(object value, int64 index1, int64 index2, int64 index3)
O P
[C#]
public void SetValue(object value, long index1, long index2, long index3)
Q R
Summary
S
Sets a value to the element at the specified position in the three-dimensional System.Array. The indexes are specified as 64-bit integers.
T U V W X Y Z
162
Contents | Index
System
Array SetValue() Method
Parameters Parameter
Description
value
The new value for the specified element.
index1
A 64-bit integer that represents the first-dimension index of the System.Array element to set.
index2
A 64-bit integer that represents the second-dimension index of the System.Array element to set.
index3
A 64-bit integer that represents the third-dimension index of the System.Array element to set.
A B C D E F G H
Description
I
The System.Array.GetLowerBound and System.Array.GetUpperBound methods can determine whether any of the indexes is out of bounds. For more information about conversions, see System.Convert.
J K
Exceptions
M
L
N
Exception
System.ArgumentException
System.IndexOutOfRangeException
Condition
O
The current System.Array does not have exactly three dimensions.
P
-or-
Q
value does not contain a type that can be widened, using the standard widening conversions, to the element type of the current System.Array.
R S T
index1 or index2 or index3 is outside the range of valid indices for the corresponding dimension of the current System.Array.
U V W
Array.SetValue(System.Object, System.Int64[]) Method
X [ILASM]
Y
.method public hidebysig instance void SetValue(object value, class System.Int64[] indices)
Z
[C#]
public void SetValue(object value, params long[] indices)
163
Contents | Index
Array
System
SetValue() Method
Summary Sets a value to the element at the specified position in the multidimensional System.Array. The indexes are specified as an array of 64-bit integers. A
Parameters
B C D E F
Parameter
Description
value
The new value for the specified element.
indices
A one-dimensional array of 64-bit integers that represent the indices specifying the position of the element to set.
G H
Description
I
The number of elements in indices must equal the number of dimensions in the System.Array. All elements in the indices array must collectively specify the position of the desired element in the multidimensional System.Array. The System.Array.GetLowerBound and System.Array.GetUpperBound methods can determine whether any of the values in the indices array is out of bounds. For more information about conversions, see System.Convert.
J K L M N
Exceptions
O P
Exception
Condition
System.ArgumentNullException
indices is null.
Q R S
The number of dimensions in the current System.Array is not equal to the number of elements in indices.
T U
System.ArgumentException
V W
-orvalue does not contain a type that can be widened, using the standard widening conversions, to the element type of the current System.Array.
X Y Z
164
Contents | Index
System
Array Sort() Method
Array.Sort(System.Array) Method [ILASM]
.method public hidebysig static void Sort(class System.Array array) [C#]
A
public static void Sort(Array array)
B C
Summary
D
Sorts the elements of the specified one-dimensional System.Array.
E
Parameters
F G
Parameter
Description
array
A one-dimensional System.Array to sort.
H I J
Description
K
This version of System.Array.Sort is equivalent to System.Array.Sort(array, null, array.GetLowerBound(0), array.Length, null). Each element of array is required to implement the System.IComparable interface to be capable of comparisons with every other element in array.
L M N O
Exceptions
P
Exception
Condition
System.ArgumentNullException
array is null.
System.RankException
array has more than one dimension.
System.ArgumentException
One or more elements in array do not implement the System.IComparable interface.
Q R S T U V W
Example
X
using System;
Y namespace Samples { public class ArraySort {
Z
165
Contents | Index
Array
System
Sort() Method
public static void Main() { string[] strings = { "one", "two", "three", "four"}; Console.Write("Array elements: "); foreach(String s in strings) Console.Write("{0} ", s); Console.WriteLine(); Array.Sort(strings); Console.Write("Array elements: "); foreach(string s in strings) Console.Write("{0} ", s); }
A B C D E F }
G
}
H
The output is
I
Array elements: one two three four Array elements: four one three two
J K L M
Array.Sort(System.Array, System.Int32, System.Int32) Method
N
[ILASM]
O
.method public hidebysig static void Sort(class System.Array array, int32 index, int32 length) [C#]
P
public static void Sort(Array array, int index, int length)
Q R
Summary
S
Sorts the elements in the specified range of the specified one-dimensional System.Array.
T
Parameters
U V
Parameter
Description
W
array
A one-dimensional System.Array to sort.
index
A System.Int32 that contains the index at which sorting starts.
length
A System.Int32 that contains the number of elements to sort.
X Y Z
166
Contents | Index
System
Array Sort() Method
Description This version of System.Array.Sort is equivalent to System.Array.Sort(array, null, index, length, null). Each element of array is required to implement the System.IComparable interface to be capable of comparisons with every other element in array. If the sort is not successfully completed, the results are unspecified.
A B C D
Exceptions
E
Exception
Condition
System.ArgumentNullException
array is null.
System.RankException
array has more than one dimension.
F G H I
index < array.GetLowerBound(0). System.ArgumentOutOfRangeException
J
-or-
K
length < 0.
L
index and length do not specify a valid range in array. System.ArgumentException
M
-or-
N
One or more elements in array do not implement the System.IComparable interface.
O P
Example
Q
using System;
R
namespace Samples { public class ArraySort { public static void Main() { string[] strings = {"one", "two", "three", "four", "five", "six"}; Console.Write("Array elements:" ); foreach(string s in strings) Console.Write("{0} ", s); Console.WriteLine(); Array.Sort(strings, 0, 4); Console.Write("Sorted array: " ); foreach(string s in strings)
S T U V W X Y Z
167
Contents | Index
Array
System
Sort() Method
Console.Write("{0} ", s); } } }
A
The output is
B C
Array elements:one two three four five six Sorted array: four one three two five six
D E
G
Array.Sort(System.Array, System.Int32, System.Int32, System.Collections.IComparer) Method
H
[ILASM]
I
.method public hidebysig static void Sort(class System.Array array, int32 index, int32 length, class System.Collections.IComparer comparer)
F
[C#]
J
public static void Sort(Array array, int index, int length, IComparer comparer)
K L
Summary
M
Sorts the elements in the specified section of the specified one-dimensional System.Array using the specified System.Collections.IComparer implementation.
N
Parameters
O P
Parameter
Description
R
array
A one-dimensional System.Array to sort.
S
index
A System.Int32 that contains the index at which sorting starts.
length
A System.Int32 that contains the number of elements to sort.
comparer
The System.Collections.IComparer implementation to use when comparing elements. Specify a null reference to use the System.IComparable implementation of each element.
Q
T U V W X Y
Description
Z
This version of System.Array.Sort is equivalent to System.Array.Sort(array, null, index, length, comparer).
168
Contents | Index
System
Array Sort() Method
If comparer is a null reference, each element of array is required to implement the System.IComparable interface to be capable of comparisons with every other element in array. If the sort is not successfully completed, the results are unspecified. A
Exceptions Exception
B C
Condition
D System.ArgumentNullException
array is null.
E
System.RankException
array has more than one dimension.
F
index < array.GetLowerBound(0).
G
-or-
H
length < 0.
I
index and length do not specify a valid range in array.
J
-or-
K
comparer is a null reference, and one or more elements in array do not implement the System.IComparable interface.
L
System.ArgumentOutOfRangeException
System.ArgumentException
M N
Example
O
using System; using System.Collections;
P Q
namespace Samples { public class ArraySort { public class MyComparer: IComparer { public int Compare(Object a, Object b) { return ((IComparable)a).CompareTo(b); } } public static void Main() { string[] strings = {"one", "two", "three", "four", "five", "six"}; Console.Write("Array elements: " ); foreach(string s in strings)
R S T U V W X Y Z
169
Contents | Index
Array
System
Sort() Method
Console.Write("{0} ", s); Console.WriteLine(); Array.Sort(strings, 0, 6, new MyComparer()); Console.Write("Sorted array: " ); foreach(string s in strings) Console.Write("{0} ", s);
A B }
C
} }
D
The output is
E F
Array elements: one two three four five six Sorted array: five four one six three two
G H I
Array.Sort(System.Array, System.Array) Method
J
[ILASM]
K
.method public hidebysig static void Sort(class System.Array keys, class System.Array items)
L
[C#]
public static void Sort(Array keys, Array items)
M N
Summary
O
Sorts the specified pair of one-dimensional System.Array objects (one containing a set of keys and the other containing corresponding items) based on the keys in the first specified System.Array.
P Q R
Parameters
S T U
Parameter
Description
keys
A one-dimensional System.Array that contains the keys to sort.
items
A one-dimensional System.Array that contains the items that correspond to each of element of keys. Specify a null reference to sort only keys.
V W X Y
Description
Z
This version of System.Array.Sort is equivalent to System.Array.Sort(keys, items, keys.GetLowerBound(0), keys.Length, null).
170
Contents | Index
System
Array Sort() Method
Each key in keys is required to have a corresponding item in items. The sort is performed according to the order of keys. After a key is repositioned during the sort, the corresponding item in items is similarly repositioned. Only keys.Length elements of items are sorted. Therefore, items is sorted according to the arrangement of the corresponding keys in keys. If the sort is not successfully completed, the results are unspecified. Each element of keys is required to implement the System.IComparable interface to be capable of comparisons with every other element in keys.
A B C D
Exceptions
E
Exception
Condition
System.ArgumentNullException
keys is null.
System.RankException
keys has more than one dimension. -oritems is not a null reference and has more than one dimension.
F G
System.ArgumentException
H I J K L
items is not a null reference, and keys.GetLowerBound(0) does not equal items.GetLowerBound(0). -oritems is not a null reference, and keys.Length > items.Length. -orOne or more elements in keys do not implement the System.IComparable interface.
M N O P Q R
Example
S
using System;
T namespace Samples { public class ArraySort { public static void Main() { string[] strings = {"one", "two", "three", "four"}; int[] ints = {0, 2, 3, 1}; Console.Write("Array elements: " ); foreach(string s in strings) Console.Write("{0} ", s); Console.WriteLine(); Console.Write("Key array: " );
U V W X Y Z
171
Contents | Index
Array
System
Sort() Method
foreach(int i in ints) Console.Write("{0} ", i); Console.WriteLine(); Array.Sort(ints, strings); Console.Write("Sorted array: " ); foreach(string s in strings) Console.Write("{0} ", s);
A B }
C }
D
}
E
The output is
F Array elements: one two three four Key array: 0 2 3 1 Sorted array: one four two three
G H I J
Array.Sort(System.Array, System.Array, System.Int32, System.Int32) Method
K
[ILASM]
L
.method public hidebysig static void Sort(class System.Array keys, class System.Array items, int32 index, int32 length)
M
[C#]
public static void Sort(Array keys, Array items, int index, int length)
N O
Summary
P
Sorts the specified ranges of the specified pair of one-dimensional System.Array objects (one containing a set of keys and the other containing corresponding items) based on the keys in the first specified System.Array.
Q R
Parameters
S T
Parameter
Description
keys
A one-dimensional System.Array that contains the keys to sort.
items
A one-dimensional System.Array that contains the items that correspond to each element in keys. Specify a null reference to sort only keys.
Y
index
A System.Int32 that contains the index at which sort begins.
Z
length
A System.Int32 that contains the number of elements to sort.
U V W X
172
Contents | Index
System
Array Sort() Method
Description This version of System.Array.Sort is equivalent to System.Array.Sort(keys, items, index, length, null). Each key in keys is required to have a corresponding item in items. The sort is performed according to the order of keys. After a key is repositioned during the sort, the corresponding item in items is similarly repositioned. Therefore, items is sorted according to the arrangement of the corresponding keys in keys. If the sort is not successfully completed, the results are undefined. Each element of keys is required to implement the System.IComparable interface to be capable of comparisons with every other element in keys.
A B C D E F G
Exceptions
H
Exception
Condition
System.ArgumentNullException
keys is null.
J
keys has more than one dimension.
K
-or-
L
items is not a null reference and has more than one dimension.
M
System.RankException
I
N
index < keys.GetLowerBound(0). System.ArgumentOutOfRangeException
O
-orP
length < 0.
Q
items is not a null reference, and keys.GetLowerBound(0) does not equal items.GetLowerBound(0).
R S
-orT
index and length do not specify a valid range in key. System.ArgumentException
-or-
U
items is not a null reference, and index and length do not specify a valid range in items.
V W
-or-
X
One or more elements in keys do not implement the System.IComparable interface.
Y Z
173
Contents | Index
Array
System
Sort() Method
Example using System; namespace Samples { public class ArraySort { public static void Main() { string[] strings = {"one", "two", "three", "four", "five", "six"}; int[] ints = {4, 2, 5, 3, 1, 0}; Console.Write("Array elements: " ); foreach(string s in strings) Console.Write("{0} ", s); Console.WriteLine(); Console.Write("Key array: " ); foreach(int i in ints) Console.Write("{0} ", i); Console.WriteLine(); Array.Sort(ints, strings, 0, 4); Console.Write("Sorted array: " ); foreach(string s in strings) Console.Write("{0} ", s); } } }
A B C D E F G H I J K L M N O P
The output is
Q Array elements: one two three four five six Key array: 4 2 5 3 1 0 Sorted array: two four one three five six
R S T
Array.Sort(System.Array, System.Array, System.Int32, System.Int32, System.Collections.IComparer) Method
U V
[ILASM]
W
.method public hidebysig static void Sort(class System.Array keys, class System. Array items, int32 index, int32 length, class System.Collections.IComparer comparer)
X
[C#]
Y
public static void Sort(Array keys, Array items, int index, int length, IComparer comparer)
Z
174
Contents | Index
System
Array Sort() Method
Summary Sorts the specified range of the specified pair of one-dimensional System.Array objects (one containing a set of keys and the other containing corresponding items) based on the keys in the first specified System.Array using the specified System.Collections.IComparer implementation.
A B C
Parameters
D
Parameter
Description
keys
A one-dimensional System.Array that contains the keys to sort.
items
A one-dimensional System.Array that contains the items that correspond to each element of keys. Specify a null reference to sort only keys.
index
A System.Int32 that contains the index at which sorting starts.
length
A System.Int32 that contains the number of elements to sort.
comparer
The System.Collections.IComparer implementation to use when comparing elements. Specify a null reference to use the System.IComparable implementation of each element.
E F G H I J K L M N
Description
O
Each key in keys is required to have a corresponding item in items. The sort is performed according to the order of keys. After a key is repositioned during the sort, the corresponding item in items is similarly repositioned. Only keys.Length elements of items will be sorted. Therefore, items is sorted according to the arrangement of the corresponding keys in keys. If the sort is not successfully completed, the results are undefined. If comparer is a null reference, each element of keys is required to implement the System.IComparable interface to be capable of comparisons with every other element in keys.
P Q R S T U V W X Y Z
175
Contents | Index
Array
System
Sort() Method
Exceptions Exception
Condition
System.ArgumentNullException
keys is null.
A B
keys has more than one dimension.
C D
System.RankException
-oritems is not a null reference and has more than one dimension.
E F
index < keys.GetLowerBound(0).
G
System.ArgumentOutOfRangeException
H I
-orlength < 0. items is not a null reference, and keys.GetLowerBound(0) does not equal items.GetLowerBound(0).
J
-or-
K
index and length do not specify a valid range in keys.
L
-or-
M
System.ArgumentException
N
items is not a null reference, and index and length do not specify a valid range in items. -or-
O
comparer is a null reference, and one or more elements in keys do not implement the System.IComparable interface.
P Q R S
Example
T
using System; using System.Collections;
U
namespace Samples { public class ArraySort { public class MyComparer: IComparer { public int Compare(Object a, Object b) { return ((IComparable)a).CompareTo(b); } }
V W X Y Z
176
Contents | Index
System
Array Sort() Method
public static void Main() { string[] strings = {"one", "two", "three", "four", "five", "six"}; int[] ints = {0, 2, 3, 1, 5, 4}; Console.Write("Array elements: " ); foreach(string s in strings) Console.Write("{0} ", s); Console.WriteLine(); Console.Write("Key array: " ); foreach(int i in ints) Console.Write("{0} ", i); Console.WriteLine(); Array.Sort(ints, strings, 0, 4, new MyComparer()); Console.Write("Sorted array: " ); foreach(string s in strings) Console.Write("{0} ", s); }
A B C D E F G H I J
}
K
}
L
The output is
M Array elements: one two three four five six Key array: 0 2 3 1 5 4 Sorted array: one four two three five six
N O P
Array.Sort(System.Array, System.Array, System.Collections.IComparer) Method
Q
[ILASM]
S
.method public hidebysig static void Sort(class System.Array keys, class System.Array items, class System.Collections.IComparer comparer)
T
R
[C#]
U
public static void Sort(Array keys, Array items, IComparer comparer)
V
Summary
W
Sorts the specified pair of one-dimensional System.Array objects (one containing a set of keys and the other containing corresponding items) based on the keys in the first specified System.Array using the specified System.Collections.IComparer implementation.
X Y Z
177
Contents | Index
Array
System
Sort() Method
Parameters A
Parameter
Description
keys
A one-dimensional System.Array that contains the keys to sort.
items
A one-dimensional System.Array that contains the items that correspond to each element in keys. Specify a null reference to sort only keys.
comparer
The System.Collections.IComparer implementation to use when comparing elements. Specify a null reference to use the System.IComparable implementation of each element.
B C D E F G
Description
H
This version of System.Array.Sort is equivalent to System.Array.Sort(keys, items, keys.GetLowerBound(0), keys.Length, comparer). Each key in keys is required to have a corresponding item in items. The sort is performed according to the order of keys. After a key is repositioned during the sort, the corresponding item in items is similarly repositioned. Only keys.Length elements of items are sorted. Therefore, items is sorted according to the arrangement of the corresponding keys in keys. If the sort is not successfully completed, the results are unspecified. If comparer is a null reference, each element of keys is required to implement the System.IComparable interface to be capable of comparisons with every other element in keys.
I J K L M N O
Exceptions
P Q R
Exception
Condition
System.ArgumentNullException
keys is null.
System.RankException
keys has more than one dimension. -oritems is not a null reference and has more than one dimension.
System.ArgumentException
items is not a null reference, and keys.GetLowerBound(0) does not equal items.GetLowerBound(0). -oritems is not a null reference, and keys.Length > items.Length. -orcomparer is a null reference, and one or more elements in keys do not implement the System. IComparable interface.
S T U V W X Y Z
178
Contents | Index
System
Array Sort() Method
Example using System; using System.Collections;
A namespace Samples { public class ArraySort { public class MyComparer: IComparer { public int Compare(Object a, Object b) { return -((IComparable)a).CompareTo(b); } } public static void Main() { string[] strings = {"one", "two", "three", "four", "five", "six"}; int[] ints = {2, 4, 3, 5, 1, 0}; Console.Write("Array elements: " ); foreach(string s in strings) Console.Write("{0} ", s); Console.WriteLine(); Console.Write("Key array: " ); foreach(int i in ints) Console.Write("{0} ", i); Console.WriteLine(); Array.Sort(ints, strings, new MyComparer()); Console.Write("Sorted array: " ); foreach(string s in strings) Console.Write("{0} ", s); } } }
B C D E F G H I J K L M N O P Q R S T U
The output is
V
Array elements: one two three four five six Key array: 2 4 3 5 1 0 Sorted array: four two three one five six
W X Y Z
179
Contents | Index
Array
System
Sort() Method
Array.Sort(System.Array, System.Collections.IComparer) Method [ILASM]
A
.method public hidebysig static void Sort(class System.Array array, class System.Collections.IComparer comparer)
B
[C#]
public static void Sort(Array array, IComparer comparer)
C D
Summary
E
Sorts the elements in the specified one-dimensional System.Array using the specified System.Collections.IComparer implementation.
F G
Parameters
H I J
Parameter
Description
array
The one-dimensional System.Array to sort.
comparer
The System.Collections.IComparer implementation to use when comparing elements. Specify a null reference to use the System.IComparable implementation of each element.
K L M N
Description
O
This version of System.Array.Sort is equivalent to System.Array.Sort(array, null, array.GetLowerBound(0), array.Length, comparer). If comparer is a null reference, each element of array is required to implement the System.IComparable interface to be capable of comparisons with every other element in array. If the sort is not successfully completed, the results are unspecified.
P Q R S
Exceptions
T U
Exception
Condition
W
System.ArgumentNullException
array is null.
X
System.RankException
array has more than one dimension.
System.ArgumentException
comparer is a null reference, and one or more elements in array do not implement the System.IComparable interface.
V
Y Z
180
Contents | Index
System
Array Sort() Method
Example using System; using System.Collections;
A
namespace Samples { public class ArraySort { public class MyReverseComparer: IComparer { public int Compare(Object a, Object b) { return -((IComparable)a).CompareTo(b); } } public static void Main() { string[] strings = {"One", "two", "Three", "four", "Five", "six"}; Console.Write("Array elements: " ); foreach(string s in strings) Console.Write("{0} ", s); Console.WriteLine(); Array.Sort(strings, new MyReverseComparer()); Console.Write("Sorted Array: " ); foreach(string s in strings) Console.Write("{0} ", s); Console.WriteLine(); Array.Sort(strings, new CaseInsensitiveComparer()); Console.Write("Sorted Array: " ); foreach(string s in strings) Console.Write("{0} ", s); Console.WriteLine(); } } }
B C D E F G H I J K L M N O P Q R S T U
The output is
V Array elements: One two Three four Five six Sorted Array: two Three six One four Five Sorted Array: Five four One six Three two
W X Y Z
181
Contents | Index
Array
System
Add() Method
IList.Add(System.Object) Method [ILASM]
A
.method private final hidebysig virtual int32 System.Collections.IList.Add(object value)
B
[C#]
int IList.Add(object value)
C D
Summary
E
Implemented to support the System.Collections.IList interface. [Note: For more information, see System.Collections.IList.Add.]
F G
Example
H
using System; using System.Collections;
I namespace Samples { class ArrayAdd { public static void Main() { string[] strings = {"damien", "mark"}; try { AddToList(strings, "brad"); } catch(NotSupportedException e) { Console.WriteLine("Exception: {0}", e); } } public static void AddToList(IList il, object o) { il.Add(o); } } }
J K L M N O P Q R S T U V W
The output is
X Exception: System.NotSupportedException: Collection was of a fixed size. at System.Array.System.Collections.IList.Add(Object value) at Samples.ArrayAdd.AddToList(IList il, Object o) in C:\Books\BCL\Samples\ System\Array\Add(System.Object)\Array.cs:line 22 at Samples.ArrayAdd.Main() in C:\Books\BCL\Samples\System\Array\Add(System.Object)\Array.cs:line 13
Y Z
182
Contents | Index
System
Array Clear() Method
IList.Clear() Method [ILASM]
.method private final hidebysig virtual void System.Collections.IList.Clear() [C#]
A
void IList.Clear()
B C
Summary
D
Implemented to support the System.Collections.IList interface. [Note: For more information, see System.Collections.IList.Clear.]
E F
Example
G
using System; using System.Collections;
H I
namespace Samples { public class ArrayClear { public static void Main() { int[] ints = {0, 1, 2, 3}; foreach(int i in ints) Console.Write("{0} ", i); Console.WriteLine(); ClearList(ints); foreach(int i in ints) Console.Write("{0} ", i); Console.WriteLine(); } public static void ClearList(IList il) { il.Clear(); } } }
J K L M N O P Q R S T U V
The output is
W X
0 1 2 3 0 0 0 0
Y Z
183
Contents | Index
Array
System
Contains() Method
IList.Contains(System.Object) Method [ILASM]
A
.method private final hidebysig virtual bool System.Collections.IList.Contains(object value)
B
[C#]
bool IList.Contains(object value)
C D
Summary
E
Implemented to support the System.Collections.IList interface. [Note: For more information, see System.Collections.IList.Contains.]
F G
Example
H
using System; using System.Collections;
I
namespace Samples { class ArrayContains { public static void Main() { object[] objects = {0, 1, 2, 3}; foreach(object o in objects) Console.Write("{0} ", o); Console.WriteLine(); DisplayMatches(objects, new object[] {0, 3, 6, 9}); string[] strings = {"damien", "mark", "brad"}; foreach(string s in strings) Console.Write("{0} ", s); Console.WriteLine(); DisplayMatches(strings, new string[] {"brad", "maire"}); } public static void DisplayMatches(IList il, object[] objects) { foreach(object o in objects) if(il.Contains(o)) Console.WriteLine("List contains {0}", o); } } }
J K L M N O P Q R S T U V W X Y Z
184
Contents | Index
System
Array IndexOf() Method
The output is 0 1 2 3 List contains 0 List contains 3 damien mark brad List contains brad
A B C D
IList.IndexOf(System.Object) Method
E
[ILASM]
F
.method private final hidebysig virtual int32 System.Collections.IList.IndexOf(object value)
G
[C#]
H
int IList.IndexOf(object value)
I
Summary
J
Implemented to support the System.Collections.IList interface. [Note: For more information, see System.Collections.IList.IndexOf.]
K L
Example
M
using System; using System.Collections;
N O
namespace Samples { public class ArrayIndexOf { public static void Main() { string[] strings = {"damien", "mark", "brad"}; Console.Write("Array values: " ); foreach(string s in strings) Console.Write("{0} ", s); Console.WriteLine(); foreach(string s in new string[] {"brad", "maire"}) DisplayIndexOf(strings, s); } public static void DisplayIndexOf(IList il, object o) { Console.WriteLine( "First occurrence of {0} is {1}", o, il.IndexOf(o)); } } }
P Q R S T U V W X Y Z
185
Contents | Index
Array
System
Insert() Method
The output is Array values: damien mark brad First occurrence of brad is 2 First occurrence of maire is -1
A B C
IList.Insert(System.Int32, System.Object) Method
D
[ILASM]
E
.method private final hidebysig virtual void System.Collections.IList.Insert(int32 index, object value)
F
[C#]
G
void IList.Insert(int index, object value)
H
Summary
I
Implemented to support the System.Collections.IList interface. [Note: For more information, see System.Collections.IList.Insert.]
J K L
Example
M
using System; using System.Collections;
N namespace Samples { public class ArrayInsert { public static void Main() { String[] strings = {"", "mark", "brad"}; try { InsertAtFront(strings, "damien"); } catch(NotSupportedException e) { Console.WriteLine("Exception {0}", e); } } public static void InsertAtFront(IList il, object o) { il.Insert(0, o); } } }
O P Q R S T U V W X Y Z
186
Contents | Index
System
Array Remove() Method
The output is Exception System.NotSupportedException: Collection was of a fixed size. at System.Array.System.Collections.IList.Insert(Int32 index, Object value) at Samples.ArrayInsert.InsertAtFront(IList il, Object o) in C:\Books\BCL\ Samples\System\Array\Insert(System.Int32,System.Object)\Array.cs:line 22 at Samples.ArrayInsert.Main() in C:\Books\BCL\Samples\System\Array\Insert (System.Int32,System.Object)\Array.cs:line 13
A B C D E
IList.Remove(System.Object) Method
F
[ILASM]
G
.method private final hidebysig virtual void System.Collections.IList.Remove(object value)
H
[C#]
void IList.Remove(object value)
I
Summary
J
Implemented to support the System.Collections.IList interface. [Note: For more information, see System.Collections.IList.Remove.]
K
Example
M
using System; using System.Collections;
N
L
O namespace Samples { public class ArrayRemove { public static void Main() { string[] strings = {"one", "two", "three"}; try { RemoveFriomList(strings, "two"); } catch(NotSupportedException e) { Console.WriteLine("Exception {0}", e); } } public static void RemoveFriomList(IList il, object o) { il.Remove(o); } } }
P Q R S T U V W X Y Z
187
Contents | Index
Array
System
RemoveAt() Method
The output is Exception System.NotSupportedException: Collection was of a fixed size. at System.Array.System.Collections.IList.Remove(Object value) at Samples.ArrayRemove.RemoveFriomList(IList il, Object o) in C:\Books\BCL\Samples\System\Array\Remove(System.Object)\Array.cs:line 22 at Samples.ArrayRemove.Main() in C:\Books\BCL\Samples\System\Array\ Remove(System.Object)\Array.cs:line 13
A B C D E
IList.RemoveAt(System.Int32) Method
F
[ILASM]
G
.method private final hidebysig virtual void System.Collections.IList.RemoveAt(int32 index)
H
[C#]
void IList.RemoveAt(int index)
I J
Summary
K
Implemented to support the System.Collections.IList interface. [Note: For more information, see System.Collections.IList.RemoveAt.]
L M
Example
N
using System; using System.Collections;
O
namespace Samples { public class ArrayRemoveAt { public static void Main() { string[] strings = {"one", "two", "three"}; try { RemoveFromList(strings, 1); } catch(NotSupportedException e) { Console.WriteLine("Exception {0}", e); } } public static void RemoveFromList(IList il, int i) { il.RemoveAt(i); } } }
P Q R S T U V W X Y Z
188
Contents | Index
System
Array Count Property
The output is Exception System.NotSupportedException: Collection was of a fixed size. at System.Array.System.Collections.IList.RemoveAt(Int32 index) at Samples.ArrayRemoveAt.RemoveFromList(IList il, Int32 i) in C:\Books\BCL\Samples\System\Array\RemoveAt(System.Int32)\Array.cs:line 22 at Samples.ArrayRemoveAt.Main() in C:\Books\BCL\Samples\System\Array\ RemoveAt(System.Int32)\Array.cs:line 13
A B C D E
ICollection.Count Property
F [ILASM]
G
.property int32 ICollection.Count { public hidebysig virtual abstract specialname int32 get_ICollection.Count() }
H
[C#]
I
int ICollection.Count { get; }
J
Summary
K
Implemented to support the System.Collections.ICollection interface. [Note: For more information, see System.Collections.ICollection.Count.]
L M
Example
N
using System; using System.Collections;
O P
namespace Samples { public class ArrayCount { public static void Main() { string[] strings = {"brad", "tamara", "boston"}; CollectionProperties(strings); } public static void CollectionProperties(ICollection ic) { Console.WriteLine("Count: {0}", ic.Count); Console.WriteLine("IsSynchronized: {0}", ic.IsSynchronized); } } }
Q R S T U V W X Y Z
189
Contents | Index
Array
System
Item Property
The output is Count: 3 IsSynchronized: False
A B C
IList.Item Property
D
[ILASM]
.property instance object System.Collections.IList.Item(int32) {}
E
[C#]
object IList.this int index {get; set;}
F G
Summary
H
Implemented to support the System.Collections.IList interface. [Note: For more information, see System.Collections.IList.Item.]
I J
Example
K
using System; using System.Collections;
L M
namespace Samples { public class ArrayItem { public static void Main() { int[] integers = {0, 1, 2}; DisplayList(integers); string[] strings = {"brad", "tamara", "boston"}; DisplayList(strings); } public static void DisplayList(IList il) { for(int i = 0; i < il.Count; i++) Console.Write("{0} ", il[i]); Console.WriteLine(); } } }
N O P Q R S T U V W X Y
The output is
Z 0 1 2 brad tamara boston
190
Contents | Index
System.Collections ArrayList
BCL
IList Object ICollection
A
IEnumerable
B
ICloneable
C
ArrayList
D
Summary
E
Implements a variable-size System.Collections.IList that uses an array of objects to store its elements.
F G
Type Summary
H
public class ArrayList : IList, ICollection, IEnumerable, ICloneable { // Constructors public ArrayList (); public ArrayList (int capacity); public ArrayList (ICollection c); // Properties public virtual public virtual public virtual public virtual public virtual public virtual public virtual
I J K L M
int Capacity { set; get; } int Count { get; } bool IsFixedSize { get; } bool IsReadOnly { get; } bool IsSynchronized { get; } object this[int index] { set; get; } object SyncRoot { get; }
N O P Q R
// Methods CF public static ArrayList Adapter (IList list); public virtual int Add (object value); public virtual void AddRange (ICollection c); public virtual int BinarySearch (int index, int count, object value, IComparer comparer); CF public virtual int BinarySearch (object value); CF public virtual int BinarySearch (object value, IComparer comparer); public virtual void Clear (); public virtual object Clone (); public virtual bool Contains (object item); public virtual void CopyTo (int index, Array array, int arrayIndex, int count);
S T U V W X Y Z
191
Contents | Index
ArrayList
System.Collections
ArrayList Class
CF MS CF
A B
CF
C CF
D E
CF
F G H I J
CF CF
K CF
L M
CF MS CF
N O P Q
CF
R S T
CF
U V W X
MS CF
Y Z
public virtual void CopyTo (Array array); public virtual void CopyTo (Array array, int arrayIndex); public static ArrayList FixedSize (ArrayList list); public static IList FixedSize (IList list); public virtual IEnumerator GetEnumerator (); public virtual IEnumerator GetEnumerator (int index, int count); public virtual ArrayList GetRange (int index, int count); public virtual int IndexOf (object value); public virtual int IndexOf (object value, int startIndex); public virtual int IndexOf (object value, int startIndex, int count); public virtual void Insert (int index, object value); public virtual void InsertRange (int index, ICollection c); public virtual int LastIndexOf (object value); public virtual int LastIndexOf (object value, int startIndex); public virtual int LastIndexOf (object value, int startIndex, int count); public static ArrayList ReadOnly (ArrayList list); public static IList ReadOnly (IList list); public virtual void Remove (object obj); public virtual void RemoveAt (int index); public virtual void RemoveRange (int index, int count); public static ArrayList Repeat (object value, int count); public virtual void Reverse (); public virtual void Reverse (int index, int count); public virtual void SetRange (int index, ICollection c); public virtual void Sort (); public virtual void Sort (int index, int count, IComparer comparer); public virtual void Sort (IComparer comparer); public static ArrayList Synchronized (ArrayList list); public static IList Synchronized (IList list); public virtual object[] ToArray (); public virtual Array ToArray (Type type); public virtual void TrimToSize ();
}
192
Contents | Index
System.Collections
ArrayList ArrayList Class
JM The IndexOf(string, int, int) method used to have as its last parameter the name “lastIndex.” This name caused confusion regarding whether the index was included in the search or not (inclusive or exclusive). Thus, as part of the standardization process the name got changed to “count” to avoid that confusion.
A B
BG Note the heavy use of wrapper collections on ArrayList to add in functionality like thread safety or making a list read-only. This is very useful in that it allows users to write their code using ArrayList and then add in thread safety without having to change more than one line of code. At least, that was the original goal. However, there are two drawbacks with this approach. One is a subtle performance penalty — every method call on ArrayList is virtual, meaning it cannot be inlined and is therefore slower than it could be. The second is that the design isn’t quite what people need, at least for synchronization. Sometimes users may want code that does two operations with an ArrayList in a consistent state, like this:
C D E F G H I J
ArrayList list = ArrayList.Synchronized(someOtherArrayList); if (list.Count > 0) Object node = list[0];
K L
At this point, our threadsafe wrapper will not work as expected. True, the Count property will be accessed in a thread-safe way, as will the first element of the ArrayList. However, the way our design for the threadsafe wrapper works requires that we take a lock when calling each method, then release the lock after calling each method. Therefore, after we have retrieved the Count property, another thread could add or remove an element from the list, meaning that the next line might fail. The correct way to write code like this would be to use the SyncRoot property:
M N O P Q R
lock(list.SyncRoot) { if (list.Count > 0) Object node = list[0]; }
S T U
This code is correct and has the added benefit of taking the lock only once, instead of twice. Note the thread-safe wrapper collections are expected to use the SyncRoot property (defined on ICollection) to implement their thread-safety guarantees, so doing this in one part of your code is fully compatible with using a thread-safe wrapper in a different section of your code.
V W X Y
continued
Z
193
Contents | Index
ArrayList
System.Collections
ArrayList Class
For these reasons, the SyncRoot property is a great idea and the idea of a thread-safe wrapper is less appealing than you’d like to believe. If we were designing collections over again, we might not allow subclasses of our collections for performance reasons and because they don’t add a lot of value. The IList interface should be rich enough for most users, and if it isn’t, the correct approach is to write another interface. Classes implementing that interface are free to use ArrayList internally for their own implementation details if necessary.
A B C D
JR Since an ArrayList is simply a wrapper on top of an Array, my comment about Array’s Sort and BinarySearch methods and exceptions applies to ArrayList as well.
E F G H
Description
I
System.Collections.ArrayList implements a variable-size System.Collections.IList that uses an array of objects to store the elements. A System.Collections.ArrayList has a System.Collections.ArrayList.Capacity, which is the allocated length of the internal array. The total number of elements contained by a list is its System.Collections.ArrayList.Count. As elements are added to a list, its capacity is automatically increased as required by reallocating the internal array.
J K L M N
Example
O
using System; using System.Collections;
P Q
namespace Samples { public class ArrayListSamples { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add(42); a.Add(new object()); Console.WriteLine("-- ArrayList --" ); Console.WriteLine("Count: {0}", a.Count); Console.WriteLine("Capacity: {0}", a.Capacity ); Console.Write("Values:"); PrintElements(a); a.Reverse(); Console.Write("Values:"); PrintElements(a); a.Remove(new object());
R S T U V W X Y Z
194
Contents | Index
System.Collections
ArrayList ArrayList() Constructor
a.Remove("damien"); Console.Write("Values:"); PrintElements(a); } public static void PrintElements(IEnumerable ie) { IEnumerator e = ie.GetEnumerator(); while(e.MoveNext()) Console.Write(" {0}", e.Current ); Console.WriteLine(); }
A B C D E
} }
F G
The output is
H
-- ArrayList -Count: 3 Capacity: 16 Values: damien 42 System.Object Values: System.Object 42 damien Values: System.Object 42
I J K L M
ArrayList() Constructor
N
[ILASM]
O
public rtspecialname specialname instance void .ctor()
P
[C#]
public ArrayList()
Q
Summary
R
Constructs and initializes a new instance of the System.Collections.ArrayList class that is empty and has the default initial System.Collections.ArrayList.Capacity.
S
Description
U
The default initial System.Collections.ArrayList.Capacity of a System.Collections.ArrayList is 16.
V
T
W X Y Z
195
Contents | Index
ArrayList
System.Collections
ArrayList() Constructor
Example using System; using System.Collections;
A namespace Samples { public class ArrayListConstructor { public static void Main() { ArrayList a = new ArrayList(); Console.WriteLine("Count: {0}", a.Count); Console.WriteLine("Default Capacity: {0}", a.Capacity ); } } }
B C D E F G H I
The output is
J Count: 0 Default Capacity: 16
K L M
ArrayList(System.Int32) Constructor
N
[ILASM]
O
public rtspecialname specialname instance void .ctor(int32 capacity)
P
[C#]
public ArrayList(int capacity)
Q R
Summary
S
Constructs and initializes a new instance of the System.Collections.ArrayList class that is empty and has the specified initial System.Collections.ArrayList.Capacity.
T U
Parameters
V W
Parameter
Description
capacity
A System.Int32 that specifies the number of elements that the new instance is initially capable of storing.
X Y Z
196
Contents | Index
System.Collections
ArrayList ArrayList() Constructor
Description If capacity is zero, the System.Collections.ArrayList.Capacity of the current instance is set to 16 when the first element is added. A
Exceptions
B C
Exception
Condition
System.ArgumentOutOfRangeException
capacity < 0.
D E F
Example
G
using System; using System.Collections;
H I
namespace Samples { public class ArrayListConstructor { public static void Main() { ArrayList a = new ArrayList(32); Console.WriteLine("Count: {0}", a.Count); Console.WriteLine("Default Capacity: {0}", a.Capacity); } } }
J K L M N O P Q
The output is
R S
Count: 0 Default Capacity: 32
T U
ArrayList(System.Collections.ICollection) Constructor
V
[ILASM]
W
public rtspecialname specialname instance void .ctor(class System.Collections.ICollection c)
X
[C#]
Y
public ArrayList(ICollection c)
Z
197
Contents | Index
ArrayList
System.Collections
ArrayList() Constructor
Summary Constructs and initializes a new instance of the System.Collections.ArrayList class with the elements from the specified System.Collections.ICollection. The initial System.Collections.ArrayList.Count and System.Collections.ArrayList.Capacity of the new list are both equal to the number of elements in the specified collection.
A B C D
Parameters
E F G
Parameter
Description
c
The System.Collections.ICollection whose elements are copied to the new list.
H I J
Description
K
The elements in the new System.Collections.ArrayList instance are in the same order as contained in c.
L
Exceptions
M N
Exception
Condition
System.ArgumentNullException
c is null.
O P Q R
Example
S
using System; using System.Collections;
T namespace Samples { public class ArrayListConstructor { public static void Main() { string[] s = {"damien", "mark", "brad"}; ArrayList a = new ArrayList(s); Console.WriteLine("Count: {0}", a.Count); Console.WriteLine("Default Capacity: {0}", a.Capacity); PrintElements(a); s[0] = "maire"; s[1] = "sacha";
U V W X Y Z
198
Contents | Index
System.Collections
ArrayList Capacity Property
s[2] = "tamara"; PrintElements(a); } public static void PrintElements(IEnumerable ie) { IEnumerator e = ie.GetEnumerator(); while(e.MoveNext()) Console.Write("{0} ", e.Current ); Console.WriteLine(); }
A B C D
}
E
}
F
The output is
G Count: 3 Default Capacity: 3 damien mark brad damien mark brad
H I J K
ArrayList.Capacity Property
L
[ILASM]
M
.property int32 Capacity { public hidebysig virtual specialname int32 get_Capacity() public hidebysig virtual specialname void set_Capacity(int32 value) }
N
[C#]
O
public virtual int Capacity { get; set; }
P
Summary
Q
Gets or sets the number of elements that the current instance is capable of storing.
R
Description
S
[Note: The System.Collections.ArrayList.Capacity of a System.Collections.ArrayList is the size of the internal array used to hold the elements of that list. When it is set, the internal array is reallocated to the specified value.]
T U
Default
W
If an attempt is made to set System.Collections.ArrayList.Capacity to a value less than or equal to 0, it is set to the default capacity of 16. If the System.Collections.ArrayList.Count of the current instance exceeds the System.Collections.ArrayList.Capacity of the current instance while adding elements to the current instance, the capacity of the list is doubled by automatically reallocating the internal array before copying the old elements and adding the new elements.
X
V
Y Z
199
Contents | Index
ArrayList
System.Collections
Count Property
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
System.Collections.ArrayList.Capacity is set to a value that is less than the System.Collections.ArrayList.Count of the current instance.
A B C D E
Example
F
using System; using System.Collections;
G namespace Samples { public class ArrayListCapacity { public static void Main() { ArrayList a = new ArrayList(); Console.WriteLine("Capacity: {0}", a.Capacity); a.Capacity = 32; Console.WriteLine("Capacity: {0}", a.Capacity); } } }
H I J K L M N O
The output is
P Q
Capacity: 16 Capacity: 32
R S
ArrayList.Count Property
T U
[ILASM]
V
[C#]
.property int32 Count { public hidebysig virtual specialname int32 get_Count() } public virtual int Count { get; }
W X
Summary
Y
Gets the number of elements contained in the current instance.
Z
200
Contents | Index
System.Collections
ArrayList IsFixedSize Property
Description System.Collections.ArrayList.Count is the number of elements that are contained by the System.Collections.ArrayList. The count of a list is always less than or equal to System.Collections.ArrayList.Capacity of that list. [Note: This property is implemented to support the System.Collections.IList interface.]
A B C
Default
D
If the System.Collections.ArrayList.Count exceeds the System.Collections.ArrayList.Capacity of the current instance while adding elements to the current instance, the capacity of the list is doubled by automatically reallocating the internal array before copying the old elements and adding the new elements.
E F G H
Example
I
using System; using System.Collections;
J K
namespace Samples { public class ArrayListCount { public static void Main() { ArrayList a = new ArrayList(); Console.WriteLine("Count: {0}", a.Count); a.Add("damien"); a.Add("mark"); a.Add("brad"); Console.WriteLine("Count: {0}", a.Count); } } }
L M N O P Q R S T
The output is
U Count: 0 Count: 3
V W
ArrayList.IsFixedSize Property
X
[ILASM]
Y
.property bool IsFixedSize { public hidebysig virtual specialname bool get_IsFixedSize() }
Z
[C#]
public virtual bool IsFixedSize { get; }
201
Contents | Index
ArrayList
System.Collections
IsReadOnly Property
Summary Gets a System.Boolean indicating whether the System.Collections.ArrayList.Capacity of the current instance cannot be changed. A B
Property Value
C
true if the System.Collections.ArrayList.Capacity of the current instance cannot be changed; otherwise, false.
D E
Description
F
[Note: Elements cannot be added or removed from a System.Collections.ArrayList with a fixed size, while existing elements can be modified.This property is implemented to support the System.Collections.IList interface.]
G H I
Default
J
The default value for this property is false.
K L
ArrayList.IsReadOnly Property
M
[ILASM]
N
.property bool IsReadOnly { public hidebysig virtual specialname bool get_IsReadOnly() }
O
[C#]
public virtual bool IsReadOnly { get; }
P Q
Summary
R
Gets a value indicating whether the current instance is read-only.
S
Property Value
T
true if the current instance is read-only; otherwise, false.
U V
Description
W
[Note: The elements of a System.Collections.ArrayList that is read-only cannot be modified, nor can elements be added to or removed from that list. This property is implemented to support the System.Collections.IList interface.]
X Y
Default
Z
The default value of this property is false.
202
Contents | Index
System.Collections
ArrayList IsSynchronized Property
Example using System; using System.Collections;
A namespace Samples { public class ArrayListIsReadOnly { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); ArrayList b = ArrayList.ReadOnly(a); IsArrayListReadOnly(a); IsArrayListReadOnly(b); } public static void IsArrayListReadOnly(ArrayList a) { if(a.IsReadOnly) Console.WriteLine("ArrayList is read only"); else Console.WriteLine("ArrayList is not read only"); } } }
B C D E F G H I J K L M N O P
The output is
Q ArrayList is not read only ArrayList is read only
R S T
ArrayList.IsSynchronized Property
U [ILASM]
V
.property bool IsSynchronized { public hidebysig virtual specialname bool get_IsSynchronized() } [C#]
W
public virtual bool IsSynchronized { get; }
X Y
Summary
Z
Gets a value indicating whether access to the current instance is synchronized (thread-safe).
203
Contents | Index
ArrayList
System.Collections
IsSynchronized Property
Property Value true if access to the current instance is synchronized (thread-safe); otherwise, false. A
Description
B
To guarantee the thread safety of the System.Collections.ArrayList, all operations must be done through the wrapper returned by the System.Collections. ArrayList.Synchronized method. [Note: This property is implemented to support the System.Collections.IList interface.]
C D E F
Default
G
The default value of this property is false.
H I
Example
J
using System; using System.Collections;
K namespace Samples { public class ArrayListIsSynchronized { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); ArrayList b = ArrayList.Synchronized(a); IsArrayListSynchronized(a); IsArrayListSynchronized(b); } public static void IsArrayListSynchronized(ArrayList a) { if(a.IsSynchronized) Console.WriteLine("ArrayList is synchronized"); else Console.WriteLine("ArrayList is not synchronized"); } } }
L M N O P Q R S T U V W X Y
The output is
Z
ArrayList is not synchronized ArrayList is synchronized
204
Contents | Index
System.Collections
ArrayList Item Property
ArrayList.Item Property [ILASM]
.property object Item[int32 index] { public hidebysig virtual specialname object get_Item(int32 index) public hidebysig virtual specialname void set_Item(int32 index, object value) }
A B
[C#]
C
public virtual object this[int index] { get; set; }
D
Summary
E
Gets or sets the element at the specified index of the current instance.
F G
Parameters
H
Parameter
Description
index
A System.Int32 that specifies the zero-based index of the element in the current instance to get or set. This value is greater than or equal to 0, and less than the System.Collections.ArrayList.Count of the current instance.
I J K L
Description
M
[Note: This property provides the ability to access a specific element in the collection by using the following syntax: myCollection[index]. This property is implemented to support the System.Collections.IList interface.]
N O
Exceptions
Q
P
R
Exception
System.ArgumentOutOfRangeException
Condition
S
index < 0.
T
-or-
U
index >= System.Collections.ArrayList.Count of the current instance.
V W X Y Z
205
Contents | Index
ArrayList
System.Collections
SyncRoot Property
Example using System; using System.Collections;
A
namespace Samples { public class ArrayListItem { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); a[0] = "maire"; a[1] = "sacha"; a[2] = "tamara"; for(int i = 0; i < a.Count; i++) Console.Write("{0} ", a[i]); Console.WriteLine(); } } }
B C D E F G H I J K L M
The output is
N
maire sacha tamara
O P
ArrayList.SyncRoot Property
Q [ILASM]
R
.property object SyncRoot { public hidebysig virtual specialname object get_SyncRoot() }
S
[C#]
T
public virtual object SyncRoot { get; }
U
Summary
V
Gets an object that can be used to synchronize access to the current instance.
W
Description
X
Program code must perform synchronized operations on the System.Collections.ArrayList.SyncRoot of the current instance, not directly on the current instance. This ensures proper operation of collections that are derived from other objects. Specifically, it maintains proper synchronization with other threads that might be simultaneously modifying the current instance.
Y Z
206
Contents | Index
System.Collections
ArrayList Adapter() Method
Default This method returns a reference to the current instance. [Note: This property is implemented to support the System.Collections.IList interface.]
A B
Example
C
using System; using System.Collections;
D E
namespace Samples { public class ArrayListSyncRoot { public static void Main() { ArrayList a = new ArrayList(); lock(a.SyncRoot) { a.Add("damien"); a.Add("mark"); a.Add("brad"); foreach(Object o in a) Console.WriteLine(o); } } } }
F G H I J K L M N O P
The output is
Q damien mark brad
R S T
ArrayList.Adapter(System.Collections.IList) Method
U
[ILASM]
V
.method public hidebysig static class System.Collections.ArrayList Adapter(class System.Collections.IList list)
W
[C#]
X
public static ArrayList Adapter(IList list)
Y
Summary
Z
Creates a System.Collections.ArrayList that is a wrapper for the specified System.Collections.IList. 207
Contents | Index
ArrayList
System.Collections
Adapter() Method
Parameters Parameter
Description
list
The System.Collections.IList to wrap.
A B C
Description
D
This method returns a System.Collections.ArrayList that contains a reference to the System.Collections.IList list. Any modifications to the elements in either the returned list or list are reflected in the other. [Note: The System.Collections.ArrayList class provides generic System.Collections.ArrayList.Reverse, System.Collections.ArrayList.BinarySearch and System.Collections.ArrayList.Sort methods. This wrapper provides a means to use those methods on System.Collections.IList list without implementing the methods for the list. Performing these operations through the wrapper may be less efficient than operations applied directly to the list.]
E F G H I J K L
Exceptions
M N O
Exception
Condition
System.ArgumentNullException
list is null.
P Q
Example
R
using System; using System.Collections;
S
namespace Samples { public class ArrayListAdapter { public static void Main() { string[] s = {"damien", "mark", "brad"}; ArrayList a = ArrayList.Adapter(s); Console.WriteLine("Count: {0}", a.Count); Console.WriteLine("Default Capacity: {0}", a.Capacity ); PrintElements(a); s[1] = "brad"; s[2] = "mark"; PrintElements(a);
T U V W X Y Z
208
Contents | Index
System.Collections
ArrayList Add() Method
} public static void PrintElements(IEnumerable ie) { Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o); Console.WriteLine(); }
A B C
}
D
}
E
The output is
F Count: 3 Default Capacity: 3 Values: damien mark brad Values: damien brad mark
G H I J
ArrayList.Add(System.Object) Method
K
[ILASM]
L
.method public hidebysig virtual int32 Add(object value)
M
[C#]
public virtual int Add(object value)
N
Summary
O
Adds the specified System.Object to the end of the current instance.
P Q
Parameters
R
Parameter
Description
value
The System.Object to be added to the end of the current instance.
S T U V
Return Value
W
A System.Int32 that specifies the index of the current instance at which value has been added.
X Y Z
209
Contents | Index
ArrayList
System.Collections
Add() Method
Exceptions Exception
Condition
System.NotSupportedException
The current instance is read-only or has a fixed size.
A B C D
Example
E
using System; using System.Collections;
F namespace Samples { public class ArrayListAdd { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); Console.WriteLine("-- ArrayList --" ); Console.WriteLine("Count: {0}", a.Count); Console.WriteLine("Capacity: {0}", a.Capacity ); PrintElements(a); } public static void PrintElements(IEnumerable ie) { Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o); Console.WriteLine(); } } }
G H I J K L M N O P Q R S T U
The output is
V W
-- ArrayList -Count: 3 Capacity: 16 Values: damien mark brad
X Y Z
210
Contents | Index
System.Collections
ArrayList AddRange() Method
ArrayList.AddRange(System.Collections.ICollection) Method [ILASM]
.method public hidebysig virtual void AddRange(class System.Collections.ICollection c)
A
[C#]
B
public virtual void AddRange(ICollection c)
C
Summary
D
Adds the elements of the specified System.Collections.ICollection to the end of the current instance.
E F
Parameters
G H
Parameter
Description
c
The System.Collections.ICollection whose elements are added to the end of the current instance.
I J K L
Default
M
If the System.Collections.ArrayList.Count of the current instance plus the size of the collection being added is greater than the System.Collections.ArrayList.Capacity of the current instance, the capacity of the current instance is either doubled or increased to the new System.Collections.ArrayList.Count, whichever is greater. The internal array is reallocated to accommodate the new elements and the existing elements are copied to the new array before the new elements are added. [Note: For the default implementation, if the current instance can accommodate the new elements without increasing the System.Collections.ArrayList.Capacity, this method is an O(n) operation, where n is the number of elements to be added. If the capacity needs to be increased to accommodate the new elements, this method becomes an O(n+m) operation, where n is the number of elements to be added and m is System.Collections.ArrayList.Count.]
N O P Q R S T U V
Exceptions
W
Exception
Condition
System.ArgumentNullException
c is null.
System.NotSupportedException
The current instance is read-only or has a fixed size.
X Y Z
211
Contents | Index
ArrayList
System.Collections
BinarySearch() Method
Example using System; using System.Collections;
A namespace Samples { public class ArrayListAddRange { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.AddRange(new string[]{"mark", "brad"}); Console.WriteLine("Count: {0}", a.Count); Console.WriteLine("Default Capacity: {0}", a.Capacity ); PrintElements(a); } public static void PrintElements(IEnumerable ie) { Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o); Console.WriteLine(); } } }
B C D E F G H I J K L M N O
The output is
P Count: 3 Default Capacity: 16 Values: damien mark brad
Q R S
ArrayList.BinarySearch(System.Int32, System.Int32, System.Object, System.Collections.IComparer) Method
T U
[ILASM]
V
.method public hidebysig virtual int32 BinarySearch(int32 index, int32 count, object value, class System.Collections.IComparer comparer)
W
[C#]
X
public virtual int BinarySearch(int index, int count, object value, IComparer comparer)
Y Z
212
Contents | Index
System.Collections
ArrayList BinarySearch() Method
Summary Searches the specified range in the current instance for the specified System.Object using the specified System.Collections.IComparer implementation. A
Parameters
B C
Parameter
Description
index
A System.Int32 that specifies the index at which searching starts. This value is greater than or equal to zero, and less than the System.Collections.ArrayList.Count of the current instance.
D
count
A System.Int32 that specifies the number of elements to search, beginning with index. This value is greater than or equal to zero, and less than or equal to the System.Collections.ArrayList.Count of the current instance minus index.
value
The System.Object for which to search.
comparer
The System.Collections.IComparer implementation to use when comparing elements. Specify null to use the System.IComparable implementation of each element.
E F G H I J K L M
Return Value
N
A System.Int32 that specifies the results of the search as follows:
O P
Return Value
Description
The index of value in the current instance.
value was found.
The bitwise complement of the index of the first element that is greater than value.
value was not found, and at least one element in the range of index to index + count – 1 in the current instance is greater than value.
Q R S
The bitwise complement of (index + count)
T U
value was not found, and value is greater than all elements in the range of index to index + count – 1 in the current instance.
V W X Y
[Note: If value is not found and the current instance is already sorted, the bitwise complement of the return value indicates the index in the current instance where value would be found in the range of index to index + count – 1.]
Z
213
Contents | Index
ArrayList
System.Collections
BinarySearch() Method
Description [Note: A null reference can be compared with any type; therefore, comparisons with a null reference do not generate exceptions. A null reference evaluates to less than any non-null object, or equal to another null reference, when the two are compared.]
A B
Default
C
This method uses System.Array.BinarySearch to search for value. value is compared to elements in a binary search of the range of index to index + count – 1 in the current instance until an element with a value greater than or equal to value is found or the end of the range is reached. If comparer is null, the System.IComparable implementation of the element being compared—or of value if the element being compared does not implement the interface—is used to make the comparison. If value does not implement the System.IComparable interface and is compared to an element that does not implement the interface either, System.ArgumentException is thrown. If the current instance is not already sorted, correct results are not guaranteed. [Note: For the default implementation, this method is an O(logcount) operation.]
D E F G H I J K
Exceptions
L M
Exception
Condition
N O
System.Collections.ArrayList.Count of the current instance – index < count.
P
-or-
Q
System.ArgumentException
R
comparer is null, and both value and at least one element of the current instance do not implement the System.IComparable interface. -or-
S
comparer is null, and value is not assignment-compatible with at least one element in the current instance.
T U
index < 0. System.ArgumentOutOfRangeException
V W
-orcount < 0.
X Y Z
214
Contents | Index
System.Collections
ArrayList BinarySearch() Method
Example using System; using System.Collections;
A namespace Samples { public class ArrayListBinarySearch { public class MyReverseComparer: IComparer { public int Compare(Object a, Object b) { return -((IComparable)a).CompareTo(b); } } public static void Main() { ArrayList a = new ArrayList(); a.Add("mark"); a.Add("sacha"); a.Add("brad"); a.Add("tamara"); a.Add("damien"); a.Add("maire"); IComparer ic = new MyReverseComparer(); a.Sort(ic); Console.Write("Values: "); foreach(object o in a) Console.Write("{0} ", o); Console.WriteLine(); SearchFor(a, "maire", ic); SearchFor(a, "leah", ic); SearchFor(a, "zoe", ic); } public static void SearchFor(ArrayList a, string s, IComparer ic) { int i = a.BinarySearch(s, ic); if(i > 0) { Console.WriteLine( "Object: {0}, was found at: {1}", s, i ); } else if(~i == a.Count) { Console.WriteLine( "Object: {0}, was not found", s); Console.WriteLine(
B C D E F G H I J K L M N O P Q R S T U V W X Y Z
215
Contents | Index
ArrayList
System.Collections
BinarySearch() Method
"No object in the array had a greater value."); } else { Console.WriteLine("Object: {0}, was not found", s); Console.WriteLine( "The next larger object is at index: {0}.", ~i ); }
A B C }
D
} }
E F
The output is
G Values: tamara sacha mark maire damien brad Object: maire, was found at: 3 Object: leah, was not found The next larger object is at index: 4. Object: zoe, was not found The next larger object is at index: 0.
H I J K L M
ArrayList.BinarySearch(System.Object) Method
N
[ILASM]
.method public hidebysig virtual int32 BinarySearch(object value)
O
[C#]
public virtual int BinarySearch(object value)
P Q
Summary
R
Searches the current instance for the specified System.Object.
S
Parameters
T U
Parameter
Description
value
The System.Object for which to search.
V W X
Return Value
Y
A System.Int32 that specifies the results of the search as follows:
Z
216
Contents | Index
System.Collections
ArrayList BinarySearch() Method
Return Value
Description
The index of value in the current instance.
value was found.
A
The bitwise complement of the index of the first element that is greater than value.
value was not found, and at least one element in the current instance is greater than value.
B
The bitwise complement of the System.Collections.ArrayList.Count of the current instance.
value was not found, and value is greater than all elements in the current instance.
D
C
E F G
[Note: If value is not found and the current instance is already sorted, the bitwise complement of the return value indicates the index in the current instance where value would be found.]
H
Description
J
[Note: A null reference can be compared with any type; therefore, comparisons with a null reference do not generate exceptions. A null reference evaluates to less than any non-null object, or equal to another null reference, when the two are compared.]
K
I
L M
Default
N
This method uses System.Array.BinarySearch to search for value. value is compared to elements in a binary search of the current instance until an element with a value greater than or equal to value is found. The System.IComparable implementation of the element being compared—or of value if the element being compared does not implement the interface—is used to make the comparison. If value does not implement the System.IComparable interface and is compared to an element that does not implement the interface either, System.ArgumentException is thrown. If the current instance is not already sorted, correct results are not guaranteed. [Note: For the default implementation, this method is an O(logn) operation where n is equal to the System.Collections.ArrayList.Count of the current instance.]
O P Q R S T U V W X Y Z
217
Contents | Index
ArrayList
System.Collections
BinarySearch() Method
Exceptions Exception
Condition
A
Both value and at least one element of the current instance do not implement the System.IComparable interface.
B C
System.ArgumentException
-orvalue is not assignment-compatible with at least one element in the current instance.
D E F G
Example
H
using System; using System.Collections;
I
namespace Samples { public class ArrayListBinarySearch { public static void Main() { ArrayList a = new ArrayList(); a.Add("mark"); a.Add("sacha"); a.Add("brad"); a.Add("tamara"); a.Add("damien"); a.Add("maire"); a.Sort(); Console.Write("Values: "); foreach(object o in a) Console.Write("{0} ", o); Console.WriteLine(); SearchFor(a, "maire"); SearchFor(a, "leah"); SearchFor(a, "zoe"); } public static void SearchFor(ArrayList a, string s) { int i = a.BinarySearch(s); if(i > 0) { Console.WriteLine( "Object: {0}, was found at: {1}", s, i ); } else if(~i == a.Count) { Console.WriteLine( "Object: {0}, was not found", s);
J K L M N O P Q R S T U V W X Y Z
218
Contents | Index
System.Collections
ArrayList BinarySearch() Method
Console.WriteLine( "No object in the array had a greater value."); } else { Console.WriteLine("Object: {0}, was not found", s); Console.WriteLine( "The next larger object is at index: {0}.", ~i ); }
A B C D
} }
E
}
F
The output is
G
Values: brad damien maire mark sacha tamara Object: maire, was found at: 2 Object: leah, was not found The next larger object is at index: 2. Object: zoe, was not found No object in the array had a greater value.
H I J K L
ArrayList.BinarySearch(System.Object, System.Collections.IComparer) Method
M N
[ILASM]
O
.method public hidebysig virtual int32 BinarySearch(object value, class System.Collections.IComparer comparer)
P
[C#]
Q
public virtual int BinarySearch(object value, IComparer comparer)
R
Summary
S
Searches the current instance for the specified System.Object using the specified System.Collections.IComparer implementation.
T U
Parameters
V
Parameter
Description
value
The System.Object for which to search.
comparer
The System.Collections.IComparer implementation to use when comparing elements. Specify null to use the System.IComparable implementation of each element.
W X Y Z
219
Contents | Index
ArrayList
System.Collections
BinarySearch() Method
Return Value A System.Int32 that specifies the results of the search as follows: A B C
Return Value
Description
The index of value in the current instance.
value was found.
The bitwise complement of the index of the first element that is greater than value.
value was not found, and at least one element in the current instance is greater than value.
The bitwise complement of the System.Collections.ArrayList.Count of the current instance.
value was not found, and value is greater than all elements in the current instance.
D E F G H I
[Note: If value is not found and the current instance is already sorted, the bitwise complement of the return value indicates the index in the current instance where value would be found.]
J K L
Description
M
[Note: A null reference can be compared with any type; therefore, comparisons with a null reference do not generate exceptions. A null reference evaluates to less than any non-null object, or equal to another null reference, when the two are compared.]
N O P
Default
Q
This method uses System.Array.BinarySearch to search for value. value is compared to elements in a binary search of the current instance until an element with a value greater than or equal to value is found. If comparer is null, the System.IComparable implementation of the element being compared—or of value if the element being compared does not implement the interface—is used to make the comparison. If value does not implement the System.IComparable interface and is compared to an element that does not implement the interface either, System.ArgumentException is thrown. If the current instance is not already sorted, correct results are not guaranteed. [Note: For the default implementation, this method is an O(logn) operation where n is equal to the System.Collections.ArrayList.Count of the current instance.]
R S T U V W X Y Z
220
Contents | Index
System.Collections
ArrayList BinarySearch() Method
Exceptions Exception
Condition A
System.Argument Exception
comparer is null, and both value and at least one element in the current instance do not implement the System.IComparable interface.
B
-or-
C
comparer is null, and value is not assignment-compatible with at least one element in the current instance.
D E F
Example
G
using System; using System.Collections;
H I
namespace Samples { public class ArrayListBinarySearch { public class MyComparer: IComparer { public int Compare(Object a, Object b) { return ((IComparable)a).CompareTo(b); } } public static void Main() { ArrayList a = new ArrayList(); a.Add("mark"); a.Add("sacha"); a.Add("brad"); a.Add("tamara"); a.Add("damien"); a.Add("maire"); a.Sort(); Console.Write("Values: "); foreach(object o in a) Console.Write("{0} ", o); Console.WriteLine(); SearchFor(a, "maire"); SearchFor(a, "leah"); SearchFor(a, "zoe"); } public static void SearchFor(ArrayList a, string s) {
J K L M N O P Q R S T U V W X Y Z
221
Contents | Index
ArrayList
System.Collections
Clear() Method
int i = a.BinarySearch(s, new MyComparer()); if(i > 0) { Console.WriteLine( "Object: {0}, was found at: {1}", s, i ); } else if(~i == a.Count) { Console.WriteLine( "Object: {0}, was not found", s); Console.WriteLine( "No object in the array had a greater value."); } else { Console.WriteLine("Object: {0}, was not found", s); Console.WriteLine( "The next larger object is at index: {0}.", ~i ); }
A B C D E F G H I }
J }
K
}
L
The output is
M Values: brad damien maire mark sacha tamara Object: maire, was found at: 2 Object: leah, was not found The next larger object is at index: 2. Object: zoe, was not found No object in the array had a greater value.
N O P Q R S
ArrayList.Clear() Method
T
[ILASM]
.method public hidebysig virtual void Clear()
U
[C#]
public virtual void Clear()
V W
Summary
X
Sets the elements in the current instance to zero, false, or null, depending upon the element type.
Y Z
222
Contents | Index
System.Collections
ArrayList Clear() Method
Description [Note: This method is implemented to support the System.Collections.IList interface.] A
Behaviors
B
Reference-type elements are set to null. Value-type elements are set to zero, except for System.Boolean elements, which are set to false.
C D
Default
E
This method uses System.Array.Clear to reset the values of the current instance. System.Collections.ArrayList.Count is set to zero. System.Collections.ArrayList.Capacity is not changed.
F G H
Usage
I
To reset the System.Collections.ArrayList.Capacity of the current instance, call System.Collections.ArrayList.TrimToSize or set the System.Collections.ArrayList.Capacity property directly.
J K L
Exceptions
M N
Exception
Condition
System.NotSupportedException
The current instance is read-only or has a fixed size.
O P Q
Example
R
using System; using System.Collections;
S T
namespace Samples { public class ArrayListClear { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); PrintElements(a); a.Clear();
U V W X Y Z
223
Contents | Index
ArrayList
System.Collections
Clone() Method
PrintElements(a); } public static void PrintElements(IEnumerable ie) { Console.WriteLine("Values:"); foreach(object o in ie) Console.WriteLine(o); }
A B C }
D
}
E
The output is
F Values: damien mark brad Values:
G H I J K
ArrayList.Clone() Method
L
[ILASM]
M
.method public hidebysig virtual object Clone() [C#]
N
public virtual object Clone()
O
Summary
P
Returns a System.Object that is a copy of the current instance.
Q R
Description
S
[Note: This method is implemented to support the System.ICloneable interface.]
T
Default
U
This method uses System.Array.Copy to clone the current instance.
V W
Example
X
using System; using System.Collections;
Y
namespace Samples { public class ArrayListClone {
Z
224
Contents | Index
System.Collections
ArrayList Contains() Method
public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); PrintElements(a); ArrayList b = (ArrayList)a.Clone(); a.Clear(); PrintElements(a); PrintElements(b); } public static void PrintElements(IEnumerable ie) { Console.WriteLine("Values:"); foreach(object o in ie) Console.WriteLine(o); }
A B C D E F G H I
}
J
}
K
The output is
L
Values: damien mark brad Values: Values: damien mark brad
M N O P Q R S
ArrayList.Contains(System.Object) Method
T
[ILASM]
U
.method public hidebysig virtual bool Contains(object item)
V
[C#]
public virtual bool Contains(object item)
W
Summary
X
Determines whether the specified System.Object is contained in the current instance.
Y Z
225
Contents | Index
ArrayList
System.Collections
Contains() Method
Parameters Parameter
Description
item
The System.Object to locate in the current instance.
A B C D
Return Value
E
true if item is contained in the current instance; otherwise, false.
F
Description
G
[Note: This method is implemented to support the System.Collections.IList interface.]
H
Default
I
This method determines equality by calling the System.Object.Equals implementation of the type of item. [Note: For the default implementation, this method is an O(n) operation where n is equal to the System.Collections.ArrayList.Count of the current instance. If the current instance is sorted, it is more efficient to call System.Collections.ArrayList.BinarySearch method.]
J K L M N
Example
O
using System; using System.Collections;
P Q
namespace Samples { public class MyName { private string name; public MyName(string name) { this.name = name; } public override bool Equals(object o) { Console.WriteLine("Equals called with {0} and {1}", this, o); MyName m = o as MyName; return string.Compare(name, m.name, true) == 0;
R S T U V W X Y Z
226
Contents | Index
System.Collections
ArrayList Contains() Method
} public override int GetHashCode() { return name.GetHashCode(); } public override string ToString() { return name; } } public class ArrayListContains { public static void Main() { ArrayList a = new ArrayList(); a.Add(new MyName("damien")); a.Add(new MyName("mark")); a.Add(new MyName("brad")); MyName m = new MyName("mark"); if(a.Contains(m)) Console.WriteLine("'a' contains else Console.WriteLine("'a' does not m = new MyName("maire"); if(a.Contains(m)) Console.WriteLine("'a' contains else Console.WriteLine("'a' does not } }
A B C D E F G H I J \"{0}\"", m);
K
contain \"{0}\"", m);
L M
\"{0}\"", m);
N
contain \"{0}\"", m);
O P
}
Q
The output is
R S
Equals called with mark and damien Equals called with mark and mark 'a' contains "mark" Equals called with maire and damien Equals called with maire and mark Equals called with maire and brad 'a' does not contain "maire"
T U V W X Y Z
227
Contents | Index
ArrayList
System.Collections
CopyTo() Method
ArrayList.CopyTo(System.Int32, System.Array, System.Int32, System.Int32) Method [ILASM]
A
.method public hidebysig virtual void CopyTo(int32 index, class System.Array array, int32 arrayIndex, int32 count)
B
[C#]
C
public virtual void CopyTo(int index, Array array, int arrayIndex, int count)
D E
Summary
F
Copies the specified range of elements from the current instance to the specified System.Array, starting at the specified index of the array.
G
Parameters
H I
Parameter
Description
index
A System.Int32 that specifies the index in the current instance at which copying begins. This value is greater than or equal to 0, and less than the System.Collections.ArrayList.Count of the current instance.
array
The one-dimensional System.Array that is the destination of the elements copied from the current instance.
arrayIndex
A System.Int32 that specifies the first index of array to which the elements of the current instance are copied. This value is greater than or equal to 0, and less than array.Length minus count.
count
A System.Int32 that specifies the number of elements to copy. This value is greater than or equal to 0, and less than both the System.Collections.ArrayList.Count of the current instance minus index and array.Length minus arrayIndex.
J K L M N O P Q R S T U
Default
V
This method uses System.Array.Copy to copy the current instance to array.
W X Y Z
228
Contents | Index
System.Collections
ArrayList CopyTo() Method
Exceptions Exception
Condition
System.ArgumentNullException
array is null.
A
System.ArgumentOutOfRangeException
B
index < 0.
C
-or-
D
arrayIndex < 0.
E
-orF
count < 0.
G
array has more than one dimension.
H
-or-
I
index >= System.Collections.ArrayList.Count of the current instance. System.ArgumentException
J
-or-
K
count >= System.Collections.ArrayList.Count of the current instance – index.
L
-or-
M
count >= array.Length – arrayIndex. System.InvalidCastException
N
At least one element of the current instance is not assignment-compatible with the type of array.
O P Q
Example
R
using System; using System.Collections;
S T
namespace Samples { public class ArrayListCopyTo { public static void Main() { string[] s = new string[] {"1","2","3","4","5","6",}; ArrayList a = new ArrayList(); a.Add("brad"); a.Add("damien"); a.Add("mark"); a.CopyTo(0, s, 3, 3);
U V W X Y Z
229
Contents | Index
ArrayList
System.Collections
CopyTo() Method
PrintElements(a); PrintElements(s); } public static void PrintElements(IEnumerable ie) { Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o); Console.WriteLine(); }
A B C D }
E }
F
The output is
G H
Values: brad damien mark Values: 1 2 3 brad damien mark
I J K
ArrayList.CopyTo(System.Array) Method
L
[ILASM]
.method public hidebysig virtual void CopyTo(class System.Array array)
M
[C#]
public virtual void CopyTo(Array array)
N O
Summary
P
Copies the elements from the current instance to the specified System.Array.
Q
Parameters
R S
Parameter
Description
array
The one-dimensional System.Array that is the destination of the elements copied from the current instance. The System.Array.Length of this array is greater than or equal to the System.Collections.ArrayList.Count of the current instance.
T U V W X
Default
Y
This method uses System.Array.Copy to copy the current instance to array.
Z
230
Contents | Index
System.Collections
ArrayList CopyTo() Method
Exceptions Exception
Condition
System.ArgumentNullException
array is null.
System.ArgumentException
array has more than one dimension. -orSystem.Collections.ArrayList.Count of the current instance > array.Length.
A
System.InvalidCastException
B C D E F
At least one element in the current instance is not assignment-compatible with the type of array.
G H
Example
I
using System; using System.Collections;
J K
namespace Samples { public class ArrayListCopyTo { public static void Main() { string[] s = new string[3]; ArrayList a = new ArrayList(); a.Add("brad"); a.Add("damien"); a.Add("mark"); a.CopyTo(s); a.Clear(); PrintElements(a); PrintElements(s); } public static void PrintElements(IEnumerable ie) { Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o); Console.WriteLine(); } } }
L M N O P Q R S T U V W X Y Z
231
Contents | Index
ArrayList
System.Collections
CopyTo() Method
The output is Values: Values: brad damien mark
A B C
ArrayList.CopyTo(System.Array, System.Int32) Method
D
[ILASM]
E
.method public hidebysig virtual void CopyTo(class System.Array array, int32 arrayIndex)
F
[C#]
public virtual void CopyTo(Array array, int arrayIndex)
G H
Summary
I
Copies the elements from the current instance to the specified System.Array, starting at the specified index of the array.
J K
Parameters
L M
Parameter
Description
array
The one-dimensional System.Array that is the destination of the elements copied from the current instance. The System.Array.Length of this array is greater than or equal to the sum of arrayIndex and the System.Collections.ArrayList.Count of the current instance.
arrayIndex
A System.Int32 that specifies the first index of array to which the elements of the current instance are copied. This value is greater than or equal to zero, and less than array.Length.
N O P Q R S T
Description
U
[Note: This method is implemented to support the System.Collections.IList interface.]
V
Default
W
This method uses System.Array.Copy to copy the current instance to array.
X Y Z
232
Contents | Index
System.Collections
ArrayList CopyTo() Method
Exceptions Exception
Condition
System.ArgumentNullException
array is null.
System.ArgumentOutOfRangeException
arrayIndex < 0.
System.ArgumentException
array has more than one dimension. -orarrayIndex >= array.Length. -orarrayIndex + System.Collections.ArrayList.Count of the current instance > array.Length.
A
System.InvalidCastException
B C D E F G H
At least one element in the current instance is not assignment-compatible with the type of array.
I J
Example
K
using System; using System.Collections;
L M
namespace Samples { public class ArrayListCopyTo { public static void Main() { string[] s = new string[] {"1", "2", "3", "4", "5", "6"}; ArrayList a = new ArrayList(); a.Add("brad"); a.Add("damien"); a.Add("mark"); a.CopyTo(s, 1); PrintElements(a); PrintElements(s); } public static void PrintElements(IEnumerable ie) { Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o); Console.WriteLine(); } } }
N O P Q R S T U V W X Y Z
233
Contents | Index
ArrayList
System.Collections
FixedSize() Method
The output is Values: brad damien mark Values: 1 brad damien mark 5 6
A B C
ArrayList.FixedSize(System.Collections.ArrayList) Method
D
[ILASM]
E
.method public hidebysig static class System.Collections.ArrayList FixedSize(class System.Collections.ArrayList list)
F
[C#]
public static ArrayList FixedSize(ArrayList list)
G H
Summary
I
Returns a System.Collections.ArrayList wrapper with a fixed size.
J
Parameters
K L M
Parameter
Description
list
The System.Collections.ArrayList to wrap.
N O
Description
P
This method returns a fixed-size System.Collections.ArrayList that contains a reference to list. Operations that attempt add to or delete from this new list will throw System.NotSupportedException. Any modifications of the elements in either the returned list or list will be reflected in the other. [Note: The System.Collections.ArrayList.IsFixedSize property of the new list is true. Every other property value of the new list references the same property value of list. By performing operations on the new list, this wrapper can be used to prevent additions to and deletions from the System.Collections.ArrayList list. The elements of the list can still be modified by operations on the returned list.]
Q R S T U V W
Exceptions
X Y
Exception
Condition
System.ArgumentNullException
list is null.
Z
234
Contents | Index
System.Collections
ArrayList FixedSize() Method
Example using System; using System.Collections;
A namespace Samples { public class ArrayListFixedSize { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); ArrayList b = ArrayList.FixedSize(a); PrintElements(b); try { a.Add("maire"); PrintElements(b); b.Add("tamara"); } catch(NotSupportedException e) { Console.WriteLine("FixedSize ArrayList {0}", e); } } public static void PrintElements(IEnumerable ie) { Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o); Console.WriteLine(); } } }
B C D E F G H I J K L M N O P Q R S T U
The output is
V W
Values: damien mark brad Values: damien mark brad maire FixedSize ArrayList System.NotSupportedException: Collection was of a fixed size. at System.Collections.FixedSizeArrayList.Add(Object obj) at Samples.ArrayListFixedSize.Main() in C:\Books\BCL\Samples\System.Collections\ArrayList\FixedSize(System.Collections.ArrayList)\ArrayList.cs:line 20
X Y Z
235
Contents | Index
ArrayList
System.Collections
FixedSize() Method
ArrayList.FixedSize(System.Collections.IList) Method [ILASM]
A
.method public hidebysig static class System.Collections.IList FixedSize(class System.Collections.IList list)
B
[C#]
public static IList FixedSize(IList list)
C D
Summary
E
Returns a System.Collections.IList wrapper with a fixed size.
F
Parameters
G H I
Parameter
Description
list
The System.Collections.IList to wrap.
J K
Return Value
L
A System.Collections.IList wrapper with a fixed size.
M
Description
N
This wrapper can be used to prevent additions to and deletions from the original System.Collections.IList. The elements can still be modified or replaced. A collection with a fixed size is simply a collection with a wrapper that prevents adding and removing elements; therefore, if changes are made to the underlying collection, including the addition or removal of elements, the fixed-size collection reflects those changes.
O P Q R
Exceptions
S T
Exception
Condition
System.ArgumentNullException
list is null.
U V W X
ArrayList.GetEnumerator() Method
Y
[ILASM]
.method public hidebysig virtual class System.Collections.IEnumerator GetEnumerator()
Z
[C#]
public virtual IEnumerator GetEnumerator()
236
Contents | Index
System.Collections
ArrayList GetEnumerator() Method
Summary Returns a System.Collections.IEnumerator for the current instance.
Description
A
If the the current instance is modified while an enumeration is in progress, a call to System.Collections.IEnumerator.MoveNext or System.Collections.IEnumerator.Reset throws System.InvalidOperationException. [Note: For detailed information regarding the use of an enumerator, see System.Collections.IEnumerator. This property is implemented to support the System.Collections.IList interface.]
B C D E F G
Example using System; using System.Collections;
H
namespace Samples { public class ArrayListGetEnumerator { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); IEnumerator e = a.GetEnumerator(); while(e.MoveNext()) Console.Write("{0} ", e.Current); Console.WriteLine(); } } }
J
I
K L M N O P Q R S T
The output is
U
damien mark brad
V W
ArrayList.GetEnumerator(System.Int32, System.Int32) Method
X
[ILASM]
Y
.method public hidebysig virtual class System.Collections.IEnumerator GetEnumerator(int32 index, int32 count)
Z
[C#]
public virtual IEnumerator GetEnumerator(int index, int count)
237
Contents | Index
ArrayList
System.Collections
GetEnumerator() Method
Summary Returns a System.Collections.IEnumerator for the specified section of the current instance. A
Parameters
B C D
Parameter
Description
index
A System.Int32 that specifies the index of the current instance before which the enumerator is initially placed. This value is greater than or equal to 0, and less than the System.Collections.ArrayList.Count of the current instance.
count
A System.Int32 that specifies the number of elements, beginning with index, in the current instance over which the enumerator can iterate. This value is greater than or equal to 0, and less than or equal to the System.Collections.ArrayList.Count of the current instance minus index.
E F G H I J K
Return Value
L
A System.Collections.IEnumerator that can iterate over the range of index to index + count – 1 in the current instance.
M N
Description
O
The enumerator only enumerates over the range of the current instance from index to index + count – 1. If the current instance is modified while an enumeration is in progress, a call to System.Collections.IEnumerator.MoveNext or System.Collections.IEnumerator.Reset will throw System.InvalidOperationException. [Note: For detailed information regarding the use of an enumerator, see System.Collections.IEnumerator.]
P Q R S T
Default
U
The enumerator is initially placed just before the element at position index in the current instance. A call to System.Collections.IEnumerator.Reset returns the enumerator to this position. If the enumerator is positioned over an element in the range of index – 1 to index + count, and the elements of the current instance have not been modified while the enumeration was in progress, a call to System.Collections.IEnumerator.MoveNext either returns true and advances the enumerator one element in the current instance, or returns false and leaves the enumerator in its current position.
V W X Y Z
238
Contents | Index
System.Collections
ArrayList GetRange() Method
Exceptions Exception
Condition A
index < 0. System.ArgumentOutOfRangeException
-or-
System.ArgumentException
index + count > System.Collections.ArrayList.Count of the current instance.
B C
count < 0.
D E F
Example
G
using System; using System.Collections;
H
namespace Samples { public class ArrayListGetEnumerator { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); IEnumerator e = a.GetEnumerator(1,2); while(e.MoveNext()) Console.Write("{0} ", e.Current); Console.WriteLine(); } } }
J
I
K L M N O P Q R S T
The output is
U V
mark brad
W
ArrayList.GetRange(System.Int32, System.Int32) Method
X
[ILASM]
Y
.method public hidebysig virtual class System.Collections.ArrayList GetRange(int32 index, int32 count)
Z
[C#]
public virtual ArrayList GetRange(int index, int count)
239
Contents | Index
ArrayList
System.Collections
GetRange() Method
Summary Returns a System.Collections.ArrayList that represents the specified range of the current instance. A
Parameters
B C D
Parameter
Description
index
A System.Int32 that specifies the zero-based index in the current instance at which the range starts. This value is between 0 and the System.Collections. ArrayList.Count of the current instance minus count, inclusive.
count
A System.Int32 that specifies the number of elements in the range. This value is between 0 and the System.Collections.ArrayList.Count of the current instance minus index, inclusive.
E F G H I J
Return Value
K
A System.Collections.ArrayList that represents the range in the current instance from index to index + count – 1.
L M
Default
N
This method does not create copies of the elements: the new System.Collections.ArrayList instance is a view window into the source list. Therefore, all subsequent changes to the source list must be done through this view window System.Collections.ArrayList. If changes are made directly to the source list, the view window list is invalidated and any operations on it throw System.InvalidOperationException.
O P Q R
Exceptions
S T
Exception
Condition
U
index < 0.
V W
System.ArgumentOutOfRangeException
-or-
System.ArgumentException
System.Collections.ArrayList.Count of the current instance – index < count.
count < 0.
X Y Z
240
Contents | Index
System.Collections
ArrayList IndexOf() Method
Example using System; using System.Collections;
A namespace Samples { public class ArrayListGetRange { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); a.Add("maire"); a.Add("tamara"); a.Add("sacha"); ArrayList b = a.GetRange(1,4); Console.Write("Values: "); foreach(object o in b) Console.Write("{0} ", o); Console.WriteLine(); } } }
B C D E F G H I J K L M N
The output is
O P
Values: mark brad maire tamara
Q R
ArrayList.IndexOf(System.Object) Method
S [ILASM]
.method public hidebysig virtual int32 IndexOf(object value)
T
[C#]
U
public virtual int IndexOf(object value)
V
Summary
W
Searches the current instance, returning the index of the first occurrence of the specified System.Object.
X Y Z
241
Contents | Index
ArrayList
System.Collections
IndexOf() Method
Parameters Parameter
Description
value
The System.Object to locate in current instance.
A B C
Return Value
D
A System.Int32 that specifies the index of the first occurrence of value in the current instance, if found; otherwise, –1. [Note: This provides the caller with a standard code for a failed search.]
E F G
Description
H
[Note: This method is implemented to support the System.Collections.IList interface.]
I
Default
J
This method uses System.Array.IndexOf to search the current instance for value. [Note: For the default implementation, this method performs a linear search. On average, this is an O(n/2) operation, where n is count. The longest search is an O(n) operation.]
K L M
Example
N
using System; using System.Collections;
O
namespace Samples { public class ArrayListIndexOf { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); string s = "mark"; int i = a.IndexOf(s); Console.WriteLine( "{0} is found at {1}", s, i); } } }
P Q R S T U V W X Y Z
The output is mark is found at 1
242
Contents | Index
System.Collections
ArrayList IndexOf() Method
ArrayList.IndexOf(System.Object, System.Int32) Method [ILASM]
.method public hidebysig virtual int32 IndexOf(object value, int32 startIndex) [C#]
A
public virtual int IndexOf(object value, int startIndex)
B C
Summary
D
Searches the current instance, returning the index of the first occurrence of the specified System.Object in the specified range.
E F
Parameters
G H
Parameter
Description
value
The System.Object to locate in the current instance.
startIndex
A System.Int32 that specifies the index at which searching begins. This value is between 0 and the System.Collections.ArrayList.Count of the current instance minus 1, inclusive.
I J K L M
Return Value
N
A System.Int32 that specifies the index of the first occurrence of value in the current instance, if found within the range startIndex to the end of the current instance; otherwise, –1. [Note: This provides the caller with a standard code for a failed search.]
O P Q
Default
R
This method uses System.Array.IndexOf to search the current instance for value. [Note: For the default implementation, this method performs a linear search. On average, this is an O(n/2) operation, where n is count. The longest search is an O(n) operation.]
S T U
Exceptions Exception
V W
Condition
X
startIndex < 0. System.ArgumentOutOfRangeException
Y
-orZ
startIndex >= System.Collections.ArrayList.Count of the current instance.
243
Contents | Index
ArrayList
System.Collections
IndexOf() Method
Example using System; using System.Collections;
A namespace Samples { public class ArrayListIndexOf { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); string s = "brad"; int i = a.IndexOf(s, 1); Console.WriteLine( "{0} is found at {1}", s, i); } } }
B C D E F G H I J K L
The output is
M
brad is found at 2
N O P
ArrayList.IndexOf(System.Object, System.Int32, System.Int32) Method
Q
[ILASM]
R
.method public hidebysig virtual int32 IndexOf(object value, int32 startIndex, int32 count)
S
[C#]
public virtual int IndexOf(object value, int startIndex, int count)
T U
Summary
V
Searches the current instance, returning the index of the first occurrence of the specified System.Object in the specified range.
W X Y Z
244
Contents | Index
System.Collections
ArrayList IndexOf() Method
Parameters Parameter
Description
value
The System.Object to locate in current instance.
startIndex
A System.Int32 that specifies the index at which to begin searching. This value is greater than or equal to zero, and less than the System.Collections.ArrayList.Count of the current instance.
A
count
B C D E
A System.Int32 that specifies the number of elements to search. This value is between 0 and the System.Collections.ArrayList.Count of the current instance minus startIndex, inclusive.
F G H
Return Value
I
A System.Int32 that specifies the index of the first occurrence of value in the current instance, within the range startIndex to startIndex + count – 1, if found; otherwise, –1. [Note: This provides the caller with a standard code for a failed search.]
J K L
Default
M
This method uses System.Array.IndexOf to search the current instance for value. [Note: For the default implementation, this method performs a linear search. On average, this is an O(n/2) operation, where n is count. The longest search is an O(n) operation.]
N O P
Exceptions
Q
Exception
Condition
R
startIndex >= System.Collections.ArrayList.Count of the current instance.
S T
-orSystem.ArgumentOutOfRangeException
U
count < 0.
V
-or-
W
count > System.Collections.ArrayList.Count of the current instance – startIndex.
X Y Z
245
Contents | Index
ArrayList
System.Collections
Insert() Method
Example using System; using System.Collections;
A namespace Samples { public class ArrayListIndexOf { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); string s = "brad"; int i = a.IndexOf(s, 1, 2); Console.WriteLine( "{0} is found at {1}", s, i); } } }
B C D E F G H I J K L
The output is
M
brad is found at 2
N O P
ArrayList.Insert(System.Int32, System.Object) Method
Q
[ILASM]
R
.method public hidebysig virtual void Insert(int32 index, object value)
S
public virtual void Insert(int index, object value)
[C#]
T
Summary
U
Inserts the specified System.Object into the current instance at the specified index.
V W X Y Z
246
Contents | Index
System.Collections
ArrayList Insert() Method
Parameters Parameter
Description
index
A System.Int32 that specifies the index in the current instance at which value is inserted. This value is between 0 and the System.Collections.ArrayList.Count of the current instance, inclusive.
A
value
B C D
The System.Object to insert.
E
Description
F
[Note: This method is implemented to support the System.Collections.IList interface.]
G H
Default
I
If the System.Collections.ArrayList.Count of the current instance is equal to the System.Collections.ArrayList.Capacity of the current instance, the capacity of the list is doubled by automatically reallocating the internal array before the new element is inserted. If index is equal to the System.Collections.ArrayList.Count of the current instance, value is added to the end of the current instance.
J K L M
Exceptions
N O
Exception
System.ArgumentOutOfRangeException
System.NotSupportedException
Condition
P
index < 0.
Q
-or-
R
index > System.Collections.ArrayList.Count of the current instance.
S T
The current instance is read-only or has a fixed size.
U V
Example
W
using System; using System.Collections;
X Y
namespace Samples { public class ArrayListInsert { public static void Main()
Z
247
Contents | Index
ArrayList
System.Collections
InsertRange() Method
{ ArrayList a = new ArrayList(); a.Add("damien"); a.Add("brad"); a.Insert(1, "mark"); foreach(string s in a) Console.WriteLine(s);
A B C
} }
D
}
E
The output is
F
damien mark brad
G H I J K
ArrayList.InsertRange(System.Int32, System.Collections.ICollection) Method
L
[ILASM]
M
.method public hidebysig virtual void InsertRange(int32 index, class System.Collections.ICollection c)
N
[C#]
public virtual void InsertRange(int index, ICollection c)
O P
Summary
Q
Inserts the elements of the specified System.Collections.ICollection at the specified index of the current instance.
R S
Parameters
T U
Parameter
Description
index
A System.Int32 that specifies the index in the current instance at which the new elements are inserted. This value is between 0 and the System.Collections.ArrayList.Count of the current instance, inclusive.
c
The System.Collections.ICollection whose elements are inserted into the current instance.
V W X Y Z
248
Contents | Index
System.Collections
ArrayList InsertRange() Method
Default If the System.Collections.ArrayList.Count of the current instance plus the size of System.Collections.ICollection c is greater than the System.Collections.ArrayList.Capacity of the current instance, the capacity of the current instance is either doubled or increased to the new count, whichever yields a greater capacity. The internal array is reallocated to accommodate the new elements. If index is equal to the System.Collections.ArrayList.Count of the current instance, the elements of c are added to the end of the current instance. The order of the elements in the System.Collections.ICollection c is preserved in the current instance.
A B C D E F G
Exceptions
H
Exception
Condition
System.ArgumentNullException
c is null.
J
index < 0.
K
index > System.Collections.ArrayList.Count of the current instance.
L
System.ArgumentOutOfRangeException System.NotSupportedException
I
M
The current instance is read-only or has a fixed size.
N O
Example
P
using System; using System.Collections;
Q R
namespace Samples { public class ArrayListInsertRange { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); string[] names = {"maire", "sacha", "tamara"}; a.InsertRange(3, names); foreach(string s in a) Console.WriteLine(s); } } }
S T U V W X Y Z
249
Contents | Index
ArrayList
System.Collections
LastIndexOf() Method
The output is damien mark brad maire sacha tamara
A B C D E
ArrayList.LastIndexOf(System.Object) Method
F [ILASM]
G
.method public hidebysig virtual int32 LastIndexOf(object value)
H
[C#]
public virtual int LastIndexOf(object value)
I J
Summary
K
Searches the current instance, returning the index of the last occurrence of the specified System.Object.
L M
Parameters
N O P
Parameter
Description
value
The System.Object to locate in the current instance.
Q R
Return Value
S
A System.Int32 that specifies the index of the last occurrence of value in the current instance, if found; otherwise, –1. [Note: This provides the caller with a standard code for a failed search.]
T U
Default
V
This method uses System.Array.LastIndexOf to search the current instance for value. [Note: For the default implementation, this method performs a linear search. On average, this is an O(n/2) operation, where n is System.Collections.ArrayList.Count of the current instance. The longest search is an O(n) operation.]
W X Y Z
250
Contents | Index
System.Collections
ArrayList LastIndexOf() Method
Example using System; using System.Collections;
A
namespace Samples { public class ArrayListLastIndexOf { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); a.Add("maire"); a.Add("tamara"); a.Add("sacha"); string s = "mark"; int i = a.LastIndexOf(s); Console.WriteLine( "{0} is last found at {1}", s, i); } } }
B C D E F G H I J K L M
The output is
N
mark is last found at 1
O P
ArrayList.LastIndexOf(System.Object, System.Int32) Method
Q
[ILASM]
R
.method public hidebysig virtual int32 LastIndexOf(object value, int32 startIndex)
S
[C#]
public virtual int LastIndexOf(object value, int startIndex)
T
Summary
U
Searches the current instance, returning the index of the last occurrence of the specified System.Object in the specified range of the current instance.
V W X Y Z
251
Contents | Index
ArrayList
System.Collections
LastIndexOf() Method
Parameters Parameter
Description
value
The System.Object to locate in the current instance.
startIndex
A System.Int32 that specifies the index at which searching starts. This value is between 0 and the System.Collections.ArrayList.Count of the current instance minus 1, inclusive.
A B C D E F
Return Value
G
A System.Int32 that specifies the index of the last occurrence of value in the range of startIndex through the first element of the current instance, if found; otherwise, –1. [Note: This provides the caller with a standard code for a failed search.]
H I J
Default
K
This method uses System.Array.LastIndexOf to search the current instance for value. [Note: For the default implementation, this method performs a linear search. On average, this is an O(count/2) operation. The longest search is an O(count) operation.]
L M
Exceptions
N O
Exception
P
Condition startIndex < 0.
Q System.ArgumentOutOfRangeException
R S
-orstartIndex >= System.Collections.ArrayList.Count of the current instance.
T U
Example
V
using System; using System.Collections;
W
namespace Samples { public class ArrayListLastIndexOf { public static void Main() { ArrayList a = new ArrayList();
X Y Z
252
Contents | Index
System.Collections
ArrayList LastIndexOf() Method
a.Add("damien"); a.Add("mark"); a.Add("brad"); a.Add("maire"); a.Add("tamara"); a.Add("sacha"); int start = 3; string s = "mark"; int i = a.LastIndexOf(s, start); Console.WriteLine( "{0} is last found at {1} when starting at {2}", s, i, start);
A B C D E
}
F
}
G
}
H
The output is
I mark is last found at 1 when starting at 2
J K
ArrayList.LastIndexOf(System.Object, System.Int32, System.Int32) Method
L
[ILASM]
M
.method public hidebysig virtual int32 LastIndexOf(object value, int32 startIndex, int32 count)
N
[C#]
O
public virtual int LastIndexOf(object value, int startIndex, int count)
P
Summary
Q
Searches the current instance, returning the index of the last occurrence of the specified System.Object in the specified range.
R S
Parameters
T U
Parameter
Description
value
The System.Object to locate in the current instance.
W
startIndex
A System.Int32 that specifies the index at which searching starts.
X
count
A System.Int32 that specifies the number of elements to search, beginning with startIndex.
V
Y Z
253
Contents | Index
ArrayList
System.Collections
LastIndexOf() Method
Return Value A System.Int32 that specifies the index of the last occurrence of value in the current instance, within the range startIndex through startIndex – count + 1, if found; otherwise, –1. [Note: This provides the caller with a standard code for a failed search.]
A B
Default
C
This method uses System.Array.LastIndexOf to search the current instance for value. [Note: For the default implementation, this method performs a linear search. On average, this is an O(count/2) operation. The longest search is an O(count) operation.]
D E F
Exceptions
G H
Exception
Condition
System.ArgumentOutOfRangeException
startIndex < 0. -orcount < 0. -orstartIndex >= System.Collections.ArrayList.Count of the current instance. -orcount >= System.Collections.ArrayList.Count of the current instance. -orcount > startIndex + 1.
I J K L M N O P Q R
Example
S
using System; using System.Collections;
T U
namespace Samples { public class ArrayListLastIndexOf { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); a.Add("mark"); int start = 3;
V W X Y Z
254
Contents | Index
System.Collections
ArrayList ReadOnly() Method
int length = 2; string s = "damien"; int i = a.LastIndexOf(s, start, length); Console.WriteLine( "{0} is last found at {1} when starting at {2}", s, i, start); Console.WriteLine("-1 means not found");
A B
}
C
}
D
}
E
The output is
F damien is last found at -1 when starting at 3 -1 means not found
G H I
ArrayList.ReadOnly(System.Collections.ArrayList) Method
J
[ILASM]
K
.method public hidebysig static class System.Collections.ArrayList ReadOnly(class System.Collections.ArrayList list)
L
[C#]
public static ArrayList ReadOnly(ArrayList list)
M N
Summary
O
Returns a read-only System.Collections.ArrayList wrapper.
P
Parameters
Q
Parameter
Description
list
The System.Collections.ArrayList to wrap.
R S T U
Description
V
This method returns a read-only System.Collections.ArrayList that contains a reference to list. Operations that attempt add to, delete from, or modify the elements of this new list will throw System.NotSupportedException. Any modifications of the elements list will be reflected in the new list. [Note: The System.Collections.ArrayList.IsReadOnly and System.Collections.ArrayList.IsFixedSize properties of the new list are true. Every other property value of the new list references the same property value of list. By performing
W X Y Z
255
Contents | Index
ArrayList
System.Collections
ReadOnly() Method
operations on the new list, this wrapper can be used to prevent additions to, deletions from, and modifications of the System.Collections.ArrayList list.] A
Exceptions
B C D
Exception
Condition
System.ArgumentNullException
list is null.
E F
Example
G
using System; using System.Collections;
H
namespace Samples { public class ArrayListReadOnly { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); ArrayList b = ArrayList.ReadOnly(a); PrintElements(b); try { a.Add("maire"); PrintElements(a); PrintElements(b); b.Add("tamara"); } catch(NotSupportedException e) { Console.WriteLine("ReadOnly ArrayList {0}", e); } } public static void PrintElements(IEnumerable ie) { Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o); Console.WriteLine(); } } }
I J K L M N O P Q R S T U V W X Y Z
256
Contents | Index
System.Collections
ArrayList ReadOnly() Method
The output is Values: damien mark brad Values: damien mark brad maire Values: damien mark brad maire ReadOnly ArrayList System.NotSupportedException: Collection is read-only. at System.Collections.ReadOnlyArrayList.Add(Object obj) at Samples.ArrayListReadOnly.Main() in C:\Books\BCL\Samples\System.Collections\ ArrayList\ReadOnly(System.Collections.ArrayList)\ArrayList.cs:line 21
A B C D E
ArrayList.ReadOnly(System.Collections.IList) Method
F
[ILASM]
G
.method public hidebysig static class System.Collections.IList ReadOnly(class System.Collections.IList list)
H
[C#]
I
public static IList ReadOnly(IList list)
J
Summary
K
Returns a read-only System.Collections.IList wrapper.
L M
Parameters
N O
Parameter
Description
list
The System.Collections.IList to wrap.
P Q R
Description
S
To prevent any modifications to list, expose list only through this wrapper. A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the readonly collection reflects those changes.
T U V W
Exceptions
X
Exception
Condition
Y
System.ArgumentNullException
list is null.
Z
257
Contents | Index
ArrayList
System.Collections
Remove() Method
ArrayList.Remove(System.Object) Method [ILASM]
.method public hidebysig virtual void Remove(object obj)
A
[C#]
public virtual void Remove(object obj)
B C
Summary
D
Removes the first occurrence of the specified System.Object from the current instance.
E
Parameters
F G
Parameter
Description
obj
The System.Object to remove from the current instance.
H I J K
Description
L
[Note: This method is implemented to support the System.Collections.IList interface.]
M
Default
N
This method determines equality by calling System.Object.Equals. If and only if obj is found in the current instance, obj is removed from the current instance, the rest of the elements are shifted down to fill the position vacated by obj, the System.Collections.ArrayList.Count of the current instance is decreased by one, and the position that was previously the last element in the current instance is set to null. If obj is not found in the current instance, the current instance remains unchanged. [Note: For the default implementation, this method performs a linear search. On average, this is an O(n/2) operation, where n is System.Collections.ArrayList.Count of the current instance. The longest search is an O(n) operation.]
O P Q R S T U
Exceptions
V W
Exception
Condition
System.NotSupportedException
The current instance is read-only or has a fixed size.
X Y Z
258
Contents | Index
System.Collections
ArrayList RemoveAt() Method
Example using System; using System.Collections;
A namespace Samples { public class ArrayListRemove { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); a.Add("mark"); a.Remove("mark"); PrintElements(a); } public static void PrintElements(IEnumerable ie) { Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o); Console.WriteLine(); } } }
B C D E F G H I J K L M N O P
The output is
Q Values: damien brad mark
R S
ArrayList.RemoveAt(System.Int32) Method
T
[ILASM]
U
.method public hidebysig virtual void RemoveAt(int32 index)
V
[C#]
public virtual void RemoveAt(int index)
W
Summary
X
Removes the element at the specified index from the current instance.
Y Z
259
Contents | Index
ArrayList
System.Collections
RemoveAt() Method
Parameters Parameter
Description
index
A System.Int32 that specifies the zero-based index of the element to remove from the current instance. This value is between 0 and the System.Collections.ArrayList.Count of the current instance, inclusive.
A B C D E
Description
F
[Note: This method is implemented to support the System.Collections.IList interface.]
G H
Default
I
The element at position index is removed from the current instance, the rest of the elements are shifted down to fill the position vacated by that element, the System.Collections.ArrayList.Count of the current instance is decreased by one, and the position that was previously the last element in the current instance is set to null.
J K L
Exceptions
M N
Exception
Condition
O
index < 0.
P System.ArgumentOutOfRangeException
Q R S
System.NotSupportedException
-orindex >= System.Collections.ArrayList.Count of the current instance. The current instance is read-only or has a fixed size.
T U
Example
V
using System; using System.Collections;
W X
namespace Samples { public class ArrayListRemoveAt { public static void Main() { ArrayList a = new ArrayList();
Y Z
260
Contents | Index
System.Collections
ArrayList RemoveRange() Method
a.Add("damien"); a.Add("mark"); a.Add("brad"); a.RemoveAt(1); PrintElements(a);
A
} public static void PrintElements(IEnumerable ie) { Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o); Console.WriteLine(); }
B C D E F
}
G
}
H
The output is
I
Values: damien brad
J K
ArrayList.RemoveRange(System.Int32, System.Int32) Method
L
[ILASM]
M
.method public hidebysig virtual void RemoveRange(int32 index, int32 count)
N
[C#]
O
public virtual void RemoveRange(int index, int count)
P
Summary
Q
Removes the specified range of elements from the current instance.
R S
Parameters
T
Parameter
Description
index
A System.Int32 that specifies the zero-based index of the first element of the range of elements in the current instance to remove. This value is between 0 and the System.Collections.ArrayList.Count of the current instance minus count, inclusive.
count
U V W X
A System.Int32 that specifies the number of elements to remove. This value is between 0 and the System.Collections.ArrayList.Count of the current instance minus index, inclusive.
Y Z
261
Contents | Index
ArrayList
System.Collections
RemoveRange() Method
Default The elements in the range of index to index + count – 1 are removed from the current instance, the rest of the elements are shifted down to fill the position vacated by those elements, the System.Collections.ArrayList.Count of the current instance is decreased by count, and the count positions that were previously the last elements in the current instance are set to null.
A B C D
Exceptions
E
Exception
F
Condition index < 0.
G H
System.ArgumentOutOfRangeException
-or-
System.ArgumentException
System.Collections.ArrayList.Count of the current instance – index < count.
System.NotSupportedException
The current instance is read-only or has a fixed size.
I J K L
count < 0.
M N
Example
O
using System; using System.Collections;
P namespace Samples { public class ArrayListRemoveRange { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); a.RemoveRange(0, 1); PrintElements(a); } public static void PrintElements(IEnumerable ie) { Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o);
Q R S T U V W X Y Z
262
Contents | Index
System.Collections
ArrayList Repeat() Method
Console.WriteLine(); } } }
A
The output is
B C
Values: mark brad
D E
ArrayList.Repeat(System.Object, System.Int32) Method
F [ILASM]
G
.method public hidebysig static class System.Collections.ArrayList Repeat(object value, int32 count)
H
[C#]
I
public static ArrayList Repeat(object value, int count)
J
Summary
K
Returns a new System.Collections.ArrayList whose elements are copies of the specified System.Object.
L M
Parameters
N
Parameter
Description
value
The System.Object used to initialize the new System.Collections.ArrayList instance.
count
A System.Int32 that specifies the number of times value is copied into the new System.Collections.ArrayList instance.
O P Q R S T
Return Value
U
A new System.Collections.ArrayList with count number of elements, all of which are copies of value.
V W
Description
X
If count is less than the default initial capacity, 16, the System.Collections.ArrayList.Capacity of the new System.Collections.ArrayList instance is set to the default initial capacity. Else, the capacity is set to count. The System.Collections.ArrayList.Count of the new instance is set to count.
Y Z
263
Contents | Index
ArrayList
System.Collections
Reverse() Method
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
count < 0.
A B C D
Example
E
using System; using System.Collections;
F namespace Samples { public class ArrayListRepeat { public static void Main() { ArrayList a = ArrayList.Repeat("brad", 3); PrintElements(a); } public static void PrintElements(IEnumerable ie) { Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o); Console.WriteLine(); } } }
G H I J K L M N O P Q R
The output is
S Values: brad brad brad
T U
ArrayList.Reverse() Method
V
[ILASM]
W
.method public hidebysig virtual void Reverse()
X
[C#]
public virtual void Reverse()
Y Z
Summary Reverses the sequence of the elements in the current instance.
264
Contents | Index
System.Collections
ArrayList Reverse() Method
Default This method uses System.Array.Reverse to modify the ordering of the elements in the current instance. A
Exceptions
B C
Exception
Condition
System.NotSupportedException
The current instance is read-only.
D E F
Example
G
using System; using System.Collections;
H I
namespace Samples { public class ArrayListReverse { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); PrintElements(a); a.Reverse(); PrintElements(a); } public static void PrintElements(IEnumerable ie) { Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o); Console.WriteLine(); } } }
J K L M N O P Q R S T U V W
The output is
X Y
Values: damien mark brad Values: brad mark damien
Z
265
Contents | Index
ArrayList
System.Collections
Reverse() Method
ArrayList.Reverse(System.Int32, System.Int32) Method [ILASM]
.method public hidebysig virtual void Reverse(int32 index, int32 count)
A
[C#]
public virtual void Reverse(int index, int count)
B C
Summary
D
Reverses the sequence of the elements in the specified range of the current instance.
E
Parameters
F G
Parameter
Description
index
A System.Int32 that specifies the zero-based index in the current instance at which reversing starts. This value is between 0 and the System.Collections.ArrayList.Count of the current instance minus count, inclusive.
count
A System.Int32 that specifies the number of elements to reverse. This value is between 0 and the System.Collections.ArrayList.Count of the current instance minus index, inclusive.
H I J K L M N
Default
O
This method uses System.Array.Reverse to modify the ordering of the current instance.
P Q
Exceptions
R S
Exception
T
Condition index < 0.
U V
System.ArgumentOutOfRangeException
-or-
System.ArgumentException
System.Collections.ArrayList.Count of the current instance – index < count.
System.NotSupportedException
The current instance is read-only.
W X Y
count < 0.
Z
266
Contents | Index
System.Collections
ArrayList SetRange() Method
Example using System; using System.Collections;
A namespace Samples { public class ArrayListReverse { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark"); a.Add("brad"); a.Sort(); PrintElements(a); a.Reverse(1,2); PrintElements(a); } public static void PrintElements(IEnumerable ie) { Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o); Console.WriteLine(); } } }
B C D E F G H I J K L M N O P
The output is
Q R
Values: brad damien mark Values: brad mark damien
S T
ArrayList.SetRange(System.Int32, System.Collections.ICollection) Method
U
[ILASM]
V
.method public hidebysig virtual void SetRange(int32 index, class System.Collections.ICollection c)
W
[C#]
X
public virtual void SetRange(int index, ICollection c)
Y
Summary
Z
Copies the elements of the specified System.Collections.ICollection to a range in the current instance. 267
Contents | Index
ArrayList
System.Collections
SetRange() Method
Parameters Parameter
Description
index
A System.Int32 that specifies the zero-based index in the current instance at which to start copying the elements of c. This value is between 0 and the System.Collections.ArrayList.Count of the current instance minus c.Count, inclusive.
c
The System.Collections.ICollection whose elements to copy to the current instance.
A B C D E F G
Default
H
This method uses the System.Collections.ICollection.CopyTo implementation of System.Collections.ICollection c.
I J
Exceptions
K L
Exception
M
Condition index < 0.
N
System.ArgumentOutOfRangeException
O P
-orSystem.Collections.ArrayList.Count of the current instance – index < c.Count.
Q
System.ArgumentNullException
c is null.
R
System.NotSupportedException
The current instance is read-only.
S T
Example
U
using System; using System.Collections;
V W
namespace Samples { public class ArrayListSetRange { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien");
X Y Z
268
Contents | Index
System.Collections
ArrayList Sort() Method
a.Add("mark"); a.Add("brad"); a.SetRange(0, new string[]{"maire", "sacha", "tamara"}); Console.WriteLine("Count: {0}", a.Count); Console.WriteLine("Default Capacity: {0}", a.Capacity ); PrintElements(a);
A B
} public static void PrintElements(IEnumerable ie) { Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o); Console.WriteLine(); }
C D E F G
}
H
}
I
The output is
J Count: 3 Default Capacity: 16 Values: maire sacha tamara
K L M
ArrayList.Sort() Method
N
[ILASM]
O
.method public hidebysig virtual void Sort()
P
[C#]
public virtual void Sort()
Q R
Summary
S
Sorts the elements of the current instance.
T
Default
U
The System.IComparable implementation of each element in the current instance is used to make the sorting comparisons. If the sort is not successfully completed, the results are unspecified. [Note: For the default implementation, this method uses System.Array.Sort, which uses the Quicksort algorithm. This is an O(n logn) operation, where n is the number of elements to sort.]
V W X Y Z
269
Contents | Index
ArrayList
System.Collections
Sort() Method
Exceptions Exception
Condition
System.InvalidCastException
One or more elements in the current instance do not implement the System.IComparable interface.
System.NotSupportedException
The current instance is read-only.
A B C D E F
Example
G
using System; using System.Collections;
H
namespace Samples { public class MyName: IComparable { private string name; public MyName(string name) { this.name = name; } public int CompareTo(object o) { MyName m = o as MyName; Console.WriteLine ("Comparing {0} with {1}", this, o); return string.Compare(name, m.name, true); } public override bool Equals(object obj) { return CompareTo(obj) == 0; } public override int GetHashCode() { return name.GetHashCode (); } public override string ToString() { return name; } } public class ArrayListSort { public static void Main() { ArrayList a = new ArrayList(); a.Add(new MyName("emma"));
I J K L M N O P Q R S T U V W X Y Z
270
Contents | Index
System.Collections
ArrayList Sort() Method
a.Add(new MyName("boston")); a.Add(new MyName("joshua")); a.Add(new MyName("hannah")); a.Sort(); PrintElements(a);
A
} public static void PrintElements(IEnumerable ie) { Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o); Console.WriteLine(); }
B C D E F
}
G
}
H
The output is
I Comparing emma with boston Comparing boston with hannah Comparing boston with joshua Comparing emma with joshua Comparing joshua with hannah Comparing emma with hannah Values: boston emma hannah joshua
J K L M N O
ArrayList.Sort(System.Int32, System.Int32, System.Collections.IComparer) Method
P Q
[ILASM]
R
.method public hidebysig virtual void Sort(int32 index, int32 count, class System.Collections.IComparer comparer)
S
[C#]
public virtual void Sort(int index, int count, IComparer comparer)
T U
Summary
V
Sorts the elements in the specified range of the current instance using the specified System.Collections.IComparer implementation.
W X Y Z
271
Contents | Index
ArrayList
System.Collections
Sort() Method
Parameters Parameter
Description
index
A System.Int32 that specifies the zero-based index at which sorting starts. This value is between 0 and the System.Collections.ArrayList.Count of the current instance minus count, inclusive.
count
A System.Int32 that specifies the number of elements to sort. This value is between 0 and the System.Collections.ArrayList.Count of the current instance minus index, inclusive.
comparer
The System.Collections.IComparer implementation to use when comparing elements. Specify null to use the System.IComparable implementation of each element in the current instance.
A B C D E F G H I
Default
J
If comparer is null, the System.IComparable implementation of each element in the current instance is used to make the sorting comparisons. If the sort is not successfully completed, the results are unspecified. [Note: For the default implementation, this method uses System.Array.Sort, which uses the Quicksort algorithm. This is an O(n logn) operation, where n is the number of elements to sort.]
K L M N O
Exceptions
P Q
Exception
Condition
R
index < 0.
S T
System.ArgumentOutOfRangeException
-or-
System.ArgumentException
System.Collections.ArrayList.Count of the current instance – index < count.
System.InvalidCastException
comparer is null, and one or more elements in the current instance do not implement the System.IComparable interface.
System.NotSupportedException
The current instance is read-only.
count < 0.
U V W X Y Z
272
Contents | Index
System.Collections
ArrayList Sort() Method
Example using System; using System.Collections;
A
namespace Samples { public class ArrayListSort { public class MyReverseComparer: IComparer { public int Compare(Object a, Object b) { return -((IComparable)a).CompareTo(b); } } public static void Main() { ArrayList a = new ArrayList(); a.Add("maire"); a.Add("sacha"); a.Add("tamara"); a.Add("brad"); a.Add("damien"); a.Add("mark"); a.Sort(0, 4, new MyReverseComparer()); PrintElements(a); } public static void PrintElements(IEnumerable ie) { Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o); Console.WriteLine(); } } }
B C D E F G H I J K L M N O P Q R S T
The output is
U V
Values: tamara sacha maire brad damien mark
W
ArrayList.Sort(System.Collections.IComparer) Method
X
[ILASM]
Y
.method public hidebysig virtual void Sort(class System.Collections.IComparer comparer)
Z
[C#]
public virtual void Sort(IComparer comparer)
273
Contents | Index
ArrayList
System.Collections
Sort() Method
Summary Sorts the elements of current instance using the specified System.Collections.IComparer. A
Parameters
B C D
Parameter
Description
comparer
The System.Collections.IComparer implementation to use when comparing elements. Specify null to use the System.IComparable implementation of each element in the current instance.
E F G H
Default
I
If comparer is null, the System.IComparable implementation of each element in the current instance is used to make the sorting comparisons. If the sort is not successfully completed, the results are unspecified. [Note: For the default implementation, this method uses System.Array.Sort, which uses the Quicksort algorithm. This is an O(n logn) operation, where n is the number of elements to sort.]
J K L M N
Exceptions
O P
Exception
Condition
System.InvalidCastException
comparer is null, and one or more elements in the current instance do not implement the System.IComparable interface.
System.NotSupportedException
The current instance is read-only.
Q R S T U V
Example
W
using System; using System.Collections;
X
namespace Samples { public class ArrayListSort { public class MyReverseComparer: IComparer {
Y Z
274
Contents | Index
System.Collections
ArrayList Synchronized() Method
public int Compare(Object a, Object b) { return -((IComparable)a).CompareTo(b); }
A
} public static void Main() { ArrayList a = new ArrayList(); a.Add("maire"); a.Add("sacha"); a.Add("tamara"); a.Add("brad"); a.Add("damien"); a.Add("mark"); a.Sort(new MyReverseComparer()); PrintElements(a); } public static void PrintElements(IEnumerable ie) { Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o); Console.WriteLine(); }
B C D E F G H I J K L M
}
N
}
O
The output is
P Values: tamara sacha mark maire damien brad
Q R
ArrayList.Synchronized(System.Collections.ArrayList) Method
S
[ILASM]
T
.method public hidebysig static class System.Collections.ArrayList Synchronized(class System.Collections.ArrayList list)
U
[C#]
V
public static ArrayList Synchronized(ArrayList list)
W
Summary
X
Returns a System.Collections.ArrayList wrapper around the specified System.Collections.ArrayList that is synchronized (thread-safe).
Y Z
275
Contents | Index
ArrayList
System.Collections
Synchronized() Method
Parameters Parameter
Description
list
The System.Collections.ArrayList to synchronize.
A B C
Description
D
This method returns a thread-safe System.Collections.ArrayList that contains a reference to list. Any modifications of the elements in either the returned list or list will be reflected in the other. [Note: The System.Collections.ArrayList.IsSynchronized property of the new list is true. Every other property value of the new list references the same property value of list. By performing operations on the new list, this wrapper can be used to guarantee thread-safe access to the System.Collections.ArrayList list.]
E F G H I J
Exceptions
K L M
Exception
Condition
System.ArgumentNullException
list is null.
N
Example
O
using System; using System.Collections;
P Q
namespace Samples { public class ArrayListSynchronized { public static void Main() { ArrayList a = new ArrayList(); ArrayList b = ArrayList.Synchronized(a); IsArrayListSynchronized(a); IsArrayListSynchronized(b); } public static void IsArrayListSynchronized(ArrayList a) { if(a.IsSynchronized) Console.WriteLine("ArrayList is synchronized"); else Console.WriteLine("ArrayList is not synchronized"); } } }
R S T U V W X Y Z
276
Contents | Index
System.Collections
ArrayList Synchronized() Method
The output is ArrayList is not synchronized ArrayList is synchronized
A B
ArrayList.Synchronized(System.Collections.IList) Method
C
[ILASM]
D
.method public hidebysig static class System.Collections.IList Synchronized(class System.Collections.IList list)
E
[C#]
F
public static IList Synchronized(IList list)
G
Summary
H
Returns a System.Collections.IList wrapper that is synchronized (thread-safe).
I J
Parameters
K
Parameter
Description
list
The System.Collections.IList to synchronize.
L M N O
Description
P
To guarantee the thread safety of the System.Collections.ArrayList, all operations must be done through this wrapper. Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads. The following code example shows how to lock the collection using the System.Collections.ArrayList.SyncRoot during the entire enumeration:
Q R S T U V W
ArrayList myCollection = new ArrayList(); lock( myCollection.SyncRoot ) { foreach ( Object item in myCollection ) { // Insert your code here. } }
X Y Z
277
Contents | Index
ArrayList
System.Collections
ToArray() Method
Exceptions Exception
Condition
System.ArgumentNullException
list is null.
A B C D
ArrayList.ToArray() Method
E
[ILASM]
F
.method public hidebysig virtual class System.Object[] ToArray() [C#]
G
public virtual object[] ToArray()
H
Summary
I
Copies the elements of the current instance to a new System.Object array.
J K
Default
L
The elements are copied using System.Array.Copy. [Note: For the default implementation, this method is an O(n) operation, where n is the System.Collections.ArrayList.Count of the current instance.]
M N O
Example
P
using System; using System.Collections;
Q namespace Samples { public class ArrayListToArray { public static void Main() { ArrayList a = new ArrayList(); a.Add("maire"); a.Add("sacha"); a.Add("tamara"); a.Add("brad"); a.Add("damien"); a.Add("mark"); object[] o = a.ToArray(); PrintElements(o); } public static void PrintElements(IEnumerable ie)
R S T U V W X Y Z
278
Contents | Index
System.Collections
ArrayList ToArray() Method
{ Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o); Console.WriteLine();
A
}
B
}
C
}
D
The output is
E Values: maire sacha tamara brad damien mark
F G
ArrayList.ToArray(System.Type) Method
H
[ILASM]
I
.method public hidebysig virtual class System.Array ToArray(class System.Type type)
J
[C#]
K
public virtual Array ToArray(Type type)
L
Summary
M
Copies the elements of the current instance to a new array of the specified System.Type.
N O
Parameters
P
Parameter
Description
type
The System.Type of the System.Array to create and copy the elements of the current instance.
Q R S T
Default
U
The elements are copied using System.Array.Copy. [Note: For the default implementation, this method is an O(n) operation, where n is the System.Collections.ArrayList.Count of the current instance.]
V W X Y Z
279
Contents | Index
ArrayList
System.Collections
ToArray() Method
Exceptions Exception
Condition
System.ArgumentNullException
type is null.
System.InvalidCastException
At least one element of the current instance cannot be cast to the System.Type type.
A B C D E F
Example
G
using System; using System.Collections;
H
namespace Samples { public class ArrayListSort { public static void Main() { ArrayList a = new ArrayList(); a.Add("maire"); a.Add("sacha"); a.Add("tamara"); a.Add("brad"); a.Add("damien"); a.Add("mark"); string[] s = (string[]) a.ToArray(typeof(string)); PrintElements(s); } public static void PrintElements(IEnumerable ie) { Console.Write("Values: "); foreach(object o in ie) Console.Write("{0} ", o); Console.WriteLine(); } } }
I J K L M N O P Q R S T U V
The output is
W X
Values: maire sacha tamara brad damien mark
Y Z
280
Contents | Index
System.Collections
ArrayList TrimToSize() Method
ArrayList.TrimToSize() Method [ILASM]
.method public hidebysig virtual void TrimToSize() [C#]
A
public virtual void TrimToSize()
B C
Summary
D
Sets the System.Collections.ArrayList.Capacity of the current instance to the System.Collections.ArrayList.Count of the current instance.
E F
Description
G
[Note: This method can be used to minimize the memory overhead of the current instance if no new elements will be added to it. To completely clear all elements from the current instance, call the System.Collections.ArrayList.Clear method before calling System.Collections.ArrayList.TrimToSize.]
H I J
Default
K
If the System.Collections.ArrayList.Count of the current instance is zero, the System.Collections.ArrayList.Capacity of the current instance is set to the default initial capacity of 16.
L M N O
Exceptions
P
Exception
Condition
System.NotSupportedException
The current instance is read-only or has a fixed size.
Q R S
Example
T
using System; using System.Collections;
U V
namespace Samples { public class ArrayListTrimToSize { public static void Main() { ArrayList a = new ArrayList(); a.Add("damien"); a.Add("mark");
W X Y Z
281
Contents | Index
ArrayList
System.Collections
TrimToSize() Method
a.Add("damien"); Console.WriteLine("Count: {0}", a.Count); Console.WriteLine("Capacity: {0}", a.Capacity ); a.TrimToSize(); Console.WriteLine("Count: {0}", a.Count); Console.WriteLine("Capacity: {0}", a.Capacity );
A B }
C
} }
D
The output is
E F
Count: 3 Capacity: 16 Count: 3 Capacity: 3
G H I J K L M N O P Q R S T U V W X Y Z
282
Contents | Index
System ArrayTypeMismatchException
BCL
Object Exception
ISerializable
NotStandardized
A B
SystemException ArrayTypeMismatchException
C D
Summary
E
Represents the error that occurs when an attempt is made to store an element of the wrong type in an array.
F G
Type Summary
H
public class ArrayTypeMismatchException : SystemException { // Constructors public ArrayTypeMismatchException (); public ArrayTypeMismatchException (string message); public ArrayTypeMismatchException (string message, Exception innerException); MS CF protected ArrayTypeMismatchException (SerializationInfo info, StreamingContext context); }
I J K L M N O
BA It is interesting to look at the exceptions that are only thrown by the runtime, such as ArrayTypeMismatchException, NullReferenceException, and ExecutionEngionException. Even though we did not expect these exceptions to be thrown by user code, we included the standard constructors. We believe that consistency is the overriding principle in this case; therefore, we did not force ourselves to come up with clear scenarios that require these constructors. That said, we do see developers throwing them explicitly in code designed to test exception handling.
P Q R S T U V
Description
W
System.ArrayTypeMismatchException is thrown when the system cannot convert the element to the type declared for the array. [Note: This exception will not be thrown if the element can be converted to the type declared for the array. For example, an element of type System.Byte can be stored in an array declared to store System.Int32 values, but an element of type System.String cannot be stored in a System.Int32 array because conversion between these types is not supported.]
X Y Z
283
Contents | Index
ArrayTypeMismatchException
System
ArrayTypeMismatchException() Constructor
[Note: This exception is thrown by the System.Array.Copy method if a widening conversion cannot be performed on the operand to convert it to the array type. It is generally unnecessary for applications to throw this exception. The following IL instructions throw System.ArrayTypeMismatchException.]
A B
Example
C
using System;
D namespace Samples { public class ArrayTypeMisMatch { public static void Main() { string[] strings = {"one", "two", "three"}; int[] ints = {1, 2, 3}; try { Array.Copy(strings, ints, 3); } catch(ArrayTypeMismatchException e) { Console.WriteLine("Exception: {0}", e); } } } }
E F G H I J K L M N O P
The output is
Q R
Exception: System.ArrayTypeMismatchException: Source array type cannot be assigned to destination array type. at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length) at System.Array.Copy(Array sourceArray, Array destinationArray, Int32 length) at Samples.ArrayTypeMisMatch.Main() in C:\Books\BCL\Samples\System\ ArrayTypeMismatchException\ArrayTypeMismatchException.cs:line 13
S T U V W X
ArrayTypeMismatchException() Constructor
Y
[ILASM]
public rtspecialname specialname instance void .ctor()
Z
[C#]
public ArrayTypeMismatchException()
284
Contents | Index
System
ArrayTypeMismatchException ArrayTypeMismatchException() Constructor
Summary Constructs and initializes a new instance of the System.ArrayTypeMismatchException class. A
Description
B
This constructor initializes the System.ArrayTypeMismatchException.Message property of the new instance to a system-supplied message that describes the error, such as “Source array type cannot be assigned to destination array type.” This message takes into account the current system culture. The System.ArrayTypeMismatchException.InnerException property is initialized to null.
C D E F G H
ArrayTypeMismatchException(System.String) Constructor
I
[ILASM]
J
public rtspecialname specialname instance void .ctor(string message)
K
[C#]
public ArrayTypeMismatchException(string message)
L
Summary
M
Constructs and initializes a new instance of the System.ArrayTypeMismatchException class.
N O P
Parameters
Q
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
R S T U V
Description
W
This constructor initializes the System.ArrayTypeMismatchException.Message property of the new instance using message. If message is null, the System.ArrayTypeMismatchException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.ArrayTypeMismatchException.InnerException property is initialized to null.
X Y Z
285
Contents | Index
ArrayTypeMismatchException
System
ArrayTypeMismatchException() Constructor
ArrayTypeMismatchException(System.String, System.Exception) Constructor [ILASM]
A
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
B
[C#]
C
public ArrayTypeMismatchException(string message, Exception innerException)
D E
Summary
F
Constructs and initializes a new instance of the System.ArrayTypeMismatchException class.
G
Parameters
H I
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
J K L M N O P
Description
Q
This constructor initializes the System.ArrayTypeMismatchException.Message property of the new instance using message, and the System.Exception.InnerException property using innerException. If message is null, the System.ArrayTypeMismatchException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
R S T U V W X Y Z
286
Contents | Index
System
ArrayTypeMismatchException ArrayTypeMismatchException() Constructor
ArrayTypeMismatchException(System.Runtime.Serialization.Serialization Info, System.Runtime.Serialization.StreamingContext) Constructor [ILASM]
A
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
B C
[C#]
protected ArrayTypeMismatchException(SerializationInfo info, StreamingContext context)
D E
Summary
F
Initializes a new instance of the System.ArrayTypeMismatchException class with serialized data.
G H I
Parameters
J
Parameter
Description
info
The object that holds the serialized object data.
context
The contextual information about the source or destination.
K L M N O
Description
P
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
Q R S T U V W X Y Z
287
Contents | Index
System.Text ASCIIEncoding
BCL
Object
A
Encoding
B
ASCIIEncoding
C
Summary
D
Represents an ASCII character implementation of System.Text.Encoding.
E
Type Summary
F
public class ASCIIEncoding : Encoding { // Constructors public ASCIIEncoding ();
G H I
// Methods public override int GetByteCount (char[] chars, int index, int count); public override int GetByteCount (string chars); public override int GetBytes (char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex); public override int GetBytes (string chars, int charIndex, int charCount, byte[] bytes, int byteIndex); public override int GetCharCount (byte[] bytes, int index, int count); public override int GetChars (byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex); public override int GetMaxByteCount (intcharCount); public override int GetMaxCharCount (int byteCount); CF public override string GetString (byte[] bytes); CF public override string GetString (byte[] bytes, int byteIndex, int byteCount);
J K L M N O P Q R S T U V W X Y Z
}
288
Contents | Index
System.Text
ASCIIEncoding ASCIIEncoding() Constructor
BA Regrettably, the ASCIIEncoding class does not follow the standard naming convention: it should really be called AsciiEncoding. We settled on the naming convention for abbreviations too late in the cycle to fix this.
A B
BG We hope that users will not choose ASCII for persisting data in files when they can control the file format. We have fully shifted to Unicode, and our recommended text transfer format is UTF-8, which is as compact as ASCII for US English text, yet also supports all Unicode characters.
C D E
JR Normally, there is no need for your application code to construct an Encoding-
F
derived object (such as ASCIIEncoding). Instead, you normally obtain an Encodingderived object by calling one of Encoding class’s static, read-only properties. Here is an example:
G H
ASCIIEncoding asciiEncoding = Encoding.ASCII;
I
This is more efficient because it returns a reference to a single ASCIIEncoding object rather than creating new ASCIIEncoding objects.
J K L
Description
M
System.Text.ASCIIEncoding encodes characters as single 7-bit ASCII characters. This encoding supports Unicode code points between U+0000 and U+007F, inclusive. [Note: The limited range of code points supported by System.Text.ASCIIEncoding makes ASCII inadequate for many internationalized applications. System.Text.UTF8Encoding and System.Text.UnicodeEncoding provide encodings that are more suitable for internationalized applications.]
N O P Q R S
ASCIIEncoding() Constructor
T
[ILASM]
U
public rtspecialname specialname instance void .ctor() [C#]
V
public ASCIIEncoding()
W
Summary
X
Constructs a new instance of the System.Text.ASCIIEncoding class.
Y Z
289
Contents | Index
ASCIIEncoding
System.Text
GetByteCount() Method
Example Programs should not normally use the constructor to create an ASCIIEncoding class; use ASCIIEncoding a = Encoding.ASCII instead. A using System; using System.Text;
B C
namespace Samples { public class ASCIIEncodingConstructor { public static void Main() { ASCIIEncoding a = new ASCIIEncoding(); String s = "This is Pi (\u03a0)"; foreach(Int16 c in s) Console.Write("{0}, ", c); Console.WriteLine(); Byte[] ascii = a.GetBytes(s); foreach(Byte b in ascii) Console.Write("{0}, ", b); Console.WriteLine(); } } }
D E F G H I J K L M N O
The output is
P 84, 104, 105, 115, 32, 105, 115, 32, 80, 105, 32, 40, 928, 41, 84, 104, 105, 115, 32, 105, 115, 32, 80, 105, 32, 40, 63, 41,
Q R S T
ASCIIEncoding.GetByteCount(System.Char[], System.Int32, System.Int32) Method
U
[ILASM]
V
.method public hidebysig virtual int32 GetByteCount(class System.Char[] chars, int32 index, int32 count)
W
[C#]
public override int GetByteCount(char[] chars, int index, int count)
X Y
Summary
Z
Determines the exact number of bytes required to encode the specified range of the specified array of characters as ASCII-encoded characters.
290
Contents | Index
System.Text
ASCIIEncoding GetByteCount() Method
Parameters Parameter
Description
chars
A System.Char array containing the characters to encode as ASCII-encoded characters.
B
index
A System.Int32 that specifies the first index of chars to encode.
C
count
A System.Int32 that specifies the number of elements in chars to encode.
A
D E
Return Value
F
A System.Int32 containing the number of bytes required to encode the range in chars from index to index + count – 1 as ASCII-encoded characters.
G H
Description
I
[Note: This method overrides System.Text.Encoding.GetByteCount.]
J K
Exceptions
L
Exception
Condition
System.ArgumentNullException
chars is null.
System.ArgumentOutOfRangeException
index < 0. -orcount < 0. -orindex and count do not specify a valid range in chars (i.e., ( index + count – 1) > chars.Length).
M N O P Q R S T
Example
U
using System; using System.Text;
V W
namespace Samples { public class ASCIIEncodingGetByteCount { public static void Main() { Char[] c = new Char[] {'\u0054', '\u0074', '\u03a0', '\u03a3'};
X Y Z
291
Contents | Index
ASCIIEncoding
System.Text
GetByteCount() Method
ASCIIEncoding a = (ASCIIEncoding) Encoding.ASCII; int i = a.GetByteCount(c, 1, 3); Console.WriteLine("{0} bytes are need to convert the " + "subpart of the char array to ASCII.", i);
A }
B }
C
}
D
The output is
E 3 bytes are needed to convert the subpart of the char array to ASCII.
F G
ASCIIEncoding.GetByteCount(System.String) Method
H [ILASM]
I
.method public hidebysig virtual int32 GetByteCount(string chars)
J
[C#]
public override int GetByteCount(string chars)
K L
Summary
M
Determines the exact number of bytes required to encode the specified string as ASCIIencoded characters.
N
Parameters
O P
Parameter
Description
chars
A System.String to encode as ASCII-encoded characters.
Q R S T
Description
U
[Note: This method overrides System.Text.Encoding.GetByteCount.]
V
Exceptions
W X Y
Exception
Condition
System.ArgumentNullException
chars is null.
Z
292
Contents | Index
System.Text
ASCIIEncoding GetBytes() Method
Example using System; using System.Text;
A
namespace Samples { public class ASCIIEncodingGetByteCount { public static void Main() { string s = "This is Pi (\u03a0)"; ASCIIEncoding a = (ASCIIEncoding) Encoding.ASCII; int i = a.GetByteCount(s); Console.WriteLine( "{0} bytes are needed to convert 's' to ASCII.", i); } } }
B C D E F G H I J
The output is
K L
14 bytes are needed to convert the string to ASCII.
M
ASCIIEncoding.GetBytes(System.Char[], System.Int32, System.Int32, System.Byte[], System.Int32) Method
O
[ILASM]
P
.method public hidebysig virtual int32 GetBytes(class System.Char[] chars, int32 charIndex, int32 charCount, class System.Byte[] bytes, int32 byteIndex)
Q
N
[C#]
R
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
S T
Summary
U
Encodes the specified range of the specified array of characters into the specified range of the specified array of bytes as ASCII-encoded characters.
V W X Y Z
293
Contents | Index
ASCIIEncoding
System.Text
GetBytes() Method
Parameters Parameter
Description
B
chars
A System.Char array containing the characters to encode as ASCII-encoded characters.
C
charIndex
A System.Int32 that specifies the first index of chars to encode.
charCount
A System.Int32 that specifies the number of elements in chars to encode.
bytes
A System.Byte array to encode.
byteIndex
A System.Int32 that specifies the first index of bytes to encode into.
A
D E F G H
Return Value
I
A System.Int32 whose value equals the number of bytes encoded into bytes as ASCIIencoded characters.
J K
Description
L
Every System.Char object in chars that is encoded into bytes and that does not have an ASCII equivalent (i.e., has a code point greater than U+007f) will be encoded as a question mark (?). [Note: This method overrides System.Text.Encoding.GetBytes.]
M N
Exceptions
O P
Exception
Condition
System.ArgumentException
(bytes.Length – byteIndex) < charCount.
System.ArgumentNullException
chars is null. -orbytes is null.
System.ArgumentOutOfRangeException
charIndex < 0. -orcharCount < 0. -or(chars.Length – charIndex) < charCount. -orbyteIndex < 0. -orbyteIndex > bytes.Length.
Q R S T U V W X Y Z
294
Contents | Index
System.Text
ASCIIEncoding GetBytes() Method
Example using System; using System.Text;
A namespace Samples { public class ASCIIEncodingGetBytes { public static void Main() { Char[] c = new Char[]{'T', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 's', 'a', 'm', 'p', 'l', 'e', ' ', 's', 't', 'r', 'i', 'n', 'g', '.'}; ASCIIEncoding a = (ASCIIEncoding) Encoding.ASCII; int count = a.GetByteCount(c, 4, 10); Byte[] bytes = new Byte[count]; a.GetBytes(c, 4, 10, bytes, 0); Console.Write("Encoded bytes: "); foreach(Byte b in bytes) Console.Write("{0}, ", b); Console.WriteLine(); } } }
B C D E F G H I J K L M N
The output is
O P
Encoded bytes: 32, 105, 115, 32, 97, 32, 115, 97, 109, 112,
Q R
ASCIIEncoding.GetBytes(System.String, System.Int32, System.Int32, System.Byte[], System.Int32) Method
S
[ILASM]
T
.method public hidebysig virtual int32 GetBytes(string chars, int32 charIndex, int32 charCount, class System.Byte[] bytes, int32 byteIndex)
U
[C#]
V
public override int GetBytes(string chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
W X
Summary
Y
Encodes the specified range of the specified string into the specified range of the specified array of bytes as ASCII-encoded characters.
Z
295
Contents | Index
ASCIIEncoding
System.Text
GetBytes() Method
Parameters Parameter
Description
chars
A System.String to encode as ASCII-encoded characters.
charIndex
A System.Int32 that specifies the first index of chars from which to encode.
charCount
A System.Int32 that specifies the number of elements in chars to encode.
bytes
A System.Byte array to encode.
byteIndex
A System.Int32 that specifies the first index of bytes to encode into.
A B C D E F G
Return Value
H
A System.Int32 whose value equals the number of bytes encoded into bytes as ASCIIencoded characters.
I J
Description
K
Every System.Char object in chars that is encoded into bytes and that does not have an ASCII equivalent (i.e., has a code point greater than U+007f) will be encoded as a question mark (?). [Note: This method overrides System.Text.Encoding.GetBytes.]
L M N
Exceptions
O P
Exception
Condition
System.ArgumentException
(bytes.Length – byteIndex) < charCount.
System.ArgumentNullException
chars is null. -orbytes is null.
System.ArgumentOutOfRangeException
charIndex < 0. -orcharCount < 0. -or(chars.Length – charIndex) < charCount. -orbyteIndex < 0. -orbyteIndex >= bytes.Length.
Q R S T U V W X Y Z
296
Contents | Index
System.Text
ASCIIEncoding GetCharCount() Method
Example using System; using System.Text;
A
namespace Samples { public class ASCIIEncodingGetBytes { public static void Main() { String s = "This is a string"; ASCIIEncoding a = (ASCIIEncoding) Encoding.ASCII; int count = a.GetByteCount(s.ToCharArray(), 4, 10); Byte[] bytes = new Byte[count]; a.GetBytes(s, 4, 10, bytes, 0); Console.Write("Encoded bytes: "); foreach(Byte b in bytes) Console.Write("{0}, ", b); Console.WriteLine(); } } }
B C D E F G H I J K L
The output is
M Encoded bytes: 32, 105, 115, 32, 97, 32, 32, 115, 116, 114,
N O
ASCIIEncoding.GetCharCount(System.Byte[], System.Int32, System.Int32) Method
P Q
[ILASM]
R
.method public hidebysig virtual int32 GetCharCount(class System.Byte[] bytes, int32 index, int32 count)
S
[C#]
T
public override int GetCharCount(byte[] bytes, int index, int count)
U
Summary
V
Determines the exact number of characters that will be produced by decoding the specified range of the specified array of bytes as ASCII-encoded characters.
W X Y Z
297
Contents | Index
ASCIIEncoding
System.Text
GetCharCount() Method
Parameters Parameter
Description
bytes
A System.Byte array to decode as ASCII-encoded characters.
C
index
A System.Int32 that specifies the first index in bytes to decode.
D
count
A System.Int32 that specifies the number of elements in bytes to decode.
A B
E F
Return Value
G
A System.Int32 whose value equals the number of characters a call to System.Text.ASCIIEncoding.GetChars will produce if presented with the specified range of bytes. [Note: This value does not take into account the state in which the current instance was left following the last call to System.Text.ASCIIEncoding.GetChars. This contrasts with System.Text.Decoder.GetChars, which maintains state information across calls.]
H I J K L
Description
M
[Note: This method overrides System.Text.Encoding.GetCharCount.]
N
Exceptions
O P
Exception
Condition
System.ArgumentNullException
bytes is null.
Q R S
index < 0.
T
-orSystem.ArgumentOutOfRangeException
U
count < 0. -or-
V
(bytes.Length – index) < count.
W X Y Z
298
Contents | Index
System.Text
ASCIIEncoding GetChars() Method
Example using System; using System.Text;
A namespace Samples { public class ASCIIEncodingGetCharCount { public static void Main() { Byte[] b = new Byte[] {84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 115, 97, 109, 112, 108, 101, 32, 115, 116, 114, 105, 110, 103,}; ASCIIEncoding a = (ASCIIEncoding) Encoding.ASCII; int i = a.GetCharCount(b, 0, 10); Console.WriteLine( "{0} characters need to convert " + "this part of byte array to Unicode", i); } } }
B C D E F G H I J K L M
The output is
N O
10 characters need to convert this part of byte array to Unicode
P Q
ASCIIEncoding.GetChars(System.Byte[], System.Int32, System.Int32, System.Char[], System.Int32) Method
R
[ILASM]
S
.method public hidebysig virtual int32 GetChars(class System.Byte[] bytes, int32 byteIndex, int32 byteCount, class System.Char[] chars, int32 charIndex)
T
[C#]
U
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
V W
Summary
X
Decodes the specified range of the specified array of bytes into the specified range of the specified array of characters as ASCII-encoded characters.
Y Z
299
Contents | Index
ASCIIEncoding
System.Text
GetChars() Method
Parameters Parameter
Description
bytes
A System.Byte array to decode as ASCII-encoded characters.
C
byteIndex
A System.Int32 that specifies the first index of bytes from which to decode.
D
byteCount
A System.Int32 that specifies the number of elements in bytes to decode.
chars
A System.Char array of characters to decode into.
charIndex
A System.Int32 that specifies the first index of chars to store the decoded bytes.
A B
E F G H I
Return Value
J
A System.Int32 whose value equals the number of characters decoded into chars as ASCII-encoded characters.
K L
Description
M
[Note: This method overrides System.Text.Encoding.GetChars. System.Text.ASCIIEncoding.GetChars can be used to determine the exact number of characters that will be produced for a specified range of bytes. Alternatively, the System.Text.ASCIIEncoding.GetMaxCharCount method can be used to determine the maximum number of characters that will be produced for a specified number of bytes, regardless of the actual byte values. ]
N O P Q R S T U V W X Y Z
300
Contents | Index
System.Text
ASCIIEncoding GetChars() Method
Exceptions Exception
Condition
System.ArgumentException
(chars.Length – charIndex) < byteCount.
System.ArgumentNullException
bytes is null. -orchars is null.
System.ArgumentOutOfRangeException
A B C D E
byteIndex < 0. -orbyteCount < 0. -or(bytes.Length – byteIndex) < byteCount. -orcharIndex < 0. -orcharIndex > chars.Length.
F G H I J K L
Example
M
using System; using System.Text;
N O
namespace Samples { public class ASCIIEncodingGetChars { public static void Main() { Byte[] b = new Byte[] {84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 115, 97, 109, 112, 108, 101, 32, 115, 116, 114, 105, 110, 103,}; ASCIIEncoding a = (ASCIIEncoding) Encoding.ASCII; int i = a.GetCharCount(b, 0, 10); Char[] c = new Char[i]; a.GetChars(b, 0, 10, c, 0); foreach(Char d in c) Console.Write(d); Console.WriteLine(); } } }
P Q R S T U V W X Y Z
301
Contents | Index
ASCIIEncoding
System.Text
GetMaxByteCount() Method
The output is This is a
A B
ASCIIEncoding.GetMaxByteCount(System.Int32) Method
C [ILASM]
D
.method public hidebysig virtual int32 GetMaxByteCount(int32 charCount) [C#]
E
public override int GetMaxByteCount(int charCount)
F G
Summary
H
Returns the maximum number of bytes required to encode the specified number of characters as ASCII-encoded characters, regardless of the actual character values.
I
Parameters
J K L M
Parameter
Description
charCount
A System.Int32 that specifies the number of characters to encode as ASCIIencoded characters.
N O
Return Value
P
A System.Int32 containing the maximum number of bytes required to encode charCount characters as ASCII-encoded characters.
Q R
Description
S
[Note: This method overrides System.Text.Encoding.GetMaxByteCount. Use this method to determine a minimum buffer size for byte arrays passed to the System.Text.ASCIIEncoding.GetBytes or System.Text.Encoding.GetBytes method for the current instance. Using this minimum buffer size can help ensure that buffer overflow exceptions do not occur.]
T U V W X
Exceptions
Y Z
Exception
Condition
System.ArgumentOutOfRangeException
charCount < 0.
302
Contents | Index
System.Text
ASCIIEncoding GetMaxCharCount() Method
Example using System; using System.Text;
A namespace Samples { public class ASCIIEncodingGetMaxByteCount { public static void Main() { ASCIIEncoding a = (ASCIIEncoding) Encoding.ASCII; int c = 42; int b = a.GetMaxByteCount(c); Console.WriteLine( "The maximum number of bytes to encode " + "{0} characters is {1}.", c, b); } } }
B C D E F G H I J K
The output is
L The maximum number of bytes to encode 42 characters is 42.
M N
ASCIIEncoding.GetMaxCharCount(System.Int32) Method
O
[ILASM]
P
.method public hidebysig virtual int32 GetMaxCharCount(int32 byteCount)
Q
[C#]
public override int GetMaxCharCount(int byteCount)
R
Summary
S
Gets the maximum number of characters produced by decoding a specified number of bytes as ASCII-encoded characters, regardless of the actual byte values.
T U V
Parameters
W
Parameter
Description
byteCount
A System.Int32 that specifies the number of bytes to decode as ASCIIencoded characters.
X Y Z
303
Contents | Index
ASCIIEncoding
System.Text
GetMaxCharCount() Method
Return Value A System.Int32 containing the maximum number of characters that would be produced by decoding byteCount bytes as ASCII-encoded characters. A B
Description
C
[Note: This method overrides System.Text.Encoding.GetMaxCharCount. Use this method to determine the minimum buffer size for character arrays passed to the System.Text.ASCIIEncoding.GetChars or the System.Text.Encoding.GetChars methods. Using this minimum buffer size can help ensure that buffer overflow exceptions do not occur.]
D E F G
Exceptions
H I
Exception
Condition
J
System.ArgumentOutOfRangeException
byteCount < 0.
K L
Example
M
using System; using System.Text;
N O
namespace Samples { public class ASCIIEncodingGetMaxCharCount { public static void Main() { ASCIIEncoding a = new ASCIIEncoding(); byte[] bytes = new byte[]{72, 101, 108, 108, 111}; int i = a.GetMaxCharCount(bytes.Length); Console.WriteLine( "The maximum number of Chars to encode " + "{0} bytes is {1}.", bytes.Length, i); char[] chars = new char[i]; a.GetChars(bytes, 0, bytes.Length, chars, 0); foreach(char c in chars) Console.Write(c); Console.WriteLine(); } } }
P Q R S T U V W X Y Z
304
Contents | Index
System.Text
ASCIIEncoding GetString() Method
The output is The maximum number of Chars to encode 5 bytes is 5. Hello
A B
ASCIIEncoding.GetString(System.Byte[]) Method
C
[ILASM] .method public hidebysig virtual string GetString(class System.Byte[] bytes) [C#] public override string GetString(byte[] bytes)
D E F G
Summary
H
Decodes the specified array of bytes as a string of ASCII-encoded characters.
I
Parameters Parameter
J K
Description
L
bytes
A System.Byte array to decode as ASCII-encoded characters.
M N
Return Value
O
A System.String containing the decoded representation of bytes as ASCII-encoded characters.
P Q
Description
R
[Note: This method overrides System.Text.Encoding.GetString.]
S T
Exceptions
U
Exception
Condition
System.ArgumentNullException
bytes is null.
V W X Y Z
305
Contents | Index
ASCIIEncoding
System.Text
GetString() Method
Example using System; using System.Text;
A namespace Samples { public class ASCIIEncodingGetString { public static void Main() { Byte[] b = new Byte[] {84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 115, 97, 109, 112, 108, 101, 32, 115, 116, 114, 105, 110, 103,}; ASCIIEncoding a = (ASCIIEncoding) Encoding.ASCII; string s = a.GetString(b); Console.WriteLine(s); } } }
B C D E F G H I J K L
The output is
M
This is a sample string
N O
Q
ASCIIEncoding.GetString(System.Byte[], System.Int32, System.Int32) Method
R
[ILASM]
S
.method public hidebysig virtual string GetString(class System.Byte[] bytes, int32 byteIndex, int32 byteCount)
P
[C#]
T
public override string GetString(byte[] bytes, int byteIndex, int byteCount)
U V
Summary
W
Decodes the specified range of the specified array of bytes as a string of ASCII-encoded characters.
X Y Z
306
Contents | Index
System.Text
ASCIIEncoding GetString() Method
Parameters Parameter
Description
bytes
A System.Byte array to decode as ASCII-encoded characters.
byteIndex
A System.Int32 that specifies the first index of bytes from which to decode.
C
byteCount
A System.Int32 that specifies the number of elements in bytes to decode.
D
A B
E F
Return Value
G
A System.String object containing the decoded representation of the range in bytes from byteIndex to byteIndex + byteCount – 1 as ASCII-encoded characters.
H I
Description
J
[Note: This method overrides System.Text.Encoding.GetString.]
K
Exceptions
L M
Exception
Condition
System.ArgumentNullException
bytes is null.
O
byteIndex < 0.
P
-or-
Q
byteCount < 0.
R
System.ArgumentOutOfRangeException
N
-or-
S
(bytes.Length – byteIndex) < byteCount.
T U
Example
V
using System; using System.Text;
W X
namespace Samples { public class ASCIIEncodingGetString { public static void Main() {
Y Z
307
Contents | Index
ASCIIEncoding
System.Text
GetString() Method
Byte[] b = new Byte[] {84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 115, 97, 109, 112, 108, 101, 32, 115, 116, 114, 105, 110, 103,}; ASCIIEncoding a = (ASCIIEncoding) Encoding.ASCII; string s = a.GetString(b, 0, 10); Console.WriteLine(s);
A B C }
D
} }
E F
The output is
G This is a
H I J K L M N O P Q R S T U V W X Y Z
308
Contents | Index
System AsyncCallback Delegate
BCL
Object ICloneable
A
Delegate ISerializable MulticastDelegate
NotStandardized
NotStandardized
B
AsyncCallback
C D
Summary
E
References one or more methods called when an asynchronous operation completes.
F
Type Summary
G
public delegate void AsyncCallback (IAsyncResult ar);
H I
JR I like the asynchronous programming model a lot and I recommend that everyone learn to apply it where appropriate to improve the performance and scalability of their applications.
J K L M
Parameters
N
Parameter
Description
ar
A System.IAsyncResult object containing information about the asynchronous operation that has completed.
O P Q R
Example
S
using using using using
T
System; System.IO; System.Text; System.Threading;
U V
namespace Samples { public class AsyncCallBackSample { const int limit = 512; const int readlimit = 15; public class StateHolder { public byte[] bytes ; public FileStream fs ;
W X Y Z
309
Contents | Index
AsyncCallback Delegate
System
AsyncCallback Delegate Class
} public static void Main() { string s = "filestream.txt"; FileStream fs = new FileStream(s, FileMode.Open, FileAccess.Read); StateHolder sh = new StateHolder(); sh.fs = fs; sh.bytes = new Byte[limit]; AsyncCallback ac = new AsyncCallback(CallMe); fs.BeginRead(sh.bytes, 0, readlimit, ac, sh); Thread.Sleep(2000); Console.WriteLine(); Console.WriteLine("Finishing Main()"); } public static void CallMe(IAsyncResult asyncResult) { StateHolder sh = (StateHolder) asyncResult.AsyncState; FileStream fs = sh.fs; int count = fs.EndRead(asyncResult); Console.Write("Bytes read: {0} ", count); if(count != 0) { Decoder d = Encoding.UTF8.GetDecoder(); char[] chars = null; int i = d.GetCharCount(sh.bytes, 0, count); chars = new Char[i]; count = d.GetChars(sh.bytes, 0, count, chars, 0); Console.WriteLine(new string(chars)); fs.BeginRead(sh.bytes, 0, readlimit, new AsyncCallback(CallMe), sh); } else { fs.Close() ; } }
A B C D E F G H I J K L M N O P Q R S }
T }
U
The output is
V W
Bytes read: 15 Hello world..
X
Bytes read: 15 Goodbye world
Y
Bytes read: 5 ...
Z Bytes read: 0 Finishing Main()
310
Contents | Index
System Attribute
BCL
Object
A
Attribute AttributeUsageAttribute
B
CLSCompliantAttribute
C
ConditionalAttribute
D
FlagsAttribute
E
ObsoletAttribute
F
SecurityAttribute
G
CodeAccessSecurityAttribute
H EnvironmentPermissionAttribute
I FileIOPermissionAttribute
J SecurityPermissionAttribute
K
Summary
L
Serves as the base class for custom attributes.
M
Type Summary
N O
public abstract class Attribute { // Constructors protected Attribute ();
P Q R
// Properties MS CF public virtual object TypeId { get; }
S
// Methods public override bool Equals (object obj); public static Attribute GetCustomAttribute (Assembly element, Type attributeType); MS public static Attribute GetCustomAttribute (Assembly element, Type attributeType, bool inherit); public static Attribute GetCustomAttribute (MemberInfo element, Type attributeType); MS public static Attribute GetCustomAttribute (MemberInfo element, Type attributeType, bool inherit); public static Attribute GetCustomAttribute (Module element, Type attributeType);
T U V W X Y Z
311
Contents | Index
Attribute
System
Attribute Class
MS public static Attribute GetCustomAttribute (Module element, Type attributeType, bool inherit); public static Attribute GetCustomAttribute (ParameterInfo element, Type attributeType); MS public static Attribute GetCustomAttribute (ParameterInfo element, Type attributeType, bool inherit); public static Attribute[] GetCustomAttributes (Assembly element); MS public static Attribute[] GetCustomAttributes (Assembly element, bool inherit); public static Attribute[] GetCustomAttributes (Assembly element, Type attributeType); MS public static Attribute[] GetCustomAttributes (Assembly element, Type attributeType, bool inherit); public static Attribute[] GetCustomAttributes (MemberInfo element); MS public static Attribute[] GetCustomAttributes (MemberInfo element, bool inherit); public static Attribute[] GetCustomAttributes (MemberInfo element, Type type); MS public static Attribute[] GetCustomAttributes (MemberInfo element, Type type, bool inherit); public static Attribute[] GetCustomAttributes (Module element); MS public static Attribute[] GetCustomAttributes (Module element, bool inherit); public static Attribute[] GetCustomAttributes (Module element, Type attributeType); MS public static Attribute[] GetCustomAttributes (Module element, Type attributeType, bool inherit); public static Attribute[] GetCustomAttributes (ParameterInfo element); MS public static Attribute[] GetCustomAttributes (ParameterInfo element, bool inherit); public static Attribute[] GetCustomAttributes (ParameterInfo element, Type attributeType); MS public static Attribute[] GetCustomAttributes (ParameterInfo element, Type attributeType, bool inherit); public override int GetHashCode (); MS CF public virtual bool IsDefaultAttribute (); public static bool IsDefined (Assembly element, Type attributeType); MS public static bool IsDefined (Assembly element, Type attributeType, bool inherit);
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
312
Contents | Index
System
Attribute Attribute Class
MS
MS
MS
MS
public static bool IsDefined (MemberInfo element, Type attributeType); public static bool IsDefined (MemberInfo element, Type attributeType, bool inherit); public static bool IsDefined (Module element, Type attributeType); public static bool IsDefined (Module element, Type attributeType, bool inherit); public static bool IsDefined (ParameterInfo element, Type attributeType); public static bool IsDefined (ParameterInfo element, Type attributeType, bool inherit); public virtual bool Match (object obj);
A B C D E F G H
}
I J
BA The ability to extend the metadata format in a structured way is an important
K
advance of the CLI. The development community has always had a need to add declarative information to code. With the advent of custom attributes, we are no longer limited to the glacially slow pace of adding new keywords to languages or the ugly and error-prone pre-processor support for adding declarative markup to code.
L M N O
JR I agree with Brad. Custom attributes is an incredibly useful and innovative feature. I’m constantly coming up with new ways to apply them. For example, I’ve created my own custom attribute to help me with command-line argument parsing. I define a structure with fields and apply an instance of my attribute to each field. The attribute indicates the command-line switch letter and I implemented a method that can parse command-line arguments and set the appropriate fields in the structure. Then, the rest of my code just accesses the structure’s fields. Adding new commandline switches is a breeze. I’ve also used attributes to localize strings for enum values and for defining strings to present for a user that correspond with programmatic values. Creative use of custom attributes can greatly simplify development effort and improve extensibility.
P Q R S T U V W X
Description
Y
All attributes, whether built-in or user-defined, derive directly or indirectly from System.Attribute. Attributes inherit certain default behaviors: the attribute may be associated with any target element (see System.AttributeTargets); may or may not be inherited by a derived element; and multiple instances may or may not be allowed on
Z
313
Contents | Index
Attribute
System
Attribute Class
the same target element. These behaviors are specified using System.AttributeUsageAttribute. [Note: An attribute is an annotation that may be placed on an element of source code and used to store application-specific information at compile time. This information is stored in the metadata and can be accessed either during application execution, through a process known as reflection, or when another tool reads the metadata. Attributes might change the behavior of the application during execution, provide transaction information about an object, or convey organizational information to a designer.] The CLI predefines some attribute types and uses them to control runtime behavior. Some languages predefine attribute types to represent language features not directly represented in the Common Language Specification (CLS). User-defined attribute classes, inheriting from System.Attribute, may also be created. The definition of such a class includes the name of the attribute, its default behavior, and the information to be stored.
A B C D E F G H I
Example
J
using System; using System.Reflection;
K namespace Samples { [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)] public class AuthorAttribute: Attribute { private string familyName; private string givenName; public AuthorAttribute(string familyName) { this.familyName = familyName; } public override String ToString() { return String.Format("Author: {0} {1}", familyName, givenName); } public string FamilyName { get {return familyName;} } public string GivenName { get {return givenName;} set {givenName = value;} } }
L M N O P Q R S T U V W X Y Z
314
Contents | Index
System
Attribute Attribute() Constructor
[Author("Watkins", GivenName = "Damien")] [Author("Abrams")] public class AttributeSample { [Author("Abrams", GivenName = "Brad")] public static void Main() { Type t = typeof(AttributeSample); Attribute[] attributes = Attribute.GetCustomAttributes(t); foreach(Attribute a in attributes) { if(a is AuthorAttribute) { AuthorAttribute at = a as AuthorAttribute; Console.WriteLine("Given Name: {0}", at.GivenName); Console.WriteLine("Family Name: {0}", at.FamilyName); Console.WriteLine("------------------------------"); } } } }
A B C D E F G H I J K
}
L
The output is
M
Given Name: Family Name: Abrams -----------------------------Given Name: Damien Family Name: Watkins ------------------------------
N O P Q R
Attribute() Constructor
S
[ILASM]
T
family rtspecialname specialname instance void .ctor()
U
[C#]
protected Attribute()
V W
Summary
X
Constructs a new instance of the System.Attribute class.
Y Z
315
Contents | Index
Attribute
System
TypeId Property
Attribute.TypeId Property [ILASM]
.property object TypeId { public hidebysig virtual specialname object get_TypeId() }
A
[C#]
public virtual object TypeId { get; }
B C
Summary
D
When implemented in a derived class, gets a unique identifier for this Attribute.
E F
Property Value
G
An System.Object that is a unique identifier for the attribute.
H
Description
I
As implemented, this identifier is merely the System.Type of the attribute. However, it is intended that the unique identifier be used to identify two attributes of the same type.
J K L
Attribute.Equals(System.Object) Method
M
[ILASM]
.method public hidebysig virtual bool Equals(object obj)
N
[C#]
O
public override bool Equals(object obj)
P
Summary
Q
Determines whether the current instance and the specified System.Object represent the same type and value.
R S
Parameters
T U
Parameter
Description
obj
The System.Object to compare to the current instance.
V W X
Return Value
Y
A System.Boolean where true indicates obj represents the same type and value as the current instance. If obj is a null reference or is not an instance of System.Attribute, it returns false.
Z
316
Contents | Index
System
Attribute GetCustomAttribute() Method
Description [Note: This method overrides System.Object.Equals.] A
Attribute.GetCustomAttribute(System.Reflection.Assembly, System.Type) Method
B
[ILASM]
D
.method public hidebysig static class System.Attribute GetCustomAttribute(class System.Reflection.Assembly element, class System.Type attributeType)
E
C
[C#]
F
public static Attribute GetCustomAttribute(Assembly element, Type attributeType)
G
Summary
H
Returns an instance of a specified custom attribute if a single instance of the attribute is in the metadata for the specified assembly.
I J
Parameters
K L
Parameter
Description
element
A System.Reflection.Assembly instance.
N
attributeType
The System.Type of the custom attribute for which to check.
O
M
P Q
Return Value
R
The single instance of System.Attribute of type attributeType that is applied to element. Returns null if the specified attribute was not found.
S T
Description
U
[Note: If multiple instances of attributeType can be applied to element, use System.Attribute.GetCustomAttributes.] This member must be implemented if the Runtime Infrastructure Library is present in the implementation.
V W X Y Z
317
Contents | Index
Attribute
System
GetCustomAttribute() Method
Exceptions Exception
Condition
System.ArgumentNullException
element or attributeType is null.
System.ArgumentException
attributeType is not a type derived from System.Attribute.
System.Reflection. AmbiguousMatchException
More than one instance of the specified custom attribute was found.
A B C D E F G
Example
H
using System; using System.Reflection;
I [assembly: Samples.Author("Damien Watkins")]
J
namespace Samples { [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)] public class AuthorAttribute: Attribute { private string author; public AuthorAttribute(string author) { this.author = author; } public override String ToString() { return String.Format("Author: {0}", author); } }
K L M N O P Q R S T U
public class AttributeGetCustomAttribute { public static void Main() { Assembly e = Assembly.GetExecutingAssembly(); Attribute a = Attribute.GetCustomAttribute(e, typeof(AuthorAttribute)); Console.WriteLine("Name: {0} ", e.FullName); Console.WriteLine(a); } }
V W X Y Z }
318
Contents | Index
System
Attribute GetCustomAttribute() Method
The output is Name: Attribute, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null Author: Damien Watkins
A B
Attribute.GetCustomAttribute(System.Reflection.Assembly, System.Type, System.Boolean) Method
D
[ILASM]
E
.method public hidebysig static class System.Attribute GetCustomAttribute(class System.Reflection.Assembly element, class System.Type attributeType, bool inherit)
F
C
[C#]
G
public static Attribute GetCustomAttribute(Assembly element, Type attributeType, bool inherit)
H I
Summary
J
Retrieves a custom attribute of a specified type applied to a specified assembly or optionally inherited from a base class.
K L
Parameters
M
Parameter
Description
element
An object derived from class System.Reflection.Assembly that describes a reusable, versionable, collection of modules.
attributeType
The System.Type object to which the custom attributes are applied.
inherit
This parameter is ignored, and does not affect the operation of this method.
N O P Q R S T
Return Value
U
null, if no custom attribute of type attributeType is applied to element or a System.Attribute reference to the single custom attribute of type attributeType that is applied to element.
V W X Y Z
319
Contents | Index
Attribute
System
GetCustomAttribute() Method
Exceptions Exception
Condition
System.ArgumentNullException
element or attributeType is null.
System.ArgumentException
attributeType is not derived from System.Attribute.
System.Reflection.AmbiguousMatchException
More than one of the requested attributes was found.
A B C D E F G
I
Attribute.GetCustomAttribute(System.Reflection.MemberInfo, System.Type) Method
J
[ILASM]
K
.method public hidebysig static class System.Attribute GetCustomAttribute(class System.Reflection.MemberInfo element, class System.Type attributeType)
L
[C#]
H
public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType)
M N
Summary
O
Returns an instance of a specified custom attribute if a single instance of the attribute is in the metadata for the specified member.
P Q
Parameters
R S T
Parameter
Description
element
An instance of a type derived from System.Reflection.MemberInfo that describes a type member.
attributeType
The System.Type of the custom attribute for which to check.
U V W X
Return Value
Y
The single instance of System.Attribute of type attributeType that is applied to element. Returns null if the specified attribute was not found.
Z
320
Contents | Index
System
Attribute GetCustomAttribute() Method
Description [Note: If multiple instances of attributeType can be applied to element, use System.Attribute.GetCustomAttributes.] This member must be implemented if the Reflection Library is present in the implementation.
A B
Exceptions
C
Exception
Condition
System.ArgumentNullException
element or attributeType is null.
System.ArgumentException
attributeType is not a type derived from System.Attribute.
System.NotSupportedException
element does not represent a constructor, method, property, event, type, or field member.
System.Reflection.AmbiguousMatchException
More than one instance of the specified custom attribute was found.
D E F G H I J K L
Example
M
using System; using System.Reflection;
N O
namespace Samples { [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)] public class AuthorAttribute: Attribute { private string author; public AuthorAttribute(string author) { this.author = author; } public override String ToString() { return String.Format("Author: {0}", author); } }
P Q R S T U V W X Y Z
[Author("Damien Watkins")] public class AttributeGetCustomAttribute
321
Contents | Index
Attribute
System
GetCustomAttribute() Method
{ [Author("Brad Abrams")] public AttributeGetCustomAttribute(string s) { Console.WriteLine(s); } [Author("Damien Watkins")] public static void Main() { Type t = typeof(AttributeGetCustomAttribute); MemberInfo[] m = t.GetMembers(); foreach(MemberInfo i in m) { Console.Write("Member: {0} ", i.Name); Attribute a = Attribute.GetCustomAttribute(i, typeof(AuthorAttribute)); Console.WriteLine(a); } }
A B C D E F G H I J }
K
}
L
The output is
M Member: Member: Member: Member: Member: Member:
N O P Q
GetHashCode Equals ToString Main Author: Damien Watkins GetType .ctor Author: Brad Abrams
R
Attribute.GetCustomAttribute(System.Reflection.MemberInfo, System.Type, System.Boolean) Method
S T
[ILASM]
U
.method public hidebysig static class System.Attribute GetCustomAttribute(class System.Reflection.MemberInfo element, class System.Type attributeType, bool inherit)
V W
[C#]
public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType, bool inherit)
X Y
Summary
Z
Retrieves a custom attribute of a specified type applied to a specified member of a class or optionally inherited from a base class. 322
Contents | Index
System
Attribute GetCustomAttribute() Method
Parameters Parameter
Description
element
An object derived from class System.Reflection.MemberInfo that describes a constructor, event, field, method, or property member of a class.
attributeType
The System.Type object to which the custom attributes are applied.
inherit
If true, specifies to also search the ancestors of element for custom attributes.
A B C D E F
Return Value
G
null, if no custom attribute of type attributeType is applied to element, or an System.Attribute reference to the single custom attribute of type attributeType that is applied to element.
H I J
Exceptions
K
Exception
Condition
L
System.ArgumentNullException
element or attributeType is null.
M
System.ArgumentException
attributeType is not derived from System.Attribute.
N
System.NotSupportedException
element is not a constructor, method, property, event, type, or field.
System.Reflection.AmbiguousMatchException
O P Q
More than one of the requested attributes was found.
R S
Example
T
The following code example illustrates the use of GetCustomAttribute, taking a System.Reflection.MemberInfo as a parameter.
U V
Attribute.GetCustomAttribute(System.Reflection.Module, System.Type) Method
W
[ILASM]
Y
.method public hidebysig static class System.Attribute GetCustomAttribute(class System.Reflection.Module element, class System.Type attributeType)
Z
X
[C#]
public static Attribute GetCustomAttribute(Module element, Type attributeType)
323
Contents | Index
Attribute
System
GetCustomAttribute() Method
Summary Returns an instance of a specified custom attribute if a single instance of the attribute is in the metadata for the specified module. A
Parameters
B C
Parameter
Description
E
element
A System.Reflection.Module instance.
F
attributeType
The System.Type of the custom attribute for which to check.
D
G H
Return Value
I
The single instance of System.Attribute of type attributeType that is applied to element. Returns null if the specified attribute was not found.
J K
Description
L
[Note: If multiple instances of attributeType can be applied to element, use System.Attribute.GetCustomAttributes.] This member must be implemented if the Reflection Library is present in the implementation.
M N O
Exceptions
P Q R
Exception
Condition
System.ArgumentNullException
element or attributeType is null.
System.ArgumentException
attributeType is not a type derived from System.Attribute.
System.Reflection.AmbiguousMatchException
More than one instance of the specified custom attribute was found.
S T U V W X Y Z
324
Contents | Index
System
Attribute GetCustomAttribute() Method
Example using System; using System.Reflection;
A [module: Samples.Author("Damien Watkins")]
B namespace Samples { [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)] public class AuthorAttribute: Attribute { private string author; public AuthorAttribute(string author) { this.author = author; } public override String ToString() { return String.Format("Author: {0}", author); } }
C D E F G H I J K L M
public class AttributeGetCustomAttribute { public static void Main() { Module m = Assembly.GetExecutingAssembly(). GetModule("Attribute.exe"); Attribute a = Attribute.GetCustomAttribute(m, typeof(AuthorAttribute)); Console.WriteLine("Module: {0}", m.FullyQualifiedName); Console.WriteLine(a); } }
N O P Q R S T U
}
V
The output is
W Module: C:\Books\BCL\Samples\System\Attribute\ GetCustomAttribute(System.Reflection.Module,System.Type)\Attribute.exe Author: Damien Watkins
X Y Z
325
Contents | Index
Attribute
System
GetCustomAttribute() Method
Attribute.GetCustomAttribute(System.Reflection.Module, System.Type, System.Boolean) Method [ILASM]
A
.method public hidebysig static class System.Attribute GetCustomAttribute(class System.Reflection.Module element, class System.Type attributeType, bool inherit)
B
[C#]
C
public static Attribute GetCustomAttribute(Module element, Type attributeType, bool inherit)
D E
Summary
F
Retrieves a custom attribute of a specified type applied to a specified module or optionally inherited from a base class.
G H
Parameters
I J
Parameter
Description
element
An object derived from class System.Reflection.Module that describes a portable executable file.
attributeType
The System.Type object to which the custom attributes are applied.
inherit
This parameter is ignored, and does not affect the operation of this method.
K L M N O P
Return Value
Q
null, if no custom attribute of type attributeType is applied to element or a System.Attribute reference to the single custom attribute of type attributeType that is applied to element.
R S T
Exceptions
U V
Exception
Condition
System.ArgumentNullException
element or attributeType is null.
System.ArgumentException
attributeType is not derived from System.Attribute.
System.Reflection.AmbiguousMatchException
More than one of the requested attributes was found.
W X Y Z
326
Contents | Index
System
Attribute GetCustomAttribute() Method
Attribute.GetCustomAttribute(System.Reflection.ParameterInfo, System.Type) Method [ILASM]
A
.method public hidebysig static class System.Attribute GetCustomAttribute(class System.Reflection.ParameterInfo element, class System.Type attributeType)
B
[C#]
C
public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType)
D
Summary
E
Returns an instance of a specified custom attribute if a single instance of the attribute is in the metadata for the specified parameter.
F G H
Parameters
I
Parameter
Description
element
A System.Reflection.ParameterInfo instance.
K
attributeType
The System.Type of the custom attribute for which to check.
L
J
M
Return Value
N
The single instance of System.Attribute of type attributeType that is applied to element. Returns null if the specified attribute was not found.
O
Description
Q
[Note: If multiple instances of attributeType can be applied to element, use System.Attribute.GetCustomAttributes.] This member must be implemented if the Reflection Library is present in the implementation.
R
Exceptions
U
P
S T
V
Exception
Condition
System.ArgumentNullException
element or attributeType is null.
System.ArgumentException
attributeType is not a type derived from System.Attribute.
System.Reflection.AmbiguousMatchException
More than one instance of the specified custom attribute was found.
W X Y Z
327
Contents | Index
Attribute
System
GetCustomAttribute() Method
Example using System; using System.Reflection;
A namespace Samples { [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)] public class ModifiedInMethodAttribute: Attribute { private bool isModified; public ModifiedInMethodAttribute(bool isModified) { this.isModified = isModified; } public override String ToString() { return String.Format("Is modified in method: {0}", isModified); } }
B C D E F G H I J K L
public class foo {};
M
public class AttributeGetCustomAttribute { public AttributeGetCustomAttribute( [ModifiedInMethod(false)]foo f) { Console.WriteLine(f); } public static void Main() { Type t = typeof(AttributeGetCustomAttribute); ConstructorInfo[] ci = t.GetConstructors(); foreach(ConstructorInfo c in ci) { Console.WriteLine(c); ParameterInfo[] pi = c.GetParameters(); Console.WriteLine("Parameters"); foreach(ParameterInfo p in pi) { Console.Write("\tName: {0}, ", p.Name); Console.Write("Type: {0}, ", p.ParameterType); Attribute a = Attribute.GetCustomAttribute(p, typeof(ModifiedInMethodAttribute)); Console.WriteLine(a); }
N O P Q R S T U V W X Y Z
328
Contents | Index
System
Attribute GetCustomAttribute() Method
} } } }
A
The output is
B C
Void .ctor(Samples.foo) Parameters Name: f, Type: Samples.foo, Is modified in method: False
D E F
Attribute.GetCustomAttribute(System.Reflection.ParameterInfo, System.Type, System.Boolean) Method
G H
[ILASM]
.method public hidebysig static class System.Attribute GetCustomAttribute(class System.Reflection.ParameterInfo element, class System.Type attributeType, bool inherit)
I
[C#]
K
public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType, bool inherit)
L
J
M
Summary
N
Retrieves a custom attribute of a specified type applied to a specified parameter of a member of a class or optionally inherited from a base class.
O P
Parameters
Q
Parameter
Description
element
An object derived from class System.Reflection.ParameterInfo that describes a parameter of a member of a class.
attributeType
The System.Type object to which the custom attributes are applied.
inherit
If true, specifies to also search the ancestors of element for custom attributes.
R S T U V W X
Return Value
Y
null, if no custom attribute of type attributeType is applied to element or a System.Attribute reference to the single custom attribute of type attributeType that is applied to element.
Z
329
Contents | Index
Attribute
System
GetCustomAttributes() Method
Exceptions Exception
Condition
System.ArgumentNullException
element or attributeType is null.
System.ArgumentException
attributeType is not derived from System.Attribute.
System.Reflection.AmbiguousMatchException
More than one of the requested attributes was found.
A B C D E F G H
Attribute.GetCustomAttributes(System.Reflection.Assembly) Method
I
[ILASM]
J
.method public hidebysig static class System.Attribute[] GetCustomAttributes(class System.Reflection.Assembly element)
K
[C#]
public static Attribute[] GetCustomAttributes(Assembly element)
L M
Summary
N
Returns an array of all custom attributes in the metadata for the specified assembly.
O
Parameters
P Q
Parameter
Description
R
element
A System.Reflection.Assembly instance.
S T
Return Value
U
A System.Attribute array containing all custom attributes that are applied to element. The array includes any inherited custom attributes. Returns an empty array if no custom attributes were found in the metadata for element.
V W X
Exceptions
Y Z
Exception
Condition
System.ArgumentNullException
element is null.
330
Contents | Index
System
Attribute GetCustomAttributes() Method
Example using System; using System.Reflection;
A [assembly: AssemblyTitle("Sample Programs")] [assembly: AssemblyDescription("Sample programs")]
B C
namespace Samples { public class AttributeGetCustomAttributes { public static void Main() { Assembly e = Assembly.GetExecutingAssembly(); Attribute[] attributes = Attribute.GetCustomAttributes(e); foreach(Attribute a in attributes) { Console.WriteLine(a); } } } }
D E F G H I J K L M
The output is
N O
System.Reflection.AssemblyDescriptionAttribute System.Reflection.AssemblyTitleAttribute System.Diagnostics.DebuggableAttribute
P Q R
Attribute.GetCustomAttributes(System.Reflection.Assembly, System.Boolean) Method
S T
[ILASM]
U
.method public hidebysig static class System.Attribute[] GetCustomAttributes(class System.Reflection.Assembly element, bool inherit)
V
[C#]
public static Attribute[] GetCustomAttributes(Assembly element, bool inherit)
W X
Summary
Y
Retrieves an array of the custom attributes of a specified type applied to a specified assembly or optionally inherited from a base class.
Z
331
Contents | Index
Attribute
System
GetCustomAttributes() Method
Parameters Parameter
Description
element
An object derived from class System.Reflection.Assembly that describes a reusable, versionable collection of modules.
inherit
This parameter is ignored, and does not affect the operation of this method.
A B C D E
Return Value
F
A System.Attribute array containing the custom attributes applied to element or an empty array if no such custom attributes exist.
G H I
Description
J
Return value contains the custom attributes for ancestors of element if inherit is true.
K
Exceptions
L M
Exception
Condition
N
System.ArgumentNullException
element is null.
O P
R
Attribute.GetCustomAttributes(System.Reflection.Assembly, System.Type) Method
S
[ILASM]
T
.method public hidebysig static class System.Attribute[] GetCustomAttributes(class System.Reflection.Assembly element, class System.Type attributeType)
Q
[C#]
U
public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType)
V W
Summary
X
Returns an array of the instances of a specified custom attribute if the attribute is in the metadata for the specified assembly.
Y Z
332
Contents | Index
System
Attribute GetCustomAttributes() Method
Parameters Parameter
Description
element
A System.Reflection.Assembly instance.
attributeType
The System.Type of the custom attribute for which to check.
A B C D
Return Value
E
An array of type attributeType containing the instances that are applied to element. The array includes any inherited instances of attributeType. Returns an empty array if the specified attribute was not found.
F G H
Exceptions
I J
Exception
Condition
System.ArgumentNullException
element or attributeType is null.
L
attributeType is not a type derived from System.Attribute.
M
System.ArgumentException
K
N O
Example
P
using System; using System.Reflection;
Q R
[assembly: Samples.Author("Damien Watkins")] [assembly: Samples.Author("Brad Abrams")] [assembly: AssemblyVersion("4.2.4.2")]
S T U
namespace Samples { [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] public class AuthorAttribute: Attribute { private string author; public AuthorAttribute(string author) { this.author = author; }
V W X Y Z
333
Contents | Index
Attribute
System
GetCustomAttributes() Method
public override String ToString() { return String.Format("Author: {0}", author); }
A
}
B public class AttributeGetCustomAttributes { public static void Main() { Assembly e = Assembly.GetExecutingAssembly(); Console.WriteLine("Name: {0} ", e.FullName); Attribute[] attributes = Attribute.GetCustomAttributes(e, typeof(AuthorAttribute)); foreach(Attribute a in attributes) { Console.WriteLine(a); } } }
C D E F G H I J K }
L
The output is
M N
Name: Attribute, Version=4.2.4.2, Culture=neutral, PublicKeyToken=null Author: Brad Abrams Author: Damien Watkins
O P Q
Attribute.GetCustomAttributes(System.Reflection.Assembly, System.Type, System.Boolean) Method
R S
[ILASM]
T
.method public hidebysig static class System.Attribute[] GetCustomAttributes(class System.Reflection.Assembly element, class System.Type attributeType, bool inherit)
U
[C#]
V
public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType, bool inherit)
W X
Summary
Y
Retrieves an array of the custom attributes of a specified type applied to a specified assembly or optionally inherited from a base class.
Z
334
Contents | Index
System
Attribute GetCustomAttributes() Method
Parameters Parameter
Description
element
An object derived from class System.Reflection.Assembly that describes a reusable, versionable collection of modules.
attributeType
The System.Type object to which the custom attributes are applied.
inherit
This parameter is ignored, and does not affect the operation of this method.
A B C D E F
Return Value
G
A System.Attribute array containing the custom attributes of type attributeType applied to element or an empty array if no such custom attributes exist.
H
Description
J
Return value contains the custom attributes for ancestors of element if inherit is true.
K
I
L
Exceptions
M
Exception
Condition
System.ArgumentNullException
element or attributeType is null.
System.ArgumentException
attributeType is not derived from System.Attribute.
N O P Q R S
Attribute.GetCustomAttributes(System.Reflection.MemberInfo) Method
T
[ILASM]
U
.method public hidebysig static class System.Attribute[] GetCustomAttributes(class System.Reflection.MemberInfo element)
V
[C#]
W
public static Attribute[] GetCustomAttributes(MemberInfo element)
X
Summary
Y
Returns an array of all custom attributes in the metadata for the specified member.
Z
335
Contents | Index
Attribute
System
GetCustomAttributes() Method
Parameters Parameter
Description
element
An instance of a type derived from System.Reflection.MemberInfo that describes a type member.
A B C D
Return Value
E
A System.Attribute array containing all custom attributes that are applied to element. The array includes custom attributes that are inherited by element, if any. Returns an empty array if no custom attributes were found in the metadata for element.
F G H
Description
I
This member must be implemented if the Reflection Library is present in the implementation.
J K
Exceptions
L M
Exception
Condition
System.ArgumentNullException
element is null.
System.NotSupportedException
element does not represent a constructor, method, property, event, type, or field member.
N O P Q R S
Example
T
using System; using System.Reflection;
U namespace Samples { [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] public class AuthorAttribute: Attribute { private string author; public AuthorAttribute(string author) { this.author = author;
V W X Y Z
336
Contents | Index
System
Attribute GetCustomAttributes() Method
} public override String ToString() { return String.Format("Author: {0}", author); }
A
}
B
[Author("Damien Watkins")] public class AttributeGetCustomAttributes { [Author("Mark Hammond"), Author("Brad Abrams")] public AttributeGetCustomAttributes(string s) { Console.WriteLine(s); } [Author("Damien Watkins")] public static void Main() { Type t = typeof(AttributeGetCustomAttributes); MemberInfo[] members = t.GetMembers(); foreach(MemberInfo m in members) { Console.WriteLine("Member: {0} ", m.Name); Attribute[] attributes = Attribute.GetCustomAttributes(m); foreach(Attribute a in attributes) Console.WriteLine(" {0}", a); Console.WriteLine(); } } }
C D E F G H I J K L M N O P Q
}
R
The output is
S
Member: GetHashCode
T
Member: Equals
U
Member: ToString
V W
Member: Main Author: Damien Watkins
X
Member: GetType
Y Z
Member: .ctor Author: Mark Hammond Author: Brad Abrams
337
Contents | Index
Attribute
System
GetCustomAttributes() Method
Attribute.GetCustomAttributes(System.Reflection.MemberInfo, System.Boolean) Method [ILASM]
A
.method public hidebysig static class System.Attribute[] GetCustomAttributes(class System.Reflection.MemberInfo element, bool inherit)
B
[C#]
C
public static Attribute[] GetCustomAttributes(MemberInfo element, bool inherit)
D E
Summary
F
Retrieves an array of the custom attributes of a specified member of a class or inherited from a base class.
G
Parameters
H I
Parameter
Description
element
An object derived from class System.Reflection.MemberInfo that describes a constructor, event, field, method, or property member of a class.
inherit
If true, specifies to also search the ancestors of element for custom attributes.
J K L M N O
Return Value
P
A System.Attribute array containing the custom attributes applied to element or an empty array if no such custom attributes exist.
Q R
Description
S
Return value contains the custom attributes for ancestors of element if inherit is true.
T
Exceptions
U V W
Exception
Condition
System.ArgumentNullException
element is null.
System.NotSupportedException
element is not a constructor, method, property, event, type, or field.
X Y Z
338
Contents | Index
System
Attribute GetCustomAttributes() Method
Attribute.GetCustomAttributes(System.Reflection.MemberInfo, System.Type) Method [ILASM]
A
.method public hidebysig static class System.Attribute[] GetCustomAttributes(class System.Reflection.MemberInfo element, class System.Type type)
B
[C#]
C
public static Attribute[] GetCustomAttributes(MemberInfo element, Type type)
D
Summary
E
Returns an array of the instances of a specified custom attribute if the attribute is in the metadata for the specified member.
F G
Parameters
H I
Parameter
Description
element
An instance of a type derived from System.Reflection.MemberInfo that describes a type member.
K
type
The System.Type of the custom attribute for which to check.
L
J
M N
Return Value An array of type type containing the instances that are applied to element. The array includes instances of type that are inherited by element, if any. Returns an empty array if the specified attribute was not found.
O
Description
R
This member must be implemented if the Reflection Library is present in the implementation.
S
Exceptions
U
P Q
T
V
Exception
Condition
System.ArgumentNullException
element or type is null.
X
System.ArgumentException
type is not a type derived from System.Attribute.
Y
System.NotSupportedException
element does not represent a constructor, method, property, event, type, or field member.
W
Z
339
Contents | Index
Attribute
System
GetCustomAttributes() Method
Example using System; using System.Reflection;
A namespace Samples { [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] public class AuthorAttribute: Attribute { private string author; public AuthorAttribute(string author) { this.author = author; } public override String ToString() { return String.Format("Author: {0}", author); } }
B C D E F G H I J K L
[Author("Damien Watkins")] public class AttributeGetCustomAttributes { [Author("Mark Hammond"), Author("Brad Abrams")] public AttributeGetCustomAttributes(string s) { Console.WriteLine(s); } [Author("Damien Watkins")] public static void Main() { Type t = typeof(AttributeGetCustomAttributes); MemberInfo[] members = t.GetMembers(); foreach(MemberInfo m in members) { Console.WriteLine("Member: {0} ", m.Name); Attribute[] attributes = Attribute.GetCustomAttributes(m, typeof(AuthorAttribute)); foreach(Attribute a in attributes) Console.WriteLine(" {0}", a); Console.WriteLine(); } } }
M N O P Q R S T U V W X Y Z }
340
Contents | Index
System
Attribute GetCustomAttributes() Method
The output is Member: GetHashCode
A
Member: Equals
B Member: ToString
C Member: Main Author: Damien Watkins
D E
Member: GetType
F
Member: .ctor Author: Mark Hammond Author: Brad Abrams
G H I J
Attribute.GetCustomAttributes(System.Reflection.MemberInfo, System.Type, System.Boolean) Method
K
[ILASM]
L
.method public hidebysig static class System.Attribute[] GetCustomAttributes(class System.Reflection.MemberInfo element, class System.Type type, bool inherit)
M
[C#]
N
public static Attribute[] GetCustomAttributes(MemberInfo element, Type type, bool inherit)
O P
Summary
Q
Retrieves an array of the custom attributes of a specified type applied to a specified member of a class or optionally inherited from a base class.
R S
Parameters
T U
Parameter
Description V
element
An object derived from class System.Reflection.MemberInfo that describes a constructor, event, field, method, or property member of a class.
type
The System.Type object to which the custom attributes are applied.
inherit
If true, specifies to also search the ancestors of element for custom attributes.
W X Y Z
341
Contents | Index
Attribute
System
GetCustomAttributes() Method
Return Value A System.Attribute array containing the custom attributes of type type applied to element or an empty array if no such custom attributes exist. A B
Description
C
Return value contains the custom attributes for ancestors of element if inherit is true.
D
Exceptions
E F G
Exception
Condition
System.ArgumentNullException
element or type is null.
System.ArgumentException
type is not derived from System.Attribute.
System.NotSupportedException
element is not a constructor, method, property, event, type, or field.
H I J K L M
Attribute.GetCustomAttributes(System.Reflection.Module) Method
N
[ILASM]
O
.method public hidebysig static class System.Attribute[] GetCustomAttributes(class System.Reflection.Module element)
P
[C#]
public static Attribute[] GetCustomAttributes(Module element)
Q R
Summary
S
Returns an array of all custom attributes in the metadata for the specified module.
T
Parameters
U V
Parameter
Description
element
A System.Reflection.Module instance.
W X Y Z
342
Contents | Index
System
Attribute GetCustomAttributes() Method
Return Value A System.Attribute array containing all custom attributes that are applied to element. The array includes any inherited custom attributes. Returns an empty array if no custom attributes were found in the metadata for element.
A B
Description
C
This member must be implemented if the Reflection Library is present in the implementation.
D E
Exceptions Exception
F G
Condition
H System.ArgumentNullException
element is null.
I J
Example
K
using System; using System.Reflection;
L M
[module: Samples.Author("Damien Watkins")]
N
namespace Samples { [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] public class AuthorAttribute: Attribute { private string author; public AuthorAttribute(string author) { this.author = author; } public override String ToString() { return String.Format("Author: {0}", author); } }
O P Q R S T U V W X Y
public class AttributeGetCustomAttributes { public static void Main() {
Z
343
Contents | Index
Attribute
System
GetCustomAttributes() Method
Module[] modules = Assembly.GetExecutingAssembly(). GetModules(); foreach(Module m in modules) { Console.WriteLine("Module: {0}", m.FullyQualifiedName); Attribute[] attributes = Attribute.GetCustomAttributes(m); foreach(Attribute a in attributes) Console.WriteLine(a); }
A B C D E }
F
} }
G
The output is
H I
Module: C:\Books\BCL\Samples\System\Attribute\ GetCustomAttributes(System.Reflection.Module)\Attribute.exe Author: Damien Watkins
J K L
Attribute.GetCustomAttributes(System.Reflection.Module, System.Boolean) Method
M N
[ILASM]
O
.method public hidebysig static class System.Attribute[] GetCustomAttributes(class System.Reflection.Module element, bool inherit)
P
[C#]
Q
public static Attribute[] GetCustomAttributes(Module element, bool inherit)
R
Summary
S
Retrieves an array of the custom attributes of a specified type applied to a specified module or optionally inherited from a base class.
T U
Parameters
V W
Parameter
Description
element
An object derived from class System.Reflection.Module that describes a portable executable file.
inherit
This parameter is ignored, and does not affect the operation of this method.
X Y Z
344
Contents | Index
System
Attribute GetCustomAttributes() Method
Return Value A System.Attribute array containing the custom attributes applied to element or an empty array if no such custom attributes exist. A
Description
B
Return value contains the custom attributes for ancestors of element if inherit is true.
C D
Exceptions
E
Exception
Condition
F
System.ArgumentNullException
element or attributeType is null.
G H I
Attribute.GetCustomAttributes(System.Reflection.Module, System.Type) Method
K
[ILASM]
L
.method public hidebysig static class System.Attribute[] GetCustomAttributes(class System.Reflection.Module element, class System.Type attributeType)
M
J
[C#]
N
public static Attribute[] GetCustomAttributes(Module element, Type attributeType)
O
Summary
P
Returns an array of the instances of a specified custom attribute if the attribute is in the metadata for the specified module.
Q R
Parameters
S T
Parameter
Description
element
A System.Reflection.Module instance.
V
attributeType
The System.Type of the custom attribute for which to check.
W
U
X Y
Return Value
Z
An array of type attributeType containing the instances that are applied to element. The array includes any inherited instances of attributeType. Returns an empty array if the specified attribute was not found. 345
Contents | Index
Attribute
System
GetCustomAttributes() Method
Description This member must be implemented if the Reflection Library is present in the implementation. A
Exceptions
B C D E
Exception
Condition
System.ArgumentNullException
element or attributeType is null.
System.ArgumentException
attributeType is not a type derived from System.Attribute.
F G H I
Example
J
using System; using System.Reflection;
K [module: Samples.Author("Damien Watkins")] [module: Samples.Author("Mark Hammond")] [module: Samples.Author("Brad Abrams")]
L M
namespace Samples { [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] public class AuthorAttribute: Attribute { private string author; public AuthorAttribute(string author) { this.author = author; } public override String ToString() { return String.Format("Author: {0}", author); } }
N O P Q R S T U V W X
public class AttributeGetCustomAttributes { public static void Main() { Module m = Assembly.GetExecutingAssembly(). GetModule("Attribute.exe");
Y Z
346
Contents | Index
System
Attribute GetCustomAttributes() Method
Console.WriteLine("Module: {0}", m.FullyQualifiedName); Attribute[] attributes = Attribute.GetCustomAttributes(m, typeof(AuthorAttribute)); foreach(Attribute a in attributes) Console.WriteLine(a);
A B C
} }
D
}
E
The output is
F Module: C:\Books\BCL\Samples\System\Attribute\ GetCustomAttributes(System.Reflection.Module,System.Type)\Attribute.exe Author: Mark Hammond Author: Brad Abrams Author: Damien Watkins
G H I J
Attribute.GetCustomAttributes(System.Reflection.Module, System.Type, System.Boolean) Method
K
[ILASM]
M
.method public hidebysig static class System.Attribute[] GetCustomAttributes(class System.Reflection.Module element, class System.Type attributeType, bool inherit)
N
L
[C#]
O
public static Attribute[] GetCustomAttributes(Module element, Type attributeType, bool inherit)
P
Summary
Q
Retrieves an array of the custom attributes of a specified type applied to a specified module or optionally inherited from a base class.
R S T
Parameters
U
Parameter
Description
element
An object derived from class System.Reflection.Module that describes a portable executable file.
attributeType
The System.Type object to which the custom attributes are applied.
inherit
This parameter is ignored, and does not affect the operation of this method.
V W X Y Z
347
Contents | Index
Attribute
System
GetCustomAttributes() Method
Return Value A System.Attribute array containing the custom attributes of type attributeType applied to element or an empty array if no such custom attributes exist. A B
Description
C
Return value contains the custom attributes for ancestors of element if inherit is true.
D
Exceptions
E F
Exception
Condition
G
System.ArgumentNullException
element or attributeType is null.
System.ArgumentException
attributeType is not derived from System.Attribute.
H I J K
Attribute.GetCustomAttributes(System.Reflection.ParameterInfo) Method
L
[ILASM]
M
.method public hidebysig static class System.Attribute[] GetCustomAttributes(class System.Reflection.ParameterInfo element)
N
[C#]
O
public static Attribute[] GetCustomAttributes(ParameterInfo element)
P
Summary
Q
Returns an array of all custom attributes in the metadata for the specified parameter.
R S
Parameters
T U
Parameter
Description
V
element
A System.Reflection.ParameterInfo instance.
W X
Return Value
Y
A System.Attribute array containing all custom attributes that are applied to element. The array includes any inherited custom attributes. Returns an empty array if no custom attributes were found in the metadata for element.
Z
348
Contents | Index
System
Attribute GetCustomAttributes() Method
Description This member must be implemented if the Reflection Library is present in the implementation. A
Exceptions
B C
Exception
Condition
System.ArgumentNullException
element is null.
D E F
Example
G
using System; using System.Reflection;
H I
namespace Samples { [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)] public class AuthorAttribute: Attribute { private string author; public AuthorAttribute(string author) { this.author = author; } public override String ToString() { return String.Format("Author: {0}", author); } }
J K L M N O P Q R S
public class foo {};
T
public class AttributeGetCustomAttributesSample { public AttributeGetCustomAttributesSample( [Author("Damien Watkins")]foo f) { Console.WriteLine(f); } public static void Main() { Type t = typeof(AttributeGetCustomAttributesSample); ConstructorInfo[] ci = t.GetConstructors(); foreach(ConstructorInfo c in ci) {
U V W X Y Z
349
Contents | Index
Attribute
System
GetCustomAttributes() Method
Console.WriteLine("Name: {0}", c.Name); ParameterInfo[] pi = c.GetParameters(); foreach(ParameterInfo p in pi) { Console.WriteLine("Parameter Name: {0}", p.Name); Console.WriteLine("Type: {0}", p.ParameterType); Attribute[] attributes = Attribute.GetCustomAttributes(p); foreach(Attribute a in attributes) Console.WriteLine(a); }
A B C D E
} }
F
} }
G H
The output is
I
Name: .ctor Parameter Name: f Type: Samples.foo Author: Damien Watkins
J K L M
Attribute.GetCustomAttributes(System.Reflection.ParameterInfo, System.Boolean) Method
N O
[ILASM]
P
.method public hidebysig static class System.Attribute[] GetCustomAttributes(class System.Reflection.ParameterInfo element, bool inherit)
Q
[C#]
R
public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inherit)
S
Summary
T
Retrieves an array of the custom attributes of a specified type applied to a specified parameter of a member of a class or optionally inherited from a base class.
U V
Parameters
W X Y
Parameter
Description
element
An object derived from class System.Reflection.ParameterInfo that describes a parameter of a member of a class.
inherit
If true, specifies to also search the ancestors of element for custom attributes.
Z
350
Contents | Index
System
Attribute GetCustomAttributes() Method
Return Value A System.Attribute array containing the custom attributes applied to element or an empty array if no such custom attributes exist. A
Description
B
Return value contains the custom attributes for ancestors of element if inherit is true.
C D
Exceptions
E
Exception
Condition
F
System.ArgumentNullException
element is null.
G H I
Attribute.GetCustomAttributes(System.Reflection.ParameterInfo, System.Type) Method
J K
[ILASM]
L
.method public hidebysig static class System.Attribute[] GetCustomAttributes(class System.Reflection.ParameterInfo element, class System.Type attributeType)
M
[C#]
N
public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType)
O
Summary
P
Returns an array of the instances of a specified custom attribute if the attribute is in the metadata for the specified parameter.
Q
Parameters
S
R
T
Parameter
Description
element
A System.Reflection.ParameterInfo instance.
V
attributeType
The System.Type of the custom attribute for which to check.
W
U
X Y
Return Value
Z
An array of type attributeType containing the instances that are applied to element. The array includes any inherited instances of attributeType. Returns an empty array if the specified attribute was not found. 351
Contents | Index
Attribute
System
GetCustomAttributes() Method
Description If element represents a method parameter, the array returned by System.Attribute.GetCustomAttributes includes any attributeType instances for the parameter element in the base methods. This member must be implemented if the Reflection Library is present in the implementation.
A B C
Exceptions
D E F
Exception
Condition
System.ArgumentNullException
element or attributeType is null.
System.ArgumentException
attributeType is not a type derived from System.Attribute.
G H I J
Example
K
using System; using System.Reflection;
L M
namespace Samples { [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)] public class ModifiedInMethodAttribute: Attribute { private bool isModified; public ModifiedInMethodAttribute(bool isModified) { this.isModified = isModified; } public override String ToString() { return String.Format("Is modified in method: {0}", isModified); } }
N O P Q R S T U V W X
public class foo {};
Y public class AttributeGetCustomAttributes { public AttributeGetCustomAttributes( [ModifiedInMethod(false)]foo f)
Z
352
Contents | Index
System
Attribute GetCustomAttributes() Method
{ Console.WriteLine(f); } public static void Main() { Type t = typeof(AttributeGetCustomAttributes); ConstructorInfo[] ci = t.GetConstructors(); foreach(ConstructorInfo c in ci) { Console.WriteLine(c); ParameterInfo[] pi = c.GetParameters(); foreach(ParameterInfo p in pi) { Console.WriteLine("Name: {0}", p.Name); Console.WriteLine("Type: {0}", p.ParameterType); Attribute[] attributes = Attribute.GetCustomAttributes(p, typeof(ModifiedInMethodAttribute)); foreach(Attribute a in attributes) Console.WriteLine(a); } } }
A B C D E F G H I J K L M
}
N
}
O
The output is
P Void .ctor(Samples.foo) Name: f Type: Samples.foo Is modified in method: False
Q R S T
Attribute.GetCustomAttributes(System.Reflection.ParameterInfo, System.Type, System.Boolean) Method
U V
[ILASM]
.method public hidebysig static class System.Attribute[] GetCustomAttributes(class System.Reflection.ParameterInfo element, class System.Type attributeType, bool inherit)
W
[C#]
Y
public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType, bool inherit)
Z
X
353
Contents | Index
Attribute
System
GetHashCode() Method
Summary Retrieves an array of the custom attributes of a specified type applied to a specified parameter of a member of a class or optionally inherited from a base class. A
Parameters
B C
Parameter
Description
element
An object derived from class System.Reflection.ParameterInfo that describes a parameter of a member of a class.
attributeType
The System.Type object to which the custom attributes are applied.
inherit
If true, specifies to also search the ancestors of element for custom attributes.
D E F G H I J
Return Value
K
A System.Attribute array containing the custom attributes of type attributeType applied to element or an empty array if no such custom attributes exist.
L M
Description
N
Return value contains the custom attributes for ancestors of element if inherit is true.
O
Exceptions
P Q
Exception
Condition
System.ArgumentNullException
element or attributeType is null.
System.ArgumentException
attributeType is not derived from System.Attribute.
R S T U V W
Attribute.GetHashCode() Method
X
[ILASM]
Y
.method public hidebysig virtual int32 GetHashCode() [C#]
Z
public override int GetHashCode()
354
Contents | Index
System
Attribute IsDefined() Method
Summary Generates a hash code for the current instance.
Description
A
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
B C D
Attribute.IsDefaultAttribute() Method
E
[ILASM]
F
.method public hidebysig virtual bool IsDefaultAttribute()
G
[C#]
H
public virtual bool IsDefaultAttribute()
I
Summary
J
When overridden in a derived class, returns an indication whether the value of this instance is the default value for the derived class.
K L
Return Value
M
true if this instance is the default attribute for the class; otherwise, false.
N
Description
O
The default implementation of this class returns false, and must be implemented in the derived class to be useful to that class. The implementation of this method in a derived class compares the value of this instance to a standard, default value obtained by some means, then returns a Boolean value that indicates whether the value of this instance is equal to the standard. The standard value is typically coded as a constant in the implementation, or stored programmatically in a field used by the implementation.
P Q R S T U V
Attribute.IsDefined(System.Reflection.Assembly, System.Type) Method
W
[ILASM]
X
.method public hidebysig static bool IsDefined(class System.Reflection.Assembly element, class System.Type attributeType)
Y
[C#]
Z
public static bool IsDefined(Assembly element, Type attributeType)
355
Contents | Index
Attribute
System
IsDefined() Method
Summary Returns a System.Boolean value indicating whether a specified custom attribute is present in the metadata for the specified assembly. A
Parameters
B C
Parameter
Description
E
element
A System.Reflection.Assembly instance.
F
attributeType
The System.Type of the custom attribute for which to check.
D
G H
Return Value
I
true if a custom attribute of type attributeType is applied to element; otherwise, false.
J K
Description
L
This member must be implemented if the Runtime Infrastructure Library is present in the implementation.
M
Exceptions
N O
Exception
Condition
System.ArgumentNullException
element or attributeType is null.
System.ArgumentException
attributeType is not derived from System.Attribute.
P Q R S T U
Example
V
using System; using System.Reflection;
W
[assembly: Samples.MyCustom]
X namespace Samples { [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)] public class MyCustomAttribute: Attribute {}
Y Z
356
Contents | Index
System
Attribute IsDefined() Method
public class AttributeGetCustomAttribute { public static void Main() { Assembly e = Assembly.GetExecutingAssembly(); Console.WriteLine("Name: {0} ", e.FullName); if(Attribute.IsDefined(e, typeof(MyCustomAttribute))) Console.WriteLine("MyCustom attribute defined"); else Console.WriteLine("MyCustom attribute not defined"); } }
A B C D E F
}
G
The output is
H Name: Attribute, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null MyCustom attribute defined
I J K
Attribute.IsDefined(System.Reflection.Assembly, System.Type, System.Boolean) Method
L M
[ILASM]
N
.method public hidebysig static bool IsDefined(class System.Reflection.Assembly element, class System.Type attributeType, bool inherit) [C#]
O
public static bool IsDefined(Assembly element, Type attributeType, bool inherit)
P Q
Summary
R
Determines whether any custom attributes of a specified type are applied to a specified assembly.
S T
Parameters
U
Parameter
Description
element
An object derived from class System.Reflection.Assembly that describes a reusable, versionable collection of modules.
attributeType
The System.Type object to which the custom attributes are applied.
inherit
This parameter is ignored, and does not affect the operation of this method.
V W X Y Z
357
Contents | Index
Attribute
System
IsDefined() Method
Return Value true if a custom attribute of type attributeType is applied to element; otherwise, false. A
Description
B
This method ignores the value of parameter inherit. The ancestors of element are not searched for custom attributes.
C D
Exceptions
E F G
Exception
Condition
System.ArgumentNullException
element or attributeType is null.
System.ArgumentException
attributeType is not derived from System.Attribute.
H I J K L
Attribute.IsDefined(System.Reflection.MemberInfo, System.Type) Method
M
[ILASM]
N
.method public hidebysig static bool IsDefined(class System.Reflection.MemberInfo element, class System.Type attributeType)
O
[C#]
public static bool IsDefined(MemberInfo element, Type attributeType)
P Q
Summary
R
Returns a System.Boolean value indicating whether a specified custom attribute is present in the metadata for the specified member.
S T
Parameters
U V W
Parameter
Description
element
An instance of a type derived from System.Reflection.MemberInfo that describes a type member.
attributeType
The System.Type of the custom attribute for which to check.
X Y Z
358
Contents | Index
System
Attribute IsDefined() Method
Return Value true if a custom attribute of type attributeType is applied to element either directly or through inheritance; otherwise, false. A
Description
B
This member must be implemented if the Reflection Library is present in the implementation.
C D
Exceptions
E F
Exception
Condition
System.ArgumentNullException
element or attributeType is null.
H
System.ArgumentException
attributeType is not derived from System.Attribute.
I
System.NotSupportedException
element is not a constructor, method, property, event, type, or field.
G
J K L M
Example
N
using System; using System.Reflection;
O
namespace Samples { [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)] public class MyCustomAttribute: Attribute {}
P Q R S T
public class AttributeIsDefined { [MyCustom] public AttributeIsDefined(string s) { Console.WriteLine(s); } [MyCustom] public static void Main() { Type t = typeof(AttributeIsDefined); MemberInfo[] m = t.GetMembers(); foreach(MemberInfo i in m) {
U V W X Y Z
359
Contents | Index
Attribute
System
IsDefined() Method
Console.Write("Member: {0} ", i.Name); if(Attribute.IsDefined(i, typeof(MyCustomAttribute))) Console.WriteLine("MyCustom attribute defined"); else Console.WriteLine("MyCustom attribute not defined");
A B
} }
C }
D
}
E
The output is
F Member: Member: Member: Member: Member: Member:
G H I J
GetHashCode MyCustom attribute not defined Equals MyCustom attribute not defined ToString MyCustom attribute not defined Main MyCustom attribute defined GetType MyCustom attribute not defined .ctor MyCustom attribute defined
K
Attribute.IsDefined(System.Reflection.MemberInfo, System.Type, System.Boolean) Method
L M
[ILASM]
N
.method public hidebysig static bool IsDefined(class System.Reflection.MemberInfo element, class System.Type attributeType, bool inherit)
O
[C#]
P
public static bool IsDefined(MemberInfo element, Type attributeType, bool inherit)
Q R
Summary
S
Determines whether any custom attributes of a specified type are applied to a specified member of a class or optionally inherited from a base class.
T
Parameters
U V
Parameter
Description
element
An object derived from class System.Reflection.MemberInfo that describes a constructor, event, field, method, type, or property member of a class.
attributeType
The System.Type object to which the custom attributes are applied.
inherit
If true, specifies to also search the ancestors of element for custom attributes.
W X Y Z
360
Contents | Index
System
Attribute IsDefined() Method
Return Value true if a custom attribute of type attributeType is applied to element; otherwise, false.
Description
A
The ancestors of element are searched for custom attributes if inherit is true and element is a method or a type. inherit is ignored if element is a constructor, field, property, or event.
B C D
Exceptions
E
Exception
Condition
System.ArgumentNullException
element or attributeType is null.
System.ArgumentException
attributeType is not derived from System.Attribute.
System.NotSupportedException
element is not a constructor, method, property, event, type, or field.
F G H I J K L M
Attribute.IsDefined(System.Reflection.Module, System.Type) Method
N
[ILASM]
O
.method public hidebysig static bool IsDefined(class System.Reflection.Module element, class System.Type attributeType)
P
[C#]
Q
public static bool IsDefined(Module element, Type attributeType)
R
Summary
S
Returns a System.Boolean value indicating whether a specified custom attribute is present in the metadata for the specified module.
T U
Parameters
V W
Parameter
Description X
element
A System.Reflection.Module instance.
Y
attributeType
The System.Type of the custom attribute for which to check.
Z
361
Contents | Index
Attribute
System
IsDefined() Method
Return Value true if a custom attribute of type attributeType is applied to element; otherwise, false. A
Description
B
This member must be implemented if the Reflection Library is present in the implementation.
C D
Exceptions
E F G
Exception
Condition
System.ArgumentNullException
element or attributeType is null.
System.ArgumentException
attributeType is not derived from System.Attribute.
H I J K
Example
L
using System; using System.Reflection;
M N
[module: Samples.MyCustom]
O
namespace Samples { [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)] public class MyCustomAttribute: Attribute {}
P Q R S
public class AttributeIsDefinedSample { public static void Main() { Module[] modules = Assembly.GetExecutingAssembly(). GetModules(); foreach(Module m in modules) { Console.WriteLine("Module: {0} ", m.FullyQualifiedName); if(Attribute.IsDefined(m, typeof(MyCustomAttribute))) Console.WriteLine("MyCustom attribute defined");
T U V W X Y Z
362
Contents | Index
System
Attribute IsDefined() Method
else Console.WriteLine("MyCustom attribute not defined"); } }
A
} }
B C
The output is
D Module: C:\Books\BCL\Samples\System\Attribute\ IsDefined(System.Reflection.Module,System.Type)\Attribute.exe MyCustom attribute defined
E F G
Attribute.IsDefined(System.Reflection.Module, System.Type, System.Boolean) Method
H I
[ILASM]
J
.method public hidebysig static bool IsDefined(class System.Reflection.Module element, class System.Type attributeType, bool inherit)
K
[C#]
L
public static bool IsDefined(Module element, Type attributeType, bool inherit)
M
Summary
N
Determines whether any custom attributes of a specified type are applied to a specified module.
O P
Parameters
Q
Parameter
Description
element
An object derived from class System.Reflection.Module that describes a portable executable file.
attributeType
The System.Type object to which the custom attributes are applied.
inherit
This parameter is ignored, and does not affect the operation of this method.
R S T U V W X
Return Value
Y
true if a custom attribute of type attributeType is applied to element; otherwise, false.
Z
363
Contents | Index
Attribute
System
IsDefined() Method
Description This method ignores the value of parameter inherit. The ancestors of element are not searched for custom attributes. A
Exceptions
B C D E
Exception
Condition
System.ArgumentNullException
element or attributeType is null.
System.ArgumentException
attributeType is not derived from System.Attribute.
F G H I
Attribute.IsDefined(System.Reflection.ParameterInfo, System.Type) Method
J K
[ILASM]
L
.method public hidebysig static bool IsDefined(class System.Reflection.ParameterInfo element, class System.Type attributeType)
M
[C#]
N
public static bool IsDefined(ParameterInfo element, Type attributeType)
O
Summary
P
Returns a System.Boolean value indicating whether a specified custom attribute is present in the metadata for the specified parameter.
Q R
Parameters
S T U
Parameter
Description
element
A System.Reflection.ParameterInfo instance.
attributeType
The System.Type of the custom attribute for which to check.
V W X Y
Return Value
Z
true if a custom attribute of type attributeType is applied to element either directly or through inheritance; otherwise, false.
364
Contents | Index
System
Attribute IsDefined() Method
Description This member must be implemented if the Reflection Library is present in the implementation. A
Exceptions
B C
Exception
Condition
System.ArgumentNullException
element or attributeType is null.
E
attributeType is not derived from System.Attribute.
F
System.ArgumentException
D
G H
Example
I
using System; using System.Reflection;
J K
namespace Samples { [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)] public class MyCustomAttribute: Attribute{}
L M N O
public class foo {};
P
public class AttributeIsDefined { public AttributeIsDefined([MyCustom]foo f) { Console.WriteLine(f); } public static void Main() { Type t = typeof(AttributeIsDefined); ConstructorInfo[] ci = t.GetConstructors(); foreach(ConstructorInfo c in ci) { Console.WriteLine(c); ParameterInfo[] pi = c.GetParameters(); Console.WriteLine("Parameters"); foreach(ParameterInfo p in pi) { Console.Write("Name: {0} ", p.Name); Console.Write("Type: {0} ", p.ParameterType);
Q R S T U V W X Y Z
365
Contents | Index
Attribute
System
IsDefined() Method
if(Attribute.IsDefined(p, typeof(MyCustomAttribute))) Console.WriteLine("MyCustom attribute defined"); else Console.WriteLine("MyCustom attribute not defined");
A }
B
}
C
} }
D
}
E
The output is
F Void .ctor(Samples.foo) Parameters Name: f Type: Samples.foo MyCustom attribute defined
G H I J K
Attribute.IsDefined(System.Reflection.ParameterInfo, System.Type, System.Boolean) Method
L
[ILASM]
.method public hidebysig static bool IsDefined(class System.Reflection.ParameterInfo element, class System.Type attributeType, bool inherit)
M N
[C#]
O
public static bool IsDefined(ParameterInfo element, Type attributeType, bool inherit)
P Q
Summary
R
Determines whether any custom attributes of a specified type are applied to a specified parameter of a member of a class or optionally inherited from a base class.
S T
Parameters
U V
Parameter
Description
element
An object derived from class System.Reflection.ParameterInfo that describes a parameter of a member of a class.
attributeType
The System.Type object to which the custom attributes are applied.
inherit
If true, specifies to also search the ancestors of element for custom attributes.
W X Y Z
366
Contents | Index
System
Attribute Match() Method
Return Value true if a custom attribute of type attributeType is applied to element; otherwise, false.
Description
A
The ancestors of element are searched for custom attributes if inherit is true and element is a method. inherit is ignored if element is a constructor or a type.
B C D
Exceptions
E
Exception
Condition
System.ArgumentNullException
element or attributeType is null.
System.ArgumentException
attributeType is not derived from System.Attribute.
System.ExecutionEngineException
element is not a method, constructor, or type.
F G H I J K L
Attribute.Match(System.Object) Method
M
[ILASM]
N
.method public hidebysig virtual bool Match(object obj)
O
[C#]
P
public virtual bool Match(object obj)
Q
Summary
R
When overridden in a derived class, returns a value indicating whether this instance equals a specified object.
S T
Parameters
U
Parameter
Description
obj
A System.Object to compare with this instance of Attribute.
V W X Y
Return Value
Z
true if this instance equals obj; otherwise, false.
367
Contents | Index
Attribute
System
Match() Method
Description This method determines if one Attribute equals another. Its default implementation is the same as System.Attribute.Equals, which performs a value and reference comparison. Override this method to implement support for attribute values, such as flags or bitfields, that consist of components that are meaningful in themselves. For example, consider an attribute whose value is a binary field divided into a bitfield of flags. Two instances of this attribute have one flag in set in common while all the other flags differ. The Equal method cannot determine that the two instances have the same flag set, but the Match method can.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
368
Contents | Index
System AttributeTargets Enum
BCL
Object
A
IComparable
ValueType Enum
B
IFormattable AttributeTargets
IConvertible
NotStandardized
C D
Summary
E
Enumerates the application elements to which it is valid to attach an attribute.
F
Type Summary
G
public enum AttributeTargets { All = Assembly | 0x2 | Class | Struct | Enum | Constructor | Method | Property | Field | Event | Interface | Parameter | Delegate | ReturnValue, Assembly = 0x1, Class = 0x4, Constructor = 0x20, Delegate = 0x1000, Enum = 0x10, Event = 0x200, Field = 0x100, Interface = 0x400, Method = 0x40, Module = 0x2, Parameter = 0x800, Property = 0x80, ReturnValue = 0x2000, Struct = 0x8, }
H I J K L M N O P Q R S
BA This enum is intended allow members to be combined via the bitwise OR opera-
T
tion such that you can indicate a custom attribute on Classes or Enums; for example:
U
AttributeTargets.Class | AttributeTargets.Enum
V
You can recognize enums that were designed for this style of usage by noticing the enum name is plural (AttributeTargets rather than AttributeTarget) and by the FlagAttribute custom attribute applied to the type.
W X
You might wonder why we put the hard-wired 0x2 in the All field. We left it in for binary compatibility with the Microsoft .NET Framework, which defines an
Y Z
continued
369
Contents | Index
AttributeTargets Enum
System
AttributeTargets Enum
enum member called Module with that value. The Module member is not required in the standard because we wanted to emphasize assembly as the smallest unit of encapsulation.
A B
JR When defining your own custom attribute, be sure to apply the AttributeUsage attribute to it, setting the AttributeTargets value.
C D E
Description
F
System.AttributeTargets is used as a parameter for System.AttributeUsageAttribute to enable an attribute to be associated with one or more kinds of application elements.
G H
Example
I
For brevity, the program only checks for the existence of one custom attibute, but for completeness, attributes are applied to most targets in the source code. The value AttributeTargets.All could also have been used in the following program instead of using individual values.
J K L M
using System; using System.Reflection;
N
[assembly: Samples.MyCustom] [module: Samples.MyCustom]
O P
namespace Samples { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Event | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Module | AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] public class MyCustomAttribute: Attribute {}
Q R S T U V W X Y Z
370
Contents | Index
System
AttributeTargets Enum AttributeTargets Enum
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public class MyOtherCustomAttribute: Attribute{}
A public class Foo {}
B public interface IFoo { [MyCustom] int age { get;} }
C D E F
[MyCustom] public struct Bar {}
G [MyCustom, MyOtherCustom, MyOtherCustom] public class AttributeTargetsSample { [MyCustom] enum Color {black, white} [MyCustom] public delegate int D(); [MyCustom] public event D MyD; [MyCustom] private int i; [MyCustom] public static void Main() { Assembly e = Assembly.GetExecutingAssembly(); Console.WriteLine("Name: {0} ", e.FullName); if(Attribute.IsDefined(e, typeof(MyCustomAttribute))) Console.WriteLine("MyCustom attribute defined"); else Console.WriteLine("MyCustom attribute not defined"); } [return: MyCustom] public static int MyMethod([MyCustom] Foo f) { return 42; } }
H I J K L M N O P Q R S T U V
}
W
The output is
X Y
Name: AttributeTargets, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null MyCustom attribute defined
Z
371
Contents | Index
AttributeTargets Enum
System
All Field
AttributeTargets.All Field [ILASM]
.field public static literal valuetype System.AttributeTargets All
A
[C#]
All = Assembly | 0x2 | Class | Struct | Enum | Constructor | Method | Property | Field | Event | Interface | Parameter | Delegate | ReturnValue
B C D
Summary
E
Attribute can be applied to any element.
F G
AttributeTargets.Assembly Field
H
[ILASM]
.field public static literal valuetype System.AttributeTargets Assembly
I
[C#]
J
Assembly = 0x1
K
Summary
L
Attribute can be applied to an assembly.
M N
AttributeTargets.Class Field
O P
[ILASM]
Q
[C#]
.field public static literal valuetype System.AttributeTargets Class Class = 0x4
R S
Summary
T
Attribute can be applied to a class.
U V
AttributeTargets.Constructor Field
W [ILASM]
X
.field public static literal valuetype System.AttributeTargets Constructor [C#]
Y
Constructor = 0x20
Z
Summary Attribute can be applied to a constructor. 372
Contents | Index
System
AttributeTargets Enum Field Field
AttributeTargets.Delegate Field [ILASM]
.field public static literal valuetype System.AttributeTargets Delegate [C#]
A
Delegate = 0x1000
B C
Summary
D
Attribute can be applied to a delegate.
E F
AttributeTargets.Enum Field
G
[ILASM]
H
.field public static literal valuetype System.AttributeTargets Enum [C#]
I
Enum = 0x10
J
Summary
K
Attribute can be applied to an enumeration.
L M N
AttributeTargets.Event Field
O
[ILASM]
.field public static literal valuetype System.AttributeTargets Event
P
[C#]
Q
Event = 0x200
R
Summary
S
Attribute can be applied to an event.
T U
AttributeTargets.Field Field
V
[ILASM]
W
.field public static literal valuetype System.AttributeTargets Field
X
[C#]
Field = 0x100
Y Z
Summary Attribute can be applied to a field.
373
Contents | Index
AttributeTargets Enum
System
Interface Field
AttributeTargets.Interface Field [ILASM]
.field public static literal valuetype System.AttributeTargets Interface
A
[C#]
Interface = 0x400
B C
Summary
D
Attribute can be applied to an interface.
E F
AttributeTargets.Method Field
G
[ILASM]
H
.field public static literal valuetype System.AttributeTargets Method [C#]
I
Method = 0x40
J K
Summary
L
Attribute can be applied to a method.
M N
AttributeTargets.Module Field
O
[ILASM]
.field public static literal valuetype System.AttributeTargets Module
P
[C#]
Q
Module = 0x2
R
Summary
S
Attribute can be applied to a module.
T U
Description
V
This member must be implemented if the Runtime Infrastructure Library is present in the implementation.
W X Y
AttributeTargets.Parameter Field
Z
[ILASM]
.field public static literal valuetype System.AttributeTargets Parameter [C#]
Parameter = 0x800
374
Contents | Index
System
AttributeTargets Enum Struct Field
Summary Attribute can be applied to a parameter. A
AttributeTargets.Property Field
B
[ILASM]
C
.field public static literal valuetype System.AttributeTargets Property
D
[C#]
Property = 0x80
E F
Summary
G
Attribute can be applied to a property.
H I
AttributeTargets.ReturnValue Field
J
[ILASM]
K
.field public static literal valuetype System.AttributeTargets ReturnValue
L
[C#]
ReturnValue = 0x2000
M
Summary
N
Attribute can be applied to a return value.
O P Q
AttributeTargets.Struct Field
R
[ILASM]
S
.field public static literal valuetype System.AttributeTargets Struct [C#]
T
Struct = 0x8
U
Summary
V
Attribute can be applied to a value type.
W X Y Z
375
Contents | Index
System AttributeUsageAttribute
BCL
Object
A
Attribute
B
AttributeUsageAttribute
C
Summary
D
Specifies the behavior of a custom attribute when that attribute is defined.
E
Type Summary
F
public sealed class AttributeUsageAttribute : Attribute { // Constructors public AttributeUsageAttribute (AttributeTargets validOn);
G H I
// Properties public bool AllowMultiple { set; get; } public bool Inherited { set; get; } public AttributeTargets ValidOn { get; }
J K L
}
M
Description
N
[Note: Custom attributes may be applied to various application (“target”) elements, such as classes, parameters, and structures (see System.AttributeTargets for the full list). The System.AttributeUsageAttribute class contains three properties that govern custom attribute behavior: the kinds of application elements the attribute may be associated with; whether the attribute may or may not be inherited by derived elements; and whether multiple instances of the attribute may or may not be allowed on the same target element.]
O P Q R S T U V W X Y Z
376
Contents | Index
System
AttributeUsageAttribute AttributeUsageAttribute Class
BA Notice that this custom attribute is sealed. In general I am not a big fan of randomly sealing classes to prevent extensibility. (I prefer non-virtual methods for that purpose.) However, for custom attributes it is a good practice. In the .NET Framework, the reflection code path that looks up custom attributes from members is slightly faster if it does not have to consider subclasses of the target attribute.
A B C
BG In general, sealing a class or making members non-virtual (when appropriate)
D
can help a JIT to inline methods. Inlining has always been a powerful optimization, but virtual methods can prevent inlining. Sealing members or leaving them non-virtual also allows you more flexibility in changing your class’s implementation in the future, by limiting users’ points of customization. Non-virtual members definitely have an appropriate place both as a design point and as an implementation detail for better performance.
E F G H I
Users defining their own custom attributes should specify the AttributeTargetAttribute at all times. Like this:
J K
[AttributeUsage (AttributeTargets.Methods | AttributeTargets.Properites, AllowMultiple=false)] public class MyNewAttribute : Attribute { public MyNewAttribute () {} }
L M N O P
We begrudgingly added the AttributeTargetAttribute to the Attribute class so that people subclassing Attribute didn’t need to understand another custom attribute when creating their own custom attribute. However, this allows people using that new attribute to put the attribute in potentially surprising places. If you define an attribute to function as a marker on an assembly, your program might not work as expected if you happen to find the custom attribute applied to the return value of a method. Class library authors really need to understand and use this attribute.
Q R S T U V W X Y Z
377
Contents | Index
AttributeUsageAttribute
System
AttributeUsageAttribute Class
Example For brevity, the program only checks for the existence of one custom attribute, but for completeness attributes are applied to most targets in the source code. A using System; using System.Reflection;
B C
[assembly: Samples.MyCustom] [module: Samples.MyCustom]
D E
namespace Samples { [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)] public class MyCustomAttribute: Attribute {}
F G H I
public class Foo {}
J
public interface IFoo { [MyCustom] int age { get;} }
K L M N
[MyCustom] public struct Bar {}
O P
[MyCustom] public class AttributeUsageSample { [MyCustom] enum Color {black, white} [MyCustom] public delegate int D(); [MyCustom] public event D MyD; [MyCustom] private int i; [MyCustom] public static void Main() { Assembly e = Assembly.GetExecutingAssembly(); Console.WriteLine("Name: {0} ", e.FullName); if(Attribute.IsDefined(e, typeof(MyCustomAttribute))) Console.WriteLine("MyCustom attribute defined"); else
Q R S T U V W X Y Z
378
Contents | Index
System
AttributeUsageAttribute AttributeUsageAttribute() Constructor
Console.WriteLine("MyCustom attribute not defined"); } [return: MyCustom] public static int MyMethod([MyCustom] Foo f) { return 42; }
A B C
} }
D
The output is
E F
Name: AttributeUsageAttribute, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null MyCustom attribute defined
G H I
AttributeUsageAttribute(System.AttributeTargets) Constructor
J
[ILASM]
K
public rtspecialname specialname instance void .ctor(valuetype System.AttributeTargets validOn)
L
[C#]
M
public AttributeUsageAttribute(AttributeTargets validOn)
N
Summary
O
Constructs and initializes a new instance of the System.AttributeUsageAttribute class.
P Q
Parameters
R S
Parameter
Description T
validOn
The set of application elements to which the attribute will be applied. When indicating multiple application elements, validOn is a bitwise OR combination of System.AttributeTargets enumeration values.
U V W
Description
X
The new instance will be constructed with the specified value of validOn and the properties System.AttributeUsageAttribute.AllowMultiple and System.AttributeUsageAttribute.Inherited set to their default values (false and true, respectively).
Y Z
379
Contents | Index
AttributeUsageAttribute
System
AllowMultiple Property
AttributeUsageAttribute.AllowMultiple Property [ILASM]
.property bool AllowMultiple { public hidebysig specialname instance bool get_AllowMultiple() public hidebysig specialname instance void set_AllowMultiple(bool value) }
A B
[C#]
C
public bool AllowMultiple { get; set; }
D
Summary
E
Gets or sets a value indicating whether more than one instance of a specified attribute is permitted to be applied to any given program element.
F G H
Property Value
I
A System.Boolean where true indicates more than one instance of the attribute is permitted to be applied; otherwise, false. The default is false.
J K
Description
L
[Note: It is expected that compilers will validate this property; this property is not validated during execution.]
M N O
AttributeUsageAttribute.Inherited Property
P
[ILASM]
Q
.property bool Inherited { public hidebysig specialname instance bool get_Inherited() public hidebysig specialname instance void set_Inherited(bool value) }
R
[C#]
S
public bool Inherited { get; set; }
T
Summary
U
Gets or sets a System.Boolean value indicating whether the attribute can be inherited by subclasses of the class to which the attribute is applied.
V W
Property Value
X
true indicates the attribute is inherited by subclasses; otherwise, false. The default is true.
Y Z
380
Contents | Index
System
AttributeUsageAttribute ValidOn Property
Description Information on an inherited attribute will be included in the metadata for the class on which it is applied, but will not be included in the metadata for classes that derive from it. A metadata consumer (such as reflection) is required therefore to traverse up the inheritance chain of a class if that consumer is interested in System.Attribute data that is marked inherited, but applied to an ancestor class. There is nothing for the compiler to validate at compile time.
A B C D E
AttributeUsageAttribute.ValidOn Property
F
[ILASM]
G
.property valuetype System.AttributeTargets ValidOn { public hidebysig specialname instance valuetype System.AttributeTargets get_ValidOn() }
H
[C#]
I
public AttributeTargets ValidOn { get; }
J
Summary
K
Gets the set of values sent to the System.AttributeUsageAttribute constructor that indicate to which targets the custom attribute may be applied.
L M
Property Value
N
One or more of the System.AttributeTargets values sent to the constructor, combined by a bitwise OR operation.
O P Q R S T U V W X Y Z
381
Contents | Index
System Boolean Structure
BCL
Object
A
ValueType IComparable
B
Boolean IConvertible
NotStandardized
C
Summary
D
Represents a Boolean value.
E F
Type Summary
G
public struct Boolean : IComparable, IConvertible { // Fields public static readonly string FalseString = "False"; public static readonly string TrueString = "True";
H I J K
// Methods public int CompareTo (object obj); public override bool Equals (object obj); public override int GetHashCode (); MS public TypeCode GetTypeCode (); public static bool Parse (string value); public override string ToString (); public string ToString (IFormatProvider provider);
L M N O P
// MS MS MS MS MS MS MS MS MS MS MS MS MS MS MS
Explicit Interface Members bool IConvertible.ToBoolean(IFormatProvider provider); byte IConvertible.ToByte(IFormatProvider provider); char IConvertible.ToChar(IFormatProvider provider); DateTime IConvertible.ToDateTime(IFormatProvider provider); decimal IConvertible.ToDecimal(IFormatProvider provider); double IConvertible.ToDouble(IFormatProvider provider); short IConvertible.ToInt16(IFormatProvider provider); int IConvertible.ToInt32(IFormatProvider provider); long IConvertible.ToInt64(IFormatProvider provider); sbyte IConvertible.ToSByte(IFormatProvider provider); float IConvertible.ToSingle(IFormatProvider provider); object IConvertible.ToType(Type type,IFormatProvider provider); ushort IConvertible.ToUInt16(IFormatProvider provider); uint IConvertible.ToUInt32(IFormatProvider provider); ulong IConvertible.ToUInt64(IFormatProvider provider);
Q R S T U V W X Y Z
}
383
Contents | Index
Boolean Structure
System
FalseString Field
JR Note that Parse performs a case-insensitive comparison against “true” or “false.” Note that FalseString and TrueString are defined as “True” and “False”; the strings are not localized.
A B C
Description
D
The System.Boolean value type represents the logical values true and false.
E F
Example
G
using System;
H
namespace Samples { public class BooleanSample { public static void Main() { Boolean b = true; if(b) Console.WriteLine("'b' is true"); b = false; if(!b) Console.WriteLine("'b' is not true now"); } } }
I J K L M N O P Q
The output is
R S
'b' is true 'b' is not true now
T U V
Boolean.FalseString Field
W
[ILASM]
X
.field public static initOnly string FalseString [C#]
Y
public static readonly string FalseString = "False"
Z
Summary Contains a System.String representation of the logical value false. 384
Contents | Index
System
Boolean Structure TrueString Field
Description The value of this System.String is False. A
Example
B
using System;
C
namespace Samples { public class BooleanFalseString { public static void Main() { Console.WriteLine(Boolean.FalseString); } } }
D E F G H I
The output is
J
False
K L
Boolean.TrueString Field
M
[ILASM]
N
.field public static initOnly string TrueString
O
[C#]
P
public static readonly string TrueString = "True"
Q
Summary
R
Contains a System.String representation of the logical value true.
S
Description
T
The value of this System.String is True.
U V
Example
W
using System;
X
namespace Samples { public class BooleanTrueString { public static void Main() {
Y Z
385
Contents | Index
Boolean Structure
System
CompareTo() Method
Console.WriteLine(Boolean.TrueString); } } }
A
The output is
B C
True
D E
Boolean.CompareTo(System.Object) Method
F
[ILASM]
.method public final hidebysig virtual int32 CompareTo(object obj)
G
[C#]
H
public int CompareTo(object obj)
I
Summary
J
Returns the sort order of the current instance compared to the specified System.Object.
K L
Parameters
M N O
Parameter
Description
obj
A System.Object to compare to the current instance.
P
Return Value
Q
A System.Int32 containing a value that reflects the sort order of the current instance as compared to obj. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number.
R S T U V
Return Value
Condition
any negative number
Current instance is false and obj is true.
zero
Current instance – obj.
any positive number
Current instance is true and obj is false, or obj is a null reference.
W X Y Z
Description [Note: This method is implemented to support the System.IComparable interface.] 386
Contents | Index
System
Boolean Structure CompareTo() Method
Exceptions Exception
Condition
System.ArgumentException
obj is not a System.Boolean and is not a null reference.
A B C
Example
D
using System;
E
namespace Samples { public class BooleanCompareTo { public static void Main() { Boolean b = true; Console.WriteLine("'b' is {0}", b); Console.WriteLine("'b' compared to 'true': {0}", b.CompareTo(true)); Console.WriteLine("'b' compared to 'false': {0}", b.CompareTo(false)); Console.WriteLine("'b' compared to 'null': {0}", b.CompareTo(null)); b = false; Console.WriteLine("'b' is {0}", b); Console.WriteLine("'b' compared to 'true': {0}", b.CompareTo(true)); Console.WriteLine("'b' compared to 'false': {0}", b.CompareTo(false)); Console.WriteLine("'b' compared to 'null': {0}", b.CompareTo(null)); } } }
'b' 'b' 'b' 'b' 'b' 'b' 'b' 'b'
F G H I J K L M N O P Q R S T U
The output is
V
is True compared compared compared is False compared compared compared
W to 'true': 0 to 'false': 1 to 'null': 1
X Y Z
to 'true': -1 to 'false': 0 to 'null': 1
387
Contents | Index
Boolean Structure
System
Equals() Method
Boolean.Equals(System.Object) Method [ILASM]
.method public hidebysig virtual bool Equals(object obj)
A
[C#]
public override bool Equals(object obj)
B C
Summary
D
Determines whether the current instance and the specified System.Object represent the same type and value.
E F
Parameters
G H
Parameter
Description
obj
The System.Object to compare to the current instance.
I J K
Return Value
L
true if obj is a System.Boolean with the same value as the current instance. If obj is a null reference or is not an instance of System.Boolean, returns false.
M N
Description
O
[Note: This method overrides System.Object.Equals.]
P Q
Example
R
using System;
S
namespace Samples { public class BooleanEquals { public static void Main() { Boolean b = true; Console.WriteLine("'b' is {0}", b); Console.WriteLine("Is 'b' equal to true: {0}", b.Equals(true)); Console.WriteLine("Is 'b' equal to false: {0}", b.Equals(false)); Console.WriteLine("Is 'b' equal to null: {0}", b.Equals(null));
T U V W X Y Z
388
Contents | Index
System
Boolean Structure GetHashCode() Method
b = false; Console.WriteLine("'b' is {0}", b); Console.WriteLine("Is 'b' equal to true: {0}", b.Equals(true)); Console.WriteLine("Is 'b' equal to false: {0}", b.Equals(false)); Console.WriteLine("Is 'b' equal to null: {0}", b.Equals(null));
A B C
}
D
} }
E F
The output is
G 'b' is Is 'b' Is 'b' Is 'b' 'b' is Is 'b' Is 'b' Is 'b'
True equal equal equal False equal equal equal
H
to true: True to false: False to null: False
I J
to true: False to false: True to null: False
K L M
Boolean.GetHashCode() Method
N
[ILASM]
O
.method public hidebysig virtual int32 GetHashCode()
P
[C#]
public override int GetHashCode()
Q R
Summary
S
Generates a hash code for the current instance.
T
Return Value
U
A System.Int32 value containing a hash code for the current instance.
V W
Description
X
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
Y Z
389
Contents | Index
Boolean Structure
System
GetTypeCode() Method
Example using System; namespace Samples { public class BooleanGetHashCode { public static void Main() { Boolean b = true; Console.WriteLine("'b' ({0}) hash code {1}", b, b.GetHashCode()); b = false; Console.WriteLine("'b' ({0}) hash code {1}", b, b.GetHashCode()); } } }
A B C D E F G H I J
The output is
K L
'b' (True) hash code 1 'b' (False) hash code 0
M N O
Boolean.GetTypeCode() Method
P
[ILASM]
.method public final hidebysig virtual valuetype System.TypeCode GetTypeCode()
Q
[C#]
public TypeCode GetTypeCode()
R S
Summary
T
Returns the System.TypeCode for value type System.Boolean.
U V
Boolean.Parse(System.String) Method
W [ILASM]
X
.method public hidebysig static bool Parse(string value) [C#]
Y
public static bool Parse(string value)
Z
390
Contents | Index
System
Boolean Structure Parse() Method
Summary Returns the specified System.String converted to a System.Boolean value. A
Parameters
B
Parameter
Description
C D
value
A System.String containing the value to convert. The string is equivalent to either System.Boolean.TrueString or System.Boolean.FalseString, can contain leading and/or trailing whitespace, and is parsed in a case-insensitive manner.
E F G
Return Value
H
true if value is equivalent to System.Boolean.TrueString; otherwise, false.
I J
Exceptions
K
Exception
Condition
System.ArgumentNullException
value is a null reference.
System.FormatException
value is not equivalent to either System.Boolean.TrueString or System.Boolean.FalseString.
L M N O P Q
Example
R
using System; namespace Samples { public class BooleanParse { public static void Main() { try { Boolean b = Boolean.Parse(" tRUE Console.WriteLine("b is {0}", b); b = Boolean.Parse(" fAlSe "); Console.WriteLine("b is {0}", b); b = Boolean.Parse("yes"); Console.WriteLine("b is {0}", b); }
S T U V W X
");
Y Z
391
Contents | Index
Boolean Structure
System
ToString() Method
catch(FormatException e) { Console.WriteLine("Exception: {0}", e); }
A
} }
B
}
C
The output is
D b is True b is False Exception: System.FormatException: String was not recognized as a valid Boolean. at System.Boolean.Parse(String value) at Samples.BooleanParse.Main() in C:\Books\BCL\Samples\System\Boolean\ Parse(System.String)\Boolean.cs:line 15
E F G H I J
Boolean.ToString() Method
K
[ILASM]
.method public hidebysig virtual string ToString()
L
[C#]
public override string ToString()
M N
Summary
O
Returns a System.String representation of the value of the current instance.
P Q
Return Value
R
System.Boolean.FalseString if the value of the current instance is false; otherwise, System.Boolean.TrueString.
S T
Description
U
[Note: This method overrides System.Object.ToString.]
V
Example
W
using System;
X namespace Samples { public class BooleanToString { public static void Main() {
Y Z
392
Contents | Index
System
Boolean Structure ToString() Method
Boolean b = true; Console.WriteLine(b.ToString()); b = false; Console.WriteLine(b.ToString());
A
} }
B
}
C
The output is
D
True False
E F G
Boolean.ToString(System.IFormatProvider) Method
H
[ILASM]
I
.method public final hidebysig virtual string ToString(class System.IFormatProvider provider)
J
[C#]
K
public string ToString(IFormatProvider provider)
L
Summary
M
Converts the value of this instance to its equivalent String representation.
N O
Parameters
P
Parameter
Description
provider
(Reserved) A System.IFormatProvider object.
Q R S
Return Value
T
System.Boolean.TrueString if the value of this instance is true, or System.Boolean.FalseString if the value of this instance is false.
U V W
Description
X
The provider parameter is reserved. It does not participate in the execution of this method.
Y Z
393
Contents | Index
Boolean Structure
System
ToBoolean() Method
Example using System; using System.Globalization;
A namespace Samples { public class BooleanToString { public static void Main() { Boolean b = true; CultureInfo ci = new CultureInfo("th-TH"); Console.WriteLine(b.ToString(ci)); b = false; Console.WriteLine(b.ToString(ci)); } } }
B C D E F G H I J
The output is
K
True False
L M N
IConvertible.ToBoolean(System.IFormatProvider) Method
O
[ILASM]
P
.method private final hidebysig virtual bool System.IConvertible.ToBoolean(class System.IFormatProvider provider)
Q
[C#]
R
bool IConvertible.ToBoolean(IFormatProvider provider)
S T
Summary
U
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToBoolean.]
V W
IConvertible.ToByte(System.IFormatProvider) Method
X
[ILASM]
Y
.method private final hidebysig virtual unsigned int8 System.IConvertible.ToByte(class System.IFormatProvider provider)
Z
[C#]
byte IConvertible.ToByte(IFormatProvider provider)
394
Contents | Index
System
Boolean Structure ToDecimal() Method
Summary Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToByte.] A B
IConvertible.ToChar(System.IFormatProvider) Method
C
[ILASM]
D
.method private final hidebysig virtual valuetype System.Char System.IConvertible.ToChar(class System.IFormatProvider provider)
E
[C#]
F
char IConvertible.ToChar(IFormatProvider provider)
G
Summary
H
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToChar.]
I J K
IConvertible.ToDateTime(System.IFormatProvider) Method
L
[ILASM]
M
.method private final hidebysig virtual valuetype System.DateTime System.IConvertible.ToDateTime(class System.IFormatProvider provider)
N
[C#]
O
DateTime IConvertible.ToDateTime(IFormatProvider provider)
P
Summary
Q
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDateTime.]
R S T
IConvertible.ToDecimal(System.IFormatProvider) Method
U
[ILASM]
V
.method private final hidebysig virtual decimal System.IConvertible.ToDecimal(class System.IFormatProvider provider)
W
[C#]
X
decimal IConvertible.ToDecimal(IFormatProvider provider)
Y
Summary
Z
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDecimal.]
395
Contents | Index
Boolean Structure
System
ToDouble() Method
IConvertible.ToDouble(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual float64 System.IConvertible.ToDouble(class System.IFormatProvider provider)
B
[C#]
double IConvertible.ToDouble(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDouble.]
F G H
IConvertible.ToInt16(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual int16 System.IConvertible.ToInt16(class System.IFormatProvider provider)
K
[C#]
short IConvertible.ToInt16(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt16.]
O P Q
IConvertible.ToInt32(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual int32 System.IConvertible.ToInt32(class System.IFormatProvider provider)
T
[C#]
int IConvertible.ToInt32(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt32.]
X Y Z
396
Contents | Index
System
Boolean Structure ToSingle() Method
IConvertible.ToInt64(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual int64 System.IConvertible.ToInt64(class System.IFormatProvider provider)
A
[C#]
B
long IConvertible.ToInt64(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt64.]
E F G
IConvertible.ToSByte(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual int8 System.IConvertible.ToSByte(class System.IFormatProvider provider)
J
[C#]
K
sbyte IConvertible.ToSByte(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSByte.]
N O P
IConvertible.ToSingle(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual float32 System.IConvertible.ToSingle(class System.IFormatProvider provider)
S
[C#]
T
float IConvertible.ToSingle(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSingle.]
W X Y Z
397
Contents | Index
Boolean Structure
System
ToType() Method
IConvertible.ToType(System.Type, System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual object System.IConvertible.ToType(class System.Type type, class System.IFormatProvider provider)
B
[C#]
object IConvertible.ToType(Type type, IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToType.]
F G H
IConvertible.ToUInt16(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual unsigned int16 System.IConvertible.ToUInt16(class System.IFormatProvider provider)
K
[C#]
ushort IConvertible.ToUInt16(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt16.] This member is not CLS-compliant.
O P Q
IConvertible.ToUInt32(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual unsigned int32 System.IConvertible.ToUInt32(class System.IFormatProvider provider)
T
[C#]
uint IConvertible.ToUInt32(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt32.] This member is not CLS-compliant.
X Y Z
398
Contents | Index
System
Boolean Structure ToUInt64() Method
IConvertible.ToUInt64(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual unsigned int64 System.IConvertible.ToUInt64(class System.IFormatProvider provider)
A
[C#]
B
ulong IConvertible.ToUInt64(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt64.] This member is not CLS-compliant.
E F G H I J K L M N O P Q R S T U V W X Y Z
399
Contents | Index
System Byte Structure
BCL
Object
A
ValueType
B
Byte
C
IComparable IFormattable IConvertible
D
NotStandardized
Summary
E
Represents an 8-bit unsigned integer.
F
Type Summary
G
public struct Byte : IComparable, IFormattable, IConvertible { // Fields public const byte MaxValue = 255; public const byte MinValue = 0;
H I J K
// Methods public int CompareTo (object value); public override bool Equals (object obj); public override int GetHashCode (); MS public TypeCode GetTypeCode (); public static byte Parse (string s); public static byte Parse (string s, NumberStyles style); public static byte Parse (string s, NumberStyles style, IFormatProvider provider); CF public static byte Parse (string s, IFormatProvider provider); public override string ToString (); public string ToString (string format); public string ToString (string format, IFormatProvider provider); public string ToString (IFormatProvider provider);
L M N O P Q R S T
// MS MS MS MS MS MS MS MS MS MS MS
U V W X Y Z
Explicit Interface Members bool IConvertible.ToBoolean(IFormatProvider provider); byte IConvertible.ToByte(IFormatProvider provider); char IConvertible.ToChar(IFormatProvider provider); DateTime IConvertible.ToDateTime(IFormatProvider provider); decimal IConvertible.ToDecimal(IFormatProvider provider); double IConvertible.ToDouble(IFormatProvider provider); short IConvertible.ToInt16(IFormatProvider provider); int IConvertible.ToInt32(IFormatProvider provider); long IConvertible.ToInt64(IFormatProvider provider); sbyte IConvertible.ToSByte(IFormatProvider provider); float IConvertible.ToSingle(IFormatProvider provider);
400
Contents | Index
System
Byte Structure Byte Structure
MS MS MS MS
object IConvertible.ToType(Type type,IFormatProvider provider); ushort IConvertible.ToUInt16(IFormatProvider provider); uint IConvertible.ToUInt32(IFormatProvider provider); ulong IConvertible.ToUInt64(IFormatProvider provider);
A
}
B C
BA The naming of this class diverges from our pattern for naming integral base
D
types. Strictly following the pattern would have led us to naming this class UInt8. How ugly that would have been for such a commonly used type! After much debate we decided that bytes are so commonly mentioned in our APIs (ReadByte, WriteByte on Stream, for example) that it warranted having a good name for the base type even though it meant breaking the naming pattern. Similarly we include Byte rather than SByte in the Common Language Specification because it is much more common to view bytes as unsigned 0..255 values than –128..127 values.
E F G H I J
Description
K
The System.Byte data type represents integer values ranging from 0 to positive 255 (hexadecimal 0xFF).
L M
Example
N
using System;
O
namespace Samples { public class ByteSample { public static void Main() { byte b = Byte.MaxValue; Console.WriteLine("MaxValue is {0}", b); Console.WriteLine("MaxValue.GetHashCode is {0}", b.GetHashCode()); b = Byte.MinValue; Console.WriteLine("MinValue is {0}", b); Console.WriteLine("MinValue.GetHashCode is {0}", b.GetHashCode()); string s = Byte.MaxValue.ToString(); b = Byte.Parse(s); Console.WriteLine(b); } } }
P Q R S T U V W X Y Z
401
Contents | Index
Byte Structure
System
MaxValue Field
The output is MaxValue is 255 MaxValue.GetHashCode is 255 MinValue is 0 MinValue.GetHashCode is 0 255
A B C D E
Byte.MaxValue Field
F
[ILASM]
.field public static literal unsigned int8 MaxValue
G
[C#]
public const byte MaxValue = 255
H I
Summary
J
Contains the maximum value for the System.Byte type.
K
Description
L
The value of this constant is 255 (hexadecimal 0xFF).
M N
Example
O
using System;
P
namespace Samples { public class ByteMaxValue { public static void Main() { Console.WriteLine("Byte.MaxValue is {0}", Byte.MaxValue); Console.WriteLine("Byte.MinValue is {0}", Byte.MinValue); } } }
Q R S T U V W X
The output is
Y
Byte.MaxValue is 255 Byte.MinValue is 0
Z
402
Contents | Index
System
Byte Structure CompareTo() Method
Byte.MinValue Field [ILASM]
.field public static literal unsigned int8 MinValue [C#]
A
public const byte MinValue = 0
B C
Summary
D
Contains the minimum value for the System.Byte type.
E
Description
F
The value of this constant is 0.
G H
Example
I
using System;
J
namespace Samples { public class ByteMinValue { public static void Main() { Console.WriteLine("Byte.MaxValue is {0}", Byte.MaxValue); Console.WriteLine("Byte.MinValue is {0}", Byte.MinValue); } } }
K L M N O P Q R
The output is
S T
Byte.MaxValue is 255 Byte.MinValue is 0
U V
Byte.CompareTo(System.Object) Method
W
[ILASM]
X
.method public final hidebysig virtual int32 CompareTo(object value) [C#]
Y
public int CompareTo(object value)
Z
403
Contents | Index
Byte Structure
System
CompareTo() Method
Summary Returns the sort order of the current instance compared to the specified object. A
Parameters
B C D
Parameter
Description
value
The System.Object to compare to the current instance.
E F
Return Value
G
A System.Int32 containing a value that reflects the sort order of the current instance as compared to value. The following table defines the conditions under which the return value is a negative number, zero, or a positive number.
H I J
Return Value
Description
any negative number
Current instance < value.
zero
Current instance == value.
any positive number
Current instance > value, or value is a null reference.
K L M N O P
Description
Q
[Note: This method is implemented to support the System.IComparable interface.]
R
Exceptions
S T
Exception
Condition
U
System.ArgumentException
value is not a System.Byte and is not a null reference.
V W
Example
X
using System;
Y
namespace Samples { public class ByteCompareTo { private static string CompareBytes(byte b1, byte b2)
Z
404
Contents | Index
System
Byte Structure Equals() Method
{ int i = b1.CompareTo(b2); if(0 == i) return String.Format("{0} is equal to {1}", b1, b2); if(i > 0) return String.Format("{0} is greater than {1}", b1, b2); else return String.Format("{0} is less than {1}", b1, b2);
A B C
} public static void Main() { Console.WriteLine(CompareBytes(Byte.MaxValue, Byte.MaxValue)); Console.WriteLine(CompareBytes(Byte.MaxValue, Byte.MinValue)); Console.WriteLine(CompareBytes(Byte.MinValue, Byte.MaxValue)); }
D E F G H I
} }
J
The output is
K L
255 is equal to 255 255 is greater than 0 0 is less than 255
M N O
Byte.Equals(System.Object) Method
P
[ILASM]
.method public hidebysig virtual bool Equals(object obj)
Q
[C#]
R
public override bool Equals(object obj)
S
Summary
T
Determines whether the current instance and the specified System.Object represent the same type and value.
U
Parameters
W
V
X
Parameter
Description
obj
The System.Object to compare to the current instance.
Y Z
405
Contents | Index
Byte Structure
System
GetHashCode() Method
Return Value true if obj represents the same type and value as the current instance. If obj is a null reference or is not an instance of System.Byte, returns false. A B
Description
C
[Note: This method overrides System.Object.Equals.]
D
Example
E
using System;
F namespace Samples { public class ByteEquals { public static void Main() { Byte b = Byte.MaxValue; Console.WriteLine( "Is 'b'({0}) equal to Byte.MaxValue: {1}", b, b.Equals(Byte.MaxValue)); Console.WriteLine( "Is 'b'({0}) equal to Byte.MinValue: {1}", b, b.Equals(Byte.MinValue)); Console.WriteLine( "Is 'b'({0}) equal to 'b' is {1}", b, b.Equals(b)); } } }
G H I J K L M N O P Q R
The output is
S Is 'b'(255) equal to Byte.MaxValue: True Is 'b'(255) equal to Byte.MinValue: False Is 'b'(255) equal to 'b' is True
T U V
Byte.GetHashCode() Method
W
[ILASM]
X
.method public hidebysig virtual int32 GetHashCode()
Y
[C#]
public override int GetHashCode()
Z
406
Contents | Index
System
Byte Structure GetTypeCode() Method
Summary Generates a hash code for the current instance.
Description
A
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
B C D
Example
E
using System;
F namespace Samples { public class ByteGetHashCode { public static void Main() { Byte b = Byte.MaxValue; Console.WriteLine("'b' ({0}) hash code {1}", b, b.GetHashCode()); b = Byte.MinValue; Console.WriteLine("'b' ({0}) hash code {1}", b, b.GetHashCode()); b = Byte.MaxValue / 2; Console.WriteLine("'b' ({0}) hash code {0}", b, b.GetHashCode()); } } }
G H I J K L M N O P Q R
The output is
S 'b' (255) hash code 255 'b' (0) hash code 0 'b' (127) hash code 127
T U V
Byte.GetTypeCode() Method
W
[ILASM]
X
.method public final hidebysig virtual valuetype System.TypeCode GetTypeCode()
Y
[C#]
public TypeCode GetTypeCode()
Z
407
Contents | Index
Byte Structure
System
Parse() Method
Summary Returns the System.TypeCode for value type System.Byte. A B
Byte.Parse(System.String) Method
C
[ILASM]
.method public hidebysig static unsigned int8 Parse(string s)
D
[C#]
public static byte Parse(string s)
E F
Summary
G
Returns the specified System.String converted to a System.Byte value.
H
Parameters
I J
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Integer style.
K L M N
Description
O
This version of System.Byte.Parse is equivalent to System.Byte.Parse (s, NumberStyles.Integer, null). The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.]
P Q R S
Exceptions
T U
Exception
Condition
V
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.Byte.MaxValue or less than System.Byte.MinValue.
W X Y Z
408
Contents | Index
System
Byte Structure Parse() Method
Example using System; namespace Samples { public class ByteParse { public static void Main() { try { Byte b = Byte.Parse(" 0 "); Console.WriteLine("b is {0}", b = Byte.Parse(" +255 "); Console.WriteLine("b is {0}", b = Byte.Parse("256"); Console.WriteLine("b is {0}", } catch(OverflowException e) { Console.WriteLine("Exception: } } } }
A B C D E b);
F
b);
G
b);
H I J
{0}", e);
K L M
The output is
N
b is 0 b is 255 Exception: System.OverflowException: Value was either too large or too small for an unsigned byte. at System.Byte.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Byte.Parse(String s) at Samples.ByteParse.Main() in C:\Books\BCL\Samples\System\Byte\ Parse(System.String)\Byte.cs:line 15
O P Q R S T U
Byte.Parse(System.String, System.Globalization.NumberStyles) Method
V [ILASM]
W
.method public hidebysig static unsigned int8 Parse(string s, valuetype System.Globalization.NumberStyles style)
X
[C#]
Y
public static byte Parse(string s, NumberStyles style)
Z
Summary Returns the specified System.String converted to a System.Byte value.
409
Contents | Index
Byte Structure
System
Parse() Method
Parameters Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Integer style.
A B C D E F G
Description
H
This version of System.Byte.Parse is equivalent to System.Byte.Parse (s, style, null ). The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.]
I J K
Exceptions
L M
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.Byte.MaxValue or less than System.Byte.MinValue.
N O P Q R S T
Example
U
using System; using System.Globalization;
V
namespace Samples { public class ByteParseSample { public static void Main() { try { Byte b = Byte.Parse(" 128",
W X Y Z
410
Contents | Index
System
Byte Structure Parse() Method
NumberStyles.AllowLeadingWhite ); Console.WriteLine("b is {0}", b); b = Byte.Parse("128+", NumberStyles.AllowTrailingSign); Console.WriteLine("b is {0}", b); b = Byte.Parse("128+", NumberStyles.None); Console.WriteLine("b is {0}", b);
A B C
} catch(FormatException e) { Console.WriteLine("Exception: {0}", e); }
D E F
}
G
}
H
}
I
The output is
J b is 128 b is 128 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Byte.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Byte.Parse(String s, NumberStyles style) at Samples.ByteParseSample.Main() in C:\Books\BCL\Samples\System\Byte\ Parse(System.String,System.Globalization.NumberStyles)\Byte.cs:line 18
K L M N O P Q
Byte.Parse(System.String, System.Globalization.NumberStyles, System.IFormatProvider) Method
R S
[ILASM]
T
.method public hidebysig static unsigned int8 Parse(string s, valuetype System.Globalization.NumberStyles style, class System.IFormatProvider provider)
U
[C#]
V
public static byte Parse(string s, NumberStyles style, IFormatProvider provider)
W
Summary
X
Returns the specified System.String converted to a System.Byte value.
Y Z
411
Contents | Index
Byte Structure
System
Parse() Method
Parameters Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Integer style.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
A B C D E F G H I
Description
J
The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used.
K L M N
Exceptions
O P
Exception
Condition
Q
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.Byte. MaxValue or less than System.Byte.MinValue.
R S T U V
Example
W
using System; using System.Globalization;
X Y
namespace Samples { public class ByteParse { public static void Main()
Z
412
Contents | Index
System
Byte Structure Parse() Method
{ try { Byte b = Byte.Parse("$128", NumberStyles.AllowCurrencySymbol, new CultureInfo("en-AU")); Console.WriteLine("b is {0}", b); b = Byte.Parse("kr255", NumberStyles.AllowCurrencySymbol, new CultureInfo("da-DK")); Console.WriteLine("b is {0}", b); b = Byte.Parse("$255", NumberStyles.AllowCurrencySymbol, new CultureInfo("de-AT")); Console.WriteLine("b is {0}", b); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E F G H I J K
} }
L
}
M
The output is
N
b is 128 b is 255 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Byte.Parse(String s, NumberStyles style, IFormatProvider provider) at Samples.ByteParse.Main() in C:\Books\BCL\Samples\System\Byte\ Parse(System.String,System.Globalization.NumberStyles,System.IFormatProvider)\Byte. cs:line 20
O P Q R S T U
Byte.Parse(System.String, System.IFormatProvider) Method
V [ILASM]
W
.method public hidebysig static unsigned int8 Parse(string s, class System.IFormatProvider provider) [C#]
X
public static byte Parse(string s, IFormatProvider provider)
Y Z
Summary Returns the specified System.String converted to a System.Byte value.
413
Contents | Index
Byte Structure
System
Parse() Method
Parameters Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Integer style.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
A B C D E F
Description
G
This version of System.Byte.Parse is equivalent to System.Byte.Parse(s, NumberStyles.Integer, provider). The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used.
H I J K L
Exceptions
M N O
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.OverflowException
s represents a number greater than System.Byte. MaxValue or less than System.Byte.MinValue.
System.FormatException
s is not in the correct style.
P Q R S T
Example
U
using System; using System.Globalization;
V
namespace Samples { public class ByteParse { public static void Main() { try { Byte b = Byte.Parse("128",
W X Y Z
414
Contents | Index
System
Byte Structure ToString() Method
new CultureInfo("en-AU")); Console.WriteLine("b is {0}", b); b = Byte.Parse("255", new CultureInfo("da-DK")); Console.WriteLine("b is {0}", b); b = Byte.Parse("256", new CultureInfo("de-AT")); Console.WriteLine("b is {0}", b);
A B C
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
D E F
} }
G
}
H
The output is
I
b is 128 b is 255 Exception: System.OverflowException: Value was either too large or too small for an unsigned byte. at System.Byte.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Byte.Parse(String s, IFormatProvider provider) at Samples.ByteParse.Main() in C:\Books\BCL\Samples\System\Byte\ Parse(System.String,System.IFormatProvider)\Byte.cs:line 18
J K L M N O P
Byte.ToString() Method
Q [ILASM]
.method public hidebysig virtual string ToString()
R
[C#]
S
public override string ToString()
T
Summary
U
Returns a System.String representation of the value of the current instance.
V
Return Value
W
A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the current system culture.
X Y Z
415
Contents | Index
Byte Structure
System
ToString() Method
Description This version of System.Byte.ToString is equivalent to System.Byte.ToString(null, null). [Note: This method overrides System.Object.ToString.]
A B
Example
C
using System; using System.Globalization;
D E
namespace Samples { public class ByteToString { public static void Main() { Byte b = Byte.MaxValue; Console.WriteLine(b.ToString()); b = Byte.MinValue; Console.WriteLine(b.ToString()); b = Byte.MaxValue / 2; Console.WriteLine(b.ToString()); } } }
F G H I J K L M N
The output is
O 255 0 127
P Q R S
Byte.ToString(System.String) Method
T
[ILASM]
U
.method public hidebysig instance string ToString(string format) [C#]
V
public string ToString(string format)
W
Summary
X
Returns a System.String representation of the value of the current instance.
Y Z
416
Contents | Index
System
Byte Structure ToString() Method
Parameters Parameter
Description
format
A System.String that specifies the format of the returned string. [Note: For a list of valid values, see System.Byte.ToString(System.String, System.IFormatProvider).]
A B C D
Return Value
E
A System.String representation of the current instance formatted as specified by format. The string takes into account the current system culture.
F G
Description
H
This version of System.Byte.ToString is equivalent to System.Byte.ToString(format, null). If format is null, the general format specifier “G” is used.
I J K L
Exceptions
M
Exception
Condition
System.FormatException
format is invalid.
N O P
Example
Q
using System; using System.Globalization;
R S
namespace Samples { public class ByteToString { public static void Main() { Byte b = Byte.MaxValue; string[] strings = {"C", "D", "E", "F", "G", "N", "P", "X"}; foreach(string s in strings) Console.WriteLine(s + " " + b.ToString(s)); } } }
T U V W X Y Z
417
Contents | Index
Byte Structure
System
ToString() Method
The output is C D E F G N P X
A B C D
$255.00 255 2.550000E+002 255.00 255 255.00 25,500.00 % FF
E F
Byte.ToString(System.String, System.IFormatProvider) Method
G [ILASM]
H
.method public final hidebysig virtual string ToString(string format, class System.IFormatProvider provider)
I
[C#]
J
public string ToString(string format, IFormatProvider provider)
K
Summary
L
Returns a System.String representation of the value of the current instance.
M
Parameters
N O
Parameter
Description
format
A System.String containing a character that specifies the format of the returned string.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo instance containing culture-specific formatting information.
P Q R S T U V
Return Value
W
A System.String representation of the current instance formatted as specified by format. The string takes into account the information in the System.Globalization.NumberFormatInfo instance supplied by provider.
X Y
Description
Z
If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. If 418
Contents | Index
System
Byte Structure ToString() Method
format is a null reference, the general format specifier “G” is used. The following table lists the characters that are valid for the System.Byte type: A
Format Characters
Description
B
“C”, “c”
Currency format.
C
“D”, “d”
Decimal format.
“E”, “e”
Exponential notation format.
“F”, “f ”
Fixed-point format.
G
“G”, “g”
General format.
H
“N”, “n”
Number format.
“P”, “p”
Percent format.
“X”, “x”
Hexadecimal format.
D E F
I J K L M N
[Note: For a detailed description of formatting, see the System.IFormattable interface. This method is implemented to support the System.IFormattable interface.]
O P
Exceptions
Q
Exception
Condition
System.FormatException
format is invalid.
R S T U
Example
V
using System; using System.Globalization;
W X
namespace Samples { public class ByteToString { public static void Main() {
Y Z
419
Contents | Index
Byte Structure
System
ToString() Method
Byte b = Byte.MaxValue; CultureInfo[] cultureInfos = new CultureInfo[] { new CultureInfo("en-AU"), new CultureInfo("en-GB"), new CultureInfo("en-US")}; string[] strings = {"C", "D", "E", "F", "G", "N", "P", "X"}; foreach(CultureInfo c in cultureInfos) foreach(string s in strings) Console.WriteLine(b.ToString(s, c));
A B C D E }
F
} }
G
The output is
H I
$255.00 255 2.550000E+002 255.00 255 255.00 25,500.00 % FF £255.00 255 2.550000E+002 255.00 255 255.00 25,500.00 % FF $255.00 255 2.550000E+002 255.00 255 255.00 25,500.00 % FF
J K L M N O P Q R S T U V W X Y Z
420
Contents | Index
System
Byte Structure ToString() Method
Byte.ToString(System.IFormatProvider) Method [ILASM]
.method public final hidebysig virtual string ToString(class System.IFormatProvider provider)
A
[C#]
B
public string ToString(IFormatProvider provider)
C
Summary
D
Returns a System.String representation of the value of the current instance.
E F
Parameters
G
Parameter
Description
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
H I J K
Return Value
L
A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the information in the System.Globalization.NumberFormatInfo instance supplied by provider.
M N O
Description
P
This version of System.Byte.ToString is equivalent to System.Byte.ToString (“G,” provider). If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used.
Q R S T
Example
U
using System; using System.Globalization;
V W
namespace Samples { public class ByteToString { public static void Main() { Byte b = Byte.MaxValue; Console.WriteLine(b.ToString(
X Y Z
421
Contents | Index
Byte Structure
System
ToString() Method
new CultureInfo("en-AU"))); Console.WriteLine(b.ToString( new CultureInfo("fr-FR"))); Console.WriteLine(b.ToString( new CultureInfo("de-AT")));
A }
B }
C
}
D
The output is
E 255 255 255
F G H I J K L M N O P Q R S T U V W X Y Z
422
Contents | Index
System Char Structure
BCL
Object
A
ValueType IComparable
B
Char IConvertible
NotStandardized
C
Summary
D
Represents a Unicode character.
E F
Type Summary
G
public struct Char : IComparable, IConvertible { // Fields public const char MaxValue = = (char)0xFFFF public const char MinValue = = (char)0x0
H I J K
// Methods public int CompareTo (object value); public override bool Equals (object obj); public override int GetHashCode (); public static double GetNumericValue (char c); CF public static double GetNumericValue (string s, int index); MS public TypeCode GetTypeCode (); public static UnicodeCategory GetUnicodeCategory (char c); CF public static UnicodeCategory GetUnicodeCategory (string s, int index); public static bool IsControl (char c); CF public static bool IsControl (string s, int index); public static bool IsDigit (char c); CF public static bool IsDigit (string s, int index); public static bool IsLetter (char c); CF public static bool IsLetter (string s, int index); public static bool IsLetterOrDigit (char c); CF public static bool IsLetterOrDigit (string s, int index); public static bool IsLower (char c); CF public static bool IsLower (string s, int index); public static bool IsNumber (char c); public static bool IsNumber (string s, int index); public static bool IsPunctuation (char c); CF public static bool IsPunctuation (string s, int index);
L M N O P Q R S T U V W X Y Z
423
Contents | Index
Char Structure
System
Char Structure
CF public static bool IsSeparator (char c); CF public static bool IsSeparator (string s, int index); CF public static bool IsSurrogate (char c); CF public static bool IsSurrogate (string s, int index); CF public static bool IsSymbol (char c); CF public static bool IsSymbol (string s, int index); public static bool IsUpper (char c); CF public static bool IsUpper (string s, int index); public static bool IsWhiteSpace (char c); CF public static bool IsWhiteSpace (string s, int index); CF public static char Parse (string s); public static char ToLower (char c); MS public static char ToLower (char c, CultureInfo culture); public override string ToString (); MS public static string ToString (char c); public string ToString (IFormatProvider provider); public static char ToUpper (char c); MS public static char ToUpper (char c, CultureInfo culture);
A B C D E F G H I J K L
// MS MS MS MS MS MS MS MS MS MS MS MS MS MS MS
M N O P Q R S T U V
Explicit Interface Members bool IConvertible.ToBoolean(IFormatProvider provider); byte IConvertible.ToByte(IFormatProvider provider); char IConvertible.ToChar(IFormatProvider provider); DateTime IConvertible.ToDateTime(IFormatProvider provider); decimal IConvertible.ToDecimal(IFormatProvider provider); double IConvertible.ToDouble(IFormatProvider provider); short IConvertible.ToInt16(IFormatProvider provider); int IConvertible.ToInt32(IFormatProvider provider); long IConvertible.ToInt64(IFormatProvider provider); sbyte IConvertible.ToSByte(IFormatProvider provider); float IConvertible.ToSingle(IFormatProvider provider); object IConvertible.ToType(Type type,IFormatProvider provider); ushort IConvertible.ToUInt16(IFormatProvider provider); uint IConvertible.ToUInt32(IFormatProvider provider); ulong IConvertible.ToUInt64(IFormatProvider provider);
}
W X Y Z
424
Contents | Index
System
Char Structure Char Structure
BA In the design of this type we debated having all the predicates (IsXxx methods) in this class, versus putting them in another class. In the end we felt the simplicity of having just one class for all these operations made it worthwhile.
A
JR Note that Char is not the most accurate name for this type. A Char is really a
B
UTF-16 code point, which will be a character unless the code point represents a high or low surrogate value. A string is really a set of UTF-16 code points. To properly traverse the characters of a string, you should use the System.Globalization.StringInfo class’s methods.
C D E F
Description
G
The System.Char value type represents Unicode characters, with code points ranging from 0 to 65,535. [Note: The code point of a Unicode character is that character’s 2-byte, encoded value.] [Note: The System.Globalization.UnicodeCategory enumeration describes the categories that a Unicode character can be mapped to. For information on mapping specific Unicode characters to Unicode categories, see the UnicodeData.txt file in the Unicode Character Database at http://www.unicode.org/Public/UNIDATA/ UnicodeCharacterDatabase.html. The UnicodeData.txt file format is described at http://www.unicode.org/Public/3.1-Update/UnicodeData-3.1.0.html.]
H I J K L M N
Example
O
using System;
P Q
namespace Samples { public class CharSample { public static void Main() { Console.WriteLine("Char.MaxValue is {0}", (int) Char.MaxValue); Console.WriteLine("MaxValue hash code {0}", Char.MaxValue.GetHashCode()); Console.WriteLine("Char.MinValue is {0}", (int) Char.MinValue); Console.WriteLine("MinValue hash code {0}", Char.MinValue.GetHashCode()); Char c = '3'; double d = Char.GetNumericValue(c); Console.WriteLine("Char '{0}' has numeric value: {1}", c, d);
R S T U V W X Y Z
425
Contents | Index
Char Structure
System
MaxValue Field
c = Convert.ToChar(0X00BC); d = Char.GetNumericValue(c); Console.WriteLine("Char '{0}' has numeric c, d); c = 'A'; d = Char.GetNumericValue(c); Console.WriteLine("Char '{0}' has numeric c, d); c = '3'; Console.WriteLine("Char '{0}' is a digit: c, Char.IsDigit(c)); c = 'B'; Console.WriteLine("Char '{0}' is a digit: c, Char.IsDigit(c));
A B C D E F G
value: {1}",
value: {1}",
{1}",
{1}",
}
H
} }
I
The output is
J K
Char.MaxValue is 65535 MaxValue hash code -1 Char.MinValue is 0 MinValue hash code 0 Char '3' has numeric value: 3 Char '¼' has numeric value: 0.25 Char 'A' has numeric value: -1 Char '3' is a digit: True Char 'B' is a digit: False
L M N O P Q R
Char.MaxValue Field
S
[ILASM]
T
.field public static literal valuetype System.Char MaxValue [C#]
U
public const char MaxValue = (char)0xFFFF
V
Summary
W
Contains the maximum code point for the System.Char type.
X Y
Description
Z
The numeric value of this constant is 65,535.
426
Contents | Index
System
Char Structure MinValue Field
Example using System; namespace Samples { public class CharMaxValue { public static void Main() { Console.WriteLine("Char.MaxValue is {0}", (int) Char.MaxValue); Console.WriteLine("Char.MinValue is {0}", (int) Char.MinValue); } } }
A B C D E F G H
The output is
I J
Char.MaxValue is 65535 Char.MinValue is 0
K L
Char.MinValue Field
M
[ILASM]
N
.field public static literal valuetype System.Char MinValue
O
[C#]
public const char MinValue = (char)0x0
P
Summary
Q
Contains the minimum code point for the System.Char type.
R
Description
S
The numeric value of this constant is 0.
T U
Example
V
using System;
W namespace Samples { public class CharMinValue { public static void Main() { Console.WriteLine("Char.MaxValue is {0}", (int) Char.MaxValue);
X Y Z
427
Contents | Index
Char Structure
System
CompareTo() Method
Console.WriteLine("Char.MinValue is {0}", (int) Char.MinValue); } }
A
}
B
The output is
C
Char.MaxValue is 65535 Char.MinValue is 0
D E F
Char.CompareTo(System.Object) Method
G H
[ILASM]
I
[C#]
.method public final hidebysig virtual int32 CompareTo(object value) public int CompareTo(object value)
J K
Summary
L
Returns the sort order of the current instance compared to the specified System.Object.
M
Parameters
N O
Parameter
Description
value
The System.Object to compare to the current instance.
P Q R
Return Value
S
A System.Int32 containing a value that reflects the sort order of the current instance as compared to value. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number.
T U V W
Return Value
Description
any negative number
Current instance < value.
zero
Current instance == value.
any positive number
Current instance > value, or value is a null reference.
X Y Z
428
Contents | Index
System
Char Structure CompareTo() Method
Description The comparison performed by this method is based on the code points of the current instance and value, not necessarily their lexicographical characteristics. [Note: This method is implemented to support the System.IComparable interface.]
A B
Exceptions
C
Exception
Condition
System.ArgumentException
value is not a System.Char and is not a null reference.
D E F G
Example
H
using System;
I
namespace Samples { public class CharCompareTo { private static string CompareChars(char c1, char c2) { int i = c1.CompareTo(c2); if(0 == i) return String.Format("{0} is equal to {1}", c1, c2); if(i > 0) return String.Format("{0} is greater than {1}", c1, c2); else return String.Format("{0} is less than {1}", c1, c2); } public static void Main() { Console.WriteLine(CompareChars('A', 'A')); Console.WriteLine(CompareChars('A', 'a')); Console.WriteLine(CompareChars('a', 'A')); } } }
J K L M N O P Q R S T U V W
The output is
X Y
A is equal to A A is less than a a is greater than A
Z
429
Contents | Index
Char Structure
System
Equals() Method
Char.Equals(System.Object) Method [ILASM]
.method public hidebysig virtual bool Equals(object obj)
A
[C#]
public override bool Equals(object obj)
B C
Summary
D
Determines whether the current instance and the specified System.Object represent the same type and value.
E F
Parameters
G H
Parameter
Description
obj
The System.Object to compare to the current instance.
I J K
Return Value
L
true if obj represents the same type and value as the current instance. If obj is a null reference or is not an instance of System.Char, returns false.
M N
Description
O
The comparison performed by this method is based on the code points of the current instance and obj, not necessarily their lexicographical characteristics. [Note: This method overrides System.Object.Equals.]
P Q R
Example
S
using System;
T namespace Samples { public class CharEquals { public static void Main() { Char c = Convert.ToChar(0X7fff); Console.WriteLine( "Is c ({0}) equal to Char.MaxValue: {1}", (int) c, c.Equals(Char.MaxValue)); Console.WriteLine( "Is c ({0}) equal to Char.MinValue: {1}",
U V W X Y Z
430
Contents | Index
System
Char Structure GetHashCode() Method
(int) c, c.Equals(Char.MinValue)); Console.WriteLine( "Is c ({0}) equal to c: {1}", (int) c, c.Equals(c)); Console.WriteLine( "Is c ({0}) equal to \"32768\": {1}", (int) c, c.Equals("32768"));
A B C
} }
D
}
E
The output is Is Is Is Is
c c c c
(32767) (32767) (32767) (32767)
equal equal equal equal
F to to to to
Char.MaxValue: False Char.MinValue: False c: True "32768": False
G H I J
Char.GetHashCode() Method
K [ILASM]
.method public hidebysig virtual int32 GetHashCode()
L
[C#]
M
public override int GetHashCode()
N
Summary
O
Generates a hash code for the current instance.
P
Description
Q
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
R
Example
T
S
using System;
U
namespace Samples { public class CharGetHashCode { public static void Main() { Char c = Char.MaxValue; Console.WriteLine("c (MaxValue) hash code {0}", c.GetHashCode()); c = Char.MinValue;
V W X Y Z
431
Contents | Index
Char Structure
System
GetNumericValue() Method
Console.WriteLine("c (MinValue) hash code {0}", c.GetHashCode()); c = Convert.ToChar(0X7fff); Console.WriteLine("c ({0}) hash code {1}", (int) c, c.GetHashCode());
A }
B }
C
}
D
The output is
E c (MaxValue) hash code -1 c (MinValue) hash code 0 c (32767) hash code 2147450879
F G H I
Char.GetNumericValue(System.Char) Method
J
[ILASM]
.method public hidebysig static float64 GetNumericValue(valuetype System.Char c)
K
[C#]
L
public static double GetNumericValue(char c)
M
Summary
N
Returns the numeric value associated with the specified Unicode character.
O
Parameters
P Q R S
Parameter
Description
c
A Unicode character.
T U
Return Value
V
A System.Double representing the numeric value associated with c if and only if c has an associated numeric value; otherwise, –1.0.
W X
Description
Y
A character has an associated numeric value if and only if it is a member of one of the following categories in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.DecimalDigitNumber, System.Globalization.UnicodeCategory.LetterNumber, or System.Glo-
Z
432
Contents | Index
System
Char Structure GetNumericValue() Method
balization.UnicodeCategory.OtherNumber. This member must be implemented if the Extended Numerics Library is present in the implementation.
Example
A
using System;
B
namespace Samples { public class CharGetNumericValue { public static void Main() { Char c = '3'; Console.WriteLine( "Numeric value of Char '{0}' c, Char.GetNumericValue(c)); c = Convert.ToChar(0X00BC); Console.WriteLine( "Numeric value of Char '{0}' c, Char.GetNumericValue(c)); c = Convert.ToChar(0X03a0); Console.WriteLine( "Numeric value of Char '{0}' c, Char.GetNumericValue(c)); c = 'A'; Console.WriteLine( "Numeric value of Char '{0}' c, Char.GetNumericValue(c)); } } }
C D E F G H
is {1}",
I J is {1}",
K L M
is {1}",
N O is {1}",
P Q R S
The output is
T Numeric Numeric Numeric Numeric
value value value value
of of of of
Char Char Char Char
'3' '¼' '?' 'A'
is is is is
3 0.25 -1 -1
U V W X
Char.GetNumericValue(System.String, System.Int32) Method
Y [ILASM]
Z
.method public hidebysig static float64 GetNumericValue(string s, int32 index) [C#]
public static double GetNumericValue(string s, int index)
433
Contents | Index
Char Structure
System
GetNumericValue() Method
Summary Returns the numeric value associated with the Unicode character at the specified position in the specified System.String. A
Parameters
B C
Parameter
Description
E
s
A System.String.
F
index
A System.Int32 that specifies the position of a character in s.
D
G H
Return Value
I
A System.Double representing the numeric value associated with the System.Char at position index in s if and only if that System.Char has an associated numeric value; otherwise, –1.0.
J K L
Description
M
A character has an associated numeric value if and only if it is a member of one of the following categories in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.DecimalDigitNumber, System.Globalization.UnicodeCategory.LetterNumber, or System.Globalization.UnicodeCategory.OtherNumber. This member must be implemented if the Extended Numerics Library is present in the implementation.
N O P Q R
Exceptions
S T
Exception
Condition
U
System.ArgumentNullException
s is a null reference.
System.ArgumentOutOfRangeException
The value of index is less than zero, or greater than or equal to the length of s.
V W X Y Z
434
Contents | Index
System
Char Structure GetUnicodeCategory() Method
Example using System; namespace Samples { public class CharGetNumericValue { public static void Main() { string s = "This string has a '3' in it"; int i = s.IndexOf('3'); double d = Char.GetNumericValue(s, i); Console.WriteLine( "Numeric value of the Char at {0} is {1}", i, d); i++; d = Char.GetNumericValue(s, i); Console.WriteLine( "Numeric Value of the Char at {0} is {1}", i, d); } } }
A B C D E F G H I J K L
The output is
M
Numeric value of the Char at 19 is 3 Numeric Value of the Char at 20 is -1
N O P
Char.GetTypeCode() Method
Q
[ILASM]
R
.method public final hidebysig virtual valuetype System.TypeCode GetTypeCode()
S
[C#]
public TypeCode GetTypeCode()
T
Summary
U
Returns the System.TypeCode for value type System.Char.
V W
Char.GetUnicodeCategory(System.Char) Method
X
[ILASM]
Y
.method public hidebysig static valuetype System.Globalization.UnicodeCategory GetUnicodeCategory(valuetype System.Char c)
Z
[C#]
public static UnicodeCategory GetUnicodeCategory(char c)
435
Contents | Index
Char Structure
System
GetUnicodeCategory() Method
Summary Determines the System.Globalization.UnicodeCategory of the specified Unicode character. A
Parameters
B C D E
Parameter
Description
c
A Unicode character.
F G
Description
H
[Note: For more information regarding Unicode categories, see System.Globalization.UnicodeCategory.]
I J
Example
K
using System; using System.Globalization;
L
namespace Samples { public class CharGetUnicodeCategory { public static void Main() { Char[] chars = new Char[] {'A', '3', '}', '$'}; foreach(Char c in chars) { UnicodeCategory u = Char.GetUnicodeCategory(c); Console.WriteLine( "Unicode category of Char '{0}' is {1}", c, u); } } } }
M N O P Q R S T U V W
The output is
X Y
Unicode Unicode Unicode Unicode
Z
category category category category
of of of of
Char Char Char Char
'A' '3' '}' '$'
is is is is
UppercaseLetter DecimalDigitNumber ClosePunctuation CurrencySymbol
436
Contents | Index
System
Char Structure GetUnicodeCategory() Method
Char.GetUnicodeCategory(System.String, System.Int32) Method [ILASM]
.method public hidebysig static valuetype System.Globalization.UnicodeCategory GetUnicodeCategory(string s, int32 index)
A
[C#]
B
public static UnicodeCategory GetUnicodeCategory(string s, int index)
C
Summary
D
Determines the System.Globalization.UnicodeCategory of the character at the specified position in the specified System.String.
E
Parameters
G
F
H
Parameter
Description
s
A System.String.
index
A System.Int32 that specifies the position of a character in s.
I J K L M
Description
N
[Note: For more information regarding Unicode categories, see System.Globalization.UnicodeCategory.]
O P
Exceptions
Q
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.ArgumentOutOfRangeException
The value of index is less than zero, or greater than or equal to the length of s.
R S T U V W X Y Z
437
Contents | Index
Char Structure
System
IsControl() Method
Example using System; using System.Globalization;
A
namespace Samples { public class CharGetUnicodeCategory { public static void Main() { string s = "A3$}-"; for(int i = 0; i < s.Length; i++) { UnicodeCategory u = Char.GetUnicodeCategory(s, i); Console.WriteLine( "Unicode category of Char '{0}' is {1}", s[i], u); } } } }
B C D E F G H I J K
The output is
L
Unicode Unicode Unicode Unicode Unicode
M N O
category category category category category
of of of of of
Char Char Char Char Char
'A' '3' '$' '}' '-'
is is is is is
UppercaseLetter DecimalDigitNumber CurrencySymbol ClosePunctuation DashPunctuation
P Q
Char.IsControl(System.Char) Method
R
[ILASM]
.method public hidebysig static bool IsControl(valuetype System.Char c)
S
[C#]
T
public static bool IsControl(char c)
U
Summary
V
Determines whether the specified Unicode character is a control character.
W X
Parameters
Y Z
Parameter
Description
c
A Unicode character.
438
Contents | Index
System
Char Structure IsControl() Method
Return Value True if c is a member of the following category in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.Control; otherwise, false. A
Example
B
using System;
C
namespace Samples { public class CharIsControl { public static void Main() { Char[] chars = new Char[] {'A', '\t', '\n', '$'}; foreach(Char c in chars) { if(Char.IsControl(c)) Console.WriteLine( "Char {0} (value {1}) is control char", c, (int) c); else Console.WriteLine( "Char {0} (value {1}) is not control char", c, (int) c); } } } }
D E F G H I J K L M N O P Q
The output is
R
Char A (value 65) is not control char Char (value 9) is control char Char (value 10) is control char Char $ (value 36) is not control char
S T U V W
Char.IsControl(System.String, System.Int32) Method
X [ILASM]
.method public hidebysig static bool IsControl(string s, int32 index)
Y
[C#]
Z
public static bool IsControl(string s, int index)
439
Contents | Index
Char Structure
System
IsControl() Method
Summary Determines whether the character at the specified position in the specified System.String is a control character. A
Parameters
B C
Parameter
Description
E
s
A System.String.
F
index
A System.Int32 that specifies a character position in s.
D
G H
Return Value
I
true if the character at position index in s is a member of the following category in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.Control; otherwise, false.
J K L
Exceptions
M N
Exception
Condition
O
System.ArgumentNullException
s is a null reference.
System.ArgumentOutOfRangeException
The value of index is less than zero, or greater than or equal to the length of s.
P Q R S
Example
T
using System;
U
namespace Samples { public class CharIsControl { public static void Main() { string s = "A\t\n$"; for(int i = 0; i < s.Length; i++) { if(Char.IsControl(s, i)) Console.WriteLine(
V W X Y Z
440
Contents | Index
System
Char Structure IsDigit() Method
"Char {0} (value {1}) is control char", s[i], (int) s[i]); else Console.WriteLine( "Char {0} (value {1}) is not control char", s[i], (int) s[i]);
A B
}
C
} }
D
}
E
The output is
F
Char A (value 65) is not control char Char (value 9) is control char Char (value 10) is control char Char $ (value 36) is not control char
G H I J K
Char.IsDigit(System.Char) Method
L
[ILASM]
.method public hidebysig static bool IsDigit(valuetype System.Char c)
M
[C#]
N
public static bool IsDigit(char c)
O
Summary
P
Determines whether a Unicode character is a decimal digit.
Q R
Parameters
S
Parameter
Description
c
A Unicode character.
T U V W
Return Value
X
true if c is a member of the following category in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.DecimalDigitNumber; otherwise, false.
Y Z
441
Contents | Index
Char Structure
System
IsDigit() Method
Description [Note: System.Char.IsDigit determines if a Char is a radix-10 digit. This contrasts with System.Char.IsNumber, which determines if a System.Char is of any numeric Unicode category.]
A B
Example
C
using System;
D namespace Samples { public class CharIsDigit { public static void Main() { Char[] chars = new Char[] {'3', 'A', '9', '$', Convert.ToChar(0X00BC)}; foreach(Char c in chars) { if(Char.IsDigit(c)) Console.WriteLine( "Char '{0}' is digit", c); else Console.WriteLine( "Char '{0}' is not digit",c); } } } }
E F G H I J K L M N O P Q
The output is
R
Char Char Char Char Char
S T U
'3' 'A' '9' '$' '¼'
is is is is is
digit not digit digit not digit not digit
V W
Char.IsDigit(System.String, System.Int32) Method
X
[ILASM]
Y
.method public hidebysig static bool IsDigit(string s, int32 index) [C#]
Z
public static bool IsDigit(string s, int index)
442
Contents | Index
System
Char Structure IsDigit() Method
Summary Determines whether the character at the specified position in the specified System.String is a decimal digit. A
Parameters
B C
Parameter
Description
s
A System.String.
E
index
A System.Int32 that specifies a character position in s.
F
D
G H
Return Value
I
true if the character at position index in s is a member of the following category in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.DecimalDigitNumber; otherwise, false.
J K
Description
L
[Note: System.Char.IsDigit determines if a System.Char is a radix-10 digit. This contrasts with System.Char.IsNumber, which determines if a System.Char is of any numeric Unicode category.]
M
Exceptions
P
N O
Q
Exception
Condition
System.ArgumentNullException
s is a null reference.
S
The value of index is less than zero, or greater than or equal to the length of s.
T
System.ArgumentOutOfRangeException
R
U V
Example
W
using System;
X
namespace Samples { public class CharIsDigit { public static void Main()
Y Z
443
Contents | Index
Char Structure
System
IsLetter() Method
{ string s = "3A9$\u00BC"; for(int i = 0; i < s.Length; i++) { if(Char.IsDigit(s, i)) Console.WriteLine( "Char '{0}' is digit", s[i]); else Console.WriteLine( "Char '{0}' is not digit", s[i]); }
A B C D E }
F
} }
G
The output is
H I
Char Char Char Char Char
J K L
'3' 'A' '9' '$' '¼'
is is is is is
digit not digit digit not digit not digit
M N
Char.IsLetter(System.Char) Method
O
[ILASM]
.method public hidebysig static bool IsLetter(valuetype System.Char c)
P
[C#]
public static bool IsLetter(char c)
Q R
Summary
S
Determines whether the specified Unicode character is a letter.
T
Parameters
U V
Parameter
Description
c
A Unicode character.
W X Y
Return Value
Z
true if c is a member of one of the following categories in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.Upper444
Contents | Index
System
Char Structure IsLetter() Method
caseLetter, System.Globalization.UnicodeCategory.LowercaseLetter, System.Globalization.UnicodeCategory.TitlecaseLetter, System.Globalization.UnicodeCategory.ModifierLetter, or System.Globalization.UnicodeCategory.OtherLetter; otherwise, false.
A B
Example
C
using System;
D namespace Samples { public class CharIsLetter { public static void Main() { Char[] chars = new Char[] {'3', 'A', 'z', '$'}; foreach(Char c in chars) { if(Char.IsLetter(c)) Console.WriteLine("Char '{0}' is letter",c); else Console.WriteLine("Char '{0}' is not letter", c); } } } }
E F G H I J K L M N O
The output is Char Char Char Char
'3' 'A' 'z' '$'
is is is is
P Q
not letter letter letter not letter
R S T
Char.IsLetter(System.String, System.Int32) Method
U
[ILASM]
V
.method public hidebysig static bool IsLetter(string s, int32 index)
W
[C#]
X
public static bool IsLetter(string s, int index)
Y
Summary
Z
Determines whether the character at the specified position in the specified System.String is a letter.
445
Contents | Index
Char Structure
System
IsLetter() Method
Parameters Parameter
Description
s
A System.String.
index
A System.Int32 that specifies a character position in s.
A B C D E
Return Value
F
true if the character at position index in s is a member of one of the following categories in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.UppercaseLetter, System.Globalization.UnicodeCategory.LowercaseLetter, System.Globalization.UnicodeCategory.TitlecaseLetter, System.Globalization.UnicodeCategory.ModifierLetter, or System.Globalization.UnicodeCategory.OtherLetter; otherwise, false.
G H I J K
Exceptions
L M
Exception
Condition
N
System.ArgumentNullException
s is a null reference.
System.ArgumentOutOfRangeException
The value of index is less than zero, or greater than or equal to the length of s.
O P Q R
Example
S
using System;
T
namespace Samples { public class CharIsLetter { public static void Main() { string s = "3Az$"; for(int i = 0; i < s.Length; i++) { if(Char.IsLetter(s, i)) Console.WriteLine("Char '{0}' is letter", s[i]); else
U V W X Y Z
446
Contents | Index
System
Char Structure IsLetterOrDigit() Method
Console.WriteLine("Char '{0}' is not a letter", s[i]); } }
A
} }
B C
The output is
D Char Char Char Char
'3' 'A' 'z' '$'
is is is is
not a letter letter letter not a letter
E F G H
Char.IsLetterOrDigit(System.Char) Method
I
[ILASM]
J
.method public hidebysig static bool IsLetterOrDigit(valuetype System.Char c) [C#]
K
public static bool IsLetterOrDigit(char c)
L
Summary
M
Determines whether the specified Unicode character is either a letter or a decimal digit.
N O
Parameters
P
Parameter
Description
c
A Unicode character.
Q R S T
Return Value
U
true if c is a member of one of the following categories in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.UppercaseLetter, System.Globalization.UnicodeCategory.LowercaseLetter, System.Globalization.UnicodeCategory.TitlecaseLetter, System.Globalization.UnicodeCategory.ModifierLetter, System.Globalization.UnicodeCategory.OtherLetter, or System.Globalization.UnicodeCategory.DecimalDigitNumber; otherwise, false.
V W X Y Z
447
Contents | Index
Char Structure
System
IsLetterOrDigit() Method
Example using System; namespace Samples { public class CharIsLetterOrDigit { public static void Main() { Char[] chars = new Char[] {'3', '-', 'z', '$', Convert.ToChar(0X00BC)}; foreach(Char c in chars) { if(Char.IsLetterOrDigit(c)) Console.WriteLine("Char '{0}' is letter " + "or digit", c); else Console.WriteLine("Char '{0}' is not letter " + "or digit", c); } } } }
A B C D E F G H I J K L M
The output is
N O
Char Char Char Char Char
P Q
'3' '-' 'z' '$' '¼'
is is is is is
letter or digit not letter or digit letter or digit not letter or digit not letter or digit
R S
Char.IsLetterOrDigit(System.String, System.Int32) Method
T
[ILASM]
U
.method public hidebysig static bool IsLetterOrDigit(string s, int32 index)
V
[C#]
public static bool IsLetterOrDigit(string s, int index)
W X
Summary
Y
Determines whether the character at the specified position in the specified System.String is either a letter or a decimal digit.
Z
448
Contents | Index
System
Char Structure IsLetterOrDigit() Method
Parameters Parameter
Description
s
A System.String.
index
A System.Int32 that specifies a character position in s.
A B C D
Return Value
E
true if the character at position index in s is a member of one of the following categories in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.UppercaseLetter, System.Globalization.UnicodeCategory.LowercaseLetter, System.Globalization.UnicodeCategory.TitlecaseLetter, System.Globalization.UnicodeCategory.ModifierLetter, System.Globalization.UnicodeCategory.OtherLetter, or System.Globalization.UnicodeCategory.DecimalDigitNumber; otherwise, false.
F G H I J K
Exceptions
L M
Exception
Condition N
System.ArgumentNullException
s is a null reference.
O
System.ArgumentOutOfRangeException
The value of index is less than zero, or greater than or equal to the length of s.
P Q R
Example
S
using System;
T
namespace Samples { public class CharIsLetterOrDigit { public static void Main() { string s = "3-z$\u00bc"; for(int i = 0; i < s.Length; i++) { if(Char.IsLetterOrDigit(s, i)) Console.WriteLine("Char '{0}' is letter " + "or digit", s[i]);
U V W X Y Z
449
Contents | Index
Char Structure
System
IsLower() Method
else Console.WriteLine("Char '{0}' is not letter " + "or digit", s[i]); }
A
} }
B }
C
The output is
D E
Char Char Char Char Char
F G
'3' '-' 'z' '$' '¼'
is is is is is
letter or digit not letter or digit letter or digit not letter or digit not letter or digit
H I
Char.IsLower(System.Char) Method
J
[ILASM]
K
.method public hidebysig static bool IsLower(valuetype System.Char c)
L
[C#]
public static bool IsLower(char c)
M N
Summary
O
Determines whether the specified Unicode character is a lowercase letter.
P
Parameters
Q R
Parameter
Description
c
A Unicode character.
S T U
Return Value
V
true if c is a member of the following category in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.LowercaseLetter; otherwise, false.
W X Y Z
450
Contents | Index
System
Char Structure IsLower() Method
Example using System; namespace Samples { public class CharIsLower { public static void Main() { Char[] chars = new Char[] {'3', 'A', 'z', '$'}; foreach(Char c in chars) { if(Char.IsLower(c)) Console.WriteLine("Char '{0}' is lower case", c); else Console.WriteLine("Char '{0}' is not lower case", c); } } } }
A B C D E F G H I J K L
The output is Char Char Char Char
'3' 'A' 'z' '$'
is is is is
M
not lower case not lower case lower case not lower case
N O P Q
Char.IsLower(System.String, System.Int32) Method
R
[ILASM]
S
.method public hidebysig static bool IsLower(string s, int32 index)
T
[C#]
public static bool IsLower(string s, int index)
U V
Summary
W
Determines whether the character at the specified position in the specified System.String is a lowercase letter.
X Y Z
451
Contents | Index
Char Structure
System
IsLower() Method
Parameters Parameter
Description
s
A System.String.
index
A System.Int32 that specifies a character position in s.
A B C D
Return Value
E
true if the character at position index in s is a member of the following category in System.Globalization.UnicodeCategory:System.Globalization.UnicodeCategory.LowercaseLetter; otherwise, false.
F G H
Exceptions
I J K
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.ArgumentOutOfRangeException
The value of index is less than zero, or greater than or equal to the length of s.
L M N O
Example
P
using System;
Q
namespace Samples { public class CharIsLower { public static void Main() { string s = "3Az$"; for(int i = 0; i < s.Length; i++) { if(Char.IsLower(s, i)) Console.WriteLine("Char '{0}' is lower case", s[i]); else Console.WriteLine("Char '{0}' is not lower case", s[i]); } } } }
R S T U V W X Y Z
452
Contents | Index
System
Char Structure IsNumber() Method
The output is Char Char Char Char
'3' 'A' 'z' '$'
is is is is
not lower case not lower case lower case not lower case
A B C D
Char.IsNumber(System.Char) Method
E
[ILASM]
.method public hidebysig static bool IsNumber(valuetype System.Char c)
F
[C#]
G
public static bool IsNumber(char c)
H
Summary
I
Determines whether the specified Unicode character is a number.
J K
Parameters
L
Parameter
Description
c
A Unicode character.
M N O
Return Value
P
true if c is a member of one of the following categories in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.DecimalDigitNumber, System.Globalization.UnicodeCategory.LetterNumber, or System.Globalization.UnicodeCategory.OtherNumber; otherwise, false.
Q R S T
Description
U
[Note: System.Char.IsNumber determines if a System.Char is of any numeric Unicode category. This contrasts with System.Char.IsDigit, which determines if a System.Char is a radix-10 digit.]
V W X Y Z
453
Contents | Index
Char Structure
System
IsNumber() Method
Example using System; namespace Samples { public class CharIsNumber { public static void Main() { Char[] chars = new Char[] {'3', 'A', 'z', '$', Convert.ToChar(0X00BC)}; foreach(Char c in chars) { if(Char.IsNumber(c)) Console.WriteLine("Char '{0}' is number", c); else Console.WriteLine("Char '{0}' is not number", c); } } } }
A B C D E F G H I J K L
The output is
M
Char Char Char Char Char
N O P
'3' 'A' 'z' '$' '¼'
is is is is is
number not number not number not number number
Q R
Char.IsNumber(System.String, System.Int32) Method
S [ILASM]
T
.method public hidebysig static bool IsNumber(string s, int32 index)
U
[C#]
public static bool IsNumber(string s, int index)
V W
Summary
X
Determines whether the character at the specified position in the specified System.String is a number.
Y Z
454
Contents | Index
System
Char Structure IsNumber() Method
Parameters Parameter
Description
s
A System.String.
index
A System.Int32 that specifies a character position in s.
A B C D
Return Value
E
true if the character at position index in s is a member of one of the following categories in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.DecimalDigitNumber, System.Globalization.UnicodeCategory.LetterNumber, or System.Globalization.UnicodeCategory.OtherNumber; otherwise, false.
F G H I J
Description
K
[Note: System.Char.IsNumber determines if a System.Char is of any numeric Unicode category. This contrasts with System.Char.IsDigit, which determines if a System.Char is a radix-10 digit.]
L M N
Exceptions
O
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.ArgumentOutOfRangeException
The value of index is less than zero, or greater than or equal to the length of s.
P Q R S T
Example
U
using System;
V W
namespace Samples { public class CharIsNumber { public static void Main() { string s = "3Az$\u00bc"; for(int i = 0; i < s.Length; i++)
X Y Z
455
Contents | Index
Char Structure
System
IsPunctuation() Method
{ if(Char.IsNumber(s, i)) Console.WriteLine("Char '{0}' is a number", s[i]); else Console.WriteLine("Char '{0}' is not a number", s[i]);
A B C
} }
D
} }
E
The output is
F G
Char Char Char Char Char
H I J
'3' 'A' 'z' '$' '¼'
is is is is is
a number not a number not a number not a number a number
K L
Char.IsPunctuation(System.Char) Method
M
[ILASM]
.method public hidebysig static bool IsPunctuation(valuetype System.Char c)
N
[C#]
O
public static bool IsPunctuation(char c)
P
Summary
Q
Determines whether the specified Unicode character is a punctuation mark.
R
Parameters
S T
Parameter
Description
c
A Unicode character.
U V W
Return Value
X
true if c is a member of one of the following categories in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.ConnectorPunctuation, System.Globalization.UnicodeCategory.DashPunctuation, System.Globalization.UnicodeCategory.OpenPunctuation, System.Globalization.UnicodeCategory.ClosePunctuation, System.Glo-
Y Z
456
Contents | Index
System
Char Structure IsPunctuation() Method
balization.UnicodeCategory.InitialQuotePunctuation, System.Globalization.UnicodeCategory.FinalQuotePunctuation, or System.Globalization.UnicodeCategory.OtherPunctuation; otherwise, false. A
Example
B
using System;
C
namespace Samples { public class CharIsPunctuation { public static void Main() { Char[] chars = new Char[] {'3', '!', 'z', '$'}; foreach(Char c in chars) { if(Char.IsPunctuation(c)) Console.WriteLine( "Char '{0}' is punctuation", c); else Console.WriteLine( "Char '{0}' is not a punctuation", c); } } } }
D E F G H I J K L M N O P
The output is Char Char Char Char
'3' '!' 'z' '$'
is is is is
Q
not a punctuation punctuation not a punctuation not a punctuation
R S T
Char.IsPunctuation(System.String, System.Int32) Method
U
[ILASM]
V
.method public hidebysig static bool IsPunctuation(string s, int32 index)
W
[C#]
X
public static bool IsPunctuation(string s, int index)
Y
Summary
Z
Determines whether the character at the specified position in the specified System.String is a punctuation mark.
457
Contents | Index
Char Structure
System
IsPunctuation() Method
Parameters Parameter
Description
s
A System.String.
index
A System.Int32 that specifies a character position in s.
A B C D E
Return Value
F
true if the character at position index in s is a member of one of the following categories in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.ConnectorPunctuation, System.Globalization.UnicodeCategory.DashPunctuation, System.Globalization.UnicodeCategory.OpenPunctuation, System.Globalization.UnicodeCategory.ClosePunctuation, System.Globalization.UnicodeCategory.InitialQuotePunctuation, System.Globalization.UnicodeCategory.FinalQuotePunctuation, or System.Globalization.UnicodeCategory.OtherPunctuation; otherwise, false.
G H I J K L
Exceptions
M N
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.ArgumentOutOfRangeException
The value of index is less than zero, or greater than or equal to the length of s.
O P Q R S
Example
T
using System;
U namespace Samples { public class CharIsPunctuation { public static void Main() { string s = "3!z$"; for(int i = 0; i < s.Length; i++) { if(Char.IsPunctuation(s, i)) Console.WriteLine(
V W X Y Z
458
Contents | Index
System
Char Structure IsSeparator() Method
"Char '{0}' is punctuation mark", s[i]); else Console.WriteLine( "Char '{0}' is not punctuation mark", s[i]);
A B
}
C
} }
D
}
E
The output is
F Char Char Char Char
'3' '!' 'z' '$'
is is is is
not punctuation mark punctuation mark not punctuation mark not punctuation mark
G H I J
Char.IsSeparator(System.Char) Method
K
[ILASM]
L
.method public hidebysig static bool IsSeparator(valuetype System.Char c)
M
[C#]
public static bool IsSeparator(char c)
N
Summary
O
Determines whether the specified Unicode character is a separator character.
P Q
Parameters
R
Parameter
Description
c
A Unicode character.
S T U V
Return Value
W
true if c is a member of one of the following categories in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.SpaceSeparator, System.Globalization.UnicodeCategory.LineSeparator, or System.Globalization.UnicodeCategory.ParagraphSeparator; otherwise, false.
X Y Z
459
Contents | Index
Char Structure
System
IsSeparator() Method
Example using System; namespace Samples { public class CharIsSeparator { public static void Main() { Char[] chars = new Char[] {'3', ' ', '-', '$'}; foreach(Char c in chars) { if(Char.IsSeparator(c)) Console.WriteLine("Char '{0}' is a separator", c); else Console.WriteLine("Char '{0}' is not a separator", c); } } } }
A B C D E F G H I J K L M
The output is
N Char Char Char Char
O P
'3' ' ' '-' '$'
is is is is
not a separator a separator not a separator not a separator
Q R
Char.IsSeparator(System.String, System.Int32) Method
S
[ILASM]
T
.method public hidebysig static bool IsSeparator(string s, int32 index) [C#]
U
public static bool IsSeparator(string s, int index)
V
Summary
W
Determines whether the character at the specified position in the specified System.String is a separator character.
X Y Z
460
Contents | Index
System
Char Structure IsSeparator() Method
Parameters Parameter
Description
s
A System.String.
index
A System.Int32 that specifies a character position in s.
A B C D
Return Value
E
true if the character at position index in s is a member of one of the following categories in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.SpaceSeparator, System.Globalization.UnicodeCategory.LineSeparator, or System.Globalization.UnicodeCategory.ParagraphSeparator; otherwise, false.
F G H I J
Exceptions
K
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.ArgumentOutOfRangeException
The value of index is less than zero, or greater than or equal to the length of s.
L M N O P Q
Example
R
using System;
S
namespace Samples { public class CharIsSeparator { public static void Main() { string s = "3 -$"; for(int i = 0; i < s.Length; i++) { if(Char.IsSeparator(s, i)) Console.WriteLine("Char '{0}' is separator", s[i]); else Console.WriteLine("Char '{0}' is not separator",
T U V W X Y Z
461
Contents | Index
Char Structure
System
IsSurrogate() Method
s[i]); } } }
A
}
B
The output is
C Char Char Char Char
D E
'3' ' ' '-' '$'
is is is is
not separator separator not separator not separator
F G
Char.IsSurrogate(System.Char) Method
H
[ILASM]
I
.method public hidebysig static bool IsSurrogate(valuetype System.Char c) [C#]
J
public static bool IsSurrogate(char c)
K L
Summary
M
Determines whether the specified Unicode character is a surrogate character.
N
Parameters
O P Q
Parameter
Description
c
A Unicode character.
R S
Return Value
T
true if c is a member of the following category in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.Surrogate; otherwise, false.
U V
Example
W
using System;
X namespace Samples { public class CharIsSurrogateSample { public static void Main() {
Y Z
462
Contents | Index
System
Char Structure IsSurrogate() Method
string chars = "3 -$\U00010001"; foreach(Char c in chars) { if(Char.IsSurrogate(c)) Console.WriteLine( "Char with value {0} is a surrogate", (int) c); else Console.WriteLine( "Char with value {0} is not a surrogate", (int) c); }
A B C D E F
} }
G
}
H
The output is Char Char Char Char Char Char
with with with with with with
value value value value value value
I 51 is 32 is 45 is 36 is 55296 56321
not a surrogate not a surrogate not a surrogate not a surrogate is a surrogate is a surrogate
J K L M N O
Char.IsSurrogate(System.String, System.Int32) Method
P
[ILASM]
.method public hidebysig static bool IsSurrogate(string s, int32 index)
Q
[C#]
R
public static bool IsSurrogate(string s, int index)
S
Summary
T
Determines whether the character at the specified position in the specified System.String is a surrogate character.
U V
Parameters
W
Parameter
Description
s
A System.String.
index
A System.Int32 that specifies a character position in s.
X Y Z
463
Contents | Index
Char Structure
System
IsSurrogate() Method
Return Value true if the character at position index in s is a member of the following category in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.Surrogate; otherwise, false.
A B
Exceptions
C D
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.ArgumentOutOfRangeException
The value of index is less than zero, or greater than or equal to the length of s.
E F G H I
Example
J
using System;
K
namespace Samples { public class CharIsSurrogate { public static void Main() { string s = "3 -$\U00010001"; for(int i = 0; i < s.Length; i++) { if(Char.IsSurrogate(s, i)) Console.WriteLine( "Char with value {0} is a surrogate", (int) s[i]); else Console.WriteLine( "Char with value {0} is not a surrogate", (int) s[i]); } } } }
L M N O P Q R S T U V W X
The output is
Y Z
Char with value 51 is not a surrogate Char with value 32 is not a surrogate Char with value 45 is not a surrogate
464
Contents | Index
System
Char Structure IsSymbol() Method
Char with value 36 is not a surrogate Char with value 55296 is a surrogate Char with value 56321 is a surrogate
A B
Char.IsSymbol(System.Char) Method
C
[ILASM]
D
.method public hidebysig static bool IsSymbol(valuetype System.Char c) [C#]
E
public static bool IsSymbol(char c)
F
Summary
G
Determines whether the specified Unicode character is a symbol character.
H I
Parameters
J
Parameter
Description
c
A Unicode character.
K L M
Return Value
N
true if c is a member of one of the following categories in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.MathSymbol, System.Globalization.UnicodeCategory.CurrencySymbol, System.Globalization.UnicodeCategory.ModifierSymbol, or System.Globalization.UnicodeCategory.OtherSymbol; otherwise, false.
O P Q R S
Example
T
using System;
U namespace Samples { public class CharIsSymbol { public static void Main() { Char[] chars = new Char[] {'3', ' ', '+', '$'}; foreach(Char c in chars) { if(Char.IsSymbol(c)) Console.WriteLine("Char '{0}' is symbol", c);
V W X Y Z
465
Contents | Index
Char Structure
System
IsSymbol() Method
else Console.WriteLine("Char '{0}' is not symbol", c); } }
A
} }
B C
The output is
D Char Char Char Char
E F
'3' ' ' '+' '$'
is is is is
not symbol not symbol symbol symbol
G H
Char.IsSymbol(System.String, System.Int32) Method
I [ILASM]
J
.method public hidebysig static bool IsSymbol(string s, int32 index)
K
[C#]
public static bool IsSymbol(string s, int index)
L M
Summary
N
Determines whether the character at the specified position in the specified System.String is a symbol character.
O P
Parameters
Q R S T
Parameter
Description
s
A System.String.
index
A System.Int32 that specifies a character position in s.
U V
Return Value
W
true if the character at position index in s is a member of one of the following categories in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.MathSymbol, System.Globalization.UnicodeCategory.CurrencySymbol, System.Globalization.UnicodeCategory.ModifierSymbol, or System.Globalization.UnicodeCategory.OtherSymbol; otherwise, false.
X Y Z
466
Contents | Index
System
Char Structure IsUpper() Method
Exceptions Exception
Condition
System.ArgumentNullException
s is a null reference.
System.ArgumentOutOfRangeException
The value of index is less than zero, or greater than or equal to the length of s.
A B C D E
Example
F
using System;
G
namespace Samples { public class CharIsSymbol { public static void Main() { string s = "3 +$"; for(int i = 0; i < s.Length; i++) { if(Char.IsSymbol(s, i)) Console.WriteLine("Char '{0}' is symbol", s[i]); else Console.WriteLine("Char '{0}' is not symbol", s[i]); } } } }
H I J K L M N O P Q R S
The output is Char Char Char Char
'3' ' ' '+' '$'
is is is is
T
not symbol not symbol symbol symbol
U V W X
Char.IsUpper(System.Char) Method
Y
[ILASM]
Z
.method public hidebysig static bool IsUpper(valuetype System.Char c) [C#]
public static bool IsUpper(char c)
467
Contents | Index
Char Structure
System
IsUpper() Method
Summary Determines whether the specified Unicode character is an uppercase letter. A
Parameters
B C
Parameter
Description
D
c
A Unicode character.
E F
Return Value
G
true if c is a member of the following category in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.UppercaseLetter; otherwise, false.
H I J
Example
K
using System;
L
namespace Samples { public class CharIsUpper { public static void Main() { Char[] chars = new Char[] {'3', 'A', 'z', '$'}; foreach(Char c in chars) { if(Char.IsUpper(c)) Console.WriteLine("Char '{0}' is upper case", c); else Console.WriteLine("Char '{0}' is not upper case", c); } } } }
M N O P Q R S T U V W
The output is
X Y
Char Char Char Char
Z
'3' 'A' 'z' '$'
is is is is
not upper case upper case not upper case not upper case
468
Contents | Index
System
Char Structure IsUpper() Method
Char.IsUpper(System.String, System.Int32) Method [ILASM]
.method public hidebysig static bool IsUpper(string s, int32 index) [C#]
A
public static bool IsUpper(string s, int index)
B C
Summary
D
Determines whether the character at the specified position in the specified System.String is an uppercase letter.
E F
Parameters
G H
Parameter
Description
s
A System.String.
index
A System.Int32 that specifies a character position in s.
I J K L
Return Value
M
true if the character at position index in s is a member of the following category in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.UppercaseLetter; otherwise, false.
N O P
Exceptions
Q
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.ArgumentOutOfRangeException
The value of index is less than zero, or greater than or equal to the length of s.
R S T U V W X Y Z
469
Contents | Index
Char Structure
System
IsWhiteSpace() Method
Example using System; namespace Samples { public class CharIsUpper { public static void Main() { string s = "3Az$"; for(int i = 0; i < s.Length; i++) { if(Char.IsUpper(s, i)) Console.WriteLine("Char '{0}' is upper case", s[i]); else Console.WriteLine("Char '{0}' is not upper case", s[i]); } } } }
A B C D E F G H I J K L M
The output is
N Char Char Char Char
O P
'3' 'A' 'z' '$'
is is is is
not upper case upper case not upper case not upper case
Q R
Char.IsWhiteSpace(System.Char) Method
S [ILASM]
T
.method public hidebysig static bool IsWhiteSpace(valuetype System.Char c)
U
[C#]
public static bool IsWhiteSpace(char c)
V W
Summary
X
Determines whether the specified Unicode character is a whitespace character.
Y Z
470
Contents | Index
System
Char Structure IsWhiteSpace() Method
Parameters Parameter
Description
c
A Unicode character.
A B C
Return Value
D
true if c either has a code point of 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x0085, 0x2028, or 0x2029; or is a member of the following category in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.SpaceSeparator; otherwise, false.
E F G H
Example
I
using System;
J namespace Samples { public class CharIsWhiteSpace { public static void Main() { Char[] chars = new Char[] {'3', ' ', 'z', '\t'}; foreach(Char c in chars) { if(Char.IsWhiteSpace(c)) Console.WriteLine("Char '{0}' is white space", c); else Console.WriteLine("Char '{0}' is not white space", c); } } } }
K L M N O P Q R S T U V
The output is Char Char Char Char
'3' ' ' 'z' ' '
is is is is
W
not white space white space not white space white space
X Y Z
471
Contents | Index
Char Structure
System
IsWhiteSpace() Method
Char.IsWhiteSpace(System.String, System.Int32) Method [ILASM]
.method public hidebysig static bool IsWhiteSpace(string s, int32 index)
A
[C#]
public static bool IsWhiteSpace(string s, int index)
B C
Summary
D
Determines whether the character at the specified position in the specified System.String is a whitespace character.
E F
Parameters
G H
Parameter
Description
s
A System.String.
index
A System.Int32 that specifies a character position in s.
I J K L
Return Value
M
true if the character at position index in s either has a code point of 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x0085, 0x2028, or 0x2029; or is a member of the following category in System.Globalization.UnicodeCategory: System.Globalization.UnicodeCategory.SpaceSeparator; otherwise, false.
N O P Q
Exceptions
R S T
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.ArgumentOutOfRangeException
The value of index is less than zero, or greater than or equal to the length of s.
U V W X Y Z
472
Contents | Index
System
Char Structure Parse() Method
Example using System; namespace Samples { public class CharIsWhiteSpace { public static void Main() { string s = "3 z\t"; for(int i = 0; i < s.Length; i++) { if(Char.IsWhiteSpace(s, i)) Console.WriteLine("Char '{0}' is white space", s[i]); else Console.WriteLine("Char '{0}' is not white space", s[i]); } } } }
A B C D E F G H I J K L
The output is Char Char Char Char
'3' ' ' 'z' ' '
is is is is
M
not white space white space not white space white space
N O P Q
Char.Parse(System.String) Method
R [ILASM]
S
.method public hidebysig static valuetype System.Char Parse(string s) [C#]
T
public static char Parse(string s)
U
Summary
V
Returns the specified System.String converted to a System.Char value.
W X
Parameters
Y
Parameter
Description
s
A System.String containing a single Unicode character.
Z
473
Contents | Index
Char Structure
System
Parse() Method
Exceptions Exception
Condition
B
System.ArgumentNullException
s is a null reference.
C
System.FormatException
s does not contain exactly one character.
A
D E
Example
F
using System;
G
namespace Samples { public class CharParse { public static void Main() { try { Char c = Char.Parse("A"); Console.WriteLine("c is {0}", c = Char.Parse("\u00bc"); Console.WriteLine("c is {0}", c = Char.Parse("42"); Console.WriteLine("c is {0}", } catch(FormatException e) { Console.WriteLine("Exception: } } } }
H I J K L M N O P Q R S T U
c); c); c);
{0}", e);
The output is
V c is A c is ¼ Exception: System.FormatException: String must be only one character long. at System.Char.Parse(String s) at Samples.CharParse.Main() in C:\Books\BCL\Samples\System\Char\ Parse(System.String)\Char.cs:line 15
W X Y Z
474
Contents | Index
System
Char Structure ToLower() Method
Char.ToLower(System.Char) Method [ILASM]
.method public hidebysig static valuetype System.Char ToLower(valuetype System.Char c)
A
[C#]
B
public static char ToLower(char c)
C
Summary
D
Converts a System.Char to its lowercase equivalent.
E F
Parameters
G
Parameter
Description
c
A Unicode character.
H I J K
Return Value
L
The lowercase equivalent of c, or the value of c if and only if c is already lowercase or does not have a lowercase equivalent.
M N
Example
O
using System;
P namespace Samples { public class CharToLower { public static void Main() { Char[] chars = new Char[] {'3', 'A', 'Z', '$'}; foreach(Char c in chars) { Console.WriteLine("Char '{0}' as lower case is: {1}", c, Char.ToLower(c)); } } } }
Q R S T U V W X Y Z
475
Contents | Index
Char Structure
System
ToLower() Method
The output is Char Char Char Char
A B
'3' 'A' 'Z' '$'
as as as as
lower lower lower lower
case case case case
is: is: is: is:
3 a z $
C D
Char.ToLower(System.Char, System.Globalization.CultureInfo) Method
E [ILASM]
F
.method public hidebysig static valuetype System.Char ToLower(valuetype System.Char c, class System.Globalization.CultureInfo culture)
G
[C#]
H
public static char ToLower(char c, CultureInfo culture)
I
Summary
J
Converts the value of a specified Unicode character to its lowercase equivalent using specified culture-specific formatting information.
K L
Parameters
M N
Parameter
Description
c
A Unicode character.
culture
A System.Globalization.CultureInfo object that supplies culturespecific casing rules, or null.
O P Q R S
Return Value
T
The lowercase equivalent of c, modified according to culture or the unchanged value of c, if c is already lowercase or not alphabetic.
U V
Description
W
Use System.String.ToLower to convert a string to lowercase.
X Y Z
476
Contents | Index
System
Char Structure ToString() Method
Exceptions Exception
Condition
System.ArgumentNullException
culture is null.
A B C D
Char.ToString() Method
E
[ILASM]
F
.method public hidebysig virtual string ToString() [C#]
G
public override string ToString()
H
Summary
I
Returns a System.String representation of the value of the current instance.
J
Description
K
[Note: This method overrides System.Object.ToString.]
L M
Example
N
using System;
O namespace Samples { public class CharToString { public static void Main() { Char c = Convert.ToChar(65); Console.WriteLine(c.ToString()); c = Convert.ToChar(97); Console.WriteLine(c.ToString()); c = Convert.ToChar(0X00BC); Console.WriteLine(c.ToString()); } } }
P Q R S T U V W X Y
The output is
Z A a ¼
477
Contents | Index
Char Structure
System
ToString() Method
Char.ToString(System.Char) Method [ILASM]
.method public hidebysig static string ToString(valuetype System.Char c)
A
[C#]
public static string ToString(char c)
B C
Summary
D
Converts the specified Unicode character to its equivalent string representation.
E
Parameters
F G
Parameter
Description
c
A Unicode character.
H I J K
Char.ToString(System.IFormatProvider) Method
L
[ILASM]
M
.method public final hidebysig virtual string ToString(class System.IFormatProvider provider)
N
[C#]
O
public string ToString(IFormatProvider provider)
P
Summary
Q
Converts the value of this instance to its equivalent String representation using the specified culture-specific format information.
R S
Parameters
T U
Parameter
Description
provider
(Reserved) A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
V W X Y
Description
Z
provider is ignored; it does not participate in this operation.
478
Contents | Index
System
Char Structure ToUpper() Method
Example using System; using System.Globalization;
A namespace Samples { public class CharToString { public static void Main() { Char c = Convert.ToChar(65); Console.WriteLine(c.ToString( new CultureInfo("en-AU"))); Console.WriteLine(c.ToString( new CultureInfo("fr-FR"))); Console.WriteLine(c.ToString( new CultureInfo("de-AT"))); } } }
B C D E F G H I J K
The output is
L M
A A A
N O P
Char.ToUpper(System.Char) Method
Q [ILASM]
R
.method public hidebysig static valuetype System.Char ToUpper(valuetype System.Char c)
S
[C#]
T
public static char ToUpper(char c)
U
Summary
V
Converts a System.Char to its uppercase equivalent.
W
Parameters
X Y
Parameter
Description Z
c
A Unicode character.
479
Contents | Index
Char Structure
System
ToUpper() Method
Return Value The uppercase equivalent of c, or the value of c if and only if c is already uppercase or does not have an uppercase equivalent. A B
Example
C
using System;
D
namespace Samples { public class CharToUpper { public static void Main() { Char[] chars = new Char[] {'3', 'a', 'z', '$'}; foreach(Char c in chars) { Console.WriteLine("Char '{0}' as upper case is: {1}", c, Char.ToUpper(c)); } } } }
E F G H I J K L M
The output is
N O
Char Char Char Char
P Q
'3' 'a' 'z' '$'
as as as as
upper upper upper upper
case case case case
is: is: is: is:
3 A Z $
R S
Char.ToUpper(System.Char, System.Globalization.CultureInfo) Method
T
[ILASM]
.method public hidebysig static valuetype System.Char ToUpper(valuetype System.Char c, class System.Globalization.CultureInfo culture)
U V
[C#]
public static char ToUpper(char c, CultureInfo culture)
W X
Summary
Y
Converts the value of a specified Unicode character to its uppercase equivalent using specified culture-specific formatting information.
Z
480
Contents | Index
System
Char Structure ToBoolean() Method
Parameters Parameter
Description
c
A Unicode character.
culture
A System.Globalization.CultureInfo object that supplies culturespecific casing rules, or null.
A B C D E
Return Value
F
The uppercase equivalent of c, modified according to culture or the unchanged value of c, if c is already uppercase or not alphabetic.
G H
Description
I
Use System.String.ToUpper to convert a string to uppercase.
J K
Exceptions
L
Exception
Condition
M
System.ArgumentNullException
culture is null.
N O P
IConvertible.ToBoolean(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual bool System.IConvertible.ToBoolean(class System.IFormatProvider provider)
S
[C#]
T
bool IConvertible.ToBoolean(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToBoolean.]
W X Y Z
481
Contents | Index
Char Structure
System
ToByte() Method
IConvertible.ToByte(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual unsigned int8 System.IConvertible.ToByte(class System.IFormatProvider provider)
B
[C#]
byte IConvertible.ToByte(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToByte.]
F G H
IConvertible.ToChar(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual valuetype System.Char System.IConvertible.ToChar(class System.IFormatProvider provider)
K
[C#]
char IConvertible.ToChar(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToChar.]
O P Q
IConvertible.ToDateTime(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual valuetype System.DateTime System.IConvertible.ToDateTime(class System.IFormatProvider provider)
T
[C#]
DateTime IConvertible.ToDateTime(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDateTime.]
X Y Z
482
Contents | Index
System
Char Structure ToInt16() Method
IConvertible.ToDecimal(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual decimal System.IConvertible.ToDecimal(class System.IFormatProvider provider)
A
[C#]
B
decimal IConvertible.ToDecimal(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDecimal.]
E F G
IConvertible.ToDouble(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual float64 System.IConvertible.ToDouble(class System.IFormatProvider provider)
J
[C#]
K
double IConvertible.ToDouble(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDouble.]
N O P
IConvertible.ToInt16(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual int16 System.IConvertible.ToInt16(class System.IFormatProvider provider)
S
[C#]
T
short IConvertible.ToInt16(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt16.]
W X Y Z
483
Contents | Index
Char Structure
System
ToInt32() Method
IConvertible.ToInt32(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual int32 System.IConvertible.ToInt32(class System.IFormatProvider provider)
B
[C#]
int IConvertible.ToInt32(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt32.]
F G H
IConvertible.ToInt64(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual int64 System.IConvertible.ToInt64(class System.IFormatProvider provider)
K
[C#]
long IConvertible.ToInt64(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt64.]
O P Q
IConvertible.ToSByte(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual int8 System.IConvertible.ToSByte(class System.IFormatProvider provider)
T
[C#]
sbyte IConvertible.ToSByte(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSByte.]
X Y Z
484
Contents | Index
System
Char Structure ToUInt16() Method
IConvertible.ToSingle(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual float32 System.IConvertible.ToSingle(class System.IFormatProvider provider)
A
[C#]
B
float IConvertible.ToSingle(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSingle.]
E F G
IConvertible.ToType(System.Type, System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual object System.IConvertible.ToType(class System.Type type, class System.IFormatProvider provider)
J
[C#]
K
object IConvertible.ToType(Type type, IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToType.]
N O P
IConvertible.ToUInt16(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual unsigned int16 System.IConvertible.ToUInt16(class System.IFormatProvider provider)
S
[C#]
T
ushort IConvertible.ToUInt16(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt16.] This member is not CLS-compliant.
W X Y Z
485
Contents | Index
Char Structure
System
ToUInt32() Method
IConvertible.ToUInt32(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual unsigned int32 System.IConvertible.ToUInt32(class System.IFormatProvider provider)
B
[C#]
uint IConvertible.ToUInt32(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt32.] This member is not CLS-compliant.
F G H
IConvertible.ToUInt64(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual unsigned int64 System.IConvertible.ToUInt64(class System.IFormatProvider provider)
K
[C#]
ulong IConvertible.ToUInt64(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt64.] This member is not CLS-compliant.
O P Q R S T U V W X Y Z
486
Contents | Index
System CharEnumerator
BCL
Object IEnumerator
A
CharEnumerator ICloneable
B
Summary
C
Supports iteration over and provides read-only access to the individual characters in a System.String.
D E F
Type Summary
G
public sealed class CharEnumerator : IEnumerator, ICloneable { // Properties public char Current { get; }
H I J
// Methods public object Clone (); public bool MoveNext (); public void Reset ();
K L M
// Explicit Interface Members object IEnumerator.Current { get; }
N O
}
P Q
BA Our reason for adding this class to the BCL was not that we felt there was a
R
huge demand for enumerating characters. It was required to enable efficient support for applying foreach over strings. Simply using IEnumerator would have caused a boxing operation for each character accessed out of the string.
S T
string s = “John Smith”; foreach (char c in s) { Console.WriteLine (“{0}-”, c); }
U V W
A side note on this is that the C# compiler now does not even use this class. It specialcases foreach over strings and generates very efficient code for accessing a string that not only avoids the boxing operation, but is also as good as you could do with a
X Y Z
continued
487
Contents | Index
CharEnumerator
System
CharEnumerator Class
for loop. In particular it does not pay the cost of another allocation for the enumerator, and takes full advantage of JIT optimizations. A
This is a classic example of why explicit method implementation is such an important feature. Notice that we have both:
B C
object IEnumerator.Current { get; } public char Current { get; }
D E
We needed to have Current property return Object to satisfy the IEnumerator interface. But we also wanted to have a Current property that returned a char such that usage of this type would not force a boxing operation for each access and to make usage easier (no ugly casts). However in C# (and the CLS) it is not possible to differ only by return type. So we explicitly implement the Object version such that the property is only there when cast to the interface.
F G H I
BG The key point to understand about private interface implementation (using the C# terminology although it is more properly a subset of the CLI feature we call methodimpls) is that it allows you to override an interface method based on its return type. While it also allows you to provide different method implementations for two different versions of a method coming from different interfaces, in practice most people try to avoid problems like this. Multiple inheritance of interfaces, but not classes, seems to make the classic diamond inheritance pattern rarer, or at least significantly less confusing.
J K L M N O P
Description
Q
[Note: System.CharEnumerator is used to support the foreach statement of the C# programming language. Several independent instances of System.CharEnumerator across one or more threads can have access to a single instance of System.String. For more information regarding the use of an enumerator, see System.Collections.IEnumerator.]
R S T U
Example
V
using System;
W
namespace Samples { public class CharEnumeratorSample { public static void Main() { string s = "Hello world!";
X Y Z
488
Contents | Index
System
CharEnumerator Clone() Method
CharEnumerator e = s.GetEnumerator(); while(e.MoveNext()) Console.Write(e.Current); Console.WriteLine();
A
} }
B
}
C
The output is
D E
Hello world!
F G
CharEnumerator.Current Property
H
[ILASM]
I
.property valuetype System.Char Current { public hidebysig specialname instance valuetype System.Char get_Current() }
J
[C#]
public char Current { get; }
K L
Summary
M
Gets the element in the System.String over which the current instance is positioned.
N
Exceptions
O
Exception
Condition
System.InvalidOperationException
The current instance is positioned before the first element or after the last element of the System.String.
P Q R S T
CharEnumerator.Clone() Method
U
[ILASM]
V
.method public final hidebysig virtual object Clone()
W
[C#]
X
public object Clone()
Y
Summary
Z
Creates a copy of the current instance.
489
Contents | Index
CharEnumerator
System
Clone() Method
Return Value A System.Object with the same state as the current instance. A
Description
B
The return value is a System.Object containing a copy of the state of the current instance when this method is invoked. This System.Object must be cast explicitly to a System.CharEnumerator to be made usable as one. [Note: This method is useful for saving the state of a System.CharEnumerator object while iterating through the characters of a System.String. This method is implemented to support the System.ICloneable interface.]
C D E F G
Example
H
using System;
I
namespace Samples { public class CharEnumeratorClone { public static void Main() { string s = "Hello world!"; CharEnumerator ce1 = s.GetEnumerator(); CharEnumerator ce2 = (CharEnumerator) ce1.Clone(); Display(ce1); Display(ce2); } public static void Display(CharEnumerator e) { while(e.MoveNext()) Console.Write(e.Current); Console.WriteLine(); } } }
J K L M N O P Q R S T U V
The output is
W Hello world! Hello world!
X Y Z
490
Contents | Index
System
CharEnumerator Reset() Method
CharEnumerator.MoveNext() Method [ILASM]
.method public final hidebysig virtual bool MoveNext() [C#]
A
public bool MoveNext()
B C
Summary
D
Advances the current instance to the next element of the System.String if and only if the current instance is not already placed beyond the final element of the System.String.
E F
Return Value
G
true if the enumerator was successfully advanced to the next element; otherwise, false.
H
Description
I
If the enumerator is positioned after the final element of the System.String when this method is called, the current instance remains in its current position and false is returned.
J K L
CharEnumerator.Reset() Method
M
[ILASM]
N
.method public final hidebysig virtual void Reset()
O
[C#]
public void Reset()
P Q
Summary
R
Repositions the current instance to its initial position, immediately before the first character in the System.String.
S T
Example
U
using System;
V namespace Samples { public class CharEnumeratorReset { public static void Main() { string s = "Hello world!"; CharEnumerator e = s.GetEnumerator(); Display(e);
W X Y Z
491
Contents | Index
CharEnumerator
System
Current Property
e.Reset(); Display(e); } public static void Display(CharEnumerator e) { while(e.MoveNext()) Console.Write(e.Current); Console.WriteLine(); }
A B C D
} }
E F
The output is
G Hello world! Hello world!
H I J
IEnumerator.Current Property
K [ILASM]
L
.property object IEnumerator.Current { public hidebysig virtual abstract specialname object IEnumerator.get_Current() }
M
[C#]
object IEnumerator.Current { get; }
N O
Summary
P
Implemented to support the System.Collections.IEnumerator interface. [Note: For more information, see System.Collections.IEnumerator.Current.]
Q R S T U V W X Y Z
492
Contents | Index
System CLSCompliantAttribute
BCL
Object
A
Attribute
B
CLSCompliantAttribute
C
Summary
D
Indicates whether the target of the current attribute complies with the Common Language Specification (CLS).
E F
Type Summary
G
public sealed class CLSCompliantAttribute : Attribute { // Constructors public CLSCompliantAttribute (bool isCompliant);
H I J
// Properties public bool IsCompliant { get; }
K
}
L M
BA Unfortunately, we codified the naming convention for acronyms too late to
N
fix this one. It should have been ClsCompliantAttribute rather than CLSCompliantAttribute.
O P
Notice that this attribute is just a marker intended for compilers to enforce. The runtime does enforce any CLS-compliance rules.
Q R
JR Note that the CLS only applies to publicly exposed members so compilers generally
S
only check CLS-compliance of types and members that are exposed outside of an assembly. Internal types and private methods, for example, are not checked for CLS compliance.
T U
Description
V
If no System.CLSCompliantAttribute is associated with a given assembly, that assembly is assumed not to be CLS-compliant. A type is assumed to be CLS-compliant if and only if its enclosing type (for nested types) or assembly (for top-level types) is CLS-compliant. Other members (methods, fields, properties, and events) are CLS-compliant if and only if the type in which they are defined is CLS-compliant.
W X Y Z
493
Contents | Index
CLSCompliantAttribute
System
CLSCompliantAttribute Class
[Note: The CLS is a subset of CLI features that is supported by a broad set of compliant languages and tools. CLS-compliant languages and tools are guaranteed to interoperate with other CLS-compliant languages and tools. Because the CLS defines the rules for language interoperability, its rules apply only to “externally visible” items. The CLS assumes that language interoperability is important only across the assembly boundary — that is, within a single assembly there are no restrictions as to the programming techniques that are used. Thus, the CLS rules apply only to items that are visible outside of their defining assembly and have public, family, or family-or-assembly accessibility. For more information on CLScompliance, see Partition I of the CLI Specification. This attribute can be applied to any valid attribute target. For a complete list of valid targets, see System.AttributeTargets.]
A B C D E F G
Example
H
using System;
I
[assembly: CLSCompliant(true)]
J
namespace Samples { public class CLSCompliantSample { public static void Main() { } public static uint Method1(uint i) { return i; } } }
K L M N O P Q R
The compiler output is
S
Microsoft (R) Program Maintenance Utility Version 7.00.9466 Copyright (C) Microsoft Corporation. All rights reserved.
T U
csc /debug CLSCompliantAttribute.cs Microsoft (R) Visual C# .NET Compiler version 7.00.9466 for Microsoft (R) .NET Framework version 1.0.3705 Copyright (C) Microsoft Corporation 2001. All rights reserved.
V W X
CLSCompliantAttribute.cs(12,32): error CS3001: Argument type 'uint' is not CLS-compliant CLSCompliantAttribute.cs(12,19): error CS3002: Return type of 'Samples.CLSCompliantSample.Method1(uint)' is not CLS-compliant NMAKE : fatal error U1077: 'csc' : return code '0x1' Stop.
Y Z
494
Contents | Index
System
CLSCompliantAttribute IsCompliant Property
CLSCompliantAttribute(System.Boolean) Constructor [ILASM]
public rtspecialname specialname instance void .ctor(bool isCompliant) [C#]
A
public CLSCompliantAttribute(bool isCompliant)
B C
Summary
D
Constructs and initializes a new instance of the System.CLSCompliantAttribute class.
E F
Parameters
G
Parameter
Description
isCompliant
true if the target of the new instance complies with the CLS; otherwise, false.
H I J K L
CLSCompliantAttribute.IsCompliant Property
M
[ILASM]
N
.property bool IsCompliant { public hidebysig specialname instance bool get_IsCompliant() } [C#]
O
public bool IsCompliant { get; }
P Q
Summary
R
Gets a System.Boolean indicating whether the target of the current instance is CLScompliant.
S T
Property Value
U
true if the target of the current instance complies with the CLS; otherwise, false.
V W X Y Z
495
Contents | Index
System.Security CodeAccessPermission
BCL
IPermission
A
ISecurityEncodable
Object
B
CodeAccessPermission
IStackWalk
NotStandardized
NotStandardized
C
EnvironmentPermission
IUnrestrictedPermission
D
FileIOPermission
IUnrestrictedPermission
E
SecurityPermission
IUnrestrictedPermission
NotStandardized
NotStandardized
NotStandardized
F
Summary
G
Serves as the base class for all code access permissions.
H
Type Summary
I
CF public abstract class CodeAccessPermission : IPermission, ISecurityEncodable, IStackWalk { // Constructors CF protected CodeAccessPermission ();
J K L M N O P Q R S
MS MS MS MS MS
T U V W
// CF CF CF CF CF CF CF CF CF CF CF CF CF CF CF
Methods public void Assert (); public abstract IPermission Copy (); public void Demand (); public void Deny (); public abstract void FromXml (SecurityElement elem); public abstract IPermission Intersect (IPermission target); public abstract bool IsSubsetOf (IPermission target); public void PermitOnly (); public static void RevertAll (); public static void RevertAssert (); public static void RevertDeny (); public static void RevertPermitOnly (); public override string ToString (); public abstract SecurityElement ToXml (); public virtual IPermission Union (IPermission other);
}
X Y Z
496
Contents | Index
System.Security
CodeAccessPermission CodeAccessPermission Class
BA Notice the use of SecurityElement in this class. We did not use System.Xml.XmlElement because it is defined in a different assembly, and the base MSCorlib assembly is not allowed to make references to any other assembly.
A
AH Our basic XML APIs should have been in mscorlib from day one. XML is core to
B
almost everything we do in the platform and not being able to use them in the lowest level of the library has been a problem.
C D E
Description
F
[Note: Classes derived from System.Security.CodeAccessPermission are required to override the following methods of the System.Security.CodeAccessPermission class. In addition, classes derived from System.Security.CodeAccessPermission are required to implement a constructor that takes a System.Security.Permissions.PermissionState as its only parameter.] The XML encoding of a System.Security.CodeAccessPermission instance is defined below in EBNF format. The following conventions are used: • • •
• • • •
G H I J K L
All non-literals in the grammar below are shown in normal type. All literals are in bold font. The following meta-language symbols are used: – ’*’ represents a meta-language symbol suffixing an expression that can appear zero or more times. – ’?’ represents a meta-language symbol suffixing an expression that can appear zero or one time. – ’+’ represents a meta-language symbol suffixing an expression that can appear one or more times. – ’(’,’)’ is used to group literals, non-literals, or a mixture of literals and non-literals. – ’|’ denotes an exclusive disjunction between two expressions. – ’::= ’ denotes a production rule where a left-hand non-literal is replaced by a righthand expression containing literals, non-literals, or both. ClassName is the name of the class implementing the permission, such as System.Security.Permissions.EnvironmentPermission. AssemblyName is the name of the assembly that contains the class implementing the permission, such as mscorlib. Version is the three-part version number indicating the version of the assembly implementing the permission, such as 1.0.1. StrongNamePublicKeyToken is the strong name public key token constituting the strong name of the assembly that implements the permission.
M N O P Q R S T U V W X Y Z
497
Contents | Index
CodeAccessPermission
System.Security
CodeAccessPermission Class
•
A
•
B
PermissionAttributes is any attribute and attribute value on the System.Security.IPermission element used by the permission to represent a particular permission state, for example, unrestricted “true”. PermissionXML is any valid XML used by the permission to represent permission state.
The XML encoding of a System.Security.CodeAccessPermission instance is as follows:
C D
CodeAccessPermissionXML::= (PermissionXML)?
E F G H I J K L
Example
M
CodeAccessPermission is an abstract class, see derived classes for more examples.
N
using System; using System.Security; using System.Security.Permissions;
O P Q
namespace Samples { public class CodeAccessPermissionSample { public static void Main() { string ev = "USERNAME"; EnvironmentPermission p = new EnvironmentPermission( EnvironmentPermissionAccess.Read, ev); p.Assert(); TestAccess(ev); CodeAccessPermission.RevertAssert(); p.Deny(); TestAccess(ev); CodeAccessPermission.RevertDeny(); p.PermitOnly();
R S T U V W X Y Z
498
Contents | Index
System.Security
CodeAccessPermission Assert() Method
TestAccess(ev); } public static void TestAccess(string s) { try { Console.WriteLine("Variable {0} Value: {1}", s, Environment.GetEnvironmentVariable(s)); } catch(Exception) { Console.WriteLine("Variable {0} cannot be read", s); } }
A B C D E F G
}
H
}
I
The output is
J Variable USERNAME Value: damien Variable USERNAME cannot be read Variable USERNAME Value: damien
K L M
CodeAccessPermission() Constructor
N
[ILASM]
O
family specialname instance void .ctor()
P
[C#]
protected CodeAccessPermission()
Q R
Summary
S
Constructs a new instance of the System.Security.CodeAccessPermission class.
T U
CodeAccessPermission.Assert() Method
V
[ILASM]
W
.method public final hidebysig virtual void Assert()
X
[C#]
public void Assert()
Y Z
499
Contents | Index
CodeAccessPermission
System.Security
Assert() Method
Summary Asserts that calling code can access the resource identified by the current instance through the code that calls this method, even if callers have not been granted permission to access the resource.
A B
Description
C
Calling System.Security.CodeAccessPermission.Assert stops the permission check on callers that are after the code performing the assert. An assertion is effective only if the code that calls System.Security.CodeAccessPermission.Assert passes the security check for the permission that it is asserting. [Note: Even if the callers that are after the code performing the assert do not have the requisite permissions, they can still access resources through the code that calls this method. Because the assertion only applies to the callers of the code performing the assert, a security check for the asserted permission may still fail if the code calling System.Security.CodeAccessPermission.Assert has not itself been granted that permission. A call to System.Security.CodeAccessPermission.Assert is effective until the code containing the call returns to its caller. Caution: Because calling System.Security.CodeAccessPermission.Assert removes the requirement that all code be granted permission to access the specified resource, it can open up security vulnerabilities if used incorrectly or inappropriately.]
D E F G H I J K L M N
Exceptions
O P
Exception
Condition
System.Security.SecurityException
The calling code does not have System.Security.Permissions.SecurityPermissionFlag.Assertion.
Q R S T
Permissions
U V
Permission
Description
System.Security.Permissions.SecurityPermission
Requires permission to call System.Security.CodeAccessPermission.Assert. See System.Security.Permissions.SecurityPermissionFlag.Assertion.
W X Y Z
500
Contents | Index
System.Security
CodeAccessPermission Demand() Method
CodeAccessPermission.Copy() Method [ILASM]
.method public hidebysig virtual abstract class System.Security.IPermission Copy() [C#]
A
public abstract IPermission Copy()
B C
Summary
D
Returns a System.Security.CodeAccessPermission containing the same values as the current instance.
E F
Description
G
[Note: This method is implemented to support the System.Security.IPermission interface.]
H I
Behaviors
J
The object returned by this method is required to be the same type as the current instance and to represent the same access to resources as the current instance.
K L
How and When to Override
M
Override this method to create a copy of an instance in a type derived from System.Security.CodeAccessPermission.
N O
Usage
P
Use this method to obtain a copy of the current instance that has values identical to those of the current instance.
Q R S
CodeAccessPermission.Demand() Method
T
[ILASM]
U
.method public final hidebysig virtual void Demand()
V
[C#]
public void Demand()
W X
Summary
Y
Forces a System.Security.SecurityException if all callers do not have the permission specified by the current instance.
Z
501
Contents | Index
CodeAccessPermission
System.Security
Deny() Method
Description The permissions of the code that calls this method are not examined; the check begins from the immediate caller of that code and continues until all callers have been checked, one of the callers invokes System.Security.CodeAccessPermission.Assert, or a caller has been found that is not granted the demanded permission, in which case a System.Security.SecurityException is thrown. [Note: System.Security.CodeAccessPermission.Demand is typically used by shared libraries to ensure that callers have permission to access a resource. For example, a method in a shared library calls System.Security.CodeAccessPermission.Demand for the necessary System.Security.Permissions.FileIOPermission before performing a file operation requested by the caller. This method is implemented to support the System.Security.IPermission interface.]
A B C D E F G H
Exceptions
I J
Exception
K
Condition A caller does not have the permission specified by the current instance.
L
System.Security.SecurityException
M N
A caller has called System.Security.CodeAccessPermission.Deny for the resource protected by the current instance.
O P
CodeAccessPermission.Deny() Method
Q R
[ILASM]
S
[C#]
.method public final hidebysig virtual void Deny() public void Deny()
T U
Summary
V
Denies access to the resources specified by the current instance through the code that calls this method.
W X
Description
Y
This method prevents callers from accessing the protected resource through the code that calls this method, even if those callers have been granted permission to access it. The call to System.Security.CodeAccessPermission.Deny is effective until the calling code returns.
Z
502
Contents | Index
System.Security
CodeAccessPermission FromXml() Method
[Note: System.Security.CodeAccessPermission.Deny is ignored for a permission not granted because a demand for that permission will not succeed. System.Security.CodeAccessPermission.Deny can limit the liability of the programmer or prevent accidental security vulnerabilities because it prevents the method that calls System.Security.CodeAccessPermission.Deny from being used to access the resource protected by the denied permission.]
A B C D
CodeAccessPermission.FromXml(System.Security.SecurityElement) Method
E
[ILASM]
F
.method public hidebysig virtual abstract void FromXml(class System.Security.SecurityElement elem)
G
[C#]
H
public abstract void FromXml(SecurityElement elem)
I
Summary
J
Reconstructs the state of a System.Security.CodeAccessPermission object using the specified XML encoding.
K L
Parameters
M N
Parameter
Description
elem
A System.Security.SecurityElement instance containing the XML encoding to use to reconstruct the state of a System.Security.CodeAccessPermission object.
O P Q R
Behaviors
S
The values of the current instance are set to the values of the permission object encoded in elem.
T U V
How and When to Override
W
Override this method to reconstruct subclasses of System.Security.CodeAccessPermission.
X Y
Usage
Z
This method is called by the system.
503
Contents | Index
CodeAccessPermission
System.Security
Intersect() Method
[Note: For the XML encoding for this class, see the System.Security.CodeAccessPermission class page.] A
Exceptions
B C
Exception
Condition
System.ArgumentException
elem does not contain the XML encoding for an instance of the same type as the current instance.
D E
The version number of elem is not valid.
F G H
CodeAccessPermission.Intersect(System.Security.IPermission) Method
I
[ILASM]
J
.method public hidebysig virtual abstract class System.Security.IPermission Intersect(class System.Security.IPermission target)
K
[C#]
public abstract IPermission Intersect(IPermission target)
L M
Summary
N
Returns a System.Security.CodeAccessPermission object that is the intersection of the current instance and the specified object.
O P
Parameters
Q R
Parameter
Description
target
A System.Security.CodeAccessPermission instance to intersect with the current instance.
S T U V
Return Value
W
A new System.Security.CodeAccessPermission instance that represents the intersection of the current instance and target. If the intersection is empty or target is null, returns null. If the current instance is unrestricted, returns a copy of target. If target is unrestricted, returns a copy of the current instance.
X Y Z
504
Contents | Index
System.Security
CodeAccessPermission IsSubsetOf() Method
Description [Note: This method is implemented to support the System.Security.IPermission interface.] A
How and When to Override
B
Override this method to provide a mechanism for creating an intersection of two System.Security.IPermission objects that are of the same type and are derived from System.Security.CodeAccessPermission.
C D E
Usage
F
The intersection of two permissions is a permission that secures the resources and operations secured by both permissions. Specifically, it represents the minimum permission such that any demand that passes both permissions will also pass their intersection.
G H I
Exceptions
J
Exception
Condition
System.ArgumentException
target is not null and is not a System.Security.CodeAccessPermission object.
K L M N O
CodeAccessPermission.IsSubsetOf(System.Security.IPermission) Method
P
[ILASM]
Q
.method public hidebysig virtual abstract bool IsSubsetOf(class System.Security.IPermission target)
R
[C#]
S
public abstract bool IsSubsetOf(IPermission target)
T
Summary
U
Determines whether the current instance is a subset of the specified object.
V W
Parameters
X
Parameter
Description
target
A System.Security.CodeAccessPermission instance that is to be tested for the subset relationship.
Y Z
505
Contents | Index
CodeAccessPermission
System.Security
PermitOnly() Method
Return Value true if the current instance is a subset of target; otherwise, false. If the current instance is unrestricted, and target is not, returns false. If target is unrestricted, returns true. A B
Description
C
[Note: This method is implemented to support the System.Security.IPermission interface.]
D E
How and When to Override
F
Override this method to implement the test for the subset relationship in types derived from System.Security.CodeAccessPermission.
G H
Usage
I
The current instance is a subset of target if the current instance specifies a set of accesses to resources that is wholly contained by target. For example, a permission that represents read access to a file is a subset of a permission that represents read and write access to the file. If this method returns true4, the current instance does not describe a level of access to a set of resources that is not already described by target.
J K L M
Exceptions
N O
Exception
Condition
System.ArgumentException
target is not null and is not of type System.Security.CodeAccessPermission.
P Q R S
CodeAccessPermission.PermitOnly() Method
T [ILASM]
U
.method public final hidebysig virtual void PermitOnly()
V
[C#]
public void PermitOnly()
W X
Summary
Y
Prevents callers higher in the call stack from using the code that calls this method to access all resources except for the resource specified by the current instance.
Z
506
Contents | Index
System.Security
CodeAccessPermission PermitOnly() Method
Description System.Security.CodeAccessPermission.PermitOnly is similar to System.Security.CodeAccessPermission.Deny, in that both cause stack walks to fail when they would otherwise succeed. The difference is that System.Security.CodeAccessPermission.Deny specifies permissions that will cause the stack walk to fail, but System.Security.CodeAccessPermission.PermitOnly specifies the only permissions that do not cause the stack walk to fail. Call this method to ensure that your code can be used to access only the specified resources. The call to System.Security.CodeAccessPermission.PermitOnly is effective until the calling code returns to its caller. Only one System.Security.CodeAccessPermission.PermitOnly can be active on a frame. An attempt to call System.Security.CodeAccessPermission.PermitOnly when an active System.Security.CodeAccessPermission.PermitOnly exists on the frame results in a System.Security.SecurityException. Call System.Security.CodeAccessPermission.RevertPermitOnly or System.Security.CodeAccessPermission.RevertAll to remove an active System.Security.CodeAccessPermission.PermitOnly. System.Security.CodeAccessPermission.PermitOnly is ignored for a permission not granted because a demand for that permission will not succeed. However, if code lower on the call stack later calls System.Security.CodeAccessPermission.Demand for that permission, a System.Security.SecurityException is thrown when the stack walk reaches the code that tried to call System.Security.CodeAccessPermission.PermitOnly. This is because the code that called System.Security.CodeAccessPermission.PermitOnly has not been granted the permission, even though it called System.Security.CodeAccessPermission.PermitOnly for that permission. The call stack is typically represented as growing down, so that methods higher in the call stack call methods lower in the call stack. You cannot override this method.
A B C D E F G H I J K L M N O P Q R S T
Exceptions
U
Exception
Condition
System.Security.SecurityException
There is already an active System.Security. CodeAccessPermission.PermitOnly for the current frame.
V W X Y Z
507
Contents | Index
CodeAccessPermission
System.Security
RevertAll() Method
CodeAccessPermission.RevertAll() Method [ILASM]
.method public hidebysig static void RevertAll()
A
[C#]
public static void RevertAll()
B C
Summary
D
Causes all previous overrides for the current frame to be removed and no longer in effect.
E
Description
F
If there are no overrides (System.Security.CodeAccessPermission.Assert, System.Security.CodeAccessPermission.Deny, or System.Security.CodeAccessPermission.PermitOnly) for the current frame, a System.ExecutionEngineException is thrown.
G H I J
Exceptions
K L
Exception
Condition
System.ExecutionEngineException
There is no previous System.Security.CodeAccessPermission.Assert, System.Security.CodeAccessPermission.Deny, or System.Security.CodeAccessPermission.PermitOnly for the current frame.
M N O P Q R
CodeAccessPermission.RevertAssert() Method
S
[ILASM]
.method public hidebysig static void RevertAssert()
T
[C#]
public static void RevertAssert()
U V
Summary
W
Causes any previous System.Security.CodeAccessPermission.Assert for the current frame to be removed and no longer in effect.
X Y
Description
Z
If there is no System.Security.CodeAccessPermission.Assert for the current frame, a System.ExecutionEngineException is thrown.
508
Contents | Index
System.Security
CodeAccessPermission RevertPermitOnly() Method
Exceptions Exception
Condition
System.ExecutionEngineException
There is no previous System.Security.CodeAccessPermission.Assert for the current frame.
A B C D
CodeAccessPermission.RevertDeny() Method
E
[ILASM]
F
.method public hidebysig static void RevertDeny()
G
[C#]
H
public static void RevertDeny()
I
Summary
J
Causes any previous System.Security.CodeAccessPermission.Deny for the current frame to be removed and no longer in effect.
K L
Description
M
If there is no System.Security.CodeAccessPermission.Deny for the current frame, a System.ExecutionEngineException is thrown.
N O
Exceptions Exception
P Q
Condition
R System.ExecutionEngineException
There is no previous System.Security.CodeAccessPermission.Deny for the current frame.
S T U
CodeAccessPermission.RevertPermitOnly() Method
V
[ILASM]
W
.method public hidebysig static void RevertPermitOnly()
X
[C#]
Y
public static void RevertPermitOnly()
Z
509
Contents | Index
CodeAccessPermission
System.Security
ToString() Method
Summary Causes any previous System.Security.CodeAccessPermission.PermitOnly for the current frame to be removed and no longer in effect. A B
Description
C
If there is no System.Security.CodeAccessPermission.PermitOnly for the current frame, a System.ExecutionEngineException is thrown.
D E
Exceptions
F G H I
Exception
Condition
System.ExecutionEngineException
There is no previous System.Security.CodeAccessPermission.PermitOnly for the current frame.
J K
CodeAccessPermission.ToString() Method
L [ILASM]
M
.method public hidebysig virtual string ToString()
N
[C#]
public override string ToString()
O P
Summary
Q
Returns the XML representation of the state of the current instance.
R
Description
S
[Note: The XML representation of the current instance is obtained by first calling System.Security.CodeAccessPermission.ToXml, then calling System.Object.ToString on the object returned by that method. This method overrides System.Object.ToString.]
T U V W
CodeAccessPermission.ToXml() Method
X
[ILASM]
Y
.method public hidebysig virtual abstract class System.Security.SecurityElement ToXml()
Z
[C#]
public abstract SecurityElement ToXml()
510
Contents | Index
System.Security
CodeAccessPermission Union() Method
Summary Returns the XML encoding of the current instance.
Return Value
A
A System.Security.SecurityElement containing an XML encoding of the state of the current instance.
B C D
Behaviors
E
The object returned by this method is required to use the XML encoding for the System.Security.CodeAccessPermission class as defined on the class page. The state of the current instance is required to be reproducible by invoking System.Security.CodeAccessPermission.FromXml on an instance of System.Security.CodeAccessPermission using the object returned by this method.
F G H I
How and When to Override
J
Override this method to return an object containing the XML encoding for types derived from System.Security.CodeAccessPermission.
K L
Usage
M
This method is called by the system.
N O
CodeAccessPermission.Union(System.Security.IPermission) Method
P
[ILASM]
Q
.method public hidebysig virtual class System.Security.IPermission Union(class System.Security.IPermission other)
R
[C#]
S
public virtual IPermission Union(IPermission other)
T
Summary
U
Returns a System.Security.CodeAccessPermission object that is the union of the current instance and the specified object.
V W X Y Z
511
Contents | Index
CodeAccessPermission
System.Security
Union() Method
Parameters Parameter
Description
other
A System.Security.IPermission object of the same type as the current instance to be combined with the current instance.
A B C D
Return Value
E
If other is null, returns a copy of the current instance using the System.Security.IPermission.Copy method.
F G
Description
H
[Note: This method is implemented to support the System.Security.IPermission interface.]
I J
Behaviors
K
This method returns a new System.Security.CodeAccessPermission instance that represents the union of the current instance and other. If the current instance or other is unrestricted, returns a System.Security.CodeAccessPermission instance that is unrestricted. If other is null, returns a copy of the current instance using the System.Security.IPermission.Copy method.
L M N O P
Default
Q
If other is not null, this method throws a System.NotSupportedException exception; otherwise, returns a copy of the current instance.
R S
How and When to Override
T
Override this method to provide a mechanism for creating the union of two System.Security.IPermission objects that are of the same type and are derived from System.Security.CodeAccessPermission.
U V W
Usage
X
The result of a call to System.Security.CodeAccessPermission.Union is a permission that represents all of the access to resources represented by both the current instance and other. Any demand that passes either permission passes their union.
Y Z
512
Contents | Index
System.Security
CodeAccessPermission Union() Method
Exceptions Exception
Condition
System.ArgumentException
other is not of type System.Security.CodeAccessPermission.
System.NotSupportedException
other is not null.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
513
Contents | Index
System.Security.Permissions CodeAccessSecurityAttribute
BCL
Object
A
Attribute SecurityAttribute
B
CodeAccessSecurityAttribute
C
EnvironmentPermissionAttribute
D
FileIOPermissionAttribute
E
SecurityPermissionAttribute
F G
Summary
H
This is the base class for code access security attributes.
I
Type Summary
J
CF public abstract class CodeAccessSecurityAttribute : SecurityAttribute { // Constructors CF public CodeAccessSecurityAttribute (SecurityAction action); }
K L M N
Description
O
[Note: The types that derive from System.Security.Permissions.CodeAccessSecurityAttribute are used to secure access to resources or securable operations. The security information declared by a security attribute is stored in the metadata of the attribute target, and is accessed by the system at runtime. Security attributes are used for declarative security only. Use the corresponding permission class derived from System.Security.CodeAccessPermission for imperative security.]
P Q R S T
Example
U
CodeAccessSecurityAttribute is an abstract class; see derived classes for more examples.
V W
using System; using System.Security; using System.Security.Permissions;
X Y
[assembly:EnvironmentPermissionAttribute( SecurityAction.RequestMinimum, Read="COMPUTERNAME;USERNAME")]
Z
514
Contents | Index
System.Security.Permissions
CodeAccessSecurityAttribute CodeAccessSecurityAttribute() Constructor
namespace Samples { public class EnvironmentPermissionAttributeSample { public static void Main() { string[] v = {"USERNAME", "COMPUTERNAME"}; foreach(string s in v) Console.WriteLine("Variable {0} Value: {1}", s, Environment.GetEnvironmentVariable(s)); } } }
A B C D E F G
The output is
H I
Variable USERNAME Value: damien Variable COMPUTERNAME Value: PROJECT42
J K L
CodeAccessSecurityAttribute(System.Security.Permissions.SecurityAction) Constructor
M
[ILASM]
N
public rtspecialname specialname instance void .ctor(valuetype System.Security.Permissions.SecurityAction action)
O
[C#]
P
public CodeAccessSecurityAttribute(SecurityAction action)
Q
Summary
R
Constructs and initializes a new instance of System.Security.Permissions.CodeAccessSecurityAttribute with the specified System.Security.Permissions.SecurityAction value.
S T U
Parameters Parameter
V W
Description
X
action
A System.Security.Permissions.SecurityAction value.
Y Z
515
Contents | Index
CodeAccessSecurityAttribute
System.Security.Permissions
CodeAccessSecurityAttribute() Constructor
Exceptions Exception
Condition
System.ArgumentException
action is not a valid System.Security.Permissions.SecurityAction value.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
516
Contents | Index
System.Collections Comparer
BCL
Object Comparer
A
IComparer
B C
Summary
D
Provides the default implementation of the System.Collections.IComparer interface.
E F
Type Summary public sealed class Comparer : IComparer { // Constructors MS public Comparer(CultureInfo culture);
G H I J
// Fields public static readonly Comparer Default; MS public static readonly Comparer DefaultInvariant;
K L
// Methods public int Compare(object a,object b);
M
}
N
Example
O
using System; using System.Collections;
P Q
namespace Samples { public class ComparerSamples { public static void Main() { Comparer c = Comparer.Default; string a = "apples", o = "oranges"; Console.WriteLine( "Comparing {0} to {1} returns {2}", a, o, c.Compare(a, o)); } } }
R S T U V W X Y Z
517
Contents | Index
Comparer
System.Collections
Comparer() Constructor
The output is Comparing apples to oranges returns -1
A B
Comparer(System.Globalization.CultureInfo) Constructor
C [ILASM]
D
public rtspecialname specialname instance void .ctor(class System.Globalization.CultureInfo culture)
E
[C#]
public Comparer(CultureInfo culture)
F G
Summary
H
Initializes a new instance of the System.Collections.Comparer class using the specified System.Globalization.CultureInfo.
I J
Parameters
K L
Parameter
Description
culture
The System.Globalization.CultureInfo to use for the new System.Collections.Comparer.
M N O P
Description
Q
Comparison procedures use the specified System.Globalization.CultureInfo to determine the sort order and casing rules. String comparisons might have different results depending on the culture. For more information on culture-specific comparisons, see the System.Globalization namespace.
R S T
Exceptions
U V
Exception
Condition
System.ArgumentNullException
culture is null.
W X Y Z
518
Contents | Index
System.Collections
Comparer DefaultInvariant Field
Comparer.Default Field [ILASM]
.field public static initOnly class System.Collections.Comparer Default [C#]
A
public static readonly Comparer Default
B C
Summary
D
Returns a new System.Collections.Comparer instance containing the default implementation of the System.Collections.IComparer interface.
E F
Example
G
using System; using System.Collections;
H I
namespace Samples { public class ComparerDefault { public static void Main() { Comparer c = Comparer.Default; string a = "apples", o = "oranges"; Console.WriteLine( "Comparing {0} to {1} returns {2}", o, a, c.Compare(o, a)); } } }
J K L M N O P Q R
The output is
S Comparing oranges to apples returns 1
T U
Comparer.DefaultInvariant Field
V
[ILASM]
W
.field public static initOnly class System.Collections.Comparer DefaultInvariant
X
[C#]
public static readonly Comparer DefaultInvariant
Y Z
519
Contents | Index
Comparer
System.Collections
Compare() Method
Summary Represents an instance of System.Collections.Comparer that is associated with System.Globalization.CultureInfo.InvariantCulture. A B
Description
C
Comparison procedures use the System.Globalization.CultureInfo.InvariantCulture to determine the sort order and casing rules. String comparisons might have different results depending on the culture. For more information on culture-specific comparisons, see the System.Globalization namespace.
D E F
Example
G
The following code example shows how System.Collections.Comparer.Compare returns different values depending on the culture associated with the System.Collections.Comparer.
H I J K
Comparer.Compare(System.Object, System.Object) Method
L
[ILASM]
.method public final hidebysig virtual int32 Compare(object a, object b)
M
[C#]
N
public int Compare(object a, object b)
O
Summary
P
Returns the sort order of two System.Object instances.
Q R
Parameters
S T U V
Parameter
Description
a
The first System.Object to compare.
b
The second System.Object to compare.
W X
Return Value
Y
A System.Int32 containing a value that reflects the sort order of a as compared to b. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number.
Z
520
Contents | Index
System.Collections
Comparer Compare() Method
Value
Condition
any negative number
a < b.
A
zero
a == b.
B
any positive number
a > b.
C D E
[Note: A null reference is considered to compare less than any other non-null object, and equal to any other null reference, independent of the underlying System.Type of either object.]
F G H
Description
I
The behavior of this method is as follows:
J
• • •
If a implements the System.IComparable interface, it returns a. CompareTo(b). If a does not implement the System.IComparable interface but b does, it returns the negated result of b. CompareTo(a). If a and b both are not null and do not implement the System.IComparable interface, System.ArgumentException is thrown.
K L M N O
Exceptions
P
Exception
System.ArgumentException
Condition
Q
Both a and b are not null and do not implement the System.IComparable interface.
R S
-or-
T
Both a and b are not null and are not assignmentcompatible types.
U V W X Y Z
521
Contents | Index
Comparer
System.Collections
Compare() Method
Example using System; using System.Collections;
A namespace Samples { public class ComparerCompare { public static void Main() { Comparer c = Comparer.Default; int[] integers = {0, 42}; Console.WriteLine( "Comparing {0} to {1} returns {2}", integers[0], integers[1], c.Compare(integers[0], integers[1])); } } }
B C D E F G H I J K
The output is
L Comparing 0 to 42 returns -1
M N O P Q R S T U V W X Y Z
522
Contents | Index
System.Diagnostics ConditionalAttribute
BCL
Object
A
Attribute
B
ConditionalAttribute
C
Summary
D
Indicates to compilers that a method is callable if and only if a specified pre-processing identifier has been defined on the method.
E F
Type Summary
G
public sealed class ConditionalAttribute : Attribute { // Constructors public ConditionalAttribute (string conditionString);
H I J
// Properties public string ConditionString { get; }
K
}
L M
BA There is a common misconception with usage of this custom attribute. By
N
applying the ConditionalAttribute on a method you indicate that calls to that method should be removed by the compiler if the conditionString is defined. However, the method body is always compiled into the assembly regardless of whether the conditionString is defined or not.
O P Q
BG This is another clever custom attribute, which works similarly to C-style pre-
R
processor directives but in reverse. Calls to methods with this attribute are conditionally compiled into source code, depending on whether the given symbol is defined at compile time. For debugging or tracing code, this means you simply add this attribute to the method you want to call conditionally, instead of putting #if FOO … #endif all throughout your code.
S T U V
JR The ConditionalAttribute can be applied to methods that return void only.
W X
Note that any expressions that are evaluated when calling a conditional method are not evaluated if the method is not called. For example, in the following code, GetString and Foo are not called if “xx” is not defined:
Y Z
continued
523
Contents | Index
ConditionalAttribute
System.Diagnostics
ConditionalAttribute Class
using System; using System.Diagnostics;
A
class App { static void Main() { Foo(GetString()); }
B C D
static String GetString() { return "Jeff"; }
E [Conditional("xx")] static void Foo(String s) { Console.WriteLine(s); }
F }
G
If you examined the IL produced by the compiler for Main, you’d see that it contains just one IL instruction: ret.
H I J
Description
K
[Note: A System.Diagnostics.ConditionalAttribute, which has an associated condition System.Diagnostics.ConditionalAttribute.ConditionString, can be attached to the definition of a method, creating a conditionalmethod. Thereafter, when a compiler encounters a call to that method, it may choose to ignore the call unless a compilation variable is defined at the site of the call, with a value that matches in a case-sensitive manner the System.Diagnostics.ConditionalAttribute.ConditionString supplied to the System.Diagnostics.ConditionalAttribute. Note that compilers may provide several techniques to define such compilation variables, such as: CLSCompliant compilers are permitted to ignore uses of the System.Diagnostics.ConditionalAttribute.]
L M N O P Q R S
Example
T
#undef A
U using System; using System.Diagnostics;
V W
namespace Samples { public class MyClass { [ConditionalAttribute("A")] public static void Display() {
X Y Z
524
Contents | Index
System.Diagnostics
ConditionalAttribute ConditionalAttribute() Constructor
Console.WriteLine("A was defined"); } } public class ConditionalAttributeSample { public static void Main() { MyClass.Display(); Console.WriteLine("Done"); } }
A B C D E
}
F
The output is
G H
Done
I J
ConditionalAttribute(System.String) Constructor
K [ILASM]
L
public rtspecialname specialname instance void .ctor(string conditionString) [C#]
M
public ConditionalAttribute(string conditionString)
N
Summary
O
Constructs and initializes a new instance of the System.Diagnostics.ConditionalAttribute class.
P Q
Parameters
R S
Parameter
Description T
conditionString
A System.String that contains the pre-processing identifier that makes callable the target method of the current instance.
U V W
Description
X
This constructor initializes the System.Diagnostics.ConditionalAttribute.ConditionString property of the current instance using conditionString.
Y Z
525
Contents | Index
ConditionalAttribute
System.Diagnostics
ConditionString Property
Example #define A using System; using System.Diagnostics;
A B
namespace Samples { public class MyClass { [ConditionalAttribute("A")] public static void Display() { Console.WriteLine("A was defined"); } }
C D E F G H I
public class ConditionalAttributeConstructor { public static void Main() { MyClass.Display(); Console.WriteLine("Done"); } }
J K L M N
}
O
The output is
P
A was defined Done
Q R S
ConditionalAttribute.ConditionString Property
T
[ILASM]
U
.property string ConditionString { public hidebysig specialname instance string get_ConditionString() }
V
[C#]
W
public string ConditionString { get; }
X Y
Summary
Z
Gets the System.String that contains the pre-processing identifier that makes callable the target method of the current instance.
526
Contents | Index
System.Diagnostics
ConditionalAttribute ConditionString Property
Example using System; using System.Reflection; using System.Diagnostics;
A B
namespace Samples { public class MyClass { [ConditionalAttribute("DEBUG")] public static void Display() { Console.WriteLine("DEBUG was defined"); } }
C D E F G H
public class ConditionalAttributeConditionString { public static void Main() { Type t = typeof(MyClass); MethodInfo m = t.GetMethod("Display"); Object[] attributes = m.GetCustomAttributes(false); foreach(Object o in attributes) if(o is ConditionalAttribute) Console.WriteLine( ((ConditionalAttribute)o).ConditionString); } }
I J K L M N O P
}
Q
The output is
R S
DEBUG
T U V W X Y Z
527
Contents | Index
System Console
BCL
Object
A
Console
B
Summary
C
Represents the standard input, output, and error streams for console applications.
D E
Type Summary public sealed class Console { // Properties CF public static TextWriter Error { get; } CF public static TextReader In { get; } CF public static TextWriter Out { get; }
F G H I J
// CF CF CF CF CF CF CF
K L M N O
CF CF CF CF
P Q R S T
Methods public static public static public static public static public static public static public static public static public static public static public static public static public static public static public static
CF public static CF public static CF public static public static CF public static public static public static public static
U V W X Y
public static
Z public static
Stream OpenStandardError (); Stream OpenStandardError (int bufferSize); Stream OpenStandardInput (); Stream OpenStandardInput (int bufferSize); Stream OpenStandardOutput (); Stream OpenStandardOutput (int bufferSize); int Read (); string ReadLine (); void SetError (TextWriter newError); void SetIn (TextReader newIn); void SetOut (TextWriter newOut); void Write (bool value); void Write (char value); void Write (char[] buffer); void Write (char[] buffer, int index, int count); void Write (decimal value); void Write (double value); void Write (float value); void Write (int value); void Write (long value); void Write (object value); void Write (string value); void Write (string format, object arg0); void Write (string format, object arg0, object arg1); void Write (string format, object arg0, object arg1,
528
Contents | Index
System
Console Console Class
CF CF CF
CF
CF CF CF CF
CF CF
object arg2); public static void Write (string format, params object[] arg); public static void Write (uint value); public static void Write (ulong value); public static void WriteLine (); public static void WriteLine (bool value); public static void WriteLine (char value); public static void WriteLine (char[] buffer); public static void WriteLine (char[] buffer, int index, int count); public static void WriteLine (decimal value); public static void WriteLine (double value); public static void WriteLine (float value); public static void WriteLine (int value); public static void WriteLine (long value); public static void WriteLine (object value); public static void WriteLine (string value); public static void WriteLine (string format, object arg0); public static void WriteLine (string format, object arg0, object arg1); public static void WriteLine (string format, object arg0, object arg1, object arg2); public static void WriteLine (string format, params object[] arg); public static void WriteLine (uint value); public static void WriteLine (ulong value);
A B C D E F G H I J K L M N O P Q
}
R S
BA Notice the heavy use of method overloading in this class. We special-case each
T
of the primitive types in order to avoid boxing overhead. We could have gotten away with just having the overload that takes the object, but then calls such as these would cause an extra allocation for the coercion to object:
U V W
Console.WriteLine (42);
X
and
Y
Console.WriteLine ('c');
Z
continued
529
Contents | Index
Console
System
Console Class
In general this kind of special casing is not necessary, but for a class that is likely to be used in a tight loop it can be very helpful. A
This class is a classic example of “design in reverse.” Before we designed this class we knew what we wanted the Hello World example to look like:
B C
Console.WriteLine ("Hello World");
D
We then created this class to make that sample code a reality. Even in the face of the full complexity of a well-factored I/O system, we kept the simple things simple.
E F
AH It is interesting to note that all of the Console.WriteXxx() methods are just shorthand for Console.Out.WriteXxx(). Likewise, Console.ReadXxx() is shorthand for Console.In.ReadXxx(). This design enables the In and Out streams to be available directly in the rare cases where they are needed but does not complicate the simple usage with them.
G H I J
BG The OpenStandardXxx methods that take an integer for the buffer size are really rather useless. We eventually decided that supporting buffering on the streams used for Console is a silly notion, especially since classes like StreamReader and StreamWriter may internally do their own buffering.
K L M N
KG Note that there is no easy way for a user to get a single key press: Return has to be pressed before Read or ReadLine complete. This did not seem like a critical scenario when we designed this class originally, but it is interesting to note that this has been one of our top requests for the Console class since Version 1 was released.
O P Q R
Description
S
The System.Console class provides basic input and output support for applications that read from and write characters to the console. If the console does not exist, as in a GUI application, writing to the console produces no result, and no exception is raised. The standard input, output, and error streams are represented by properties, and are automatically associated with the console when the application starts. Applications can redirect these properties to other streams; for example, streams associated with files instead of the console. [Note: For additional information see the System.Console.SetIn, System.Console.SetOut, and System.Console.SetError methods.] By default, the read methods in this class use the standard input stream and the write methods use the standard output stream.
T U V W X Y Z
530
Contents | Index
System
Console Console Class
The write methods support writing data with or without automatically appending carriage return and linefeed characters. This enables the writing of strings, formatted strings, arrays of characters, instances of primitive types, and arbitrary objects without first having to convert them to strings. This class uses synchronized System.IO.TextReader and System.IO.TextWriter instances. Multiple threads can concurrently read from and/or write to an instance of this type.
A B C D
Example
E
using System;
F namespace Samples { public class ConsoleSample { public static void Main() { Console.WriteLine("Write a string {0}", "Hello world!"); Console.WriteLine("Write a number {0}", 42); Console.WriteLine("Please enter your name:"); string name = Console.ReadLine(); Console.WriteLine("Hello {0}", name); Console.Error.WriteLine("Errors go here by default"); Console.WriteLine("Date: {0:dd/MM/yy}", DateTime.Now); int i = -42; Console.WriteLine("{0:0000}, {1, -20}, {2, 20}.", i, i, i); Console.WriteLine("{0:X}, {1:C}, {2:G}.", i, i, i); } } }
G H I J K L M N O P Q R S
The output is Write a string Hello world! Write a number 42 Please enter your name: damien Hello damien Errors go here by default Date: 05/06/03 -0042, -42 , FFFFFFD6, -$42.00, -42.
T U V W X Y
-42.
Z
531
Contents | Index
Console
System
Error Property
Console.Error Property [ILASM]
A
.property class System.IO.TextWriter Error { public hidebysig static specialname class System.IO.TextWriter get_Error() }
B
[C#]
public static TextWriter Error { get; }
C D
Summary
E
Gets the system’s standard error output stream.
F
Property Value
G
A synchronized System.IO.TextWriter object where error output is sent.
H
Description
I
This property can be redirected using the System.Console.SetError method. [Note: If the application does not have a System.Console, System.Console.Error behaves like System.IO.TextWriter.Null.]
J K L M
Example
N
using System; using System.IO;
O namespace Samples { public class ConsoleError { public static void Main() { Console.Error.WriteLine("Write to standard error"); } } }
P Q R S T U V
The output is
W Write to standard error
X Y Z
532
Contents | Index
System
Console In Property
Console.In Property [ILASM]
.property class System.IO.TextReader In { public hidebysig static specialname class System.IO.TextReader get_In() }
A
[C#]
B
public static TextReader In { get; }
C
Summary
D
Gets the system’s standard input stream.
E F
Property Value
G
A synchronized System.IO.TextReader object from which user input is received.
H
Description
I
This property can be redirected using the System.Console.SetIn method. [Note: If the application does not have a System.Console, System.Console.In behaves like System.IO.TextReader.Null.]
J K L
Example
M
using System; using System.IO;
N O
namespace Samples { public class ConsoleIn { public static void Main() { Console.Write("Please enter your name: "); string name = Console.In.ReadLine(); Console.WriteLine("Hello {0}", name); } } }
P Q R S T U V W
The output is
X Please enter your name: damien Hello damien
Y Z
533
Contents | Index
Console
System
Out Property
Console.Out Property [ILASM]
A
.property class System.IO.TextWriter Out { public hidebysig static specialname class System.IO.TextWriter get_Out() }
B
[C#]
public static TextWriter Out { get; }
C D
Summary
E
Gets the system’s standard output stream.
F
Property Value
G
A synchronized System.IO.TextWriter object where normal output is sent.
H
Description
I
This property can be redirected using the System.Console.SetOut method. [Note: If the application does not have a System.Console, System.Console.Out behaves like System.IO.TextWriter.Null.]
J K L M
Example
N
using System; using System.IO;
O namespace Samples { public class ConsoleOut { public static void Main() { TextWriter tw = Console.Out; tw.Write("Please enter your name: "); TextReader tr = Console.In; string name = tr.ReadLine(); tw.WriteLine("Hello {0}", name); } } }
P Q R S T U V W X
The output is
Y
Please enter your name: boston Hello boston
Z
534
Contents | Index
System
Console OpenStandardError() Method
Console.OpenStandardError() Method [ILASM]
.method public hidebysig static class System.IO.Stream OpenStandardError() [C#]
A
public static Stream OpenStandardError()
B C
Summary
D
Returns the standard error stream.
E
Return Value
F
A new synchronized System.IO.Stream object that writes to the console.
G H
Example using System; using System.IO;
I
namespace Samples { public class ConsoleOpenStandardError { public static void Main() { string fileName = "error.out"; TextWriter t = File.CreateText(fileName); Console.SetError(t); TextWriter e = Console.Error; e.WriteLine("Error messages go here"); e.Close(); Console.SetError(new StreamWriter( Console.OpenStandardError())); e = Console.Error; e.WriteLine("Now error messages go here"); e.Close(); } } }
K
J
L M N O P Q R S T U V W
The output is
X Y
Now error messages go here
Z
The file error.out contains Error messages go here
535
Contents | Index
Console
System
OpenStandardError() Method
Console.OpenStandardError(System.Int32) Method [ILASM]
A
.method public hidebysig static class System.IO.Stream OpenStandardError(int32 bufferSize)
B
[C#]
public static Stream OpenStandardError(int bufferSize)
C D
Summary
E
Returns the standard error stream.
F
Parameters
G H I
Parameter
Description
bufferSize
A System.Int32 that specifies the desired internal stream buffer size.
J K
Return Value
L
A new synchronized System.IO.Stream object that writes to the console.
M N
Description
O
Buffering console streams is not required to be supported. If it is not supported, the bufferSize parameter is ignored, and this method behaves identically to System.Console.OpenStandardError(). If buffering is supported, the buffering behavior of the System.Console class is implementation-defined.
P Q R S
Console.OpenStandardInput() Method
T [ILASM]
U
.method public hidebysig static class System.IO.Stream OpenStandardInput() [C#]
V
public static Stream OpenStandardInput()
W
Summary
X
Returns the standard input stream.
Y
Return Value
Z
A new synchronized System.IO.Stream object that reads from the console.
536
Contents | Index
System
Console OpenStandardInput() Method
Example using System; using System.IO;
A namespace Samples { public class ConsoleOpenStandardInput { public static void Main() { string fileName = "input.txt"; FileStream fs = File.OpenRead(fileName); Console.SetIn(new StreamReader(fs)); TextReader tr = Console.In; Console.WriteLine(tr.ReadLine()); tr.Close(); Console.SetIn(new StreamReader( Console.OpenStandardInput())); Console.Write("Please enter your name: "); string name = Console.ReadLine(); Console.WriteLine("Hello {0}", name); } } }
B C D E F G H I J K L M N
The file input.txt contains
O
Hello world!
P
The output is
Q
Hello world! Please enter your name: damien Hello damien
R S T U
Console.OpenStandardInput(System.Int32) Method
V
[ILASM]
.method public hidebysig static class System.IO.Stream OpenStandardInput(int32 bufferSize)
W
[C#]
X
public static Stream OpenStandardInput(int bufferSize)
Y
Summary
Z
Returns the standard input stream.
537
Contents | Index
Console
System
OpenStandardOutput() Method
Parameters Parameter
Description
bufferSize
A System.Int32 that specifies the desired internal stream buffer size.
A B C D
Return Value
E
A new synchronized System.IO.Stream object that reads from the console.
F
Description
G
Buffering console streams is not required to be supported. If it is not supported, the bufferSize parameter is ignored, and this method behaves identically to System.Console.OpenStandardInput(). If buffering is supported, the buffering behavior of the System.Console class is implementation-defined.
H I J K
Console.OpenStandardOutput() Method
L M
[ILASM]
N
[C#]
.method public hidebysig static class System.IO.Stream OpenStandardOutput() public static Stream OpenStandardOutput()
O P
Summary
Q
Returns the standard output stream.
R
Return Value
S
A new synchronized System.IO.Stream object that writes to the console.
T U
Example
V
using System; using System.IO;
W namespace Samples { public class ConsoleOpenStandardOutput { public static void Main() { string filename = "output.txt";
X Y Z
538
Contents | Index
System
Console OpenStandardOutput() Method
StreamWriter sw = new StreamWriter(filename); Console.SetOut(sw); Console.WriteLine("Output goes here"); sw.Close(); sw = new StreamWriter( Console.OpenStandardOutput()); Console.SetOut(sw); Console.WriteLine("Now output goes here"); sw.Close();
A B C D
} }
E
}
F
The output is
G
Now output goes here
H I
The file output.txt contains
J Output goes here
K L
Console.OpenStandardOutput(System.Int32) Method
M
[ILASM]
N
.method public hidebysig static class System.IO.Stream OpenStandardOutput(int32 bufferSize)
O
[C#]
P
public static Stream OpenStandardOutput(int bufferSize)
Q
Summary
R
Returns the standard output stream. The desired size of the internal buffer for the stream is specified.
S
Parameters
U
T
V
Parameter
Description
bufferSize
A System.Int32 that specifies the desired internal stream buffer size.
W X Y Z
Return Value A new synchronized System.IO.Stream object that writes to the console.
539
Contents | Index
Console
System
Read() Method
Description Buffering console streams is not required to be supported. If it is not supported, the bufferSize parameter is ignored, and this method behaves identically to System.Console.OpenStandardOutput(). If buffering is supported, the buffering behavior of the System.Console class is implementation-defined.
A B C D
Console.Read() Method
E
[ILASM]
.method public hidebysig static int32 Read()
F
[C#]
public static int Read()
G H
Summary
I
Reads the next character from the standard input stream.
J
Return Value
K
The next character from the character source represented as a System.Int32, or –1 if at the end of the stream.
L M
Description
N
This method will not return until the read operation is terminated; for example, by the user pressing the enter key. If data are available, the input stream contains what the user entered, suffixed with the environment-dependent newline character.
O P Q
Exceptions
R S
Exception
Condition
System.IO.IOException
An I/O error occurred.
T U V
Example
W
using System; using System.IO;
X Y
namespace Samples { public class ConsoleRead { public static void Main()
Z
540
Contents | Index
System
Console ReadLine() Method
{ Console.Write("Please enter your name: "); Console.WriteLine("Your name starts with {0}", Convert.ToChar(Console.Read()));
A
} }
B
}
C
The output is
D
Please enter your name: damien Your name starts with d
E F G
Console.ReadLine() Method
H
[ILASM]
I
.method public hidebysig static string ReadLine()
J
[C#]
public static string ReadLine()
K
Summary
L
Reads the next line of characters from the System.Console.InSystem.IO.TextReader.
M
Return Value
O
A System.String containing the next line from the input stream, or null if the end of the input stream has already been reached.
P
N
Q R
Description
S
A line is defined as a sequence of characters followed by a carriage return (Unicode 0x000d), a line feed (Unicode 0x000a), or a System.Environment.NewLine. The returned string does not contain the terminating character(s).
T U V
Exceptions
W
Exception
Condition
System.IO.IOException
An I/O error occurred.
System.OutOfMemoryException
There is insufficient memory to allocate a buffer for the returned string.
X Y Z
541
Contents | Index
Console
System
SetError() Method
Example using System; using System.IO;
A namespace Samples { public class ConsoleReadLine { public static void Main() { Console.Write("Please enter your name: "); Console.WriteLine("Hello {0}", Console.ReadLine()); } } }
B C D E F G H I
The output is
J Please enter your name: damien Hello damien
K L M
Console.SetError(System.IO.TextWriter) Method
N [ILASM]
O
.method public hidebysig static void SetError(class System.IO.TextWriter newError)
P
[C#]
public static void SetError(TextWriter newError)
Q R
Summary
S
Sets the System.Console.Error property to the specified System.IO.TextWriter.
T
Parameters
U V
Parameter
Description
newError
A System.IO.TextWriter that becomes the new standard error output stream.
W X Y
Description
Z
This method replaces the System.Console.Error property with a synchronized System.IO.TextWriter returned by System.IO.TextWriter.Synchronized(newError). 542
Contents | Index
System
Console SetError() Method
[Note: By default, the System.Console.Error property is set to the system’s standard error stream.] A
Exceptions
B
Exception
Condition
System.Security.SecurityException
The caller does not have the required permission.
System.ArgumentNullException
newError is null.
C D E F G
Permissions
H
Permission
Description
System.Security.Permissions.SecurityPermissionFlag
Requires System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode permission.
I J K L M
Example
N
using System; using System.IO;
O P
namespace Samples { public class ConsoleSetError { public static void Main() { string fileName = "error.out"; TextWriter t = File.CreateText(fileName); Console.SetError(t); TextWriter e = Console.Error; e.WriteLine("Error messages go here"); e.Close(); Console.SetError(new StreamWriter( Console.OpenStandardError())); e = Console.Error; e.WriteLine("Now error messages go here"); e.Close(); } } }
Q R S T U V W X Y Z
543
Contents | Index
Console
System
SetIn() Method
The output is Now error messages go here
A
The file error.out contains
B Error messages go here
C D E
Console.SetIn(System.IO.TextReader) Method
F
[ILASM]
.method public hidebysig static void SetIn(class System.IO.TextReader newIn)
G
[C#]
public static void SetIn(TextReader newIn)
H I
Summary
J
Sets the System.Console.In property to the specified System.IO.TextReader.
K
Parameters
L M
Parameter
Description
newIn
A System.IO.TextReader that becomes the new standard input stream.
N O P
Description
Q
This method replaces the System.Console.In property with a synchronized System.IO.TextReader returned by System.IO.TextReader.Synchronized(newIn). [Note: By default, the System.Console.In property is set to the system’s standard input stream.]
R S T U
Exceptions
V W
Exception
Condition
System.ArgumentNullException
newIn is null.
X Y Z
544
Contents | Index
System
Console SetIn() Method
Permissions Permission
Description
System.Security.Permissions.SecurityPermissionFlag
Requires permission to execute unmanaged code. See System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode.
A B C D
Example
E
using System; using System.IO;
F G
namespace Samples { public class ConsoleSetIn { public static void Main() { string fileName = "input.txt"; FileStream fs = File.OpenRead(fileName); Console.SetIn(new StreamReader(fs)); TextReader tr = Console.In; Console.WriteLine(tr.ReadLine()); tr.Close(); Console.SetIn(new StreamReader( Console.OpenStandardInput())); Console.Write("Please enter your name: "); string name = Console.ReadLine(); Console.WriteLine("Hello {0}", name); } } }
H I J K L M N O P Q R S T
The file input.txt contains
U
Hello world!
V W
The output is
X
Hello world! Please enter your name: damien Hello damien
Y Z
545
Contents | Index
Console
System
SetOut() Method
Console.SetOut(System.IO.TextWriter) Method [ILASM]
.method public hidebysig static void SetOut(class System.IO.TextWriter newOut)
A
[C#]
public static void SetOut(TextWriter newOut)
B C
Summary
D
Sets the System.Console.Out property to the specified System.IO.TextWriter.
E
Parameters
F G
Parameter
Description
newOut
A System.IO.TextWriter that becomes the new standard output stream.
H I J
Description
K
This method replaces the System.Console.Out property with a synchronized System.IO.TextWriter returned by System.IO.TextWriter.Synchronized(newOut). [Note: By default, the System.Console.Out property is set to the system’s standard output stream.]
L M N O
Exceptions
P Q
Exception
Condition
System.ArgumentNullException
newOut is null.
R S T
Permissions
U V
Permission
Description
System.Security.Permissions.SecurityPermissionFlag
Requires permission to execute unmanaged code. See System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode.
W X Y Z
546
Contents | Index
System
Console Write() Method
Example using System; using System.IO;
A namespace Samples { public class ConsoleSetOut { public static void Main() { string filename = "output.txt"; StreamWriter sw = new StreamWriter(filename); Console.SetOut(sw); Console.WriteLine("Output goes here"); sw.Close(); sw = new StreamWriter( Console.OpenStandardOutput()); Console.SetOut(sw); Console.WriteLine("Now output goes here"); sw.Close(); } } }
B C D E F G H I J K L M
The output is
N
Now output goes here
O P
The file out.txt contains
Q Output goes here
R S
Console.Write(System.Boolean) Method
T
[ILASM]
U
.method public hidebysig static void Write(bool value)
V
[C#]
public static void Write(bool value)
W
Summary
X
Writes the text representation of a System.Boolean to the System.Console.OutSystem.IO.TextWriter.
Y Z
547
Contents | Index
Console
System
Write() Method
Parameters Parameter
Description
value
The System.Boolean to write.
A B C D
Description
E
This version of System.Console.Write is equivalent to System.Console.Out.Write(value.ToString()).
F G
Exceptions
H I J
Exception
Condition
System.IO.IOException
An I/O error occurred.
K L
Example
M
See the System.Console.WriteLine version of this method.
N O
Console.Write(System.Char) Method
P [ILASM]
Q
.method public hidebysig static void Write(valuetype System.Char value) [C#]
R
public static void Write(char value)
S
Summary
T
Writes a character to the System.Console.OutSystem.IO.TextWriter.
U V
Parameters
W X
Parameter
Description
Y
value
The Unicode character to write to the text stream.
Z
548
Contents | Index
System
Console Write() Method
Exceptions Exception
Condition
System.IO.IOException
An I/O error occurred.
A B C
Example
D
See the System.Console.WriteLine version of this method.
E F
Console.Write(System.Char[]) Method
G
[ILASM]
H
.method public hidebysig static void Write(class System.Char[] buffer)
I
[C#]
J
public static void Write(char[] buffer)
K
Summary
L
Writes a character array to the System.Console.OutSystem.IO.TextWriter.
M
Parameters
N O
Parameter
Description
buffer
The Unicode character array to write to the text stream. If buffer is null, nothing is written.
P Q R S
Description
T
This version of System.Console.Write is equivalent to System.Console.Out.Write(buffer).
U V
Exceptions
W
Exception
Condition
System.IO.IOException
An I/O error occurred.
X Y Z
549
Contents | Index
Console
System
Write() Method
Example See the System.Console.WriteLine version of this method. A B
Console.Write(System.Char[], System.Int32, System.Int32) Method
C
[ILASM]
D
.method public hidebysig static void Write(class System.Char[] buffer, int32 index, int32 count)
E
[C#]
public static void Write(char[] buffer, int index, int count)
F G
Summary
H
Writes a subarray of characters to the System.Console.OutSystem.IO.TextWriter.
I
Parameters
J K
Parameter
Description
L
buffer
The Unicode character array from which characters are read.
index
A System.Int32 that specifies the starting offset in buffer at which to begin reading.
count
A System.Int32 that specifies the number of characters to write.
M N O P Q
Description
R
This version of System.Console.Write is equivalent to System.Console.Out.Write(buffer, index, count).
S T
Exceptions
U
Exception
Condition
System.ArgumentException
(index + count) is greater than the length of buffer.
Y
System.IO.IOException
An I/O error occurred.
Z
System.ArgumentOutOfRangeException
index or count is negative.
System.ArgumentNullException
buffer is null.
V W X
550
Contents | Index
System
Console Write() Method
Example See the System.Console.WriteLine version of this method. A
Console.Write(System.Decimal) Method
B
[ILASM]
C
.method public hidebysig static void Write(decimal value)
D
[C#]
public static void Write(decimal value)
E F
Summary
G
Writes the text representation of a specified System.Decimal to the System.Console.OutSystem.IO.TextWriter.
H I
Parameters
J K
Parameter
Description
value
The System.Decimal to write.
L M N
Description
O
This version of System.Console.Write is equivalent to System.Console.Out.Write(value.ToString()). This member must be implemented if the Extended Numerics Library is present in the implementation.
P Q R
Exceptions
S
Exception
Condition
System.IO.IOException
An I/O error occurred.
T U V W
Example
X
See the System.Console.WriteLine version of this method.
Y Z
551
Contents | Index
Console
System
Write() Method
Console.Write(System.Double) Method [ILASM]
.method public hidebysig static void Write(float64 value)
A
[C#]
public static void Write(double value)
B C
Summary
D
Writes the text representation of a specified System.Double to the System.Console.OutSystem.IO.TextWriter.
E F
Parameters
G H
Parameter
Description
value
The System.Double to write.
I J K
Description
L
This version of System.Console.Write is equivalent to System.Console.Out.Write(value.ToString()). This member must be implemented if the Extended Numerics Library is present in the implementation.
M N O
Exceptions
P Q
Exception
Condition
System.IO.IOException
An I/O error occurred.
R S T
Example
U
See the System.Console.WriteLine version of this method.
V W X
Console.Write(System.Single) Method
Y
[ILASM]
.method public hidebysig static void Write(float32 value)
Z
[C#]
public static void Write(float value)
552
Contents | Index
System
Console Write() Method
Summary Writes the text representation of a specified System.Single to the System.Console.OutSystem.IO.TextWriter. A
Parameters
B C
Parameter
Description
value
The System.Single to write.
D E F
Description
G
This version of System.Console.Write is equivalent to System.Console.Out.Write(value.ToString()). This member must be implemented if the Extended Numerics Library is present in the implementation.
H I J
Exceptions
K L
Exception
Condition
System.IO.IOException
An I/O error occurred.
M N O
Example
P
See the System.Console.WriteLine version of this method.
Q R S
Console.Write(System.Int32) Method
T
[ILASM]
.method public hidebysig static void Write(int32 value)
U
[C#]
V
public static void Write(int value)
W
Summary
X
Writes the text representation of a specified System.Int32 to the System.Console.OutSystem.IO.TextWriter.
Y Z
553
Contents | Index
Console
System
Write() Method
Parameters Parameter
Description
value
The System.Int32 to write.
A B C D
Description
E
This version of System.Console.Write is equivalent to System.Console.Out.Write(value.ToString()).
F G
Exceptions
H I J
Exception
Condition
System.IO.IOException
An I/O error occurred.
K L
Example
M
See the System.Console.WriteLine version of this method.
N O
Console.Write(System.Int64) Method
P [ILASM]
Q
.method public hidebysig static void Write(int64 value) [C#]
R
public static void Write(long value)
S T
Summary
U
Writes the text representation of a specified System.Int64 to the System.Console.OutSystem.IO.TextWriter.
V
Parameters
W X
Parameter
Description
value
The System.Int64 to write.
Y Z
554
Contents | Index
System
Console Write() Method
Description This version of System.Console.Write is equivalent to System.Console.Out.Write(value.ToString()). A
Exceptions
B C
Exception
Condition
System.IO.IOException
An I/O error occurred.
D E F
Example
G
See the System.Console.WriteLine version of this method.
H I J
Console.Write(System.Object) Method
K
[ILASM]
L
.method public hidebysig static void Write(object value) [C#]
M
public static void Write(object value)
N
Summary
O
Writes the text representation of a specified object to the System.Console.OutSystem.IO.TextWriter.
P Q
Parameters Parameter
R S
Description
T
value
The object to write. If value is null, System.String.Empty is written.
U V
Description
W
This version of System.Console.Write is equivalent to System.Console.Out.Write(value.ToString()). [Note: If value is null, no exception is thrown and nothing is written. Otherwise, the object’s System.Object.ToString method is called to produce the string representation, and the resulting string is written to the output stream.]
X Y Z
555
Contents | Index
Console
System
Write() Method
Exceptions Exception
Condition
System.IO.IOException
An I/O error occurred.
A B C D
Example
E
See the System.Console.WriteLine version of this method.
F G
Console.Write(System.String) Method
H
[ILASM]
.method public hidebysig static void Write(string value)
I
[C#]
J
public static void Write(string value)
K
Summary
L
Writes a specified string to the System.Console.OutSystem.IO.TextWriter.
M
Parameters
N O P Q
Parameter
Description
value
The System.String to write. If value is null, the System.String.Empty string is written.
R S
Description
T
This version of System.Console.Write is equivalent to System.Console.Out.Write(value). [Note: If specified value is null, nothing is written to the output stream.]
U V W
Exceptions
X Y
Exception
Condition
System.IO.IOException
An I/O error occurred.
Z
556
Contents | Index
System
Console Write() Method
Example See the System.Console.WriteLine version of this method. A
Console.Write(System.String, System.Object) Method
B
[ILASM]
C
.method public hidebysig static void Write(string format, object arg0)
D
[C#]
public static void Write(string format, object arg0)
E F
Summary
G
Writes a formatted string to the System.Console.OutSystem.IO.TextWriter.
H
Parameters
I J
Parameter
Description
format
A System.String that specifies the format string.
L
arg0
An object referenced in the format string.
M
K
N
Description
O
[Note: If the specified object is not referenced in format, it is ignored. For more information on format strings, see the System.String class overview.]
P Q R
Exceptions
S
Exception
Condition
System.ArgumentNullException
format is null.
System.IO.IOException
An I/O error occurred.
T U V W
The format specification in format is invalid.
X
-orSystem.FormatException
Y
The number indicating an argument to be formatted is less than zero, or greater than or equal to the number of provided objects to be formatted (1).
Z
557
Contents | Index
Console
System
Write() Method
Example See the System.Console.WriteLine version of this method. A B
Console.Write(System.String, System.Object, System.Object) Method
C
[ILASM]
D
.method public hidebysig static void Write(string format, object arg0, object arg1) [C#]
E
public static void Write(string format, object arg0, object arg1)
F
Summary
G
Writes a formatted string to the System.Console.OutSystem.IO.TextWriter.
H I
Parameters
J
Parameter
Description
L
format
A System.String that specifies the format string.
M
arg0
The first object referenced in the format string.
N
arg1
The second object referenced in the format string.
K
O P
Description
Q
[Note: If a specified object is not referenced in format, it is ignored. For more information on format strings, see the System.String class overview.]
R S
Exceptions
T
Exception
Condition
V
System.ArgumentNullException
format is null.
W
System.IO.IOException
An I/O error occurred.
System.FormatException
The format specification in format is invalid. -orThe number indicating an argument to be formatted is less than zero, or greater than or equal to the number of provided objects to be formatted (2).
U
X Y Z
558
Contents | Index
System
Console Write() Method
Example See the System.Console.WriteLine version of this method. A
Console.Write(System.String, System.Object, System.Object, System.Object) Method
B
[ILASM]
D
.method public hidebysig static void Write(string format, object arg0, object arg1, object arg2)
E
C
[C#]
F
public static void Write(string format, object arg0, object arg1, object arg2)
G
Summary
H
Writes a formatted string to the System.Console.OutSystem.IO.TextWriter.
I J
Parameters
K
Parameter
Description
L
format
A System.String that specifies the format string.
M
arg0
The first object referenced in the format string.
arg1
The second object referenced in the format string.
arg2
The third object referenced in the format string.
N O P Q R
Description
S
[Note: If a specified object is not referenced in the format string, it is ignored.] [Note: For more information on format strings see the System.String class overview.]
T U V W X Y Z
559
Contents | Index
Console
System
Write() Method
Exceptions Exception
Condition
B
System.ArgumentNullException
format is null.
C
System.IO.IOException
An I/O error occurred.
A
D
The format specification in format is invalid.
E
-orSystem.FormatException
F G
The number indicating an argument to be formatted is less than zero, or greater than or equal to the number of provided objects to be formatted (3).
H I J
Console.Write(System.String, System.Object[]) Method
K
[ILASM]
L
.method public hidebysig static void Write(string format, class System.Object[] arg) [C#]
M
public static void Write(string format, params object[] arg)
N O
Summary
P
Writes a formatted string to the System.Console.OutSystem.IO.TextWriter.
Q
Parameters
R S
Parameter
Description
T
format
A System.String that specifies the format string.
arg
An array of objects referenced in the format string.
U V W
Description
X
[Note: If a specified object is not referenced in format, it is ignored. For more information on format strings, see the System.String class overview.]
Y Z
560
Contents | Index
System
Console Write() Method
Exceptions Exception
Condition
System.ArgumentNullException
format or arg is null.
System.IO.IOException
An I/O error occurred.
C
The format specification in format is invalid.
D
-or-
E
The number indicating an argument to be formatted is less than zero, or greater than or equal to arg.Length.
F
A
System.FormatException
B
G H
Example
I
See the System.Console.WriteLine version of this method.
J K
Console.Write(System.UInt32) Method
L
[ILASM]
M
.method public hidebysig static void Write(unsigned int32 value)
N
[C#]
public static void Write(uint value)
O
Summary
P
Writes the text representation of a specified System.UInt32 to the System.Console.OutSystem.IO.TextWriter.
Q R S
Parameters
T
Parameter
Description
value
The System.UInt32 to write.
U V W X
Description
Y
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Console.Write(System.Int64). This version of System.Console.Write is equivalent to System.Console.Out.Write(value.ToString()).
Z
561
Contents | Index
Console
System
Write() Method
Exceptions Exception
Condition
System.IO.IOException
An I/O error occurred.
A B C D
Example
E
See the System.Console.WriteLine version of this method.
F G
Console.Write(System.UInt64) Method
H
[ILASM]
.method public hidebysig static void Write(unsigned int64 value)
I
[C#]
J
public static void Write(ulong value)
K
Summary
L
Writes the text representation of a specified System.UInt64 to the System.Console.OutSystem.IO.TextWriter.
M N
Parameters
O P Q
Parameter
Description
value
The System.UInt64 to write.
R S
Description
T
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Console.Write(System.Decimal). This version of System.Console.Write is equivalent to System.Console.Out.Write(value.ToString()).
U V W X
Exceptions
Y Z
Exception
Condition
System.IO.IOException
An I/O error occurred.
562
Contents | Index
System
Console WriteLine() Method
Example See the System.Console.WriteLine version of this method. A
Console.WriteLine() Method
B
[ILASM]
C
.method public hidebysig static void WriteLine()
D
[C#]
public static void WriteLine()
E F
Summary
G
Writes a line terminator to the System.Console.OutSystem.IO.TextWriter.
H
Description
I
The default line terminator is the value of the System.Environment.NewLine property. The line terminator can be set using the System.IO.TextWriter.NewLine property of the System.Console.Out stream.
J K L
Exceptions
M
Exception
Condition
System.IO.IOException
An I/O error occurred.
N O P Q
Example
R
using System;
S namespace Samples { public class ConsoleWriteLine { public static void Main() { Console.WriteLine("First line has some text"); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("and this follows two blank lines"); } } }
T U V W X Y Z
563
Contents | Index
Console
System
WriteLine() Method
The output is First line has some text
A B
and this follows two blank lines
C D
Console.WriteLine(System.Boolean) Method
E
[ILASM]
.method public hidebysig static void WriteLine(bool value)
F
[C#]
G
public static void WriteLine(bool value)
H I
Summary
J
Writes the text representation of a System.Boolean followed by a line terminator to the System.Console.OutSystem.IO.TextWriter.
K
Parameters
L M
Parameter
Description
value
The System.Boolean to write.
N O P
Description
Q
This version of System.Console.WriteLine is equivalent to System.Console.Out.WriteLine(value.ToString()). The default line terminator is the value of the System.Environment.NewLine property. The line terminator can be set using the System.IO.TextWriter.NewLine property of the System.Console.Out stream.
R S T U V
Exceptions
W X
Exception
Condition
Y
System.IO.IOException
An I/O error occurred.
Z
564
Contents | Index
System
Console WriteLine() Method
Example using System; namespace Samples { public class ConsoleWriteLine { public static void Main() { bool[] booleans = new bool[] {true, false}; foreach(bool b in booleans) Console.WriteLine(b); } } }
A B C D E F G H
The output is
I J
True False
K L
Console.WriteLine(System.Char) Method
M
[ILASM]
N
.method public hidebysig static void WriteLine(valuetype System.Char value)
O
[C#]
public static void WriteLine(char value)
P Q
Summary
R
Writes a character followed by a line terminator to the System.Console.OutSystem.IO.TextWriter.
S T
Parameters
U
Parameter
Description
value
The Unicode character to write to the text stream.
V W X Y
Description
Z
This version of System.Console.WriteLine is equivalent to System.Console.Out.WriteLine(value).
565
Contents | Index
Console
System
WriteLine() Method
The default line terminator is the value of the System.Environment.NewLine property. The line terminator can be set using the System.IO.TextWriter.NewLine property of the System.Console.Out stream. A
Exceptions
B C
Exception
Condition
System.IO.IOException
An I/O error occurred.
D E F G
Example
H
using System;
I
namespace Samples { public class ConsoleWriteLine { public static void Main() { char[] chars = new char[] {'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'}; foreach(char c in chars) Console.WriteLine(c); } } }
J K L M N O P Q R
The output is
S H e l l o
T U V W
w o r l d !
X Y Z
566
Contents | Index
System
Console WriteLine() Method
Console.WriteLine(System.Char[]) Method [ILASM]
.method public hidebysig static void WriteLine(class System.Char[] buffer) [C#]
A
public static void WriteLine(char[] buffer)
B C
Summary
D
Writes an array of characters followed by a line terminator to the System.Console.OutSystem.IO.TextWriter.
E F
Parameters
G H
Parameter
Description
buffer
The Unicode character array to write.
I J K
Description
L
This version of System.Console.WriteLine is equivalent to System.Console.Out.WriteLine(buffer). The default line terminator is the value of the System.Environment.NewLine property. The line terminator can be set using the System.IO.TextWriter.NewLine property of the System.Console.Out stream.
M N O P
Exceptions
Q R
Exception
Condition
System.IO.IOException
An I/O error occurred.
T
System.ArgumentException
buffer is null.
U
S
V W X Y Z
567
Contents | Index
Console
System
WriteLine() Method
Example using System; namespace Samples { public class ConsoleWriteLine { public static void Main() { char[] chars = new char[] {'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'}; Console.WriteLine(chars); } } }
A B C D E F G H I
The output is
J Hello world!
K L M
Console.WriteLine(System.Char[], System.Int32, System.Int32) Method
N
[ILASM]
O
.method public hidebysig static void WriteLine(class System.Char[] buffer, int32 index, int32 count)
P
[C#]
public static void WriteLine(char[] buffer, int index, int count)
Q R
Summary
S
Writes a subarray of characters followed by a line terminator to the System.Console.OutSystem.IO.TextWriter.
T U
Parameters
V W
Parameter
Description
X
buffer
The Unicode character array from which data is read.
index
A System.Int32 that specifies the index into buffer at which to begin reading.
count
A System.Int32 that specifies the number of characters to write.
Y Z
568
Contents | Index
System
Console WriteLine() Method
Description This version of System.Console.WriteLine is equivalent to System.Console.Out.WriteLine(buffer, index, count). The default line terminator is the value of the System.Environment.NewLine property. The line terminator can be set using the System.IO.TextWriter.NewLine property of the System.Console.Out stream.
A B C D
Exceptions
E
Exception
Condition
System.ArgumentException
(index + count) is greater than the length of buffer.
F G H
System.IO.IOException
An I/O error occurred.
I
System.ArgumentOutOfRangeException
index or count is negative.
J
System.ArgumentNullException
buffer is null.
K L M
Example
N
using System;
O namespace Samples { public class ConsoleWriteLine { public static void Main() { char[] chars = new char[] {'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'}; Console.WriteLine(chars, 0, 5); } } }
P Q R S T U V W X
The output is
Y Hello
Z
569
Contents | Index
Console
System
WriteLine() Method
Console.WriteLine(System.Decimal) Method [ILASM]
.method public hidebysig static void WriteLine(decimal value)
A
[C#]
public static void WriteLine(decimal value)
B C
Summary
D
Writes the text representation of a specified System.Decimal followed by a line terminator to the System.Console.OutSystem.IO.TextWriter.
E F
Parameters
G H
Parameter
Description
value
The System.Decimal to write.
I J K
Description
L
This version of System.Console.WriteLine is equivalent to System.Console.Out.WriteLine(value.ToString()). The default line terminator is the value of the System.Environment.NewLine property. The line terminator can be set using the System.IO.TextWriter.NewLine property of the System.Console.Out stream. This member must be implemented if the Extended Numerics Library is present in the implementation.
M N O P Q
Exceptions
R S
Exception
Condition
System.IO.IOException
An I/O error occurred.
T U V
Example
W
using System;
X
namespace Samples { public class ConsoleWriteLine { public static void Main()
Y Z
570
Contents | Index
System
Console WriteLine() Method
{ Decimal[] decimals = new decimal[] {Decimal.MaxValue, Decimal.MinValue, Decimal.Zero, Decimal.MinusOne}; foreach(Decimal d in decimals) Console.WriteLine(d);
A B C
} }
D
}
E
The output is
F
79228162514264337593543950335 -79228162514264337593543950335 0 -1
G H I J
Console.WriteLine(System.Double) Method
K
[ILASM]
L
.method public hidebysig static void WriteLine(float64 value) [C#]
M
public static void WriteLine(double value)
N
Summary
O
Writes the text representation of a specified System.Double followed by a line terminator to the System.Console.OutSystem.IO.TextWriter.
P Q R
Parameters
S
Parameter
Description
T
value
The System.Double to write.
U V
Description
W
This version of System.Console.WriteLine is equivalent to System.Console.Out.WriteLine(value.ToString()). The default line terminator is the value of the System.Environment.NewLine property. The line terminator can be set using the System.IO.TextWriter.NewLine property of the System.Console.Out stream. This member must be implemented if the Extended Numerics Library is present in the implementation.
X Y Z
571
Contents | Index
Console
System
WriteLine() Method
Exceptions Exception
Condition
System.IO.IOException
An I/O error occurred.
A B C
Example
D
using System;
E
namespace Samples { public class ConsoleWriteLine { public static void Main() { double[] doubles = new double[] {Double.MaxValue, Double.MinValue, Double.NaN, Double.PositiveInfinity}; foreach(double d in doubles ) Console.WriteLine(d); } } }
F G H I J K L M N O
The output is
P Q
1.79769313486232E+308 -1.79769313486232E+308 NaN Infinity
R S T U
Console.WriteLine(System.Single) Method
V
[ILASM]
.method public hidebysig static void WriteLine(float32 value)
W
[C#]
X
public static void WriteLine(float value)
Y
Summary
Z
Writes the text representation of a specified System.Single followed by a line terminator to the System.Console.OutSystem.IO.TextWriter.
572
Contents | Index
System
Console WriteLine() Method
Parameters Parameter
Description
value
The System.Single to write.
A B C
Description
D
This version of System.Console.WriteLine is equivalent to System.Console.Out.WriteLine(value.ToString()). The default line terminator is the value of the System.Environment.NewLine property. The line terminator can be set using the System.IO.TextWriter.NewLine property of the System.Console.Out stream. This member must be implemented if the Extended Numerics Library is present in the implementation.
E F G H I
Exceptions
J K
Exception
Condition L
System.IO.IOException
An I/O error occurred.
M N
Example
O
using System;
P
namespace Samples { public class ConsoleWriteLine { public static void Main() { Single[] singles = new Single[] {Single.MaxValue, Single.MinValue, Single.NaN, Single.PositiveInfinity}; foreach(Single s in singles) Console.WriteLine(s); } } }
Q R S T U V W X Y Z
573
Contents | Index
Console
System
WriteLine() Method
The output is 3.402823E+38 -3.402823E+38 NaN Infinity
A B C D
Console.WriteLine(System.Int32) Method
E
[ILASM]
F
.method public hidebysig static void WriteLine(int32 value) [C#]
G
public static void WriteLine(int value)
H I
Summary
J
Writes the text representation of a specified System.Int32 followed by a line terminator to the System.Console.OutSystem.IO.TextWriter.
K
Parameters
L M
Parameter
Description
value
The System.Int32 to write.
N O P Q
Description
R
This version of System.Console.WriteLine is equivalent to System.Console.Out.WriteLine(value.ToString()). The default line terminator is the value of the System.Environment.NewLine property. The line terminator can be set using the System.IO.TextWriter.NewLine property of the System.Console.Out stream.
S T U V
Exceptions
W X
Exception
Condition
Y
System.IO.IOException
An I/O error occurred.
Z
574
Contents | Index
System
Console WriteLine() Method
Example using System; namespace Samples { public class ConsoleWriteLine { public static void Main() { Int32[] ints = new Int32[] {Int32.MaxValue, Int32.MinValue, 0}; foreach(Int32 i in ints) Console.WriteLine(i); } } }
A B C D E F G H I J
The output is
K
2147483647 -2147483648 0
L M N
Console.WriteLine(System.Int64) Method
O
[ILASM]
P
.method public hidebysig static void WriteLine(int64 value)
Q
[C#]
public static void WriteLine(long value)
R
Summary
S
Writes the text representation of a specified System.Int64 followed by a line terminator to the System.Console.OutSystem.IO.TextWriter.
T U V
Parameters
W
Parameter
Description
value
The System.Int64 to write.
X Y Z
575
Contents | Index
Console
System
WriteLine() Method
Description This version of System.Console.WriteLine is equivalent to System.Console.Out.WriteLine(value.ToString()). The default line terminator is the value of the System.Environment.NewLine property. The line terminator can be set using the System.IO.TextWriter.NewLine property of the System.Console.Out stream.
A B C D
Exceptions
E F G
Exception
Condition
System.IO.IOException
An I/O error occurred.
H I
Example
J
using System;
K
namespace Samples { public class ConsoleWriteLine { public static void Main() { Int64[] ints = new Int64[] {Int64.MaxValue, Int64.MinValue, 0}; foreach(Int64 i in ints) Console.WriteLine(i); } } }
L M N O P Q R S T
The output is
U
9223372036854775807 -9223372036854775808 0
V W X Y
Console.WriteLine(System.Object) Method
Z
[ILASM]
.method public hidebysig static void WriteLine(object value) [C#]
public static void WriteLine(object value)
576
Contents | Index
System
Console WriteLine() Method
Summary Writes the text representation of a specified object followed by a line terminator to the System.Console.OutSystem.IO.TextWriter. A
Parameters
B C
Parameter
Description
value
The object to write. If value is null, only the line terminator is written.
D E F
Description
G
This version of System.Console.WriteLine is equivalent to System.Console.Out.WriteLine(value.ToString()). The default line terminator is the value of the System.Environment.NewLine property. The line terminator can be set using the System.IO.TextWriter.NewLine property of the System.Console.Out stream.
H I J K L
Exceptions
M
Exception
Condition
System.IO.IOException
An I/O error occurred.
N O P Q
Example
R
using System;
S namespace Samples { public class ConsoleWriteLine { public override string ToString() { return "A string representation of an instance"; } public static void Main() { object[] objects = new object[] { new object(), "Hello world!", 42}; foreach(object o in objects) Console.WriteLine(o);
T U V W X Y Z
577
Contents | Index
Console
System
WriteLine() Method
ConsoleWriteLine c = new ConsoleWriteLine(); Console.WriteLine("Are they the same?"); Console.WriteLine(c); Console.WriteLine(c.ToString());
A
} }
B }
C
The output is
D E
System.Object Hello world! 42 Are they the same? A string representation of an instance A string representation of an instance
F G H I J
Console.WriteLine(System.String) Method
K [ILASM]
L
.method public hidebysig static void WriteLine(string value) [C#]
M
public static void WriteLine(string value)
N O
Summary
P
Writes a specified System.String followed by a line terminator to the System.Console.OutSystem.IO.TextWriter.
Q
Parameters
R S
Parameter
Description
value
The System.String to write. If value is null, only the line terminator is written.
T U V W
Description
X
This version of System.Console.WriteLine is equivalent to System.Console.Out.WriteLine(value). The default line terminator is the value of the System.Environment.NewLine property. The line terminator can be set using the System.IO.TextWriter.NewLine property of the System.Console.Out stream.
Y Z
578
Contents | Index
System
Console WriteLine() Method
Exceptions Exception
Condition
System.IO.IOException
An I/O error occurred.
A B C
Example
D
using System;
E
namespace Samples { public class ConsoleWriteLine { public static void Main() { string[] strings = new string[] {"Hello world!", "Goodbye world!"}; foreach(string s in strings) { Console.WriteLine(s); } } } }
F G H I J K L M N O
The output is
P Q
Hello world! Goodbye world!
R S
Console.WriteLine(System.String, System.Object) Method
T
[ILASM]
U
.method public hidebysig static void WriteLine(string format, object arg0)
V
[C#]
public static void WriteLine(string format, object arg0)
W X
Summary
Y
Writes a formatted string and a line terminator to the System.Console.OutSystem.IO.TextWriter.
Z
579
Contents | Index
Console
System
WriteLine() Method
Parameters Parameter
Description
format
A System.String that specifies the format string.
arg0
An object referenced in the format string.
A B C D E
Description
F
The default line terminator is the value of the System.Environment.NewLine property. The line terminator can be set using the System.IO.TextWriter.NewLine property of the System.Console.Out stream. [Note: If the specified object is not referenced in format, it is ignored. For more information on format strings, see the System.String class overview.]
G H I J
Exceptions
K L M
Exception
Condition
System.ArgumentNullException
format is null.
System.IO.IOException
An I/O error occurred.
N O
The format specification in format is invalid.
P
-or-
Q
System.FormatException
R S
The number indicating an argument to be formatted is less than zero, or greater than or equal to the number of provided objects to be formatted (1).
T
Example
U
using System;
V
namespace Samples { public class ConsoleWriteLine { public static void Main() { object[] objects = new object[] { new object(), "Hello world!", 42}; foreach(object o in objects)
W X Y Z
580
Contents | Index
System
Console WriteLine() Method
Console.WriteLine("{0} ", o); } } }
A
The output is
B C
System.Object Hello world! 42
D E F
Console.WriteLine(System.String, System.Object, System.Object) Method
G [ILASM]
H
.method public hidebysig static void WriteLine(string format, object arg0, object arg1)
I
[C#]
J
public static void WriteLine(string format, object arg0, object arg1)
K
Summary
L
Writes a formatted string and a new line to the System.Console.OutSystem.IO.TextWriter.
M N
Parameters
O P
Parameter
Description
format
A System.String that specifies the format string.
arg0
The first object referenced in the format string.
S
arg1
The second object referenced in the format string.
T
Q R
U
Description
V
The default line terminator is the value of the System.Environment.NewLine property. The line terminator can be set using the System.IO.TextWriter.NewLine property of the System.Console.Out stream. [Note: If a specified object is not referenced in format, it is ignored. For more information on format strings, see the System.String class overview.]
W X Y Z
581
Contents | Index
Console
System
WriteLine() Method
Exceptions Exception
Condition
B
System.ArgumentNullException
format is null.
C
System.IO.IOException
An I/O error occurred.
A
D
The format specification in format is invalid.
E
-orSystem.FormatException
F G
The number indicating an argument to be formatted is less than zero, or greater than or equal to the number of provided objects to be formatted (2).
H I
Example
J
using System;
K
namespace Samples { public class ConsoleWriteLine { public static void Main() { Console.WriteLine("{0}, {1} ", new object(), "Hello world!"); } } }
L M N O P Q R S
The output is
T System.Object, Hello world!
U V
Console.WriteLine(System.String, System.Object, System.Object, System.Object) Method
W X
[ILASM]
Y
.method public hidebysig static void WriteLine(string format, object arg0, object arg1, object arg2)
Z
[C#]
public static void WriteLine(string format, object arg0, object arg1, object arg2)
582
Contents | Index
System
Console WriteLine() Method
Summary Writes a formatted string and a new line to the System.Console.OutSystem.IO.TextWriter. A
Parameters
B C
Parameter
Description
format
A System.String that specifies the format string.
E
arg0
The first object referenced in the format string.
F
arg1
The second object referenced in the format string.
arg2
The third object referenced in the format string.
D
G H I J
Description
K
The default line terminator is the value of the System.Environment.NewLine property. The line terminator can be set using the System.IO.TextWriter.NewLine property of the System.Console.Out stream. [Note: If a specified object is not referenced in format, it is ignored. For more information on format strings, see the System.String class overview.]
M
Exceptions
P
L
N O
Q
Exception
Condition
System.ArgumentNullException
format is null.
System.IO.IOException
An I/O error occurred.
R S T U
The format specification in format is invalid. V
-orSystem.FormatException
W
The number indicating an argument to be formatted is less than zero, or greater than or equal to the number of provided objects to be formatted (3).
X Y Z
583
Contents | Index
Console
System
WriteLine() Method
Example using System; namespace Samples { public class ConsoleWriteLine { public static void Main() { Console.WriteLine("{0}, {1}, {2}", new object(), "Hello world!", 42); } } }
A B C D E F G H I
The output is
J System.Object, Hello world!, 42
K L M
Console.WriteLine(System.String, System.Object[]) Method
N
[ILASM]
O
.method public hidebysig static void WriteLine(string format, class System.Object[] arg)
P
[C#]
public static void WriteLine(string format, params object[] arg)
Q R
Summary
S
Writes a formatted string and a new line to the System.Console.OutSystem.IO.TextWriter.
T U
Parameters
V W
Parameter
Description
X
format
A System.String that specifies the format string.
arg
An array of objects referenced in the format string.
Y Z
584
Contents | Index
System
Console WriteLine() Method
Description The default line terminator is the value of the System.Environment.NewLine property. The line terminator can be set using the System.IO.TextWriter.NewLine property of the System.Console.Out stream. [Note: If a specified object is not referenced in format, it is ignored. For more information on format strings, see the System.String class overview.]
A B C D
Exceptions
E
Exception
Condition
System.ArgumentNullException
format or arg is null.
System.IO.IOException
An I/O error occurred.
F G H I
The format specification in format is invalid. System.FormatException
J
-or-
K
The number indicating an argument to be formatted is less than zero, or greater than or equal to arg.Length.
L M
Example
N
using System;
O
namespace Samples { public class ConsoleWriteLine { public static void Main() { object[] objects = new object[] { new object(), "Hello world!", 42}; Console.WriteLine("{0}, {1}, {2}", objects); } } }
P Q R S T U V W X
The output is
Y
System.Object, Hello world!, 42
Z
585
Contents | Index
Console
System
WriteLine() Method
Console.WriteLine(System.UInt32) Method [ILASM]
.method public hidebysig static void WriteLine(unsigned int32 value)
A
[C#]
publc static void WriteLine(uint value)
B C
Summary
D
Writes the text representation of a specified System.UInt32 followed by a line terminator to the System.Console.OutSystem.IO.TextWriter.
E F
Parameters
G H I
Parameter
Description
value
The System.UInt32 to write.
J K
Description
L
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Console.WriteLine(System.Int64). This version of System.Console.WriteLine is equivalent to System.Console.Out.WriteLine(value.ToString()). The default line terminator is the value of the System.Environment.NewLine property. The line terminator can be set using the System.IO.TextWriter.NewLine property of the System.Console.Out stream.
M N O P Q
Exceptions
R S T U
Exception
Condition
System.IO.IOException
An I/O error occurred.
V W
Example
X
using System;
Y
namespace Samples { public class ConsoleWriteLine { public static void Main()
Z
586
Contents | Index
System
Console WriteLine() Method
{ UInt32[] uints = new UInt32[] {UInt32.MaxValue, UInt32.MinValue}; foreach(UInt32 i in uints) Console.WriteLine(i);
A B
}
C
} }
D
The output is
E F
4294967295 0
G H
Console.WriteLine(System.UInt64) Method
I
[ILASM]
J
.method public hidebysig static void WriteLine(unsigned int64 value)
K
[C#]
L
public static void WriteLine(ulong value)
M
Summary
N
Writes the text representation of a specified System.UInt64 followed by a line terminator to the System.Console.OutSystem.IO.TextWriter.
O P
Parameters
Q
Parameter
Description
value
The System.UInt64 to write.
R S T U
Description
V
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Console.WriteLine(System.Decimal). This version of System.Console.WriteLine is equivalent to System.Console.Out.WriteLine(value.ToString()). The default line terminator is the value of the System.Environment.NewLine property. The line terminator can be set using the System.IO.TextWriter.NewLine property of the System.Console.Out stream.
W X Y Z
587
Contents | Index
Console
System
WriteLine() Method
Exceptions Exception
Condition
System.IO.IOException
An I/O error occurred.
A B C
Example
D
using System;
E
namespace Samples { public class ConsoleWriteLine { public static void Main() { UInt64[] uints = new UInt64[] {UInt64.MaxValue, UInt64.MinValue}; foreach(UInt64 i in uints) Console.WriteLine(i); } } }
F G H I J K L M N O
The output is
P
18446744073709551615 0
Q R S T U V W X Y Z
588
Contents | Index
System Convert
BCL
Object
A
Convert
B
Summary
C
Performs conversions between base data types.
D E
Type Summary public sealed class Convert { // Fields MS public static readonly object DBNull = DBNull.Value;
F G H
// Methods MS CF public static object ChangeType (object value, TypeCode typeCode); MS public static object ChangeType (object value, TypeCode typeCode, IFormatProvider provider); MS CF public static object ChangeType (object value, Type conversionType); MS public static object ChangeType (object value, Type conversionType, IFormatProvider provider); MS public static byte[] FromBase64CharArray (char[] inArray, int offset, int length); MS public static byte[] FromBase64String (string s); MS public static TypeCode GetTypeCode (object value); MS public static bool IsDBNull (object value); MS public static int ToBase64CharArray (byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut); MS CF public static string ToBase64String (byte[] inArray); MS public static string ToBase64String (byte[] inArray, int offset, int length); public static bool ToBoolean (bool value); public static bool ToBoolean (byte value); MS public static bool ToBoolean (char value); public static bool ToBoolean (decimal value); public static bool ToBoolean (double value);
I J K L M N O P Q R S T U V W X Y Z
589
Contents | Index
Convert
System
Convert Class
A
public public public MS public MS public
static static static static static
bool bool bool bool bool
public public public MS public
static static static static
bool bool bool bool
MS CF public public public public public public public public public public public public MS CF public MS public
static static static static static static static static static static static static static static
bool bool bool bool byte byte byte byte byte byte byte byte byte byte
public public public MS public
static static static static
byte byte byte byte
B C D E F G H I J K L M N O P Q public static byte
R S
MS CF public public public public MS CF public public public MS public MS public MS public public public MS public MS public
T U V W X Y Z
static static static static static static static static static static static static static static
byte byte byte byte char char char char char char char char char char
ToBoolean ToBoolean ToBoolean ToBoolean ToBoolean
(float value); (int value); (long value); (object value); (object value, IFormatProvider provider); ToBoolean (sbyte value); ToBoolean (short value); ToBoolean (string value); ToBoolean (string value, IFormatProvider provider); ToBoolean (DateTime value); ToBoolean (uint value); ToBoolean (ulong value); ToBoolean (ushort value); ToByte (bool value); ToByte (byte value); ToByte (char value); ToByte (decimal value); ToByte (double value); ToByte (float value); ToByte (int value); ToByte (long value); ToByte (object value); ToByte (object value, IFormatProvider provider); ToByte (sbyte value); ToByte (short value); ToByte (string value); ToByte (string value, int fromBase); ToByte (string value, IFormatProvider provider); ToByte (DateTime value); ToByte (uint value); ToByte (ulong value); ToByte (ushort value); ToChar (bool value); ToChar (byte value); ToChar (char value); ToChar (decimal value); ToChar (double value); ToChar (float value); ToChar (int value); ToChar (long value); ToChar (object value); ToChar (object value, IFormatProvider provider);
590
Contents | Index
System
Convert Convert Class
public public public MS public
static static static static
MS CF public public public public MS CF public MS CF public MS CF public MS CF public MS CF public MS CF public MS CF public MS CF public MS public MS public
static static static static static static static static static static static static static static
MS CF public MS CF public public public
static static static static
CF public static MS CF public static MS CF public static MS CF public static public static public static MS public static public static public static public static public static public static MS public static MS CF public static public public public public
static static static static
MS public static public static public static
char char char char
ToChar ToChar ToChar ToChar
(sbyte value); (short value); (string value); (string value, IFormatProvider provider); char ToChar (DateTime value); char ToChar (uint value); char ToChar (ulong value); char ToChar (ushort value); DateTime ToDateTime (bool value); DateTime ToDateTime (byte value); DateTime ToDateTime (char value); DateTime ToDateTime (decimal value); DateTime ToDateTime (double value); DateTime ToDateTime (float value); DateTime ToDateTime (int value); DateTime ToDateTime (long value); DateTime ToDateTime (object value); DateTime ToDateTime (object value, IFormatProvider provider); DateTime ToDateTime (sbyte value); DateTime ToDateTime (short value); DateTime ToDateTime (string value); DateTime ToDateTime (string value, IFormatProvider provider); DateTime ToDateTime (DateTime value); DateTime ToDateTime (uint value); DateTime ToDateTime (ulong value); DateTime ToDateTime (ushort value); decimal ToDecimal (bool value); decimal ToDecimal (byte value); decimal ToDecimal (char value); decimal ToDecimal (decimal value); decimal ToDecimal (double value); decimal ToDecimal (float value); decimal ToDecimal (int value); decimal ToDecimal (long value); decimal ToDecimal (object value); decimal ToDecimal (object value, IFormatProvider provider); decimal ToDecimal (sbyte value); decimal ToDecimal (short value); decimal ToDecimal (string value); decimal ToDecimal (string value, IFormatProvider provider); decimal ToDecimal (DateTime value); decimal ToDecimal (uint value); decimal ToDecimal (ulong value);
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
591
Contents | Index
Convert
System
Convert Class
A B C D E F G H I J K L M N O P Q R S T
public public public MS public public public public public public MS public MS CF public
static static static static static static static static static static static
public public public public
static static static static
MS CF public public public public public public public public public public public public MS CF public MS public
static static static static static static static static static static static static static static
public public public MS public
static static static static
U public static
V MS CF public public public public public public public public public
W X Y Z
static static static static static static static static static
decimal ToDecimal (ushort value); double ToDouble (bool value); double ToDouble (byte value); double ToDouble (char value); double ToDouble (decimal value); double ToDouble (double value); double ToDouble (float value); double ToDouble (int value); double ToDouble (long value); double ToDouble (object value); double ToDouble (object value, IFormatProvider provider); double ToDouble (sbyte value); double ToDouble (short value); double ToDouble (string value); double ToDouble (string value, IFormatProvider isop); double ToDouble (DateTime value); double ToDouble (uint value); double ToDouble (ulong value); double ToDouble (ushort value); short ToInt16(bool value); short ToInt16(byte value); short ToInt16(char value); short ToInt16(decimal value); short ToInt16(double value); short ToInt16(float value); short ToInt16(int value); short ToInt16(long value); short ToInt16(object value); short ToInt16(object value, IFormatProvider provider); short ToInt16(sbyte value); short ToInt16(short value); short ToInt16(string value); short ToInt16(string value, int fromBase); short ToInt16(string value, IFormatProvider provider); short ToInt16(DateTime value); short ToInt16(uint value); short ToInt16(ulong value); short ToInt16(ushort value); int ToInt32(bool value); int ToInt32(byte value); int ToInt32(char value); int ToInt32(decimal value); int ToInt32(double value);
592
Contents | Index
System
Convert Convert Class
public public public MS public MS CF public
static static static static static
public public public MS public
static static static static
public static MS CF public public public public public public public public public public public public MS public MS CF public
static static static static static static static static static static static static static static
public public public MS public
static static static static
public static MS CF public public public public public public public public public public public public MS CF public
static static static static static static static static static static static static static
int int int int int
ToInt32(float value); ToInt32(int value); ToInt32(long value); ToInt32(object value); ToInt32(object value, IFormatProvider provider); int ToInt32(sbyte value); int ToInt32(short value); int ToInt32(string value); int ToInt32(string value, int fromBase); int ToInt32(string value, IFormatProvider provider); int ToInt32(DateTime value); int ToInt32(uint value); int ToInt32(ulong value); int ToInt32(ushort value); long ToInt64(bool value); long ToInt64(byte value); long ToInt64(char value); long ToInt64(decimal value); long ToInt64(double value); long ToInt64(float value); long ToInt64(int value); long ToInt64(long value); long ToInt64(object value); long ToInt64(object value, IFormatProvider provider); long ToInt64(sbyte value); long ToInt64(short value); long ToInt64(string value); long ToInt64(string value, int fromBase); long ToInt64(string value, IFormatProvider provider); long ToInt64(DateTime value); long ToInt64(uint value); long ToInt64(ulong value); long ToInt64(ushort value); sbyte ToSByte (bool value); sbyte ToSByte (byte value); sbyte ToSByte (char value); sbyte ToSByte (decimal value); sbyte ToSByte (double value); sbyte ToSByte (float value); sbyte ToSByte (int value); sbyte ToSByte (long value); sbyte ToSByte (object value);
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
593
Contents | Index
Convert
System
Convert Class
A B C D
MS
E F G H I J K L
MS
M N O P MS
Q R S MS
T U V W X MS
Y Z
MS public static sbyte ToSByte (object value, IFormatProvider provider); public static sbyte ToSByte (sbyte value); public static sbyte ToSByte (short value); public static sbyte ToSByte (string value); MS public static sbyte ToSByte (string value, int fromBase); public static sbyte ToSByte (string value, IFormatProvider provider); CF public static sbyte ToSByte (DateTime value); public static sbyte ToSByte (uint value); public static sbyte ToSByte (ulong value); public static sbyte ToSByte (ushort value); public static float ToSingle (bool value); public static float ToSingle (byte value); MS public static float ToSingle (char value); public static float ToSingle (decimal value); public static float ToSingle (double value); public static float ToSingle (float value); public static float ToSingle (int value); public static float ToSingle (long value); MS public static float ToSingle (object value); CF public static float ToSingle (object value, IFormatProvider provider); public static float ToSingle (sbyte value); public static float ToSingle (short value); public static float ToSingle (string value); public static float ToSingle (string value, IFormatProvider isop); CF public static float ToSingle (DateTime value); public static float ToSingle (uint value); public static float ToSingle (ulong value); public static float ToSingle (ushort value); public static string ToString (bool value); CF public static string ToString (bool value, IFormatProvider provider); public static string ToString (byte value); MS public static string ToString (byte value, int toBase); CF public static string ToString (byte value, IFormatProvider provider); public static string ToString (char value); CF public static string ToString (char value, IFormatProvider provider); public static string ToString (decimal value); public static string ToString (decimal value, IFormatProvider isop); public static string ToString (double value);
594
Contents | Index
System
Convert Convert Class
MS CF
MS CF MS MS CF
CF
MS CF CF MS CF
CF
CF
CF
CF
public static string ToString (double value, IFormatProvider isop); public static string ToString (float value); public static string ToString (float value, IFormatProvider isop); public static string ToString (int value); public static string ToString (int value, int toBase); public static string ToString (int value, IFormatProvider provider); public static string ToString (long value); public static string ToString (long value, int toBase); public static string ToString (long value, IFormatProvider provider); public static string ToString (object value); public static string ToString (object value, IFormatProvider provider); public static string ToString (sbyte value); public static string ToString (sbyte value, IFormatProvider provider); public static string ToString (short value); public static string ToString (short value, int toBase); public static string ToString (short value, IFormatProvider provider); public static string ToString (string value); public static string ToString (string value, IFormatProvider provider); public static string ToString (DateTime value); public static string ToString (DateTime value, IFormatProvider provider); public static string ToString (uint value); public static string ToString (uint value, IFormatProvider provider); public static string ToString (ulong value); public static string ToString (ulong value, IFormatProvider provider); public static string ToString (ushort value); public static string ToString (ushort value, IFormatProvider provider); public static ushort ToUInt16(bool value); public static ushort ToUInt16(byte value); public static ushort ToUInt16(char value); public static ushort ToUInt16(decimal value); public static ushort ToUInt16(double value); public static ushort ToUInt16(float value); public static ushort ToUInt16(int value);
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
595
Contents | Index
Convert
System
Convert Class
public static ushort ToUInt16(long value); MS public static ushort ToUInt16(object value); MS CF public static ushort ToUInt16(object value, IFormatProvider provider); public static ushort ToUInt16(sbyte value); public static ushort ToUInt16(short value); public static ushort ToUInt16(string value); MS public static ushort ToUInt16(string value, int fromBase); public static ushort ToUInt16(string value, IFormatProvider provider); MS CF public static ushort ToUInt16(DateTime value); public static ushort ToUInt16(uint value); public static ushort ToUInt16(ulong value); public static ushort ToUInt16(ushort value); public static uint ToUInt32(bool value); public static uint ToUInt32(byte value); public static uint ToUInt32(char value); public static uint ToUInt32(decimal value); public static uint ToUInt32(double value); public static uint ToUInt32(float value); public static uint ToUInt32(int value); public static uint ToUInt32(long value); MS public static uint ToUInt32(object value); MS CF public static uint ToUInt32(object value, IFormatProvider provider); public static uint ToUInt32(sbyte value); public static uint ToUInt32(short value); public static uint ToUInt32(string value); MS public static uint ToUInt32(string value, int fromBase); public static uint ToUInt32(string value, IFormatProvider provider); MS CF public static uint ToUInt32(DateTime value); public static uint ToUInt32(uint value); public static uint ToUInt32(ulong value); public static uint ToUInt32(ushort value); public static ulong ToUInt64(bool value); public static ulong ToUInt64(byte value); public static ulong ToUInt64(char value); public static ulong ToUInt64(decimal value); public static ulong ToUInt64(double value); public static ulong ToUInt64(float value); public static ulong ToUInt64(int value); public static ulong ToUInt64(long value); MS public static ulong ToUInt64(object value); MS CF public static ulong ToUInt64(object value, IFormatProvider provider);
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
596
Contents | Index
System
Convert Convert Class
public public public MS public
static static static static
ulong ulong ulong ulong
public static ulong MS CF public public public public }
static static static static
ulong ulong ulong ulong
ToUInt64(sbyte value); ToUInt64(short value); ToUInt64(string value); ToUInt64(string value, int fromBase); ToUInt64(string value, IFormatProvider provider); ToUInt64(DateTime value); ToUInt64(uint value); ToUInt64(ulong value); ToUInt64(ushort value);
A B C D E F G
BA Early in the design of the BCL we went back and forth trying to decide how we wanted conversions to be supported in the library. Initially we wanted to distribute them as instance methods in each class:
H I J
int i = 10; double d = Int32.ToDouble(i);
K L
This design has the advantage of being more easily discoverable as it does not require an intermediate object. Later, we tried a different design that had a single object with all the conversions, so that the same conversion would be:
M N
int i = 10; double d = Convert.ToDouble(i);
O P
We liked this approach because if the developer needs to change the type of the i variable to a long she would only have to change the declaration, not every usage:
Q R
long i = 10; double d = Convert.ToDouble(i);
S T
AH In the early days of .NET we had two types that could be used to represent
U
dynamically typed values: System.Object and System.Variant. System.Variant was basically a managed wrapper for OLE Automation variants.
V W
Having two ways of doing what amounts to the same thing caused tremendous confusion in the libraries. Some APIs would use Object, others would use Variant. Some even tried to support both, which introduced lots of ambiguities. We finally
X Y
continued
Z
597
Contents | Index
Convert
System
Convert Class
made the hard call to get rid of Variant. In retrospect, this was clearly the right decision. We can now say that “every piece of data in .NET is an object,” which brings about tremendous conceptual simplification.
A B
The types of operations that were traditionally provided by OLE Automation’s variant support, such VarChangeType() that converts a variant from one type to another, is now provided by the Convert class and the IConvertible interface.
C D
KG The great thing about Convert is that once you know about it, it is easy to learn the pattern, and use it for any base type conversions you need. In addition, if you’re working in a particular language, you can easily use exactly the same mechanism in a different language. Because the conversion mechanism is not part of the classes themselves, discovering it for the first time is a little more difficult: that is the trade-off.
E F G H I
It is interesting to note that we have yet to develop the same central conversion mechanism for truncating numbers. Convert uses standard banker’s rounding to convert numbers to and from strings, or each other (Convert.ToInt32(22.5) will result in a value of 22, for example) but to simply get the integer part of the number, for truncation I have to use language-specific functionality such as casting in C#, or the Int() or Fix() functions in Visual Basic. This seems to defeat a guiding principle of the framework: to provide language-neutral mechanisms for standard operations.
J K L M N
KC Type names should be noun phrases, not verb phrases. Probably a better name for this type would be Converter.
O P Q
JR When you want to convert a numeric value from one type to another, you should try to use your language’s casting syntax first. If your language doesn’t allow the cast, then you should use the methods of the Convert class. For example, Visual Basic. NET doesn’t allow casting syntax to convert a UInt32 to be cast to an Int32 but, Visual Basic. NET code can call Convert’s ToInt32 method passing a UInt32 value. Finally, some classes implement the IConvertible interface which defines methods that convert a value from one type to another. You should avoid the IConvertible methods since they usually require the object be boxed first, which adversely affects your application’s performance.
R S T U V W X Y
Description
Z
The following table shows conversions from source types to destination types. The first column contains the source types. The remaining columns indicate the destination types the source may be converted to. An ‘x’ indicates the System.Convert class implements
598
Contents | Index
System
Convert Convert Class
the conversion. [Note: The column headers correspond precisely, in order, to the source types in the first column, but have been abbreviated to fit.] A
Type
Bool Byte Char
Boolean
x
x
Byte
x
x
x
x
x
DT
Dec
Dou
I16
I32
I64
SBy
Sin
Str UI16 UI32 UI64
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
B C D E
Char DateTime
x
F
x
G
Decimal
x
x
x
x
x
x
x
x
x
x
x
x
x
H
Double
x
x
x
x
x
x
x
x
x
x
x
x
x
I
Int16
x
x
x
x
x
x
x
x
x
x
x
x
x
x
Int32
x
x
x
x
x
x
x
x
x
x
x
x
x
x
Int64
x
x
x
x
x
x
x
x
x
x
x
x
x
x
M
SByte
x
x
x
x
x
x
x
x
x
x
x
x
x
x
N
Single
x
x
x
x
x
x
x
x
x
x
x
x
x
O
String
x
x
x
x
x
x
x
x
x
x
x
x
x
x
UInt16
x
x
x
x
x
x
x
x
x
x
x
x
x
x
UInt32
x
x
x
x
x
x
x
x
x
x
x
x
x
x
S
UInt64
x
x
x
x
x
x
x
x
x
x
x
x
x
x
T
J K
x
L
P Q R
U V
If the conversion of a numeric type results in a loss of precision, no exception is thrown. However, an exception is thrown if the conversion result is a value that is larger than that which can be represented by the destination type. For example, when a System.Double is converted to a System.Single, a loss of precision may occur but no exception is thrown. However, if the magnitude of the System.Double is too large to be represented by a System.Single, a System.OverflowException is thrown.
W X Y Z
599
Contents | Index
Convert
System
DBNull Field
Convert.DBNull Field [ILASM]
.field public static initOnly object DBNull
A
[C#]
public static readonly object DBNull = DBNull.Value
B C
Summary
D
A constant representing a database column absent of data; that is, database null.
E F
Convert.ChangeType(System.Object, System.TypeCode) Method
G
[ILASM]
H
.method public hidebysig static object ChangeType(object value, valuetype System.TypeCode typeCode)
I
[C#]
J
public static object ChangeType(object value, TypeCode typeCode)
K
Summary
L
Returns a System.Object with the specified System.TypeCode and whose value is equivalent to the specified object.
M N
Parameters
O P
Parameter
Description
value
A System.Object that implements the System.IConvertible interface.
typeCode
A System.TypeCode
Q R S T U
Return Value
V
An object whose underlying System.TypeCode is typeCode and whose value is equivalent to value.
W X Y Z
600
Contents | Index
System
Convert ChangeType() Method
Exceptions Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
System.ArgumentException
typeCode is invalid.
A B C D E
Convert.ChangeType(System.Object, System.TypeCode, System.IFormatProvider) Method
F G
[ILASM]
H
.method public hidebysig static object ChangeType(object value, valuetype System.TypeCode typeCode, class System.IFormatProvider provider)
I
[C#]
J
public static object ChangeType(object value, TypeCode typeCode, IFormatProvider provider)
K
Summary
L
Returns a System.Object with the specified System.TypeCode and whose value is equivalent to the specified object. A parameter supplies culture-specific formatting information.
M N O
Parameters
P Q
Parameter
Description
value
A System.Object that implements the System.IConvertible interface.
S
typeCode
A System.TypeCode.
T
provider
A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
R
U V W
Return Value
X
An object whose underlying System.TypeCode is typeCode and whose value is equivalent to value or null if value is null and typeCode is System.TypeCode.Empty.
Y Z
601
Contents | Index
Convert
System
ChangeType() Method
Description provider enables the user to specify culture-specific conversion information about the contents of value. For example, if value is a System.String that represents a number, provider could supply culture-specific information about the notation used to represent that number.
A B
Exceptions
C D
Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
System.ArgumentException
typeCode is invalid.
E F G H I
Convert.ChangeType(System.Object, System.Type) Method
J
[ILASM]
K
.method public hidebysig static object ChangeType(object value, class System.Type conversionType)
L
[C#]
M
public static object ChangeType(object value, Type conversionType)
N O
Summary
P
Returns an System.Object with the specified System.Type and whose value is equivalent to the specified object.
Q
Parameters
R S
Parameter
Description
U
value
An System.Object that implements the System.IConvertible interface.
V
conversionType
A System.Type.
T
W X
Return Value
Y
An object whose System.Type is conversionType and whose value is equivalent to value.
Z
Description This method uses the current thread’s culture for the conversion. 602
Contents | Index
System
Convert ChangeType() Method
Exceptions Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
A B C D
Convert.ChangeType(System.Object, System.Type, System.IFormatProvider) Method
E F
[ILASM]
.method public hidebysig static object ChangeType(object value, class System.Type conversionType, class System.IFormatProvider provider)
G
[C#]
H
public static object ChangeType(object value, Type conversionType, IFormatProvider provider)
I J
Summary
K
Returns a System.Object with the specified System.Type and whose value is equivalent to the specified object. A parameter supplies culture-specific formatting information.
L M
Parameters
N
Parameter
Description
value
A System.Object that implements the System.IConvertible interface.
conversionType
A System.Type.
provider
A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
O P Q R S T U
Return Value
V
An object whose System.Type is conversionType and whose value is equivalent to value, or null, if value and conversionType are nulls, or value, if the System.Type of value and conversionType are equal.
W X Y
Description
Z
provider enables the user to specify culture-specific conversion information about the contents of value. For example, if value is a System.String that represents a number, provider could supply culture-specific information about the notation used to represent that number. 603
Contents | Index
Convert
System
FromBase64CharArray() Method
Exceptions Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible and conversionType is not null or equal to the System.Type of value.
System.ArgumentException
conversionType is invalid.
A B C D E F
Convert.FromBase64CharArray(System.Char[], System.Int32, System.Int32) Method
G H
[ILASM]
I
.method public hidebysig static class System.Byte[] FromBase64CharArray(class System.Char[] inArray, int32 offset, int32 length)
J
[C#]
K
public static byte[] FromBase64CharArray(char[] inArray, int offset, int length)
L
Summary
M
Converts the specified subset of an array of Unicode characters consisting of base 64 digits to an equivalent array of 8-bit unsigned integers. Parameters specify the offset and number of elements in the input array.
N O P
Parameters
Q R
Parameter
Description
inArray
A Unicode character array.
U
offset
A position within inArray.
V
length
The number of elements in inArray to convert.
S T
W X
Return Value
Y
An array of 8-bit unsigned integers equivalent to length elements at position offset in inArray.
Z
604
Contents | Index
System
Convert FromBase64String() Method
Description inArray is composed of base 64 digits, white space characters, and trailing padding characters. The base 64 digits in ascending order from zero are the uppercase characters ‘A’ to ‘Z’, lowercase characters ‘a’ to ‘z’, numerals ‘0’ to ‘9’, and the symbols ‘+’ and ‘/’. The white space characters are tab, blank, carriage return, and newline. An arbitrary number of white space characters can appear in inArray because all white space characters are ignored. The valueless character, ‘=’, is used for trailing padding. The end of inArray can consist of zero, one, or two padding characters.
A B C D E F
Exceptions
G
Exception
Condition
H
System.ArgumentNullException
inArray is null.
I J
offset or length is less than 0. System.ArgumentOutOfRangeException
K
-or-
L
offset plus length indicates a position not within inArray.
M
The length of inArray, ignoring white space characters, is less than 4. System.FormatException
N
-or-
O
The length of inArray, ignoring white space characters, is not an even multiple of 4.
P Q R
Convert.FromBase64String(System.String) Method
S
[ILASM]
T
.method public hidebysig static class System.Byte[] FromBase64String(string s) [C#]
U
public static byte[] FromBase64String(string s)
V
Summary
W
Converts the specified System.String representation of a value consisting of base 64 digits to an equivalent array of 8-bit unsigned integers.
X Y Z
605
Contents | Index
Convert
System
GetTypeCode() Method
Parameters Parameter
Description
s
A System.String.
A B C
Description
D
s is composed of base 64 digits, white space characters, and trailing padding characters. The base 64 digits in ascending order from zero are the uppercase characters ‘A’ to ‘Z’, lowercase characters ‘a’ to ‘z’, numerals ‘0’ to ‘9’, and the symbols ‘+’ and ‘/’. The white space characters are tab, blank, carriage return, and newline. An arbitrary number of white space characters can appear in s because all white space characters are ignored. The valueless character, ‘=’, is used for trailing padding. The end of s can consist of zero, one, or two padding characters.
E F G H I J
Exceptions
K L
Exception
Condition
System.ArgumentNullException
s is null.
System.FormatException
The length of s, ignoring white space characters, is less than 4. -orThe length of s, ignoring white space characters, is not an even multiple of 4.
M N O P Q R S T
Convert.GetTypeCode(System.Object) Method
U
[ILASM]
.method public hidebysig static valuetype System.TypeCode GetTypeCode(object value)
V
[C#]
W
public static TypeCode GetTypeCode(object value)
X
Summary
Y
Returns the System.TypeCode for the specified object.
Z
606
Contents | Index
System
Convert ToBase64CharArray() Method
Parameters Parameter
Description
value
A System.Object that implements the System.IConvertible interface.
A B C
Return Value
D
The System.TypeCode for value, or System.TypeCode.Empty if value is null.
E F
Convert.IsDBNull(System.Object) Method
G
[ILASM]
H
.method public hidebysig static bool IsDBNull(object value)
I
[C#]
J
public static bool IsDBNull(object value)
K
Summary
L
Returns an indication whether the specified object is of type System.TypeCode.DBNull.
M
Parameters
N O
Parameter
Description
value
An object.
P Q R
Return Value
S
true if value is of type System.TypeCode.DBNull; otherwise, false.
T U V
Convert.ToBase64CharArray(System.Byte[], System.Int32, System.Int32, System.Char[], System.Int32) Method
W
[ILASM]
X
.method public hidebysig static int32 ToBase64CharArray(class System.Byte[] inArray, int32 offsetIn, int32 length, class System.Char[] outArray, int32 offsetOut)
Y
[C#]
Z
public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut)
607
Contents | Index
Convert
System
ToBase64CharArray() Method
Summary Converts the value of a subset of an 8-bit unsigned integer array to an equivalent subset of a Unicode character array consisting of base 64 digits. Parameters specify the subsets as offsets of the input and output arrays and the number of elements in the input array.
A B
Parameters
C D
Parameter
Description
inArray
An input array of 8-bit unsigned integers.
G
offsetIn
A position within inArray.
H
length
The number of elements of inArray to convert.
I
outArray
An output array of Unicode characters.
offsetOut
A position within outArray.
E F
J K L
Return Value
M
A 32-bit signed integer containing the number of bytes in outArray.
N O
Description
P
The subset of length elements of inArray starting at position offsetIn is taken as a numeric value and converted to a subset of elements in outArray starting at position offsetOut. The return value indicates the number of converted elements in outArray. The subset of outArray consists of base 64 digits. The base 64 digits in ascending order from zero are the uppercase characters ’A’ to ’Z’, lowercase characters ’a’ to ’z’, numerals ’0’ to ’9’, and the symbols ’+’ and ’/’. The valueless character, ’=’, is used for trailing padding. offset and length are 32-bit signed numbers. offsetIn and offsetOut are zero-based array positions.
Q R S T U V W X Y Z
608
Contents | Index
System
Convert ToBase64String() Method
Exceptions Exception
Condition
System.ArgumentNullException
inArray is null.
A
System.ArgumentOutOfRangeException
B
offsetIn, offsetOut, or length is negative.
C
-or-
D
offsetIn plus length is greater than the length of inArray.
E
-orF
offsetOut plus the number of elements to return is greater than the length of outArray.
G H I
Convert.ToBase64String(System.Byte[]) Method
J
[ILASM]
K
.method public hidebysig static string ToBase64String(class System.Byte[] inArray)
L
[C#]
public static string ToBase64String(byte[] inArray)
M
Summary
N
Converts the value of an array of 8-bit unsigned integers to its equivalent System.String representation consisting of base 64 digits.
O
Parameters
Q
P
R
Parameter
Description
S
inArray
An array of 8-bit unsigned integers.
T U V
Description
W
The elements of inArray are taken as a numeric value and converted to a System.String representation consisting of base 64 digits. The base 64 digits in ascending order from zero are the uppercase characters ’A’ to ’Z’, lowercase characters ’a’ to ’z’, numerals ’0’ to ’9’, and the symbols ’+’ and ’/’. The valueless character, ’=’, is used for trailing padding.
X Y Z
609
Contents | Index
Convert
System
ToBase64String() Method
Exceptions Exception
Condition
System.ArgumentNullException
inArray is null.
A B C D
Convert.ToBase64String(System.Int32, System.Int32) Method
E
[ILASM]
F
.method public hidebysig static string ToBase64String(class System.Byte[] inArray, int32 offset, int32 length)
G
[C#]
H
public static string ToBase64String(byte[] inArray, int offset, int length)
I
Summary
J
Converts the value of a subset of an array of 8-bit unsigned integers to its equivalent System.String representation consisting of base 64 digits. Parameters specify the subset as an offset and number of elements in the array.
K L
Parameters
M N
Parameter
Description
inArray
An array of 8-bit unsigned integers.
Q
offset
An offset in inArray.
R
length
The number of elements of inArray to convert.
O P
S T
Return Value
U
The System.String representation in base 64 of length elements of inArray starting at position offset.
V W
Description
X
The elements of inArray are taken as a numeric value and converted to a System.String representation in base 64. The base 64 digits in ascending order from zero are the uppercase characters ’A’ to ’Z’, lowercase characters ’a’ to ’z’, numerals ’0’ to ’9’, and the symbols ’+’ and ’/’. The valueless character, ’=’, is used for trailing padding. offset and length are 32-bit signed numbers. offset is zero-based.
Y Z
610
Contents | Index
System
Convert ToBoolean() Method
Exceptions Exception
Condition
System.ArgumentNullException
inArray is null.
A
System.ArgumentOutOfRangeException
B
offset or length is negative.
C
-or-
D
offset plus length is greater than the length of inArray.
E F G
Convert.ToBoolean(System.Boolean) Method
H [ILASM]
.method public hidebysig static bool ToBoolean(bool value)
I
[C#]
J
public static bool ToBoolean(bool value)
K
Summary
L
Converts a System.Boolean to a System.Boolean.
M N
Parameters
O
Parameter
Description
P
value
The System.Boolean value to be converted.
Q R S
Return Value
T
value is returned unchanged.
U
Description
V
[Note: This method is provided for completeness.]
W X Y Z
611
Contents | Index
Convert
System
ToBoolean() Method
Example using System; namespace Samples { public class ConvertToBoolean { public static void Main() { bool b = true; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToBoolean(b)); b = false; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToBoolean(b)); } } }
A B C D E F G H I J
The output is
K
From Boolean True yields True From Boolean False yields False
L M N
Convert.ToBoolean(System.Byte) Method
O [ILASM]
P
.method public hidebysig static bool ToBoolean(unsigned int8 value) [C#]
Q
public static bool ToBoolean(byte value)
R
Summary
S
Converts a System.Byte to a System.Boolean.
T
Parameters
U V
Parameter
Description
value
The System.Byte value to be converted.
W X Y
Return Value
Z
true if value is non-zero; false if value is zero.
612
Contents | Index
System
Convert ToBoolean() Method
Example using System; namespace Samples { public class ConvertToBoolean { public static void Main() { byte b = Byte.MaxValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToBoolean(b)); b = Byte.MinValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToBoolean(b)); } } }
A B C D E F G H I J
The output is
K L
From Byte 255 yields True From Byte 0 yields False
M N
Convert.ToBoolean(System.Char) Method
O
[ILASM]
P
.method public hidebysig static bool ToBoolean(valuetype System.Char value)
Q
[C#]
public static bool ToBoolean(char value)
R
Summary
S
Calling this method always throws System.InvalidCastException.
T U
Parameters
V
Parameter
Description
value
A Unicode character.
W X Y Z
Return Value This conversion is not supported. No value is returned. 613
Contents | Index
Convert
System
ToBoolean() Method
Description This method is reserved for future use. A
Exceptions
B C D
Exception
Condition
System.InvalidCastException
This conversion is not supported.
E F G
Convert.ToBoolean(System.Decimal) Method
H
[ILASM]
.method public hidebysig static bool ToBoolean(decimal value)
I
[C#]
J
public static bool ToBoolean(decimal value)
K
Summary
L
Converts a System.Decimal to a System.Boolean.
M
Parameters
N O P
Parameter
Description
value
The System.Decimal value to be converted.
Q R
Return Value
S
true if value is non-zero; false if value is zero.
T U
Description
V
This member must be implemented if the Extended Numerics Library is present in the implementation.
W
Example
X
using System;
Y
namespace Samples { public class ConvertToBoolean {
Z
614
Contents | Index
System
Convert ToBoolean() Method
public static void Main() { Decimal d = Decimal.MaxValue; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToBoolean(d)); d = Decimal.MinValue; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToBoolean(d)); d = Decimal.MinusOne; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToBoolean(d)); d = Decimal.One; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToBoolean(d)); d = Decimal.Zero; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToBoolean(d)); }
A B C D E F G H I
}
J
}
K
The output is
L From From From From From
Decimal Decimal Decimal Decimal Decimal
79228162514264337593543950335 yields True -79228162514264337593543950335 yields True -1 yields True 1 yields True 0 yields False
M N O P Q
Convert.ToBoolean(System.Double) Method
R
[ILASM]
.method public hidebysig static bool ToBoolean(float64 value)
S
[C#]
T
public static bool ToBoolean(double value)
U
Summary
V
Converts a System.Double to a System.Boolean.
W X
Parameters
Y
Parameter
Description
value
The System.Double value to be converted.
Z
615
Contents | Index
Convert
System
ToBoolean() Method
Return Value true if value is non-zero; false if value is zero. A
Description
B
This member must be implemented if the Extended Numerics Library is present in the implementation.
C D
Example
E
using System;
F namespace Samples { public class ConvertToBoolean { public static void Main() { Double d = Double.MaxValue; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToBoolean(d)); d = Double.MinValue; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToBoolean(d)); d = Double.Epsilon; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToBoolean(d)); d = Double.PositiveInfinity; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToBoolean(d)); d = Double.NegativeInfinity; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToBoolean(d)); d = 0.0; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToBoolean(d)); d = Double.NaN; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToBoolean(d)); } } }
G H I J K L M N O P Q R S T U V W X Y
The output is
Z From Double 1.79769313486232E+308 yields True From Double -1.79769313486232E+308 yields True
616
Contents | Index
System
Convert ToBoolean() Method
From From From From From
Double Double Double Double Double
4.94065645841247E-324 yields True Infinity yields True -Infinity yields True 0 yields False NaN yields True
A B C
Convert.ToBoolean(System.Single) Method
D [ILASM]
.method public hidebysig static bool ToBoolean(float32 value)
E
[C#]
F
public static bool ToBoolean(float value)
G
Summary
H
Converts a System.Single to a System.Boolean.
I J
Parameters
K
Parameter
Description
value
The System.Single value to be converted.
L M N
Return Value
O
true if value is non-zero; false if value is zero.
P Q
Description
R
This member must be implemented if the Extended Numerics Library is present in the implementation.
S T
Example
U
using System;
V namespace Samples { public class ConvertToBoolean { public static void Main() { float f = Single.MaxValue; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToBoolean(f));
W X Y Z
617
Contents | Index
Convert
System
ToBoolean() Method
f = Single.MinValue; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToBoolean(f)); f = Single.PositiveInfinity; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToBoolean(f)); f = Single.NegativeInfinity; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToBoolean(f)); f = Single.NaN; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToBoolean(f)); f = 0; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToBoolean(f));
A B C D E F G H
} }
I
}
J
The output is
K From From From From From From
L M N O
Single Single Single Single Single Single
3.402823E+38 yields True -3.402823E+38 yields True Infinity yields True -Infinity yields True NaN yields True 0 yields False
P Q
Convert.ToBoolean(System.Int32) Method
R
[ILASM]
S
.method public hidebysig static bool ToBoolean(int32 value)
T
public static bool ToBoolean(int value)
[C#]
U
Summary
V
Converts a System.Int32 to a System.Boolean.
W
Parameters
X Y
Parameter
Description
value
The 32-bit signed integer value to be converted.
Z
618
Contents | Index
System
Convert ToBoolean() Method
Return Value true if value is non-zero; false if value is zero. A
Example
B
using System;
C
namespace Samples { public class ConvertToBoolean { public static void Main() { int i = Int32.MaxValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToBoolean(i)); i = Int32.MinValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToBoolean(i)); i = 0; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToBoolean(i)); } } }
D E F G H I J K L M N
The output is
O P
From Int32 2147483647 yields True From Int32 -2147483648 yields True From Int32 0 yields False
Q R S
Convert.ToBoolean(System.Int64) Method
T
[ILASM]
U
.method public hidebysig static bool ToBoolean(int64 value)
V
[C#]
public static bool ToBoolean(long value)
W
Summary
X
Converts a System.Int64 to a System.Boolean.
Y Z
619
Contents | Index
Convert
System
ToBoolean() Method
Parameters Parameter
Description
value
The 64-bit signed integer value to be converted.
A B C D
Return Value
E
true if value is non-zero; false if value is zero.
F
Example
G
using System;
H
namespace Samples { public class ConvertToBoolean { public static void Main() { long l = Int64.MaxValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToBoolean(l)); l = Int64.MinValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToBoolean(l)); l = 0; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToBoolean(l)); } } }
I J K L M N O P Q R S T
The output is
U
From Int64 9223372036854775807 yields True From Int64 -9223372036854775808 yields True From Int64 0 yields False
V W X Y
Convert.ToBoolean(System.Object) Method
Z
[ILASM]
.method public hidebysig static bool ToBoolean(object value) [C#]
public static bool ToBoolean(object value)
620
Contents | Index
System
Convert ToBoolean() Method
Summary Converts the value of a specified System.Object to an equivalent Boolean value. A
Parameters
B
Parameter
Description
C
value
A System.Object that implements the System.IConvertible interface or null.
D E F
Return Value
G
false if value equals null or true or false; the result of invoking the IConvertible.ToBoolean method for the underlying type of value.
H I J
Convert.ToBoolean(System.Object, System.IFormatProvider) Method
K
[ILASM]
L
.method public hidebysig static bool ToBoolean(object value, class System.IFormatProvider provider)
M
[C#]
N
public static bool ToBoolean(object value, IFormatProvider provider)
O
Summary
P
Converts the value of the specified System.Object to an equivalent Boolean value using the specified culture-specific formatting information.
Q R
Parameters
S
Parameter
Description
value
A System.Object that implements the System.IConvertible interface or null.
provider
A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
T U V W X Y
Return Value
Z
false if value equals null or true or false; the result of invoking the ToBoolean method for the underlying type of value. 621
Contents | Index
Convert
System
ToBoolean() Method
Description provider enables the user to specify culture-specific conversion information about the contents of value. For example, if value is a System.String that represents a number, provider could supply culture-specific information about the notation used to represent that number. The base types ignore provider; however, it is honored if value is a user-defined type that implements the System.IConvertible interface.
A B C D
Exceptions
E F G
Exception
Condition
System.InvalidCastException
value does not implement the System.IConvertible interface.
H I J
Convert.ToBoolean(System.SByte) Method
K [ILASM]
L
.method public hidebysig static bool ToBoolean(int8 value)
M
[C#]
public static bool ToBoolean(sbyte value)
N O
Summary
P
Converts a System.SByte to a System.Boolean.
Q
Parameters
R S
Parameter
Description
T
value
The 8-bit signed integer value to be converted.
U V
Return Value
W
true if value is non-zero; false if value is zero.
X Y
Description
Z
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToBoolean(System.Int16).
622
Contents | Index
System
Convert ToBoolean() Method
Example using System; namespace Samples { public class ConvertToBoolean { public static void Main() { sbyte s = SByte.MaxValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToBoolean(s)); s = SByte.MinValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToBoolean(s)); s = 0; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToBoolean(s)); } } }
A B C D E F G H I J K L
The output is
M
From Signed Byte 127 yields True From Signed Byte -128 yields True From Signed Byte 0 yields False
N O P Q
Convert.ToBoolean(System.Int16) Method
R
[ILASM]
S
.method public hidebysig static bool ToBoolean(int16 value) [C#]
T
public static bool ToBoolean(short value)
U
Summary
V
Converts a System.Int16 to a System.Boolean.
W X
Parameters
Y
Parameter
Description
value
The 16-bit signed integer value to be converted.
Z
623
Contents | Index
Convert
System
ToBoolean() Method
Return Value true if value is non-zero; false if value is zero. A
Example
B
using System;
C
namespace Samples { public class ConvertToBoolean { public static void Main() { short i = Int16.MaxValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToBoolean(i)); i = Int16.MinValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToBoolean(i)); i = 0; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToBoolean(i)); } } }
D E F G H I J K L M N
The output is
O P
From Int16 32767 yields True From Int16 -32768 yields True From Int16 0 yields False
Q R S
Convert.ToBoolean(System.String) Method
T
[ILASM]
U
.method public hidebysig static bool ToBoolean(string value)
V
[C#]
public static bool ToBoolean(string value)
W X
Summary
Y
Converts a System.String to a System.Boolean.
Z
624
Contents | Index
System
Convert ToBoolean() Method
Parameters Parameter
Description
value
The System.String to be converted.
A B C
Return Value
D
true if value equals System.Boolean.TrueString; false if value equals System.Boolean.FalseString.
E F
Exceptions
G
Exception
Condition
System.ArgumentNullException
value is a null reference.
System.FormatException
value is not equal to System.Boolean.TrueString or System.Boolean.FalseString.
H I J K L M
Example
N
using System;
O
namespace Samples { public class ConvertToBoolean { public static void Main() { try { string s = Boolean.TrueString; Console.WriteLine("From String {0} yields {1}", s, Convert.ToBoolean(s)); s = Boolean.FalseString; Console.WriteLine("From String {0} yields {1}", s, Convert.ToBoolean(s)); s = "true"; Console.WriteLine("From String {0} yields {1}", s, Convert.ToBoolean(s)); s = "false"; Console.WriteLine("From String {0} yields {1}", s, Convert.ToBoolean(s)); s = String.Empty;
P Q R S T U V W X Y Z
625
Contents | Index
Convert
System
ToBoolean() Method
Console.WriteLine("From String {0} yields {1}", s, Convert.ToBoolean(s)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); }
A B C
} }
D
}
E
The output is
F From String True yields True From String False yields False From String true yields True From String false yields False Exception: System.FormatException: String was not recognized as a valid Boolean. at System.Boolean.Parse(String value) at System.Convert.ToBoolean(String value) at Samples.ConvertToBoolean.Main() in C:\Books\BCL\Samples\System\Convert\ ToBoolean\ToBoolean(System.String)\Convert.cs:line 24
G H I J K L M N
Convert.ToBoolean(System.String, System.IFormatProvider) Method
O
[ILASM]
P
.method public hidebysig static bool ToBoolean(string value, class System.IFormatProvider provider) [C#]
Q
public static bool ToBoolean(string value, IFormatProvider provider)
R S
Summary
T
Converts the specified System.String representation of a logical value to its Boolean equivalent using the specified culture-specific formatting information.
U
Parameters
V W
Parameter
Description
value
A string that contains the value of either System.Boolean.TrueString or System.Boolean.FalseString.
provider
(Reserved) A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
X Y Z
626
Contents | Index
System
Convert ToBoolean() Method
Return Value true if value equals System.Boolean.TrueString, or false if value equals System.Boolean.FalseString. A
Description
B
provider is ignored; it does not participate in this operation.
C D
Exceptions
E
Exception
Condition
System.ArgumentNullException
value is a null reference.
System.FormatException
value is not equal to System.Boolean.TrueString or System.Boolean.FalseString.
F G H I J K L
Convert.ToBoolean(System.DateTime) Method
M
[ILASM]
N
.method public hidebysig static bool ToBoolean(valuetype System.DateTime value) [C#]
O
public static bool ToBoolean(DateTime value)
P
Summary
Q
Calling this method always throws System.InvalidCastException.
R S
Parameters
T
Parameter
Description
value
A System.DateTime.
U V W X
Exceptions
Y
Exception
Condition
System.InvalidCastException
This conversion is not supported.
Z
627
Contents | Index
Convert
System
ToBoolean() Method
Convert.ToBoolean(System.UInt32) Method [ILASM]
.method public hidebysig static bool ToBoolean(unsigned int32 value)
A
[C#]
public static bool ToBoolean(uint value)
B C
Summary
D
Converts a System.UInt32 to a System.Boolean.
E
Parameters
F G
Parameter
Description
value
The 32-bit unsigned integer value to be converted.
H I J K
Return Value
L
true if value is non-zero; false if value is zero.
M
Description
N
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToBoolean(System.Int64).
O P
Example
Q
using System;
R namespace Samples { public class ConvertToBoolean { public static void Main() { uint u = UInt32.MaxValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToBoolean(u)); u = UInt32.MinValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToBoolean(u)); } } }
S T U V W X Y Z
628
Contents | Index
System
Convert ToBoolean() Method
The output is From UInt32 4294967295 yields True From UInt32 0 yields False
A B
Convert.ToBoolean(System.UInt64) Method
C
[ILASM]
D
.method public hidebysig static bool ToBoolean(unsigned int64 value)
E
[C#]
public static bool ToBoolean(ulong value)
F G
Summary
H
Converts a System.UInt64 to a System.Boolean.
I
Parameters Parameter
J K
Description
L
value
The 64-bit unsigned integer value to be converted.
M N
Return Value
O
true if value is non-zero; false if value is zero.
P Q
Description
R
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToBoolean(System.Decimal).
S T
Example
U
using System;
V namespace Samples { public class ConvertToBoolean { public static void Main() { ulong u = UInt64.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToBoolean(u));
W X Y Z
629
Contents | Index
Convert
System
ToBoolean() Method
u = UInt64.MinValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToBoolean(u)); }
A
} }
B
The output is
C D
From UInt64 18446744073709551615 yields True From UInt64 0 yields False
E F G
Convert.ToBoolean(System.UInt16) Method
H
[ILASM]
.method public hidebysig static bool ToBoolean(unsigned int16 value)
I
[C#]
public static bool ToBoolean(ushort value)
J K
Summary
L
Converts a System.UInt16 to a System.Boolean.
M
Parameters
N O
Parameter
Description
value
The 16-bit unsigned integer value to be converted.
P Q R
Return Value
S
true if value is non-zero; false if value is zero.
T U
Description
V
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToBoolean(System.Int32).
W X Y Z
630
Contents | Index
System
Convert ToByte() Method
Example using System; namespace Samples { public class ConvertToBoolean { public static void Main() { ushort u = UInt16.MaxValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToBoolean(u)); u = UInt16.MinValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToBoolean(u)); } } }
A B C D E F G H I J
The output is
K L
From UInt16 65535 yields True From UInt16 0 yields False
M N
Convert.ToByte(System.Boolean) Method
O
[ILASM]
P
.method public hidebysig static unsigned int8 ToByte(bool value)
Q
[C#]
public static byte ToByte(bool value)
R
Summary
S
Converts a System.Boolean to a System.Byte.
T U
Parameters
V
Parameter
Description
value
The System.Boolean value to be converted.
W X Y Z
Return Value If value equals true, returns 1; if value equals false, returns 0. 631
Contents | Index
Convert
System
ToByte() Method
Example using System; namespace Samples { public class ConvertToByte { public static void Main() { bool b = true; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToByte(b)); b = false; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToByte(b)); } } }
A B C D E F G H I J
The output is
K L
From Boolean True yields 1 From Boolean False yields 0
M N O
Convert.ToByte(System.Byte) Method
P
[ILASM]
.method public hidebysig static unsigned int8 ToByte(unsigned int8 value)
Q
[C#]
R
public static byte ToByte(byte value)
S
Summary
T
Converts a System.Byte to a System.Byte.
U
Parameters
V W X
Parameter
Description
value
The System.Byte value to be converted.
Y Z
Return Value value is returned unchanged. 632
Contents | Index
System
Convert ToByte() Method
Description [Note: This method is provided for completeness.]
Example
A
using System;
B C
namespace Samples { public class ConvertToByte { public static void Main() { byte b = Byte.MaxValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToByte(b)); b = Byte.MinValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToByte(b)); b = Byte.MaxValue / 2; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToByte(b)); } } }
D E F G H I J K L M N
The output is
O
From Byte 255 yields 255 From Byte 0 yields 0 From Byte 127 yields 127
P Q R S
Convert.ToByte(System.Char) Method
T [ILASM]
U
.method public hidebysig static unsigned int8 ToByte(valuetype System.Char value) [C#]
V
public static byte ToByte(char value)
W
Summary
X
Converts a System.Char to a System.Byte.
Y Z
633
Contents | Index
Convert
System
ToByte() Method
Parameters Parameter
Description
value
The Unicode character to be converted interpreted as an unsigned value.
A B C
Exceptions
D E
Exception
Condition
System.OverflowException
The numeric value of value is greater than System.Byte.MaxValue.
F G H I
Example
J
using System;
K namespace Samples { public class ConvertToByte { public static void Main() { try { Char c = Char.MinValue; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToByte(c)); c = 'A'; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToByte(c)); c = Char.MaxValue; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToByte(c)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
L M N O P Q R S T U V W X Y Z
634
Contents | Index
System
Convert ToByte() Method
The output is From Char yields 0 From Char A yields 65 Exception: System.OverflowException: Value was either too large or too small for an unsigned byte. at System.Convert.ToByte(Char value) at Samples.ConvertToByte.Main() in C:\Books\BCL\Samples\System\Convert\ToByte\ ToByte(System.Char)\Convert.cs:line 18
A B C D E
Convert.ToByte(System.Decimal) Method
F
[ILASM]
G
.method public hidebysig static unsigned int8 ToByte(decimal value)
H
[C#]
I
public static byte ToByte(decimal value)
J
Summary
K
Converts a System.Decimal to a System.Byte.
L
Parameters
M N
Parameter
Description
value
The System.Decimal value to be converted.
O P Q
Description
R
Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. [Note: This process is known as banker’s rounding.] This member must be implemented if the Extended Numerics Library is present in the implementation.
S T U V
Exceptions
W
Exception
Condition
X
value is greater than System.Byte.MaxValue or less than System.Byte.MinValue.
Y
System.OverflowException
Z
635
Contents | Index
Convert
System
ToByte() Method
Example using System; namespace Samples { public class ConvertToByte { public static void Main() { try { Decimal d = Decimal.One; Console.WriteLine("From Decimal {0} yields d, Convert.ToByte(d)); d = Decimal.Zero; Console.WriteLine("From Decimal {0} yields d, Convert.ToByte(d)); d = Byte.MaxValue; Console.WriteLine("From Decimal {0} yields d, Convert.ToByte(d)); d = 25.5m; Console.WriteLine("From Decimal {0} yields d, Convert.ToByte(d)); d = Decimal.MinValue; Console.WriteLine("From Decimal {0} yields d, Convert.ToByte(d)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P Q R S
{1}",
{1}",
{1}",
{1}",
{1}",
The output is
T From Decimal 1 yields 1 From Decimal 0 yields 0 From Decimal 255 yields 255 From Decimal 25.5 yields 26 Exception: System.OverflowException: Value was either too large or too small for a UInt32. at System.Decimal.ToUInt32(Decimal d) at System.Decimal.ToByte(Decimal value) at System.Convert.ToByte(Decimal value) at Samples.ConvertToByte.Main() in C:\Books\BCL\Samples\System\Convert\ToByte\ ToByte(System.Decimal)\Convert.cs:line 24
U V W X Y Z
636
Contents | Index
System
Convert ToByte() Method
Convert.ToByte(System.Double) Method [ILASM]
.method public hidebysig static unsigned int8 ToByte(float64 value) [C#]
A
public static byte ToByte(double value)
B C
Summary
D
Converts a System.Double to a System.Byte.
E
Parameters
F G
Parameter
Description
value
The System.Double value to be converted.
H I J
Description
K
Prior to the conversion, if value is halfway between two numbers, it is rounded to the number that has an even digit in the rightmost decimal position. For example, when rounded to two decimals, the value 2.345 becomes 2.34 and the value 2.355 becomes 2.36. This member must be implemented if the Extended Numerics Library is present in the implementation.
L M N O
Exceptions
P
Exception
Condition
System.OverflowException
value is greater than System.Byte.MaxValue or less than System.Byte.MinValue, or value is equal to one of System.Double.NaN, System.Double.PositiveInfinity, or System.Double.NegativeInfinity.
Q R S T U V
Example
W
using System;
X
namespace Samples { public class ConvertToByte { public static void Main() {
Y Z
637
Contents | Index
Convert
System
ToByte() Method
try { double d = Double.Epsilon; Console.WriteLine("From Double {0} yields d, Convert.ToByte(d)); d = 0.0; Console.WriteLine("From Double {0} yields d, Convert.ToByte(d)); d = 5.5; Console.WriteLine("From Double {0} yields d, Convert.ToByte(d)); d = Double.PositiveInfinity; Console.WriteLine("From Double {0} yields d, Convert.ToByte(d)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E F G H I J
{1}",
{1}",
{1}",
{1}",
}
K
} }
L
The output is
M N
From Double 4.94065645841247E-324 yields 0 From Double 0 yields 0 From Double 5.5 yields 6 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Convert.ToInt32(Double value) at System.Convert.ToByte(Double value) at Samples.ConvertToByte.Main() in C:\Books\BCL\Samples\System\Convert\ToByte\ ToByte(System.Double)\Convert.cs:line 21
O P Q R S T U
Convert.ToByte(System.Single) Method
V [ILASM]
W
.method public hidebysig static unsigned int8 ToByte(float32 value) [C#]
X
public static byte ToByte(float value)
Y
Summary
Z
Converts a System.Single to a System.Byte.
638
Contents | Index
System
Convert ToByte() Method
Parameters Parameter
Description
value
The System.Single value to be converted.
A B C
Description
D
Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member must be implemented if the Extended Numerics Library is present in the implementation.
E F G
Exceptions
H I
Exception
Condition
System.OverflowException
value is greater than System.Byte.MaxValue or less than System.Byte.MinValue, or value is equal to one of System.Single.NaN, System.Single.PositiveInfinity, or System.Single.NegativeInfinity.
J K L M N
Example
O
using System;
P namespace Samples { public class ConvertToByte { public static void Main() { try { float f = 0f; Console.WriteLine("From Single {0} yields f, Convert.ToByte(f)); f = 0.5f; Console.WriteLine("From Single {0} yields f, Convert.ToByte(f)); f = Byte.MaxValue; Console.WriteLine("From Single {0} yields f, Convert.ToByte(f)); f = Single.MaxValue; Console.WriteLine("From Single {0} yields
Q R S T U V
{1}",
W {1}",
X Y
{1}",
Z
{1}",
639
Contents | Index
Convert
System
ToByte() Method
f, Convert.ToByte(f)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B }
C
} }
D
The output is
E F
From Single 0 yields 0 From Single 0.5 yields 0 From Single 255 yields 255 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Convert.ToInt32(Double value) at System.Convert.ToByte(Single value) at Samples.ConvertToByte.Main() in C:\Books\BCL\Samples\System\Convert\ToByte\ ToByte(System.Single)\Convert.cs:line 21
G H I J K L M
Convert.ToByte(System.Int32) Method
N [ILASM]
O
.method public hidebysig static unsigned int8 ToByte(int32 value) [C#]
P
public static byte ToByte(int value)
Q R
Summary
S
Converts a System.Int32 to a System.Byte.
T
Parameters
U V
Parameter
Description
W
value
The 32-bit signed integer value to be converted.
X Y Z
640
Contents | Index
System
Convert ToByte() Method
Exceptions Exception
Condition
System.OverflowException
value is greater than System.Byte.MaxValue or less than System.Byte.MinValue.
A B C D
Example
E
using System; namespace Samples { public class ConvertToByte { public static void Main() { try { int i = 0; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToByte(i)); i = Byte.MaxValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToByte(i)); i = Int32.MinValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToByte(i)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
F G H I J K L M N O P Q R S T U
The output is
V
From Int32 0 yields 0 From Int32 255 yields 255 Exception: System.OverflowException: Value was either too large or too small for an unsigned byte. at System.Convert.ToByte(Int32 value) at Samples.ConvertToByte.Main() in C:\Books\BCL\Samples\System\Convert\ToByte\ ToByte(System.Int32)\Convert.cs:line 18
W X Y Z
641
Contents | Index
Convert
System
ToByte() Method
Convert.ToByte(System.Int64) Method [ILASM]
.method public hidebysig static unsigned int8 ToByte(int64 value)
A
[C#]
public static byte ToByte(long value)
B C
Summary
D
Converts a System.Int64 to a System.Byte.
E
Parameters
F G
Parameter
Description
value
The 64-bit signed integer value to be converted.
H I J
Exceptions
K L
Exception
Condition
System.OverflowException
value is greater than System.Byte.MaxValue or less than System.Byte.MinValue.
M N O P
Example
Q
using System;
R
namespace Samples { public class ConvertToByte { public static void Main() { try { long l = Byte.MaxValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToByte(l)); l = Byte.MinValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToByte(l)); l = Int64.MaxValue;
S T U V W X Y Z
642
Contents | Index
System
Convert ToByte() Method
Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToByte(l)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C
} }
D
}
E
The output is
F
From Int64 255 yields 255 From Int64 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for an unsigned byte. at System.Convert.ToByte(Int64 value) at Samples.ConvertToByte.Main() in C:\Books\BCL\Samples\System\Convert\ToByte\ ToByte(System.Int64)\Convert.cs:line 18
G H I J K L
Convert.ToByte(System.Object) Method
M
[ILASM]
N
.method public hidebysig static unsigned int8 ToByte(object value)
O
[C#]
public static byte ToByte(object value)
P
Summary
Q
Converts the value of the specified System.Object to an 8-bit unsigned integer.
R S
Parameters
T
Parameter
Description
value
A System.Object that implements the System.IConvertible interface or null.
U V W X Y
Return Value
Z
An 8-bit unsigned integer equivalent to the value of value, or zero if value is null.
643
Contents | Index
Convert
System
ToByte() Method
Description The return value is the result of invoking the IConvertible.ToByte method of the underlying type of value. A
Exceptions
B C D E
Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
F G
Convert.ToByte(System.Object, System.IFormatProvider) Method
H
[ILASM]
I
.method public hidebysig static unsigned int8 ToByte(object value, class System.IFormatProvider provider)
J
[C#]
K
public static byte ToByte(object value, IFormatProvider provider)
L M
Summary
N
Converts the value of the specified System.Object to an 8-bit unsigned integer using the specified culture-specific formatting information.
O
Parameters
P Q
Parameter
Description
value
A System.Object that implements the System.IConvertible interface.
provider
A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
R S T U V
Return Value
W
An 8-bit unsigned integer equivalent to the value of value, or zero if value is null.
X Y
Description
Z
provider enables the user to specify culture-specific conversion information about the contents of value. For example, if value is a System.String that represents a number, provider could supply culture-specific information about the notation used to represent that number. 644
Contents | Index
System
Convert ToByte() Method
The base types ignore provider; however, it is honored if value is a user-defined type that implements the System.IConvertible interface. A
Convert.ToByte(System.SByte) Method
B
[ILASM]
C
.method public hidebysig static unsigned int8 ToByte(int8 value)
D
[C#]
public static byte ToByte(sbyte value)
E
Summary
F
Converts a System.SByte to a System.Byte.
G H
Parameters
I J
Parameter
Description
value
The 8-bit signed integer to be converted.
K L M
Description
N
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToByte(System.Int16).
O P
Exceptions
Q
Exception
Condition
System.OverflowException
value is less than System.Byte.MinValue.
R S T U
Example
V
using System;
W
namespace Samples { public class ConvertToByte { public static void Main() { try
X Y Z
645
Contents | Index
Convert
System
ToByte() Method
{ sbyte s = SByte.MaxValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToByte(s)); s = 0; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToByte(s)); s = SByte.MinValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToByte(s));
A B C D
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
E F G }
H
}
I
}
J
The output is
K
From Signed Byte 127 yields 127 From Signed Byte 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for an unsigned byte. at System.Convert.ToByte(SByte value) at Samples.ConvertToByte.Main() in C:\Books\BCL\Samples\System\Convert\ToByte\ ToByte(System.SByte)\Convert.cs:line 18
L M N O P Q
Convert.ToByte(System.Int16) Method
R
[ILASM]
S
.method public hidebysig static unsigned int8 ToByte(int16 value) [C#]
T
public static byte ToByte(short value)
U
Summary
V
Converts a System.Int16 to a System.Byte.
W X
Parameters
Y Z
Parameter
Description
value
The 16-bit signed integer value to be converted.
646
Contents | Index
System
Convert ToByte() Method
Exceptions Exception
Condition
System.OverflowException
value is greater than System.Byte.MaxValue or less than System.Byte.MinValue.
A B C D
Example
E
using System;
F namespace Samples { public class ConvertToByte { public static void Main() { try { short i = 0; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToByte(i)); i = Byte.MaxValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToByte(i)); i = Int16.MaxValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToByte(i)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
G H I J K L M N O P Q R S T U V
The output is
W From Int16 0 yields 0 From Int16 255 yields 255 Exception: System.OverflowException: Value was either too large or too small for an unsigned byte. at System.Convert.ToByte(Int16 value) at Samples.ConvertToByte.Main() in C:\Books\BCL\Samples\System\Convert\ToByte\ ToByte(System.Int16)\Convert.cs:line 18
X Y Z
647
Contents | Index
Convert
System
ToByte() Method
Convert.ToByte(System.String) Method [ILASM]
.method public hidebysig static unsigned int8 ToByte(string value)
A
[C#]
public static byte ToByte(string value)
B C
Summary
D
Converts a System.String representation of a number to a System.Byte.
E
Parameters
F G
Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Integer style.
H I J K
Exceptions
L M N
Exception
Condition
System.ArgumentNullException
value is a null reference.
System.FormatException
value does not consist of an optional sign followed by one or more digits (zero through nine).
System.OverflowException
The numeric value of value is greater than System.Byte.MaxValue or less than System.Byte.MinValue.
O P Q R S T
Example
U
using System;
V namespace Samples { public class ConvertToByte { public static void Main() { string s; try {
W X Y Z
648
Contents | Index
System
Convert ToByte() Method
s = (Byte.MaxValue).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToByte(s)); s = (Byte.MinValue).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToByte(s)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToByte(s));
A B C D
} catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = (Byte.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToByte(s)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
E F G H I J K L M
}
N
} }
O
The output is
P Q
From String 255 yields 255 From String 0 yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Byte.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToByte(String value) at Samples.ConvertToByte.Main() in C:\Books\BCL\Samples\System\Convert\ToByte\ ToByte(System.String)\Convert.cs:line 19 Exception: System.OverflowException: Value was either too large or too small for an unsigned byte. at System.Byte.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToByte(String value) at Samples.ConvertToByte.Main() in C:\Books\BCL\Samples\System\Convert\ToByte\ ToByte(System.String)\Convert.cs:line 29
R S T U V W X Y Z
649
Contents | Index
Convert
System
ToByte() Method
Convert.ToByte(System.String, System.Int32) Method [ILASM]
.method public hidebysig static unsigned int8 ToByte(string value, int32 fromBase)
A
[C#]
public static byte ToByte(string value, int fromBase)
B C
Summary
D
Converts the System.String representation of a number in a specified base to an equivalent 8-bit unsigned integer.
E F
Parameters
G H
Parameter
Description
value
A System.String containing a number.
fromBase
The base of the number in value, which must be 2, 8, 10, or 16.
I J K L M
Description
N
If fromBase is 16, you can prefix the number specified by the value parameter with “0x” or “0X”.
O
Exceptions
P Q
Exception
Condition
R
System.ArgumentException
fromBase is not 2, 8, 10, or 16.
System.OverflowException
value is less than System.Byte.MinValue or greater than System.Byte.MaxValue.
S T U V W
Convert.ToByte(System.String, System.IFormatProvider) Method
X
[ILASM]
Y
.method public hidebysig static unsigned int8 ToByte(string value, class System.IFormatProvider provider) [C#]
Z
public static byte ToByte(string value, IFormatProvider provider)
650
Contents | Index
System
Convert ToByte() Method
Summary Converts a System.String to a System.Byte. A
Parameters
B
Parameter
Description
C
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Integer style.
D
value
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
F
provider
E
G H
Description
I
This method parses value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is parsed using the formatting information of the current system culture.
J K L M
Exceptions
N
Exception
Condition
O
System.ArgumentNullException
value is a null reference.
P
System.FormatException
value does not consist of an optional sign followed by one or more digits (zero through nine).
System.OverflowException
The numeric value of value is greater than System.Byte.MaxValue or less than System.Byte.MinValue.
Q R S T U V
Example
W
using System; using System.Globalization;
X Y
namespace Samples { public class ConvertToByte { public static void Main()
Z
651
Contents | Index
Convert
System
ToByte() Method
{ string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; try { s = "~0"; Console.WriteLine("From String {0} yields {1}", s, Convert.ToByte(s, c)); s = (Byte.MaxValue).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToByte(s, c)); s = (Byte.MinValue).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToByte(s, c)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToByte(s, c)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = (Byte.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToByte(s, c)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E F G H I J K L M N O P Q R S }
T
} }
U V
The output is
W
From String ~0 yields 0 From String 255 yields 255 From String 0 yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Byte.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToByte(String value, IFormatProvider provider)
X Y Z
652
Contents | Index
System
Convert ToByte() Method
at Samples.ConvertToByte.Main() in C:\Books\BCL\Samples\System\Convert\ToByte\ ToByte(System.String,System.IFormatProvider)\Convert.cs:line 26 Exception: System.OverflowException: Value was either too large or too small for an unsigned byte. at System.Byte.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToByte(String value, IFormatProvider provider) at Samples.ConvertToByte.Main() in C:\Books\BCL\Samples\System\Convert\ToByte\ ToByte(System.String,System.IFormatProvider)\Convert.cs:line 36
A B C D E
Convert.ToByte(System.DateTime) Method
F [ILASM]
G
.method public hidebysig static unsigned int8 ToByte(valuetype System.DateTime value) [C#]
H
public static byte ToByte(DateTime value)
I J
Summary
K
Calling this method always throws System.InvalidCastException.
L
Parameters
M
Parameter
Description
value
A System.DateTime.
N O P Q
Exceptions
R S
Exception
Condition T
System.InvalidCastException
This conversion is not supported.
U V W
Convert.ToByte(System.UInt32) Method
X
[ILASM]
Y
.method public hidebysig static unsigned int8 ToByte(unsigned int32 value)
Z
[C#]
public static byte ToByte(uint value)
653
Contents | Index
Convert
System
ToByte() Method
Summary Converts a System.UInt32 to a System.Byte. A
Parameters
B C
Parameter
Description
D
value
The 32-bit unsigned integer value to be converted.
E F
Description
G
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToByte(System.Int64).
H I
Exceptions
J K
Exception
Condition
System.OverflowException
value is greater than System.Byte.MaxValue.
L M N
Example
O
using System;
P namespace Samples { public class ConvertToByte { public static void Main() { try { uint u = 0; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToByte(u)); u = Byte.MaxValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToByte(u)); u = UInt32.MaxValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToByte(u)); } catch(OverflowException e)
Q R S T U V W X Y Z
654
Contents | Index
System
Convert ToByte() Method
{ Console.WriteLine("Exception {0}", e); } }
A
} }
B C
The output is
D From UInt32 0 yields 0 From UInt32 255 yields 255 Exception System.OverflowException: Value was either too large or too small for an unsigned byte. at System.Convert.ToByte(UInt32 value) at Samples.ConvertToByte.Main() in C:\Books\BCL\Samples\System\Convert\ToByte\ ToByte(System.UInt32)\Convert.cs:line 18
E F G H I J
Convert.ToByte(System.UInt64) Method
K [ILASM]
L
.method public hidebysig static unsigned int8 ToByte(unsigned int64 value) [C#]
M
public static byte ToByte(ulong value)
N
Summary
O
Converts a System.UInt64 to a System.Byte.
P Q
Parameters
R
Parameter
Description
S
value
The 64-bit unsigned integer value to be converted.
T U
Description
V
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToByte(System.Decimal).
W X Y Z
655
Contents | Index
Convert
System
ToByte() Method
Exceptions Exception
Condition
System.OverflowException
value is greater than System.Byte.MaxValue.
A B C
Example
D
using System;
E
namespace Samples { public class ConvertToByte { public static void Main() { try { ulong u = Byte.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToByte(u)); u = Byte.MinValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToByte(u)); u = UInt64.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToByte(u)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
F G H I J K L M N O P Q R S T
The output is
U V
From UInt64 255 yields 255 From UInt64 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for an unsigned byte. at System.Convert.ToByte(UInt64 value) at Samples.ConvertToByte.Main() in C:\Books\BCL\Samples\System\Convert\ToByte\ ToByte(System.UInt64)\Convert.cs:line 18
W X Y Z
656
Contents | Index
System
Convert ToByte() Method
Convert.ToByte(System.UInt16) Method [ILASM]
.method public hidebysig static unsigned int8 ToByte(unsigned int16 value) [C#]
A
public static byte ToByte(ushort value)
B C
Summary
D
Converts a System.UInt16 to a System.Byte.
E
Parameters
F G
Parameter
Description
value
The 16-bit unsigned integer value to be converted.
H I J
Description
K
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToByte(System.Int32).
L M N
Exceptions
O
Exception
Condition
System.OverflowException
value is greater than System.Byte.MaxValue.
P Q R
Example
S
using System;
T U
namespace Samples { public class ConvertToByte { public static void Main() { try { ushort u = Byte.MinValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToByte(u));
V W X Y Z
657
Contents | Index
Convert
System
ToChar() Method
u = Byte.MaxValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToByte(u)); u = UInt16.MaxValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToByte(u));
A B
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
C D E }
F
} }
G
The output is
H I
From UInt16 0 yields 0 From UInt16 255 yields 255 Exception: System.OverflowException: Value was either too large or too small for an unsigned byte. at System.Convert.ToByte(UInt16 value) at Samples.ConvertToByte.Main() in C:\Books\BCL\Samples\System\Convert\ToByte\ToByte(System.UInt16)\Convert.cs:line 18
J K L M N O
Convert.ToChar(System.Boolean) Method
P
[ILASM]
.method public hidebysig static valuetype System.Char ToChar(bool value)
Q
[C#]
R
public static char ToChar(bool value)
S
Summary
T
Calling this method always throws System.InvalidCastException.
U V
Parameters
W X Y
Parameter
Description
value
A System.Boolean value.
Z
658
Contents | Index
System
Convert ToChar() Method
Exceptions Exception
Condition
System.InvalidCastException
This conversion is not supported.
A B C D
Convert.ToChar(System.Byte) Method
E
[ILASM]
F
.method public hidebysig static valuetype System.Char ToChar(unsigned int8 value)
G
[C#]
public static char ToChar(byte value)
H
Summary
I
Converts a System.Byte to a System.Char.
J K
Parameters
L
Parameter
Description
value
The System.Byte value to be converted.
M N O P
Example
Q
using System;
R namespace Samples { public class ConvertToChar { public static void Main() { try { short i = 65; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToChar(i)); i = 95; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToChar(i)); i = Int16.MinValue;
S T U V W X Y Z
659
Contents | Index
Convert
System
ToChar() Method
Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToChar(i)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C
} }
D
}
E
The output is
F
From Int16 65 yields A From Int16 95 yields _ Exception: System.OverflowException: Value was either too large or too small for a character. at System.Convert.ToChar(Int16 value) at Samples.ConvertToChar.Main() in C:\Books\BCL\Samples\System\Convert\ToChar\ ToChar(System.Int16)\Convert.cs:line 18
G H I J K L M
Convert.ToChar(System.Char) Method
N
[ILASM]
O
.method public hidebysig static valuetype System.Char ToChar(valuetype System.Char value) [C#]
P
public static char ToChar(char value)
Q R
Summary
S
Converts a System.Char to a System.Char.
T
Parameters
U V
Parameter
Description
W
value
The Unicode character to be converted.
X Y
Return Value
Z
value is returned unchanged.
660
Contents | Index
System
Convert ToChar() Method
Description [Note: This method is provided for completeness.] A
Example
B
using System;
C
namespace Samples { public class ConvertToChar { public static void Main() { char c = 'A'; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToChar(c)); } } }
D E F G H I J K
The output is
L From Char A yields A
M N
Convert.ToChar(System.Decimal) Method
O
[ILASM]
P
.method public hidebysig static valuetype System.Char ToChar(decimal value)
Q
[C#]
public static char ToChar(decimal value)
R
Summary
S
Calling this method always throws System.InvalidCastException.
T U
Parameters
V
Parameter
Description
value
A System.Decimal number.
W X Y Z
661
Contents | Index
Convert
System
ToChar() Method
Exceptions Exception
Condition
System.InvalidCastException
This conversion is not supported.
A B C D
Convert.ToChar(System.Double) Method
E
[ILASM]
F
.method public hidebysig static valuetype System.Char ToChar(float64 value) [C#]
G
public static char ToChar(double value)
H I
Summary
J
Calling this method always throws System.InvalidCastException.
K
Parameters
L M N
Parameter
Description
value
A double-precision floating-point number.
O P
Exceptions
Q R
Exception
Condition
System.InvalidCastException
This conversion is not supported.
S T U V
Convert.ToChar(System.Single) Method
W
[ILASM]
.method public hidebysig static valuetype System.Char ToChar(float32 value)
X
[C#]
Y
public static char ToChar(float value)
Z
Summary Calling this method always throws System.InvalidCastException.
662
Contents | Index
System
Convert ToChar() Method
Parameters Parameter
Description
value
A single-precision floating-point number.
A B C
Exceptions
D
Exception
Condition
System.InvalidCastException
This conversion is not supported.
E F G H I
Convert.ToChar(System.Int32) Method
J
[ILASM]
K
.method public hidebysig static valuetype System.Char ToChar(int32 value) [C#]
L
public static char ToChar(int value)
M
Summary
N
Converts a System.Int32 to a System.Char.
O P
Parameters
Q
Parameter
Description
value
The 32-bit signed integer value to be converted.
R S T
Return Value
U
value as a System.Char.
V W
Exceptions
X
Exception
Condition
System.OverflowException
value is greater than System.Char.MaxValue or less than System.Char.MinValue.
Y Z
663
Contents | Index
Convert
System
ToChar() Method
Example using System; namespace Samples { public class ConvertToChar { public static void Main() { try { int i = 65; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToChar(i)); i = 95; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToChar(i)); i = Int32.MinValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToChar(i)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P
The output is
Q
From Int32 65 yields A From Int32 95 yields _ Exception: System.OverflowException: Value was either too large or too small for a character. at System.Convert.ToChar(Int32 value) at Samples.ConvertToChar.Main() in C:\Books\BCL\Samples\System\Convert\ToChar\ ToChar(System.Int32)\Convert.cs:line 18
R S T U V W
Convert.ToChar(System.Int64) Method
X [ILASM]
Y
.method public hidebysig static valuetype System.Char ToChar(int64 value)
Z
[C#]
public static char ToChar(long value)
664
Contents | Index
System
Convert ToChar() Method
Summary Converts a System.Int64 to a System.Char. A
Parameters
B
Parameter
Description
value
The 64-bit signed integer value to be converted.
C D E F
Exceptions
G
Exception
Condition
System.OverflowException
value is greater than System.Char.MaxValue or less than System.Char.MinValue.
H I J K
Example
L
using System;
M namespace Samples { public class ConvertToChar { public static void Main() { try { long l = 65; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToChar(l)); l = 95; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToChar(l)); l = Int64.MaxValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToChar(l)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
N O P Q R S T U V W X Y Z
665
Contents | Index
Convert
System
ToChar() Method
The output is From Int64 65 yields A From Int64 95 yields _ Exception: System.OverflowException: Value was either too large or too small for a character. at System.Convert.ToChar(Int64 value) at Samples.ConvertToChar.Main() in C:\Books\BCL\Samples\System\Convert\ToChar\ ToChar(System.Int64)\Convert.cs:line 18
A B C D E F
Convert.ToChar(System.Object) Method
G
[ILASM]
.method public hidebysig static valuetype System.Char ToChar(object value)
H
[C#]
public static char ToChar(object value)
I J
Summary
K
Converts the value of the specified System.Object to a Unicode character.
L
Parameters
M N O
Parameter
Description
value
An System.Object that implements the System.IConvertible interface.
P Q
Return Value
R
The Unicode character equivalent to the value of value or System.Char.MinValue if value equals null.
S T
Description
U
The return value is the result of invoking the IConvertible.ToChar method of the underlying type of value.
V W
Exceptions
X Y
Exception
Condition
System.InvalidCastException
value does not implement the System.IConvertible interface.
Z
666
Contents | Index
System
Convert ToChar() Method
Convert.ToChar(System.Object, System.IFormatProvider) Method [ILASM]
.method public hidebysig static valuetype System.Char ToChar(object value, class System.IFormatProvider provider)
A
[C#]
B
public static char ToChar(object value, IFormatProvider provider)
C
Summary
D
Converts the value of the specified System.Object to its equivalent Unicode character using the specified culture-specific formatting information.
E F
Parameters
G H
Parameter
Description
value
A System.Object that implements the System.IConvertible interface.
provider
A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
I J K L M
Return Value
N
The Unicode character equivalent to the value of value or System.Char.MinValue if value equals null.
O P
Description
Q
The return value is the result of invoking the IConvertible.ToChar method of the underlying type of value. provider enables the user to specify culture-specific conversion information about the contents of value. For example, if value is a System.String that represents a number, provider could supply culture-specific information about the notation used to represent that number. The base types ignore provider; however, it is honored if value is a user-defined type that implements the System.IConvertible interface.
R S T U V W
Exceptions
X
Exception
Condition
System.InvalidCastException
value does not implement the System.IConvertible interface.
Y Z
667
Contents | Index
Convert
System
ToChar() Method
Convert.ToChar(System.SByte) Method [ILASM]
.method public hidebysig static valuetype System.Char ToChar(int8 value)
A
[C#]
public static char ToChar(sbyte value)
B C
Summary
D
Converts a System.SByte to a System.Char.
E
Parameters
F G
Parameter
Description
value
The System.SByte value to be converted.
H I J K
Description
L
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToChar(System.Int16).
M N
Exceptions
O P Q
Exception
Condition
System.OverflowException
value is less than System.Char.MinValue.
R S
Example
T
using System;
U
namespace Samples { public class ConvertToChar { public static void Main() { try { sbyte s = 65; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToChar(s));
V W X Y Z
668
Contents | Index
System
Convert ToChar() Method
s = 95; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToChar(s)); s = SByte.MinValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToChar(s));
A B
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
C D E
}
F
} }
G
The output is
H I
From Signed Byte 65 yields A From Signed Byte 95 yields _ Exception: System.OverflowException: Value was either too large or too small for a character. at System.Convert.ToChar(SByte value) at Samples.ConvertToChar.Main() in C:\Books\BCL\Samples\System\Convert\ToChar\ ToChar(System.SByte)\Convert.cs:line 18
J K L M N O
Convert.ToChar(System.Int16) Method
P
[ILASM]
.method public hidebysig static valuetype System.Char ToChar(int16 value)
Q
[C#]
R
public static char ToChar(short value)
S
Summary
T
Converts a System.Int16 to a System.Char.
U V W X Y Z
669
Contents | Index
Convert
System
ToChar() Method
Parameters Parameter
Description
value
The 16-bit signed integer value to be converted.
A B C
Exceptions
D E
Exception
Condition
System.OverflowException
value is less than System.Char.MinValue.
F G H I
Example
J
using System;
K
namespace Samples { public class ConvertToChar { public static void Main() { try { short i = 65; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToChar(i)); i = 95; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToChar(i)); i = Int16.MinValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToChar(i)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
L M N O P Q R S T U V W X Y Z
670
Contents | Index
System
Convert ToChar() Method
The output is From Int16 65 yields A From Int16 95 yields _ Exception: System.OverflowException: Value was either too large or too small for a character. at System.Convert.ToChar(Int16 value) at Samples.ConvertToChar.Main() in C:\Books\BCL\Samples\System\Convert\ToChar\ ToChar(System.Int16)\Convert.cs:line 18
A B C D E
Convert.ToChar(System.String) Method
F
[ILASM]
G
.method public hidebysig static valuetype System.Char ToChar(string value)
H
[C#]
I
public static char ToChar(string value)
J
Summary
K
Converts a System.String to a System.Char.
L
Parameters
M N
Parameter
Description
value
The System.String to be converted. The System.String is required to contain a single character.
O P Q R
Exceptions
S
Exception
Condition
System.FormatException
value does not contain exactly one character.
T U V W
Example
X
using System;
Y namespace Samples { public class ConvertToChar {
Z
671
Contents | Index
Convert
System
ToChar() Method
public static void Main() { string s; try { s = "A"; Console.WriteLine("From String {0} yields {1}", s, Convert.ToChar(s)); s = "AA"; Console.WriteLine("From String {0} yields {1}", s, Convert.ToChar(s)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } }
A B C D E F G H I
} }
J K
The output is
L
From String A yields A Exception: System.FormatException: String must be only one character long. at System.Convert.ToChar(String value) at Samples.ConvertToChar.Main() in C:\Books\BCL\Samples\System\Convert\ToChar\ ToChar(System.String)\Convert.cs:line 16
M N O P Q
Convert.ToChar(System.String, System.IFormatProvider) Method
R
[ILASM]
S
.method public hidebysig static valuetype System.Char ToChar(string value, class System.IFormatProvider provider)
T
[C#]
public static char ToChar(string value, IFormatProvider provider)
U V
Summary
W
Converts the first character of a System.String to a Unicode character using specified culture-specific formatting information.
X Y Z
672
Contents | Index
System
Convert ToChar() Method
Parameters Parameter
Description
value
A System.String of length 1 or null.
provider
(Reserved) A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
A B C D E
Return Value
F
The Unicode character equivalent to the first and only character in value.
G
Description
H
value must be null or a System.String containing a single character. provider is ignored; it does not participate in this operation.
I J K
Exceptions
L
Exception
Condition
M
System.ArgumentNullException
value is null.
N
System.FormatException
The length of value is not 1.
O P Q R
Convert.ToChar(System.DateTime) Method
S
[ILASM]
T
.method public hidebysig static valuetype System.Char ToChar(valuetype System.DateTime value)
U
[C#]
public static char ToChar(DateTime value)
V W
Summary
X
Calling this method always throws System.InvalidCastException.
Y Z
673
Contents | Index
Convert
System
ToChar() Method
Parameters Parameter
Description
value
A System.DateTime.
A B C
Exceptions
D E
Exception
Condition
System.InvalidCastException
This conversion is not supported.
F G H I
Convert.ToChar(System.UInt32) Method
J
[ILASM]
K
.method public hidebysig static valuetype System.Char ToChar(unsigned int32 value)
L
[C#]
public static char ToChar(uint value)
M N
Summary
O
Converts a System.UInt32 to a System.Char.
P
Parameters
Q R S
Parameter
Description
value
The 32-bit unsigned integer value to be converted.
T U
Exceptions
V W
Exception
Condition
System.OverflowException
value is greater than System.Char.MaxValue.
X Y Z
674
Contents | Index
System
Convert ToChar() Method
Example using System; namespace Samples { public class ConvertToChar { public static void Main() { try { uint u = 65; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToChar(u)); u = 95; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToChar(u)); u = UInt32.MaxValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToChar(u)); } catch(OverflowException e) { Console.WriteLine("Exception {0}", e); } } } }
A B C D E F G H I J K L M N O P
The output is
Q
From UInt32 65 yields A From UInt32 95 yields _ Exception System.OverflowException: Value was either too large or too small for a character. at System.Convert.ToChar(UInt32 value) at Samples.ConvertToChar.Main() in C:\Books\BCL\Samples\System\Convert\ToChar\ ToChar(System.UInt32)\Convert.cs:line 18
R S T U V W
Convert.ToChar(System.UInt64) Method
X
[ILASM]
Y
.method public hidebysig static valuetype System.Char ToChar(unsigned int64 value)
Z
[C#]
public static char ToChar(ulong value)
675
Contents | Index
Convert
System
ToChar() Method
Summary Converts a System.UInt64 to a System.Char. A
Parameters
B C
Parameter
Description
D
value
The 64-bit unsigned integer value to be converted.
E F
Description
G
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToChar(System.Int64).
H I
Exceptions
J K
Exception
Condition
System.OverflowException
value is greater than System.Char.MaxValue.
L M N
Example
O
using System;
P namespace Samples { public class ConvertToChar { public static void Main() { try { ulong u = 65; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToChar(u)); u = 95; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToChar(u)); u = UInt64.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToChar(u)); } catch(OverflowException e)
Q R S T U V W X Y Z
676
Contents | Index
System
Convert ToChar() Method
{ Console.WriteLine("Exception: {0}", e); } }
A
} }
B C
The output is
D From UInt64 65 yields A From UInt64 95 yields _ Exception: System.OverflowException: Value was either too large or too small for a character. at System.Convert.ToChar(UInt64 value) at Samples.ConvertToChar.Main() in C:\Books\BCL\Samples\System\Convert\ToChar\ ToChar(System.UInt64)\Convert.cs:line 18
E F G H I J
Convert.ToChar(System.UInt16) Method
K [ILASM]
L
.method public hidebysig static valuetype System.Char ToChar(unsigned int16 value) [C#]
M
public static char ToChar(ushort value)
N
Summary
O
Converts a System.UInt16 to a System.Char.
P Q
Parameters
R
Parameter
Description
S
value
The 16-bit unsigned integer value to be converted.
T U V
Description
W
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToChar(System.Int32).
X Y Z
677
Contents | Index
Convert
System
ToDateTime() Method
Example using System; namespace Samples { public class ConvertToChar { public static void Main() { ushort u = 65; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToChar(u)); u = 95; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToChar(u)); } } }
A B C D E F G H I J
The output is
K From UInt16 65 yields A From UInt16 95 yields _
L M N
Convert.ToDateTime(System.Boolean) Method
O
[ILASM]
P
.method public hidebysig static valuetype System.DateTime ToDateTime(bool value) [C#]
Q
public static DateTime ToDateTime(bool value)
R
Summary
S
Calling this method always throws System.InvalidCastException.
T
Parameters
U V
Parameter
Description
value
A Boolean value.
W X Y Z
678
Contents | Index
System
Convert ToDateTime() Method
Exceptions Exception
Condition
System.InvalidCastException
This conversion is not supported.
A B C D
Convert.ToDateTime(System.Byte) Method
E
[ILASM]
F
.method public hidebysig static valuetype System.DateTime ToDateTime(unsigned int8 value)
G
[C#]
H
public static DateTime ToDateTime(byte value)
I
Summary
J
Calling this method always throws System.InvalidCastException.
K
Parameters
L M
Parameter
Description
value
An 8-bit unsigned integer.
N O P Q
Exceptions
R
Exception
Condition
System.InvalidCastException
This conversion is not supported.
S T U V
Convert.ToDateTime(System.Char) Method
W
[ILASM]
X
.method public hidebysig static valuetype System.DateTime ToDateTime(valuetype System.Char value)
Y
[C#]
Z
public static DateTime ToDateTime(char value)
679
Contents | Index
Convert
System
ToDateTime() Method
Summary Calling this method always throws System.InvalidCastException. A
Parameters
B C
Parameter
Description
D
value
A Unicode character.
E F
Exceptions
G H I
Exception
Condition
System.InvalidCastException
This conversion is not supported.
J K
Convert.ToDateTime(System.Decimal) Method
L
[ILASM]
M
.method public hidebysig static valuetype System.DateTime ToDateTime(decimal value)
N
[C#]
O
public static DateTime ToDateTime(decimal value)
P
Summary
Q
Calling this method always throws System.InvalidCastException.
R S
Parameters
T U V
Parameter
Description
value
A System.Decimal value.
W X
Exceptions
Y Z
Exception
Condition
System.InvalidCastException
This conversion is not supported.
680
Contents | Index
System
Convert ToDateTime() Method
Convert.ToDateTime(System.Double) Method [ILASM]
.method public hidebysig static valuetype System.DateTime ToDateTime(float64 value)
A
[C#]
B
public static DateTime ToDateTime(double value)
C
Summary
D
Calling this method always throws System.InvalidCastException.
E F
Parameters
G
Parameter
Description
H
value
A double-precision floating-point value.
I J K
Exceptions
L
Exception
Condition
M
System.InvalidCastException
This conversion is not supported.
N O P
Convert.ToDateTime(System.Single) Method
Q
[ILASM]
R
.method public hidebysig static valuetype System.DateTime ToDateTime(float32 value)
S
[C#]
T
public static DateTime ToDateTime(float value)
U
Summary
V
Calling this method always throws System.InvalidCastException.
W X
Parameters
Y
Parameter
Description
value
A single-precision floating-point value.
Z
681
Contents | Index
Convert
System
ToDateTime() Method
Exceptions Exception
Condition
System.InvalidCastException
This conversion is not supported.
A B C D
Convert.ToDateTime(System.Int32) Method
E
[ILASM]
F
.method public hidebysig static valuetype System.DateTime ToDateTime(int32 value) [C#]
G
public static DateTime ToDateTime(int value)
H I
Summary
J
Calling this method always throws System.InvalidCastException.
K
Parameters
L M N
Parameter
Description
value
A 32-bit signed integer.
O P
Exceptions
Q R
Exception
Condition
System.InvalidCastException
This conversion is not supported.
S T U V
Convert.ToDateTime(System.Int64) Method
W
[ILASM]
.method public hidebysig static valuetype System.DateTime ToDateTime(int64 value)
X
[C#]
Y
public static DateTime ToDateTime(long value)
Z
Summary Calling this method always throws System.InvalidCastException. 682
Contents | Index
System
Convert ToDateTime() Method
Parameters Parameter
Description
value
A 64-bit signed integer.
A B C
Exceptions
D E
Exception
Condition F
System.InvalidCastException
This conversion is not supported.
G H I
Convert.ToDateTime(System.Object) Method
J
[ILASM]
K
.method public hidebysig static valuetype System.DateTime ToDateTime(object value)
L
[C#]
public static DateTime ToDateTime(object value)
M
Summary
N
Converts the value of the specified System.Object to a System.DateTime.
O
Parameters
P Q
Parameter
Description
value
A System.Object that implements the System.IConvertible interface or null.
R S T U
Return Value
V
A System.DateTime equivalent to the value of value, or zero if value is null.
W
Description
X
The return value is the result of invoking the IConvertible.ToDateTime method of the underlying type of value.
Y Z
683
Contents | Index
Convert
System
ToDateTime() Method
Exceptions Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
A B C D
Convert.ToDateTime(System.Object, System.IFormatProvider) Method
E
[ILASM]
F
.method public hidebysig static valuetype System.DateTime ToDateTime(object value, class System.IFormatProvider provider)
G
[C#]
H
public static DateTime ToDateTime(object value, IFormatProvider provider)
I
Summary
J
Converts the value of the specified System.Object to a System.DateTime using the specified culture-specific formatting information.
K L
Parameters
M N
Parameter
Description
value
An System.Object that implements the System.IConvertible interface.
provider
An System.IFormatProvider interface implementation that supplies culture-specific formatting information.
O P Q R S
Return Value
T
A System.DateTime equivalent to the value of value, or zero if value is null.
U V
Description
W
The return value is the result of invoking the IConvertible.ToDateTime method of the underlying type of value. provider enables the user to specify culture-specific conversion information about the contents of value. For example, if value is a System.String that represents a date, provider could supply culture-specific information about the notation used to represent that date. The base types ignore provider; however, it is honored if value is a user-defined type that implements the System.IConvertible interface.
X Y Z
684
Contents | Index
System
Convert ToDateTime() Method
Exceptions Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
A B C D
Convert.ToDateTime(System.SByte) Method
E
[ILASM]
F
.method public hidebysig static valuetype System.DateTime ToDateTime(int8 value) [C#]
G
public static DateTime ToDateTime(sbyte value)
H
Summary
I
Calling this method always throws System.InvalidCastException.
J K
Parameters
L
Parameter
Description
value
An 8-bit signed integer.
M N O P
Exceptions
Q
Exception
Condition
System.InvalidCastException
This conversion is not supported.
R S T U V
Convert.ToDateTime(System.Int16) Method
W
[ILASM]
.method public hidebysig static valuetype System.DateTime ToDateTime(int16 value)
X
[C#]
Y
public static DateTime ToDateTime(short value)
Z
Summary Calling this method always throws System.InvalidCastException. 685
Contents | Index
Convert
System
ToDateTime() Method
Parameters Parameter
Description
value
A 16-bit signed integer.
A B C
Exceptions
D E
Exception
Condition
System.InvalidCastException
This conversion is not supported.
F G H I
Convert.ToDateTime(System.String) Method
J
[ILASM]
K
.method public hidebysig static valuetype System.DateTime ToDateTime(string value)
L
[C#]
public static DateTime ToDateTime(string value)
M N
Summary
O
Converts a System.String to a System.DateTime structure.
P
Parameters
Q R
Parameter
Description
value
The System.String to be converted. The string is in a form allowed by the System.DateTime.Parse(System.String) method.
S T U V
Description
W
This method parses value using the information in a System.Globalization.DateTimeFormatInfo instance initialized for the current system culture.
X Y Z
686
Contents | Index
System
Convert ToDateTime() Method
Exceptions Exception
Condition
System.ArgumentException
value is a null reference.
System.FormatException
value cannot be converted to a System.DateTime.
A B C D
Example
E
using System;
F G
namespace Samples { public class ConvertToDateTime { public static void Main() { DateTime dt = DateTime.MinValue; Console.WriteLine("From DateTime {0} yields {1}", dt, Convert.ToDateTime(dt)); dt = DateTime.Now; Console.WriteLine("From DateTime {0} yields {1}", dt, Convert.ToDateTime(dt)); dt = DateTime.MaxValue; Console.WriteLine("From DateTime {0} yields {1}", dt, Convert.ToDateTime(dt)); } } }
H I J K L M N O P Q R
The output is
S T
From DateTime 1/01/0001 12:00:00 AM yields 1/01/0001 12:00:00 AM From DateTime 5/06/2003 8:06:52 AM yields 5/06/2003 8:06:52 AM From DateTime 31/12/9999 11:59:59 PM yields 31/12/9999 11:59:59 PM Exception: System.FormatException: String was not recognized as a valid DateTime. at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) at System.DateTime.Parse(String s, IFormatProvider provider, DateTimeStyles styles) at System.DateTime.Parse(String s, IFormatProvider provider) at System.DateTime.Parse(String s) at System.Convert.ToDateTime(String value) at Samples.ConvertToDateTime.Main() in C:\Books\BCL\Samples\System\Convert\ ToDateTime\ToDateTime(System.String)\Convert.cs:line 21
U V W X Y Z
687
Contents | Index
Convert
System
ToDateTime() Method
Convert.ToDateTime(System.String, System.IFormatProvider) Method [ILASM]
A
.method public hidebysig static valuetype System.DateTime ToDateTime(string value, class System.IFormatProvider provider)
B
[C#]
public static DateTime ToDateTime(string value, IFormatProvider provider)
C D
Summary
E
Converts a System.String to a System.DateTime structure.
F
Parameters
G H I
Parameter
Description
value
The System.String to be converted.
provider
A System.IFormatProvider that supplies a System.Globalization.DateTimeFormatInfo containing culture-specific formatting information.
J K L M
Description
N
This method parses value using the information in the System.Globalization.DateTimeFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.DateTimeFormatInfo cannot be obtained from provider, the string is parsed using the formatting information of the current system culture.
O P Q
Exceptions
R S
Exception
Condition
U
System.ArgumentException
value is a null reference.
V
System.FormatException
value cannot be converted to a System.DateTime.
T
W X Y Z
688
Contents | Index
System
Convert ToDateTime() Method
Example using System; using System.Globalization;
A namespace Samples { public class ConvertToDateTime { public static void Main() { try { CultureInfo c = new CultureInfo("fr-FR"); string s = DateTime.MinValue.ToString(c); Console.WriteLine("From DateTime {0} yields {1}", s, Convert.ToDateTime(s, c)); s = DateTime.Now.ToString(c); Console.WriteLine("From DateTime {0} yields {1}", s, Convert.ToDateTime(s, c)); s = DateTime.MaxValue.ToString(c); Console.WriteLine("From DateTime {0} yields {1}", s, Convert.ToDateTime(s, c)); s = String.Empty; Console.WriteLine("From DateTime {0} yields {1}", s, Convert.ToDateTime(s, c)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } } } }
B C D E F G H I J K L M N O P Q R S
The output is
T
From DateTime 01/01/0001 00:00:00 yields 1/01/0001 12:00:00 AM From DateTime 05/06/2003 08:11:37 yields 5/06/2003 8:11:37 AM From DateTime 31/12/9999 23:59:59 yields 31/12/9999 11:59:59 PM Exception: System.FormatException: String was not recognized as a valid DateTime. at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) at System.DateTime.Parse(String s, IFormatProvider provider, DateTimeStyles styles) at System.DateTime.Parse(String s, IFormatProvider provider) at System.Convert.ToDateTime(String value, IFormatProvider provider) at Samples.ConvertToDateTime.Main() in C:\Books\BCL\Samples\System\Convert\ ToDateTime\ToDateTime(System.String,System.IFormatProvider)\Convert.cs:line 23
U V W X Y Z
689
Contents | Index
Convert
System
ToDateTime() Method
Convert.ToDateTime(System.DateTime) Method [ILASM]
A
.method public hidebysig static valuetype System.DateTime ToDateTime(valuetype System.DateTime value)
B
[C#]
public static DateTime ToDateTime(DateTime value)
C D
Summary
E
Converts a System.DateTime to a System.DateTime.
F
Parameters
G H
Parameter
Description
I
value
The System.DateTime to be converted.
J K
Return Value
L
value is returned unchanged.
M
Description
N
[Note: This method is provided for completeness.]
O
Example
P
using System;
Q
namespace Samples { public class ConvertToDateTime { public static void Main() { DateTime dt = DateTime.MinValue; Console.WriteLine("From DateTime {0} yields {1}", dt, Convert.ToDateTime(dt)); dt = DateTime.Now; Console.WriteLine("From DateTime {0} yields {1}", dt, Convert.ToDateTime(dt)); dt = DateTime.MaxValue; Console.WriteLine("From DateTime {0} yields {1}", dt, Convert.ToDateTime(dt)); } } }
R S T U V W X Y Z
690
Contents | Index
System
Convert ToDateTime() Method
The output is From DateTime 1/01/0001 12:00:00 AM yields 1/01/0001 12:00:00 AM From DateTime 5/06/2003 8:02:12 AM yields 5/06/2003 8:02:12 AM From DateTime 31/12/9999 11:59:59 PM yields 31/12/9999 11:59:59 PM
A B C
Convert.ToDateTime(System.UInt32) Method
D
[ILASM]
E
.method public hidebysig static valuetype System.DateTime ToDateTime(unsigned int32 value)
F
[C#]
G
public static DateTime ToDateTime(uint value)
H
Summary
I
Calling this method always throws System.InvalidCastException.
J
Parameters
K L
Parameter
Description
value
A 32-bit unsigned integer.
M N O P
Exceptions
Q
Exception
Condition
System.InvalidCastException
This conversion is not supported.
R S T U
Convert.ToDateTime(System.UInt64) Method
V
[ILASM]
W
.method public hidebysig static valuetype System.DateTime ToDateTime(unsigned int64 value)
X
[C#]
Y
public static DateTime ToDateTime(ulong value)
Z
Summary Calling this method always throws System.InvalidCastException. 691
Contents | Index
Convert
System
ToDateTime() Method
Parameters Parameter
Description
value
A 64-bit unsigned integer.
A B C
Exceptions
D E
Exception
Condition
System.InvalidCastException
This conversion is not supported.
F G H I
Convert.ToDateTime(System.UInt16) Method
J
[ILASM]
K
.method public hidebysig static valuetype System.DateTime ToDateTime(unsigned int16 value)
L
[C#]
M
public static DateTime ToDateTime(ushort value)
N
Summary
O
Calling this method always throws System.InvalidCastException.
P Q
Parameters
R S T
Parameter
Description
value
A 16-bit unsigned integer.
U V
Exceptions
W X
Exception
Condition
Y
System.InvalidCastException
This conversion is not supported.
Z
692
Contents | Index
System
Convert ToDecimal() Method
Convert.ToDecimal(System.Boolean) Method [ILASM]
.method public hidebysig static decimal ToDecimal(bool value) [C#]
A
public static decimal ToDecimal(bool value)
B C
Summary
D
Converts a System.Boolean to a System.Decimal.
E
Parameters
F
Parameter
Description
value
The System.Boolean value to be converted.
G H I J
Return Value
K
If value is true, returns 1; if value is false, returns 0.
L M
Description
N
This member must be implemented if the Extended Numerics Library is present in the implementation.
O P
Example
Q
using System;
R namespace Samples { public class ConvertToDecimal { public static void Main() { bool b = true; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToDecimal(b)); b = false; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToDecimal(b)); } } }
S T U V W X Y Z
693
Contents | Index
Convert
System
ToDecimal() Method
The output is From Boolean True yields 1 From Boolean False yields 0
A B C
Convert.ToDecimal(System.Byte) Method
D
[ILASM]
.method public hidebysig static decimal ToDecimal(unsigned int8 value)
E
[C#]
public static decimal ToDecimal(byte value)
F G
Summary
H
Converts a System.Byte to a System.Decimal.
I
Parameters
J K
Parameter
Description
value
The System.Byte value to be converted.
L M N O
Description
P
This member must be implemented if the Extended Numerics Library is present in the implementation.
Q R
Example
S
using System;
T
namespace Samples { public class ConvertToDecimal { public static void Main() { byte b = Byte.MaxValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToDecimal(b)); b = Byte.MinValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToDecimal(b));
U V W X Y Z
694
Contents | Index
System
Convert ToDecimal() Method
b = Byte.MaxValue / 2; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToDecimal(b)); }
A
} }
B C
The output is
D From Byte 255 yields 255 From Byte 0 yields 0 From Byte 127 yields 127
E F G
Convert.ToDecimal(System.Char) Method
H
[ILASM]
I
.method public hidebysig static decimal ToDecimal(valuetype System.Char value)
J
[C#]
public static decimal ToDecimal(char value)
K L
Summary
M
Calling this method always throws System.InvalidCastException.
N
Parameters
O
Parameter
Description
value
A Unicode character.
P Q R S
Exceptions Exception
T U
Condition
V System.InvalidCastException
This conversion is not supported.
W X Y Z
695
Contents | Index
Convert
System
ToDecimal() Method
Convert.ToDecimal(System.Decimal) Method [ILASM]
.method public hidebysig static decimal ToDecimal(decimal value)
A
[C#]
public static decimal ToDecimal(decimal value)
B C
Summary
D
Converts a System.Decimal to a System.Decimal.
E
Parameters
F G
Parameter
Description
value
The System.Decimal value to be converted.
H I J K
Return Value
L
value is returned unchanged.
M
Description
N
[Note: This method is provided for completeness.] This member must be implemented if the Extended Numerics Library is present in the implementation.
O P
Example
Q
using System;
R namespace Samples { public class ConvertToDecimal { public static void Main() { Decimal d = Decimal.One; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToDecimal(d)); d = Decimal.Zero; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToDecimal(d)); d = Decimal.MaxValue; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToDecimal(d)); d = Decimal.MinValue;
S T U V W X Y Z
696
Contents | Index
System
Convert ToDecimal() Method
Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToDecimal(d)); d = 25.5m; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToDecimal(d)); d = -25.5m; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToDecimal(d));
A B C
}
D
} }
E F
The output is
G From From From From From From
Decimal Decimal Decimal Decimal Decimal Decimal
1 yields 1 0 yields 0 79228162514264337593543950335 yields 79228162514264337593543950335 -79228162514264337593543950335 yields -79228162514264337593543950335 25.5 yields 25.5 -25.5 yields -25.5
H I J K L
Convert.ToDecimal(System.Double) Method
M
[ILASM]
N
.method public hidebysig static decimal ToDecimal(float64 value)
O
[C#]
public static decimal ToDecimal(double value)
P
Summary
Q
Converts a System.Double to a System.Decimal.
R S
Parameters
T
Parameter
Description
value
The System.Double value to be converted.
U V W X
Return Value
Y
value as a System.Decimal. The System.Decimal contains 15 significant digits and is rounded using banker’s rounding.
Z
697
Contents | Index
Convert
System
ToDecimal() Method
Description This member must be implemented if the Extended Numerics Library is present in the implementation. A
Exceptions
B C
Exception
Condition
System.OverflowException
The numeric value of value is greater than System.Decimal.MaxValue or less than System.Decimal.MinValue.
D E F G
Example
H
using System;
I namespace Samples { public class ConvertToDecimal { public static void Main() { try { double d = Double.Epsilon; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToDecimal(d)); d = 0.0; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToDecimal(d)); d = 5.5; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToDecimal(d)); d = -5.5; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToDecimal(d)); d = Double.MaxValue; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToDecimal(d)); d = Double.MinValue; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToDecimal(d)); d = Double.PositiveInfinity; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToDecimal(d)); }
J K L M N O P Q R S T U V W X Y Z
698
Contents | Index
System
Convert ToDecimal() Method
catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A
} }
B
}
C
The output is
D E
From Double 4.94065645841247E-324 yields 0 From Double 0 yields 0 From Double 5.5 yields 5.5 From Double -5.5 yields -5.5 Exception: System.OverflowException: Value was either too large or too small for a Decimal. at System.Decimal..ctor(Double value) at System.Decimal.op_Explicit(Double value) at System.Convert.ToDecimal(Double value) at Samples.ConvertToDecimal.Main() in C:\Books\BCL\Samples\System\Convert\ ToDecimal\ToDecimal(System.Double)\Convert.cs:line 24
F G H I J K L M
Convert.ToDecimal(System.Single) Method
N [ILASM]
O
.method public hidebysig static decimal ToDecimal(float32 value) [C#]
P
public static decimal ToDecimal(float value)
Q
Summary
R
Converts a System.Single to a System.Decimal.
S T
Parameters
U
Parameter
Description
V
value
The System.Single value to be converted.
W X Y
Return Value
Z
value as a System.Decimal. The System.Decimal contains 7 significant digits and is rounded using banker’s rounding.
699
Contents | Index
Convert
System
ToDecimal() Method
Description This member must be implemented if the Extended Numerics Library is present in the implementation. A
Exceptions
B C
Exception
Condition
System.OverflowException
The numeric value of value is greater than System.Decimal.MaxValue or less than System.Decimal.MinValue.
D E F G H
Example
I
using System;
J
namespace Samples { public class ConvertToDecimal { public static void Main() { try { float f = 0f; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToDecimal(f)); f = 0.5f; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToDecimal(f)); f = -0.5f; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToDecimal(f)); f = Single.Epsilon; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToDecimal(f)); f = Single.MaxValue; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToDecimal(f)); f = Single.MinValue; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToDecimal(f)); } catch(OverflowException e) {
K L M N O P Q R S T U V W X Y Z
700
Contents | Index
System
Convert ToDecimal() Method
Console.WriteLine("Exception: {0}", e); } } }
A
}
B
The output is
C
From Single 0 yields 0 From Single 0.5 yields 0.5 From Single -0.5 yields -0.5 From Single 1.401298E-45 yields 0 Exception: System.OverflowException: Value was either too large or too small for a Decimal. at System.Decimal..ctor(Single value) at System.Decimal.op_Explicit(Single value) at System.Convert.ToDecimal(Single value) at Samples.ConvertToDecimal.Main() in C:\Books\BCL\Samples\System\Convert\ ToDecimal\ToDecimal(System.Single)\Convert.cs:line 24
D E F G H I J K
Convert.ToDecimal(System.Int32) Method
L
[ILASM]
M
.method public hidebysig static decimal ToDecimal(int32 value)
N
[C#]
O
public static decimal ToDecimal(int value)
P
Summary
Q
Converts a System.Int32 to a System.Decimal.
R S
Parameters
T
Parameter
Description
value
The 32-bit signed integer value to be converted.
U V W
Description
X
This member must be implemented if the Extended Numerics Library is present in the implementation.
Y Z
701
Contents | Index
Convert
System
ToDecimal() Method
Example using System; namespace Samples { public class ConvertToDecimal { public static void Main() { int i = Int32.MaxValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToDecimal(i)); i = 0; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToDecimal(i)); i = Int32.MinValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToDecimal(i)); } } }
A B C D E F G H I J K L
The output is
M
From Int32 2147483647 yields 2147483647 From Int32 0 yields 0 From Int32 -2147483648 yields -2147483648
N O P Q
Convert.ToDecimal(System.Int64) Method
R
[ILASM]
S
.method public hidebysig static decimal ToDecimal(int64 value) [C#]
T
public static decimal ToDecimal(long value)
U
Summary
V
Converts a System.Int64 to a System.Decimal.
W X
Parameters
Y Z
Parameter
Description
value
The 64-bit signed integer value to be converted.
702
Contents | Index
System
Convert ToDecimal() Method
Description This member must be implemented if the Extended Numerics Library is present in the implementation. A
Example
B
using System;
C
namespace Samples { public class ConvertToDecimal { public static void Main() { long l = Int64.MaxValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToDecimal(l)); l = Int64.MinValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToDecimal(l)); } } }
D E F G H I J K L M
The output is
N O
From Int64 9223372036854775807 yields 9223372036854775807 From Int64 -9223372036854775808 yields -9223372036854775808
P Q
Convert.ToDecimal(System.Object) Method
R
[ILASM]
S
.method public hidebysig static decimal ToDecimal(object value)
T
[C#]
public static decimal ToDecimal(object value)
U V
Summary
W
Converts the value of the specified System.Object to a System.Decimal number.
X Y Z
703
Contents | Index
Convert
System
ToDecimal() Method
Parameters Parameter
Description
value
A System.Object that implements the System.IConvertible interface or null.
A B C D
Return Value
E
A System.Decimal number equivalent to the value of value, or zero if value is null.
F G
Description
H
The return value is the result of invoking the IConvertible.ToDecimal method of the underlying type of value.
I J
Exceptions
K L M
Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
N O P
Convert.ToDecimal(System.Object, System.IFormatProvider) Method
Q
[ILASM]
R
.method public hidebysig static decimal ToDecimal(object value, class System.IFormatProvider provider) [C#]
S
public static decimal ToDecimal(object value, IFormatProvider provider)
T U
Summary
V
Converts the value of the specified System.Object to a System.Decimal number using the specified culture-specific formatting information.
W X Y Z
704
Contents | Index
System
Convert ToDecimal() Method
Parameters Parameter
Description
value
A System.Object that implements the System.IConvertible interface.
provider
A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
A B C D E
Return Value
F
A System.Decimal number equivalent to the value of value, or zero if value is null.
G
Description
H
The return value is the result of invoking the IConvertible.ToDecimal method of the underlying type of value. provider enables the user to specify culture-specific conversion information about the contents of value. For example, if value is a System.String that represents a number, provider could supply culture-specific information about the notation used to represent that number. The base types ignore provider; however, it is honored if value is a user-defined type that implements the System.IConvertible interface.
I J K L M N
Exceptions
O P
Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
Q R S T U
Convert.ToDecimal(System.SByte) Method
V
[ILASM]
.method public hidebysig static decimal ToDecimal(int8 value)
W
[C#]
X
public static decimal ToDecimal(sbyte value)
Y
Summary
Z
Converts a System.SByte to a System.Decimal.
705
Contents | Index
Convert
System
ToDecimal() Method
Parameters Parameter
Description
value
The System.SByte value to be converted.
A B C
Description
D
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDecimal(System.Int16). This member must be implemented if the Extended Numerics Library is present in the implementation.
E F G
Example
H
using System;
I
namespace Samples { public class ConvertToDecimal { public static void Main() { sbyte s = SByte.MaxValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToDecimal(s)); s = 0; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToDecimal(s)); s = SByte.MinValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToDecimal(s)); } } }
J K L M N O P Q R S T U
The output is
V From Signed Byte 127 yields 127 From Signed Byte 0 yields 0 From Signed Byte -128 yields -128
W X Y Z
706
Contents | Index
System
Convert ToDecimal() Method
Convert.ToDecimal(System.Int16) Method [ILASM]
.method public hidebysig static decimal ToDecimal(int16 value) [C#]
A
public static decimal ToDecimal(short value)
B C
Summary
D
Converts a System.Int16 to a System.Decimal.
E
Parameters
F
Parameter
Description
value
The 16-bit signed integer value to be converted.
G H I J
Description
K
This member must be implemented if the Extended Numerics Library is present in the implementation.
L M
Example
N
using System;
O
namespace Samples { public class ConvertToDecimal { public static void Main() { short i = Int16.MinValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToDecimal(i)); i = 0; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToDecimal(i)); i = Int16.MaxValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToDecimal(i)); } } }
P Q R S T U V W X Y Z
707
Contents | Index
Convert
System
ToDecimal() Method
The output is From Int16 -32768 yields -32768 From Int16 0 yields 0 From Int16 32767 yields 32767
A B C
Convert.ToDecimal(System.String) Method
D [ILASM]
E
.method public hidebysig static decimal ToDecimal(string value)
F
[C#]
public static decimal ToDecimal(string value)
G H
Summary
I
Converts a System.String to a System.Decimal.
J
Parameters
K L
Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Number style.
M N O P
Description
Q
This method parses value using the information in a System.Globalization.NumberFormatInfo instance initialized for the current system culture. This member must be implemented if the Extended Numerics Library is present in the implementation.
R S
Exceptions
T U
Exception
Condition
W
System.ArgumentException
value is a null reference.
X
System.FormatException
value cannot be converted to a numeric value.
System.OverflowException
The numeric value of value is greater than System.Decimal.MaxValue or less than System.Decimal.MinValue.
V
Y Z
708
Contents | Index
System
Convert ToDecimal() Method
Example using System; namespace Samples { public class ConvertToDecimal { public static void Main() { string s; try { s = "+0"; Console.WriteLine("From String {0} yields {1}", s, Convert.ToDecimal(s)); s = (Decimal.MaxValue).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToDecimal(s)); s = (Decimal.MinValue).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToDecimal(s)); s = (Decimal.MinusOne).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToDecimal(s)); s = (Decimal.One).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToDecimal(s)); s = (Decimal.Zero).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToDecimal(s)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToDecimal(s)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = (Decimal.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToDecimal(s)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
709
Contents | Index
Convert
System
ToDecimal() Method
The output is From String +0 yields 0 From String 79228162514264337593543950335 yields 79228162514264337593543950335 From String -79228162514264337593543950335 yields -79228162514264337593543950335 From String -1 yields -1 From String 1 yields 1 From String 0 yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseDecimal(String s, NumberStyles style, NumberFormatInfo info) at System.Decimal.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Decimal.Parse(String s) at System.Convert.ToDecimal(String value) at Samples.ConvertToDecimal.Main() in C:\Books\BCL\Samples\System\Convert\ ToDecimal\ToDecimal(System.String)\Convert.cs:line 31 Exception: System.OverflowException: Value was either too large or too small for a Decimal. at System.Decimal.Add(Decimal d1, Decimal d2) at System.Decimal.op_Addition(Decimal d1, Decimal d2) at Samples.ConvertToDecimal.Main() in C:\Books\BCL\Samples\System\Convert\ ToDecimal\ToDecimal(System.String)\Convert.cs:line 40
A B C D E F G H I J K L M N
Convert.ToDecimal(System.String, System.IFormatProvider) Method
O
[ILASM]
P
.method public hidebysig static decimal ToDecimal(string value, class System.IFormatProvider provider)
Q
[C#]
public static decimal ToDecimal(string value, IFormatProvider provider)
R S
Summary
T
Converts a System.String to a System.Decimal.
U
Parameters
V W
Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Number style.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
X Y Z
710
Contents | Index
System
Convert ToDecimal() Method
Description This method parses value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is parsed using the formatting information of the current system culture. This member must be implemented if the Extended Numerics Library is present in the implementation.
A B C D
Exceptions
E
Exception
Condition
System.ArgumentException
value is a null reference.
G
System.FormatException
value cannot be converted to a numeric value.
H
System.OverflowException
The numeric value of value is greater than System.Decimal.MaxValue or less than System.Decimal.MinValue.
F
I J K L
Example
M
using System; using System.Globalization;
N
namespace Samples { public class ConvertToByte { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; try { s = "~0"; Console.WriteLine("From String {0} yields s, Convert.ToDecimal(s, s = (Decimal.MaxValue).ToString(); Console.WriteLine("From String {0} yields s, Convert.ToDecimal(s, s = (Decimal.MinValue).ToString(); Console.WriteLine("From String {0} yields s, Convert.ToDecimal(s,
O P Q R S T U V W
{1}", c));
X Y
{1}", c));
Z
{1}", c));
711
Contents | Index
Convert
System
ToDecimal() Method
s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToDecimal(s, c)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = (Decimal.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToDecimal(s, c)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E F G H I }
J }
K
}
L
The output is
M
From String ~0 yields 0 From String 79228162514264337593543950335 yields 79228162514264337593543950335 From String -79228162514264337593543950335 yields -79228162514264337593543950335 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseDecimal(String s, NumberStyles style, NumberFormatInfo info) at System.Decimal.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToDecimal(String value, IFormatProvider provider) at Samples.ConvertToByte.Main() in C:\Books\BCL\Samples\System\Convert\ ToDecimal\ToDecimal(System.String,System.IFormatProvider)\Convert.cs:line 26 Exception: System.OverflowException: Value was either too large or too small for a Decimal. at System.Decimal.Add(Decimal d1, Decimal d2) at System.Decimal.op_Addition(Decimal d1, Decimal d2) at Samples.ConvertToByte.Main() in C:\Books\BCL\Samples\System\Convert\ ToDecimal\ToDecimal(System.String,System.IFormatProvider)\Convert.cs:line 35
N O P Q R S T U V W X Y
Convert.ToDecimal(System.DateTime) Method
Z
[ILASM]
.method public hidebysig static decimal ToDecimal(valuetype System.DateTime value) [C#]
public static decimal ToDecimal(DateTime value)
712
Contents | Index
System
Convert ToDecimal() Method
Summary Calling this method always throws System.InvalidCastException. A
Parameters
B
Parameter
Description
C
value
A System.DateTime.
D E F
Exceptions
G
Exception
Condition
System.InvalidCastException
This conversion is not supported.
H I J K
Convert.ToDecimal(System.UInt32) Method
L
[ILASM]
M
.method public hidebysig static decimal ToDecimal(unsigned int32 value)
N
[C#]
O
public static decimal ToDecimal(uint value)
P
Summary
Q
Converts a System.UInt32 to a System.Decimal.
R
Parameters
S T
Parameter
Description
value
The 32-bit unsigned integer value to be converted.
U V W
Description
X
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDecimal(System.Int64). This member must be implemented if the Extended Numerics Library is present in the implementation.
Y Z
713
Contents | Index
Convert
System
ToDecimal() Method
Example using System; namespace Samples { public class ConvertToDecimal { public static void Main() { uint u = UInt32.MaxValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToDecimal(u)); u = UInt32.MinValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToDecimal(u)); } } }
A B C D E F G H I J
The output is
K L
From UInt32 4294967295 yields 4294967295 From UInt32 0 yields 0
M N O
Convert.ToDecimal(System.UInt64) Method
P
[ILASM]
.method public hidebysig static decimal ToDecimal(unsigned int64 value)
Q
[C#]
public static decimal ToDecimal(ulong value)
R S
Summary
T
Converts a System.UInt64 to a System.Decimal.
U
Parameters
V W
Parameter
Description
value
The 64-bit unsigned integer value to be converted.
X Y Z
714
Contents | Index
System
Convert ToDecimal() Method
Description This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDecimal(System.Decimal). This member must be implemented if the Extended Numerics Library is present in the implementation.
A B
Example
C
using System;
D namespace Samples { public class ConvertToDecimal { public static void Main() { try { ulong u = UInt64.MinValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToByte(u)); u = UInt64.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToByte(u)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
E F G H I J K L M N O P Q R
The output is
S From UInt64 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for an unsigned byte. at System.Convert.ToByte(UInt64 value) at Samples.ConvertToDecimal.Main() in C:\Books\BCL\Samples\System\Convert\ ToDecimal\ToDecimal(System.UInt64)\Convert.cs:line 15
T U V W X
Convert.ToDecimal(System.UInt16) Method
Y
[ILASM]
Z
.method public hidebysig static decimal ToDecimal(unsigned int16 value) [C#]
public static decimal ToDecimal(ushort value)
715
Contents | Index
Convert
System
ToDecimal() Method
Summary Converts a System.UInt16 to a System.Decimal. A
Parameters
B C
Parameter
Description
D
value
The 16-bit unsigned integer value to be converted.
E F
Description
G
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDecimal(System.Int32). This member must be implemented if the Extended Numerics Library is present in the implementation.
H I J
Example
K
using System;
L
namespace Samples { public class ConvertToDecimal { public static void Main() { ushort u = UInt16.MaxValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToDecimal(u)); u = UInt16.MinValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToDecimal(u)); } } }
M N O P Q R S T U V
The output is
W
From UInt16 65535 yields 65535 From UInt16 0 yields 0
X Y Z
716
Contents | Index
System
Convert ToDouble() Method
Convert.ToDouble(System.Boolean) Method [ILASM]
.method public hidebysig static float64 ToDouble(bool value) [C#]
A
public static double ToDouble(bool value)
B C
Summary
D
Converts a System.Boolean to a System.Double.
E
Parameters
F
Parameter
Description
value
The System.Boolean value to be converted.
G H I J
Return Value
K
If value is true, returns 1; if value is false, returns 0.
L M
Description
N
This member must be implemented if the Extended Numerics Library is present in the implementation.
O P
Example
Q
using System;
R namespace Samples { public class ConvertToDouble { public static void Main() { bool b = true; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToDouble(b)); b = false; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToDouble(b)); } } }
S T U V W X Y Z
717
Contents | Index
Convert
System
ToDouble() Method
The output is From Boolean True yields 1 From Boolean False yields 0
A B
Convert.ToDouble(System.Byte) Method
C
[ILASM]
D
.method public hidebysig static float64 ToDouble(unsigned int8 value)
E
[C#]
public static double ToDouble(byte value)
F G
Summary
H
Converts a System.Byte to a System.Double.
I
Parameters
J K L
Parameter
Description
value
The System.Byte value to be converted.
M N
Description
O
This member must be implemented if the Extended Numerics Library is present in the implementation.
P Q
Example
R
using System;
S namespace Samples { public class ConvertToDouble { public static void Main() { byte b = Byte.MaxValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToDouble(b)); b = Byte.MinValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToDouble(b)); } } }
T U V W X Y Z
718
Contents | Index
System
Convert ToDouble() Method
The output is From Byte 255 yields 255 From Byte 0 yields 0
A B
Convert.ToDouble(System.Char) Method
C
[ILASM]
D
.method public hidebysig static float64 ToDouble(valuetype System.Char value)
E
[C#]
public static double ToDouble(char value)
F G
Summary
H
Calling this method always throws System.InvalidCastException.
I
Parameters
J
Parameter
Description
value
A Unicode character.
K L M N
Exceptions
O
Exception
Condition
System.InvalidCastException
This conversion is not supported.
P Q R S T
Convert.ToDouble(System.Decimal) Method
U [ILASM]
.method public hidebysig static float64 ToDouble(decimal value)
V
[C#]
W
public static double ToDouble(decimal value)
X
Summary
Y
Converts a System.Decimal to a System.Double.
Z
719
Contents | Index
Convert
System
ToDouble() Method
Parameters Parameter
Description
value
The System.Decimal value to be converted.
A B C D
Return Value
E
value as a System.Double. value is rounded using banker’s rounding.
F
Description
G
This member must be implemented if the Extended Numerics Library is present in the implementation.
H I
Example
J
using System;
K namespace Samples { public class ConvertToDouble { public static void Main() { Decimal d = Decimal.One; Console.WriteLine("From Decimal {0} yields d, Convert.ToDouble(d)); d = Decimal.Zero; Console.WriteLine("From Decimal {0} yields d, Convert.ToDouble(d)); d = Decimal.MaxValue; Console.WriteLine("From Decimal {0} yields d, Convert.ToDouble(d)); d = Decimal.MinValue; Console.WriteLine("From Decimal {0} yields d, Convert.ToDouble(d)); d = 25.5m; Console.WriteLine("From Decimal {0} yields d, Convert.ToDouble(d)); d = -25.5m; Console.WriteLine("From Decimal {0} yields d, Convert.ToDouble(d)); } } }
L M N O P Q R S T U V W X Y Z
{1}",
{1}",
{1}",
{1}",
{1}",
{1}",
720
Contents | Index
System
Convert ToDouble() Method
The output is From From From From From From
Decimal Decimal Decimal Decimal Decimal Decimal
1 yields 1 0 yields 0 79228162514264337593543950335 yields 7.92281625142643E+28 -79228162514264337593543950335 yields -7.92281625142643E+28 25.5 yields 25.5 -25.5 yields -25.5
A B C D E
Convert.ToDouble(System.Double) Method
F [ILASM]
.method public hidebysig static float64 ToDouble(float64 value)
G
[C#]
H
public static double ToDouble(double value)
I
Summary
J
Converts a System.Double to a System.Double.
K L
Parameters
M
Parameter
Description
value
The System.Double value to be converted.
N O P Q
Return Value
R
value is returned unchanged.
S
Description
T
[Note: This method is provided for completeness.] This member must be implemented if the Extended Numerics Library is present in the implementation.
U V
Example
W
using System;
X
namespace Samples { public class ConvertToDouble { public static void Main()
Y Z
721
Contents | Index
Convert
System
ToDouble() Method
{ double d = Double.MaxValue; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToDouble(d)); d = Double.MinValue; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToDouble(d)); d = Double.PositiveInfinity; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToDouble(d)); d = Double.NegativeInfinity; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToDouble(d)); d = Double.Epsilon; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToDouble(d)); d = 0.0; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToDouble(d));
A B C D E F G H I J }
K
} }
L
The output is
M N
From From From From From From
O P Q
Double Double Double Double Double Double
1.79769313486232E+308 yields 1.79769313486232E+308 -1.79769313486232E+308 yields -1.79769313486232E+308 Infinity yields Infinity -Infinity yields -Infinity 4.94065645841247E-324 yields 4.94065645841247E-324 0 yields 0
R S
Convert.ToDouble(System.Single) Method
T [ILASM]
U
.method public hidebysig static float64 ToDouble(float32 value)
V
[C#]
public static double ToDouble(float value)
W X
Summary
Y
Converts a System.Single to a System.Double.
Z
722
Contents | Index
System
Convert ToDouble() Method
Parameters Parameter
Description
value
The System.Single value to be converted.
A B C
Description
D
This member must be implemented if the Extended Numerics Library is present in the implementation.
E
Example
G
using System;
H
namespace Samples { public class ConvertToDouble { public static void Main() { float f = Single.MaxValue; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToDouble(f)); f = Single.MinValue; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToDouble(f)); f = Single.Epsilon; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToDouble(f)); f = 0f; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToDouble(f)); } } }
I
F
J K L M N O P Q R S T U V
The output is From From From From
Single Single Single Single
W
3.402823E+38 yields 3.40282346638529E+38 -3.402823E+38 yields -3.40282346638529E+38 1.401298E-45 yields 1.40129846432482E-45 0 yields 0
X Y Z
723
Contents | Index
Convert
System
ToDouble() Method
Convert.ToDouble(System.Int32) Method [ILASM]
.method public hidebysig static float64 ToDouble(int32 value)
A
[C#]
B
public static double ToDouble(int value)
C
Summary
D
Converts a System.Int32 to a System.Double.
E
Parameters
F G H
Parameter
Description
value
The 32-bit signed integer value to be converted.
I J
Description
K
This member must be implemented if the Extended Numerics Library is present in the implementation.
L M
Example
N
using System;
O namespace Samples { public class ConvertToDouble { public static void Main() { int i = Int32.MaxValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToDouble(i)); i = 0; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToDouble(i)); i = Int32.MinValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToDouble(i)); } } }
P Q R S T U V W X Y Z
724
Contents | Index
System
Convert ToDouble() Method
The output is From Int32 2147483647 yields 2147483647 From Int32 0 yields 0 From Int32 -2147483648 yields -2147483648
A B C
Convert.ToDouble(System.Int64) Method
D
[ILASM]
E
.method public hidebysig static float64 ToDouble(int64 value)
F
[C#]
public static double ToDouble(long value)
G
Summary
H
Converts a System.Int64 to a System.Double.
I J
Parameters
K
Parameter
Description
value
The 64-bit signed integer value to be converted.
L M N O
Description
P
This member must be implemented if the Extended Numerics Library is present in the implementation.
Q R
Example
S
using System;
T namespace Samples { public class ConvertToDouble { public static void Main() { long l = Int64.MaxValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToDouble(l)); l = 0; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToDouble(l)); l = Int64.MinValue;
U V W X Y Z
725
Contents | Index
Convert
System
ToDouble() Method
Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToDouble(l)); } }
A
}
B
The output is
C From Int64 9223372036854775807 yields 9.22337203685478E+18 From Int64 0 yields 0 From Int64 -9223372036854775808 yields -9.22337203685478E+18
D E F
Convert.ToDouble(System.Object) Method
G H
[ILASM]
I
[C#]
.method public hidebysig static float64 ToDouble(object value) public static double ToDouble(object value)
J K
Summary
L
Converts the value of the specified System.Object to a double-precision floating point number.
M N
Parameters
O P Q
Parameter
Description
value
A System.Object that implements the System.IConvertible interface or null.
R S
Return Value
T
A double-precision floating point number equivalent to the value of value, or zero if value is null.
U V W
Description
X
The return value is the result of invoking the IConvertible.ToDouble method of the underlying type of value.
Y Z
726
Contents | Index
System
Convert ToDouble() Method
Exceptions Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
A B C D
Convert.ToDouble(System.Object, System.IFormatProvider) Method
E
[ILASM]
F
.method public hidebysig static float64 ToDouble(object value, class System.IFormatProvider provider)
G
[C#]
H
public static double ToDouble(object value, IFormatProvider provider)
I
Summary
J
Converts the value of the specified System.Object to an double-precision floating-point number using the specified culture-specific formatting information.
K L
Parameters
M
Parameter
Description
value
A System.Object that implements the System.IConvertible interface.
provider
A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
N O P Q R S
Return Value
T
A double-precision floating-point number equivalent to the value of value, or zero if value is null.
U V
Description
W
The return value is the result of invoking the IConvertible.ToDouble method of the underlying type of value. provider enables the user to specify culture-specific conversion information about the contents of value. For example, if value is a System.String that represents a number, provider could supply culture-specific information about the notation used to represent that number.
X Y Z
727
Contents | Index
Convert
System
ToDouble() Method
The base types ignore provider; however, it is honored if value is a user-defined type that implements the System.IConvertible interface. A
Exceptions
B C D
Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
E F G
Convert.ToDouble(System.SByte) Method
H
[ILASM]
.method public hidebysig static float64 ToDouble(int8 value)
I
[C#]
public static double ToDouble(sbyte value)
J K
Summary
L
Converts a System.SByte to a System.Double.
M
Parameters
N O
Parameter
Description
value
The System.SByte value to be converted.
P Q R
Description
S
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDouble(System.Int16). This member must be implemented if the Extended Numerics Library is present in the implementation.
T U V
Example
W
using System;
X namespace Samples { public class ConvertToDouble { public static void Main()
Y Z
728
Contents | Index
System
Convert ToDouble() Method
{ sbyte s = SByte.MaxValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToDouble(s)); s = 0; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToDouble(s)); s = SByte.MinValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToDouble(s));
A B C D
}
E
}
F
}
G
The output is
H From Signed Byte 127 yields 127 From Signed Byte 0 yields 0 From Signed Byte -128 yields -128
I J K
Convert.ToDouble(System.Int16) Method
L
[ILASM]
M
.method public hidebysig static float64 ToDouble(int16 value)
N
[C#]
O
public static double ToDouble(short value)
P
Summary
Q
Converts a System.Int16 to a System.Double.
R S
Parameters
T
Parameter
Description
value
The 16-bit signed integer value to be converted.
U V W
Description
X
This member must be implemented if the Extended Numerics Library is present in the implementation.
Y Z
729
Contents | Index
Convert
System
ToDouble() Method
Example using System; namespace Samples { public class ConvertToDouble { public static void Main() { short i = Int16.MinValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToDouble(i)); i = 0; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToDouble(i)); i = Int16.MaxValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToDouble(i)); } } }
A B C D E F G H I J K
The output is
L M
From Int16 -32768 yields -32768 From Int16 0 yields 0 From Int16 32767 yields 32767
N O P
Convert.ToDouble(System.String) Method
Q [ILASM]
R
.method public hidebysig static float64 ToDouble(string value) [C#]
S
public static double ToDouble(string value)
T
Summary
U
Converts a System.String to a System.Double.
V
Parameters
W X Y
Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Float | System.Globalization.NumberStyles.AllowThousands style.
Z
730
Contents | Index
System
Convert ToDouble() Method
Description This method parses value using the information in a System.Globalization.NumberFormatInfo instance initialized for the current system culture. This member must be implemented if the Extended Numerics Library is present in the implementation.
A B
Exceptions
C D
Exception
Condition
System.ArgumentNullException
value is a null reference.
System.FormatException
value cannot be converted to a numeric value.
G
The numeric value of value is greater than System.Double.MaxValue or less than System.Double.MinValue.
H
System.OverflowException
E F
I J K
Example
L
using System;
M namespace Samples { public class ConvertToDouble { public static void Main() { string s; try { s = Double.Epsilon.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToDouble(s)); s = Double.PositiveInfinity.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToDouble(s)); s = Double.NegativeInfinity.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToDouble(s)); s = Double.NaN.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToDouble(s)); s = "+0"; Console.WriteLine("From String {0} yields {1}", s, Convert.ToDouble(s));
N O P Q R S T U V W X Y Z
731
Contents | Index
Convert
System
ToDouble() Method
s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToDouble(s)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = Double.MaxValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToDouble(s)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E F G H I }
J }
K
}
L
The output is
M From String 4.94065645841247E-324 yields 4.94065645841247E-324 From String Infinity yields Infinity From String -Infinity yields -Infinity From String NaN yields NaN From String +0 yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseDouble(String s, NumberStyles style, NumberFormatInfo info) at System.Double.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToDouble(String value) at Samples.ConvertToDouble.Main() in C:\Books\BCL\Samples\System\Convert\ ToDouble\ToDouble(System.String)\Convert.cs:line 28 Exception: System.OverflowException: Value was either too large or too small for a Double. at System.Number.ParseDouble(String s, NumberStyles style, NumberFormatInfo info) at System.Double.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToDouble(String value) at Samples.ConvertToDouble.Main() in C:\Books\BCL\Samples\System\Convert\ ToDouble\ToDouble(System.String)\Convert.cs:line 38
N O P Q R S T U V W X Y Z
732
Contents | Index
System
Convert ToDouble() Method
Convert.ToDouble(System.String, System.IFormatProvider) Method [ILASM]
.method public hidebysig static float64 ToDouble(string value, class System.IFormatProvider provider)
A
[C#]
B
public static double ToDouble(string value, IFormatProvider provider)
C
Summary
D
Converts a System.String to a System.Double.
E F
Parameters
G H
Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Float | System.Globalization.NumberStyles.AllowThousands style.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
I J K L M N
Description
O
This method parses value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is parsed using the formatting information of the current system culture. This member must be implemented if the Extended Numerics Library is present in the implementation.
P Q R S
Exceptions
T U
Exception
Condition
System.ArgumentException
value is a null reference.
System.FormatException
value cannot be converted to a numeric value.
X
The numeric value of value is greater than System.Double.MaxValue or less than System.Double.MinValue.
Y
System.OverflowException
V W
Z
733
Contents | Index
Convert
System
ToDouble() Method
Example using System; using System.Globalization;
A namespace Samples { public class ConvertToDoubleSample { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; try { s = "~0"; Console.WriteLine("From String {0} yields {1}", s, Convert.ToDouble(s, c)); s = "~" + Double.Epsilon.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToDouble(s, c)); s = Double.PositiveInfinity.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToDouble(s, c)); s = Double.NegativeInfinity.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToDouble(s, c)); s = Double.NaN.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToDouble(s, c)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToDouble(s, c)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = Double.MaxValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToDouble(s, c)); } catch(FormatException e)
B C D E F G H I J K L M N O P Q R S T U V W X Y Z
734
Contents | Index
System
Convert ToDouble() Method
{ Console.WriteLine("Exception: {0}", e); } }
A
} }
B C
The output is
D From String ~0 yields 0 From String ~4.94065645841247E-324 yields 4.94065645841247E-324 From String Infinity yields Infinity From String -Infinity yields -Infinity From String NaN yields NaN Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseDouble(String s, NumberStyles style, NumberFormatInfo info) at System.Double.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToDouble(String value, IFormatProvider provider) at Samples.ConvertToDoubleSample.Main() in C:\Books\BCL\Samples\System\Convert\ ToDouble\ToDouble(System.String,System.IFormatProvider)\Convert.cs:line 32 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseDouble(String s, NumberStyles style, NumberFormatInfo info) at System.Double.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToDouble(String value, IFormatProvider provider) at Samples.ConvertToDoubleSample.Main() in C:\Books\BCL\Samples\System\Convert\ ToDouble\ToDouble(System.String,System.IFormatProvider)\Convert.cs:line 42
E F G H I J K L M N O P
Convert.ToDouble(System.DateTime) Method
Q [ILASM]
.method public hidebysig static float64 ToDouble(valuetype System.DateTime value)
R
[C#]
S
public static double ToDouble(DateTime value)
T
Summary
U
Calling this method always throws System.InvalidCastException.
V W
Parameters
X
Parameter
Description
value
A System.DateTime.
Y Z
735
Contents | Index
Convert
System
ToDouble() Method
Exceptions Exception
Condition
System.InvalidCastException
This conversion is not supported.
A B C D
Convert.ToDouble(System.UInt32) Method
E
[ILASM]
F
.method public hidebysig static float64 ToDouble(unsigned int32 value) [C#]
G
public static double ToDouble(uint value)
H I
Summary
J
Converts a System.UInt32 to a System.Double.
K
Parameters
L M N
Parameter
Description
value
The 32-bit unsigned integer value to be converted.
O P
Description
Q
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDouble(System.Int64). This member must be implemented if the Extended Numerics Library is present in the implementation.
R S T
Example
U
using System;
V namespace Samples { public class ConvertToDouble { public static void Main() { uint u = UInt32.MaxValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToDouble(u));
W X Y Z
736
Contents | Index
System
Convert ToDouble() Method
u = UInt32.MinValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToDouble(u)); }
A
} }
B C
The output is
D
From UInt32 4294967295 yields 4294967295 From UInt32 0 yields 0
E F
Convert.ToDouble(System.UInt64) Method
G
[ILASM]
H
.method public hidebysig static float64 ToDouble(unsigned int64 value)
I
[C#]
J
public static double ToDouble(ulong value)
K
Summary
L
Converts a System.UInt64 to a System.Double.
M N
Parameters
O
Parameter
Description
value
The 64-bit unsigned integer value to be converted.
P Q R
Description
S
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDouble(System.Decimal). This member must be implemented if the Extended Numerics Library is present in the implementation.
T U V
Example
W
using System;
X
namespace Samples { public class ConvertToDouble { public static void Main()
Y Z
737
Contents | Index
Convert
System
ToDouble() Method
{ ulong u = UInt64.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToDouble(u)); u = UInt64.MinValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToDouble(u));
A B C
} }
D
}
E
The output is
F From UInt64 18446744073709551615 yields 1.84467440737096E+19 From UInt64 0 yields 0
G H I
Convert.ToDouble(System.UInt16) Method
J [ILASM]
K
.method public hidebysig static float64 ToDouble(unsigned int16 value)
L
[C#]
public static double ToDouble(ushort value)
M N
Summary
O
Converts a System.UInt16 to a System.Double.
P
Parameters
Q R S
Parameter
Description
value
The 16-bit unsigned integer value to be converted.
T U
Description
V
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDouble(System.Int32). This member must be implemented if the Extended Numerics Library is present in the implementation.
W X Y Z
738
Contents | Index
System
Convert ToInt16() Method
Example using System; namespace Samples { public class ConvertToDouble { public static void Main() { ushort u = UInt16.MaxValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToDouble(u)); u = UInt16.MinValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToDouble(u)); } } }
A B C D E F G H I J
The output is
K L
From UInt16 65535 yields 65535 From UInt16 0 yields 0
M N
Convert.ToInt16(System.Boolean) Method
O
[ILASM]
P
.method public hidebysig static int16 ToInt16(bool value)
Q
[C#]
public static short ToInt16(bool value)
R
Summary
S
Converts a System.Boolean to a System.Int16.
T U
Parameters
V
Parameter
Description
value
The System.Boolean value to be converted.
W X Y Z
Return Value If value is true, returns 1; if value is false, returns 0. 739
Contents | Index
Convert
System
ToInt16() Method
Example using System; namespace Samples { public class ConvertToInt16 { public static void Main() { bool b = true; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToInt16(b)); b = false; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToInt16(b)); } } }
A B C D E F G H I J
The output is
K L
From Boolean True yields 1 From Boolean False yields 0
M N O
Convert.ToInt16(System.Byte) Method
P
[ILASM]
.method public hidebysig static int16 ToInt16(unsigned int8 value)
Q
[C#]
public static short ToInt16(byte value)
R S
Summary
T
Converts a System.Byte to a System.Int16.
U
Parameters
V W
Parameter
Description
value
The System.Byte value to be converted.
X Y Z
740
Contents | Index
System
Convert ToInt16() Method
Example using System; namespace Samples { public class ConvertToInt16 { public static void Main() { byte b = Byte.MaxValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToInt16(b)); b = Byte.MinValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToInt16(b)); } } }
A B C D E F G H I J
The output is
K L
From Byte 255 yields 255 From Byte 0 yields 0
M N
Convert.ToInt16(System.Char) Method
O [ILASM]
.method public hidebysig static int16 ToInt16(valuetype System.Char value)
P
[C#]
Q
public static short ToInt16(char value)
R
Summary
S
Converts a System.Char to a System.Int16.
T U
Parameters
V
Parameter
Description
value
The System.Char to be converted is interpreted as an unsigned value.
W X Y Z
741
Contents | Index
Convert
System
ToInt16() Method
Exceptions Exception
Condition
System.OverflowException
The numeric value of value is greater than System.Int16.MaxValue.
A B C D
Example
E
using System;
F namespace Samples { public class ConvertToInt16 { public static void Main() { try { Char c = Char.MinValue; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToInt16(c)); c = 'A'; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToInt16(c)); c = Char.MaxValue; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToInt16(c)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
G H I J K L M N O P Q R S T U V
The output is
W From Char yields 0 From Char A yields 65 Exception: System.OverflowException: Value was either too large or too small for an Int16. at System.Convert.ToInt16(Char value) at Samples.ConvertToInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt16\ToInt16(System.Char)\Convert.cs:line 18
X Y Z
742
Contents | Index
System
Convert ToInt16() Method
Convert.ToInt16(System.Decimal) Method [ILASM]
.method public hidebysig static int16 ToInt16(decimal value) [C#]
A
public static short ToInt16(decimal value)
B C
Summary
D
Converts a System.Decimal to a System.Int16.
E
Parameters
F G
Parameter
Description
value
The System.Decimal value to be converted.
H I J
Description
K
Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member must be implemented if the Extended Numerics Library is present in the implementation.
L M N
Exceptions
O
Exception
Condition
System.OverflowException
value is greater than System.Int16.MaxValue or less than System.Int16.MinValue.
P Q R S T
Example
U
using System;
V namespace Samples { public class ConvertToInt16 { public static void Main() { Decimal d = Decimal.One; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToInt16(d));
W X Y Z
743
Contents | Index
Convert
System
ToInt16() Method
d = Decimal.Zero; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToInt16(d)); d = 25.5m; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToInt16(d)); d = -25.5m; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToInt16(d)); try { d = Decimal.MaxValue; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToInt16(d)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E F G H I J }
K
} }
L
The output is
M N
From Decimal 1 yields 1 From Decimal 0 yields 0 From Decimal 25.5 yields 26 From Decimal -25.5 yields -26 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Decimal.ToInt32(Decimal d) at System.Decimal.ToInt16(Decimal value) at System.Convert.ToInt16(Decimal value) at Samples.ConvertToInt16.Main() in C:\Books\BCL\Samples\System\Convert\ToInt16\ ToInt16(System.Decimal)\Convert.cs:line 24
O P Q R S T U V
Convert.ToInt16(System.Double) Method
W [ILASM]
X
.method public hidebysig static int16 ToInt16(float64 value) [C#]
Y
public static short ToInt16(double value)
Z
Summary Converts a System.Double to a System.Int16. 744
Contents | Index
System
Convert ToInt16() Method
Parameters Parameter
Description
value
The System.Double value to be converted.
A B C
Description
D
Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member must be implemented if the Extended Numerics Library is present in the implementation.
E F G H
Exceptions
I J
Exception
Condition
System.OverflowException
value is greater than System.Int16.MaxValue or less than System.Int16.MinValue.
K L M
Example
N
using System;
O
namespace Samples { public class ConvertToInt16 { public static void Main() { try { double d = Double.Epsilon; Console.WriteLine("From Double {0} yields d, Convert.ToInt16(d)); d = 0.0; Console.WriteLine("From Double {0} yields d, Convert.ToInt16(d)); d = 5.5; Console.WriteLine("From Double {0} yields d, Convert.ToInt16(d)); d = -5.5; Console.WriteLine("From Double {0} yields
P Q R S T U {1}",
V W
{1}",
X Y
{1}",
Z {1}",
745
Contents | Index
Convert
System
ToInt16() Method
d, Convert.ToInt16(d)); d = Double.PositiveInfinity; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToInt16(d));
A
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
B C D
} }
E }
F
The output is
G H
From Double 4.94065645841247E-324 yields 0 From Double 0 yields 0 From Double 5.5 yields 6 From Double -5.5 yields -6 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Convert.ToInt32(Double value) at System.Convert.ToInt16(Double value) at Samples.ConvertToInt16.Main() in C:\Books\BCL\Samples\System\Convert\ToInt16\ ToInt16(System.Double)\Convert.cs:line 24
I J K L M N O P
Convert.ToInt16(System.Single) Method
Q
[ILASM]
.method public hidebysig static int16 ToInt16(float32 value)
R
[C#]
public static short ToInt16(float value)
S T
Summary
U
Converts a System.Single to a System.Int16.
V
Parameters
W X
Parameter
Description
value
The System.Single value to be converted.
Y Z
746
Contents | Index
System
Convert ToInt16() Method
Description Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member must be implemented if the Extended Numerics Library is present in the implementation.
A B
Exceptions
C D
Exception
Condition
System.OverflowException
value is greater than System.Int16.MaxValue or less than System.Int16.MinValue.
E F G
Example
H
using System; namespace Samples { public class ConvertToInt16 { public static void Main() { try { float f = Int16.MaxValue; Console.WriteLine("From Single {0} yields f, Convert.ToInt16(f)); f = 25.5f; Console.WriteLine("From Single {0} yields f, Convert.ToInt16(f)); f = 0.0f; Console.WriteLine("From Single {0} yields f, Convert.ToInt16(f)); f = -25.5f; Console.WriteLine("From Single {0} yields f, Convert.ToInt16(f)); f = Single.MaxValue; Console.WriteLine("From Single {0} yields f, Convert.ToInt16(f)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
I J K L M N O
{1}",
P Q
{1}",
R {1}",
S T
{1}",
U V
{1}",
W X Y Z
747
Contents | Index
Convert
System
ToInt16() Method
The output is From Single 32767 yields 32767 From Single 25.5 yields 26 From Single 0 yields 0 From Single -25.5 yields -26 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Convert.ToInt32(Double value) at System.Convert.ToInt16(Single value) at Samples.ConvertToInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt16\ToInt16(System.Single)\Convert.cs:line 24
A B C D E F G H
Convert.ToInt16(System.Int32) Method
I
[ILASM]
.method public hidebysig static int16 ToInt16(int32 value)
J
[C#]
public static short ToInt16(int value)
K L
Summary
M
Converts a System.Int32 to a System.Int16.
N
Parameters
O P
Parameter
Description
value
The 32-bit signed integer value to be converted.
Q R S
Exceptions
T U
Exception
Condition
System.OverflowException
value is greater than System.Int16.MaxValue or less than System.Int16.MinValue.
V W X Y Z
748
Contents | Index
System
Convert ToInt16() Method
Example using System; namespace Samples { public class ConvertToInt16 { public static void Main() { try { int i = Int16.MaxValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToInt16(i)); i = 0; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToInt16(i)); i = Int16.MinValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToInt16(i)); i = Int32.MaxValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToInt16(i)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P Q R
The output is
S
From Int32 32767 yields 32767 From Int32 0 yields 0 From Int32 -32768 yields -32768 Exception: System.OverflowException: Value was either too large or too small for an Int16. at System.Convert.ToInt16(Int32 value) at Samples.ConvertToInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt16\ToInt16(System.Int32)\Convert.cs:line 21
T U V W X Y Z
749
Contents | Index
Convert
System
ToInt16() Method
Convert.ToInt16(System.Int64) Method [ILASM]
.method public hidebysig static int16 ToInt16(int64 value)
A
[C#]
public static short ToInt16(long value)
B C
Summary
D
Converts a System.Int64 to a System.Int16.
E
Parameters
F G
Parameter
Description
value
The 64-bit signed integer value to be converted.
H I J
Exceptions
K L
Exception
Condition
System.OverflowException
value is greater than System.Int16.MaxValue or less than System.Int16.MinValue.
M N O P
Example
Q
using System;
R namespace Samples { public class ConvertToInt16 { public static void Main() { try { long l = Int16.MaxValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToInt16(l)); l = 0; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToInt16(l)); l = Int16.MinValue;
S T U V W X Y Z
750
Contents | Index
System
Convert ToInt16() Method
Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToInt16(l)); l = Int64.MaxValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToInt16(l));
A
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
B C D
}
E
}
F
}
G
The output is
H From Int64 32767 yields 32767 From Int64 0 yields 0 From Int64 -32768 yields -32768 Exception: System.OverflowException: Value was either too large or too small for an Int16. at System.Convert.ToInt16(Int64 value) at Samples.ConvertToInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt16\ToInt16(System.Int64)\Convert.cs:line 21
I J K L M N O
Convert.ToInt16(System.Object) Method
P
[ILASM]
.method public hidebysig static int16 ToInt16(object value)
Q
[C#]
R
public static short ToInt16(object value)
S
Summary
T
Converts the value of the specified System.Object to a 16-bit signed integer.
U V
Parameters
W
Parameter
Description
value
A System.Object that implements the System.IConvertible interface or null.
X Y Z
751
Contents | Index
Convert
System
ToInt16() Method
Return Value A 16-bit signed integer equivalent to the value of value, or zero if value is null. A
Description
B
The return value is the result of invoking the IConvertible.ToInt16 method of the underlying type of value.
C D
Exceptions
E F G
Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
H I J
Convert.ToInt16(System.Object, System.IFormatProvider) Method
K
[ILASM]
L
.method public hidebysig static int16 ToInt16(object value, class System.IFormatProvider provider)
M
[C#]
public static short ToInt16(object value, IFormatProvider provider)
N O
Summary
P
Converts the value of the specified System.Object to a 16-bit signed integer using the specified culture-specific formatting information.
Q R
Parameters
S T U
Parameter
Description
value
An System.Object that implements the System.IConvertible interface.
provider
An System.IFormatProvider interface implementation that supplies culture-specific formatting information.
V W X Y
Return Value
Z
A 16-bit signed integer equivalent to the value of value, or zero if value is null.
752
Contents | Index
System
Convert ToInt16() Method
Description provider enables the user to specify culture-specific conversion information about the contents of value. For example, if value is a System.String that represents a number, provider could supply culture-specific information about the notation used to represent that number. The base types ignore provider; however, it is honored if value is a user-defined type that implements the System.IConvertible interface.
A B C D
Exceptions
E
Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
F G H I
Convert.ToInt16(System.SByte) Method
J
[ILASM]
K
.method public hidebysig static int16 ToInt16(int8 value)
L
[C#]
public static short ToInt16(sbyte value)
M N
Summary
O
Converts a System.SByte to a System.Int16.
P
Parameters
Q
Parameter
Description
value
The System.SByte value to be converted.
R S T U
Description
V
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt16(System.Int16).
W X Y Z
753
Contents | Index
Convert
System
ToInt16() Method
Example using System; namespace Samples { public class ConvertToInt16 { public static void Main() { sbyte s = SByte.MaxValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToInt16(s)); s = 0; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToInt16(s)); s = SByte.MinValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToInt16(s)); } } }
A B C D E F G H I J K
The output is
L M
From Signed Byte 127 yields 127 From Signed Byte 0 yields 0 From Signed Byte -128 yields -128
N O P
Convert.ToInt16(System.Int16) Method
Q [ILASM]
R
.method public hidebysig static int16 ToInt16(int16 value)
S
[C#]
public static short ToInt16(short value)
T U
Summary
V
Converts a System.Int16 to a System.Int16.
W
Parameters
X Y Z
Parameter
Description
value
The 16-bit signed integer value to be converted.
754
Contents | Index
System
Convert ToInt16() Method
Return Value value is returned unchanged.
Description
A
[Note: This method is provided for completeness.]
B C
Example
D
using System;
E namespace Samples { public class ConvertToInt16 { public static void Main() { short i = Int16.MaxValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToInt16(i)); i = Int16.MinValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToInt16(i)); i = 0; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToInt16(i)); } } }
F G H I J K L M N O P Q
The output is
R From Int16 32767 yields 32767 From Int16 -32768 yields -32768 From Int16 0 yields 0
S T U
Convert.ToInt16(System.String) Method
V
[ILASM]
W
.method public hidebysig static int16 ToInt16(string value)
X
[C#]
Y
public static short ToInt16(string value)
Z
Summary Converts a System.String to a System.Int16. 755
Contents | Index
Convert
System
ToInt16() Method
Parameters Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Integer style.
A B C D
Description
E
This method parses value using the information in a System.Globalization.NumberFormatInfo instance initialized for the current system culture.
F G
Exceptions
H I
Exception
Condition
System.ArgumentNullException
value is a null reference.
System.FormatException
value cannot be converted to a numeric value.
System.OverflowException
The numeric value of value is greater than System.Int16.MaxValue or less than System.Int16.MinValue.
J K L M N O P
Example
Q
using System;
R
namespace Samples { public class ConvertToInt16 { public static void Main() { string s; try { s = Int16.MaxValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt16(s)); s = " +0 "; Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt16(s)); s = Int16.MinValue.ToString();
S T U V W X Y Z
756
Contents | Index
System
Convert ToInt16() Method
Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt16(s)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt16(s));
A
} catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = (Int16.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt16(s)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
B C D E F G H I J
}
K
}
L
}
M
The output is
N
From String 32767 yields 32767 From String +0 yields 0 From String -32768 yields -32768 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int16.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToInt16(String value) at Samples.ConvertToInt16.Main() in C:\Books\BCL\Samples\System\Convert\ToInt16\ ToInt16(System.String)\Convert.cs:line 22 Exception: System.OverflowException: Value was either too large or too small for an Int16. at System.Int16.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToInt16(String value) at Samples.ConvertToInt16.Main() in C:\Books\BCL\Samples\System\Convert\ToInt16\ ToInt16(System.String)\Convert.cs:line 32
O P Q R S T U V W X
Convert.ToInt16(System.String, System.Int32) Method
Y
[ILASM]
Z
.method public hidebysig static int16 ToInt16(string value, int32 fromBase) [C#]
public static short ToInt16(string value, int fromBase)
757
Contents | Index
Convert
System
ToInt16() Method
Summary Converts the System.String representation of a number in a specified base to an equivalent 16-bit signed integer. A
Parameters
B C
Parameter
Description
E
value
A System.String containing a number.
F
fromBase
The base of the number in value, which must be 2, 8, 10, or 16.
D
G H
Return Value
I
A 16-bit signed integer equivalent to the number in value.
J
Description
K
If fromBase is 16, you can prefix the number specified by the value parameter with “0x” or “0X”.
L M
Exceptions
N O
Exception
Condition
P
System.ArgumentException
fromBase is not 2, 8, 10, or 16.
System.OverflowException
value is less than System.Int16.MinValue or greater than System.Int16.MaxValue.
Q R S T
Convert.ToInt16(System.String, System.IFormatProvider) Method
U
[ILASM]
V
.method public hidebysig static int16 ToInt16(string value, class System.IFormatProvider provider)
W
[C#]
X
public static short ToInt16(string value, IFormatProvider provider)
Y
Summary
Z
Converts a System.String to a System.Int16.
758
Contents | Index
System
Convert ToInt16() Method
Parameters Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Integer style.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
A B C D E
Description
F
This method parses value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is parsed using the formatting information of the current system culture.
G H I J
Exceptions
K L
Exception
Condition
System.ArgumentNullException
value is a null reference.
N
System.FormatException
value cannot be converted to a numeric value.
O P
System.OverflowException
The numeric value of value is greater than System.Int16.MaxValue or less than System.Int16.MinValue.
M
Q R S
Example
T
using System; using System.Globalization;
U V
namespace Samples { public class ConvertToInt16 { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat;
W X Y Z
759
Contents | Index
Convert
System
ToInt16() Method
n.PositiveSign = "~"; try { s = "~0"; Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt16(s, c)); s = (Int16.MaxValue).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt16(s, c)); s = (Int16.MinValue).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt16(s, c)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt16(s, c)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = (Int16.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt16(s, c)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E F G H I J K L M N O P Q
} }
R
}
S
The output is
T
From String ~0 yields 0 From String 32767 yields 32767 From String -32768 yields -32768 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int16.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToInt16(String value, IFormatProvider provider) at Samples.ConvertToInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt16\ToInt16(System.String,System.IFormatProvider)\Convert.cs:line 26 Exception: System.OverflowException: Value was either too large or too small for an Int16. at System.Int16.Parse(String s, NumberStyles style, IFormatProvider provider)
U V W X Y Z
760
Contents | Index
System
Convert ToInt16() Method
at System.Convert.ToInt16(String value, IFormatProvider provider) at Samples.ConvertToInt16.Main() in C:\Books\BCL\Samples\System\Convert\ToInt16\ ToInt16(System.String,System.IFormatProvider)\Convert.cs:line 36
A B
Convert.ToInt16(System.DateTime) Method
C
[ILASM]
D
.method public hidebysig static int16 ToInt16(valuetype System.DateTime value) [C#]
E
public static short ToInt16(DateTime value)
F
Summary
G
Calling this method always throws System.InvalidCastException.
H I
Parameters
J
Parameter
Description
value
A System.DateTime.
K L M N
Exceptions
O
Exception
Condition
System.InvalidCastException
This conversion is not supported.
P Q R S
Convert.ToInt16(System.UInt32) Method
T
[ILASM]
U
.method public hidebysig static int16 ToInt16(unsigned int32 value)
V
[C#]
public static short ToInt16(uint value)
W
Summary
X
Converts a System.UInt32 to a System.Int16.
Y Z
761
Contents | Index
Convert
System
ToInt16() Method
Parameters Parameter
Description
value
The 32-bit unsigned integer value to be converted.
A B C D
Description
E
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt16(System.Int64).
F
Exceptions
G H
Exception
Condition
System.OverflowException
value is greater than System.Int16.MaxValue.
I J K
Example
L
using System;
M
namespace Samples { public class ConvertToInt16 { public static void Main() { try { uint u = UInt32.MinValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToInt16(u)); u = UInt32.MaxValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToInt16(u)); } catch(OverflowException e) { Console.WriteLine("Exception {0}", e); } } } }
N O P Q R S T U V W X Y Z
762
Contents | Index
System
Convert ToInt16() Method
The output is From UInt32 0 yields 0 Exception System.OverflowException: Value was either too large or too small for an Int16. at System.Convert.ToInt16(UInt32 value) at Samples.ConvertToInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt16\ToInt16(System.UInt32)\Convert.cs:line 15
A B C D E
Convert.ToInt16(System.UInt64) Method
F [ILASM]
.method public hidebysig static int16 ToInt16(unsigned int64 value)
G
[C#]
H
public static short ToInt16(ulong value)
I
Summary
J
Converts a System.UInt64 to a System.Int16.
K L
Parameters
M
Parameter
Description
N
value
The 64-bit unsigned integer value to be converted.
O P
Description
Q
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt16(System.Decimal).
R S T
Exceptions
U
Exception
Condition
V
System.OverflowException
value is greater than System.Int16.MaxValue.
W X Y Z
763
Contents | Index
Convert
System
ToInt16() Method
Example using System; namespace Samples { public class ConvertToInt16 { public static void Main() { try { ulong u = UInt64.MinValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToInt16(u)); u = (ulong) Int16.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToInt16(u)); u = UInt64.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToInt16(u)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P
The output is
Q
From UInt64 0 yields 0 From UInt64 32767 yields 32767 Exception: System.OverflowException: Value was either too large or too small for an Int16. at System.Convert.ToInt16(UInt64 value) at Samples.ConvertToInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt16\ToInt16(System.UInt64)\Convert.cs:line 18
R S T U V W
Convert.ToInt16(System.UInt16) Method
X
[ILASM]
Y
.method public hidebysig static int16 ToInt16(unsigned int16 value) [C#]
Z
public static short ToInt16(ushort value)
764
Contents | Index
System
Convert ToInt16() Method
Summary Converts a System.UInt16 to a System.Int16. A
Parameters
B
Parameter
Description
value
The 16-bit unsigned integer value to be converted.
C D E
Description
F
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt16(System.Int32).
G H
Exceptions
I
Exception
Condition
System.OverflowException
value is greater than System.Int16.MaxValue.
J K L M
Example
N
using System;
O namespace Samples { public class ConvertToInt16 { public static void Main() { try { ushort u = UInt16.MinValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToInt16(u)); u = UInt16.MaxValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToInt16(u)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
P Q R S T U V W X Y Z
765
Contents | Index
Convert
System
ToInt32() Method
The output is From UInt16 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for an Int16. at System.Convert.ToInt16(UInt16 value) at Samples.ConvertToInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt16\ToInt16(System.UInt16)\Convert.cs:line 15
A B C D E
Convert.ToInt32(System.Boolean) Method
F [ILASM]
G
.method public hidebysig static int32 ToInt32(bool value) [C#]
H
public static int ToInt32(bool value)
I
Summary
J
Converts a System.Boolean to a System.Int32.
K L
Parameters
M N O
Parameter
Description
value
The System.Boolean value to be converted.
P Q
Return Value
R
If value is true, returns 1; if value is false, returns 0.
S
Example
T
using System;
U namespace Samples { public class ConvertToInt32 { public static void Main() { bool b = true; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToInt32(b)); b = false; Console.WriteLine("From Boolean {0} yields {1}",
V W X Y Z
766
Contents | Index
System
Convert ToInt32() Method
b, Convert.ToInt32(b)); } } }
A
The output is
B C
From Boolean True yields 1 From Boolean False yields 0
D E
Convert.ToInt32(System.Byte) Method
F
[ILASM]
.method public hidebysig static int32 ToInt32(unsigned int8 value)
G
[C#]
H
public static int ToInt32(byte value)
I
Summary
J
Converts a System.Byte to a System.Int32.
K L
Parameters
M
Parameter
Description
value
The System.Byte value to be converted.
N O P Q
Example
R
using System;
S namespace Samples { public class ConvertToInt32 { public static void Main() { byte b = Byte.MaxValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToInt32(b)); b = Byte.MinValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToInt32(b)); } } }
T U V W X Y Z
767
Contents | Index
Convert
System
ToInt32() Method
The output is From Byte 255 yields 255 From Byte 0 yields 0
A B C
Convert.ToInt32(System.Char) Method
D
[ILASM]
.method public hidebysig static int32 ToInt32(valuetype System.Char value)
E
[C#]
public static int ToInt32(char value)
F G
Summary
H
Converts a System.Char to a System.Int32.
I
Parameters
J K
Parameter
Description
value
The System.Char to be converted interpreted as an unsigned value.
L M N O
Example
P
using System;
Q
namespace Samples { public class ConvertToInt32 { public static void Main() { Char c = 'A'; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToInt32(c)); c = 'a'; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToInt32(c)); c = Char.MinValue; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToInt32(c)); } } }
R S T U V W X Y Z
768
Contents | Index
System
Convert ToInt32() Method
The output is From Char A yields 65 From Char a yields 97 From Char yields 0
A B C
Convert.ToInt32(System.Decimal) Method
D
[ILASM]
E
.method public hidebysig static int32 ToInt32(decimal value)
F
[C#]
public static int ToInt32(decimal value)
G
Summary
H
Converts a System.Decimal to a System.Int32.
I J
Parameters
K L
Parameter
Description
value
The System.Decimal value to be converted.
M N O
Description
P
Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member must be implemented if the Extended Numerics Library is present in the implementation.
Q R S
Exceptions
T
Exception
Condition
System.OverflowException
value is greater than System.Int32.MaxValue or less than System.Int32.MinValue.
U V W X Y Z
769
Contents | Index
Convert
System
ToInt32() Method
Example using System; namespace Samples { public class ConvertToInt32 { public static void Main() { try { Decimal d = Decimal.One; Console.WriteLine("From Decimal {0} yields d, Convert.ToInt32(d)); d = Decimal.Zero; Console.WriteLine("From Decimal {0} yields d, Convert.ToInt32(d)); d = 25.5m; Console.WriteLine("From Decimal {0} yields d, Convert.ToInt32(d)); d = -25.5m; Console.WriteLine("From Decimal {0} yields d, Convert.ToInt32(d)); d = Decimal.MaxValue; Console.WriteLine("From Decimal {0} yields d, Convert.ToInt32(d)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P Q R S T
{1}",
{1}",
{1}",
{1}",
{1}",
The output is
U From Decimal 1 yields 1 From Decimal 0 yields 0 From Decimal 25.5 yields 26 From Decimal -25.5 yields -26 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Decimal.ToInt32(Decimal d) at System.Convert.ToInt32(Decimal value) at Samples.ConvertToInt32.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt32\ToInt32(System.Decimal)\Convert.cs:line 24
V W X Y Z
770
Contents | Index
System
Convert ToInt32() Method
Convert.ToInt32(System.Double) Method [ILASM]
.method public hidebysig static int32 ToInt32(float64 value) [C#]
A
public static int ToInt32(double value)
B C
Summary
D
Converts a System.Double to a System.Int32.
E
Parameters
F G
Parameter
Description
value
The System.Double value to be converted.
H I J
Description
K
Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member must be implemented if the Extended Numerics Library is present in the implementation.
L M N
Exceptions
O
Exception
Condition
System.OverflowException
value is greater than System.Int32.MaxValue or less than System.Int32.MinValue.
P Q R S T
Example
U
using System;
V
namespace Samples { public class ConvertToInt32 { public static void Main() { try { double d = Double.Epsilon;
W X Y Z
771
Contents | Index
Convert
System
ToInt32() Method
Console.WriteLine("From Double {0} yields d, Convert.ToInt32(d)); d = 0.0; Console.WriteLine("From Double {0} yields d, Convert.ToInt32(d)); d = 5.5; Console.WriteLine("From Double {0} yields d, Convert.ToInt32(d)); d = -5.5; Console.WriteLine("From Double {0} yields d, Convert.ToInt32(d)); d = Double.PositiveInfinity; Console.WriteLine("From Double {0} yields d, Convert.ToInt32(d));
A B C D E F G
{1}",
{1}",
{1}",
{1}",
{1}",
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
H I }
J }
K
}
L
The output is
M From Double 4.94065645841247E-324 yields 0 From Double 0 yields 0 From Double 5.5 yields 6 From Double -5.5 yields -6 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Convert.ToInt32(Double value) at Samples.ConvertToInt32.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt32\ToInt32(System.Double)\Convert.cs:line 24
N O P Q R S T
Convert.ToInt32(System.Single) Method
U
[ILASM]
V
.method public hidebysig static int32 ToInt32(float32 value)
W
[C#]
public static int ToInt32(float value)
X Y
Summary
Z
Converts a System.Single to a System.Int32.
772
Contents | Index
System
Convert ToInt32() Method
Parameters Parameter
Description
value
The System.Single value to be converted.
A B C
Description
D
Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member must be implemented if the Extended Numerics Library is present in the implementation.
E F G
Exceptions
H I
Exception
Condition
System.OverflowException
value is greater than System.Int32.MaxValue or less than System.Int32.MinValue.
J K L M
Example
N
using System;
O namespace Samples { public class ConvertToInt32 { public static void Main() { float f; try { f = 0f; Console.WriteLine("From Single {0} yields f, Convert.ToInt32(f)); f = 25.5f; Console.WriteLine("From Single {0} yields f, Convert.ToInt32(f)); f = -25.5f; Console.WriteLine("From Single {0} yields f, Convert.ToInt32(f)); f = (float) Int32.MaxValue; Console.WriteLine("From Single {0} yields f, Convert.ToInt32(f)); }
P Q R S T U
{1}",
V W
{1}",
X {1}",
Y Z
{1}",
773
Contents | Index
Convert
System
ToInt32() Method
catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } try { f = Single.MaxValue; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToInt32(f)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E F G
} }
H
}
I
The output is
J From Single 0 yields 0 From Single 25.5 yields 26 From Single -25.5 yields -26 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Convert.ToInt32(Double value) at System.Convert.ToInt32(Single value) at Samples.ConvertToInt32.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt32\ToInt32(System.Single)\Convert.cs:line 22 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Convert.ToInt32(Double value) at System.Convert.ToInt32(Single value) at Samples.ConvertToInt32.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt32\ToInt32(System.Single)\Convert.cs:line 32
K L M N O P Q R S T U
Convert.ToInt32(System.Int32) Method
V
[ILASM]
W
.method public hidebysig static int32 ToInt32(int32 value) [C#]
X
public static int ToInt32(int value)
Y
Summary
Z
Converts a System.Int32 to a System.Int32.
774
Contents | Index
System
Convert ToInt32() Method
Parameters Parameter
Description
value
The 32-bit signed integer value to be converted.
A B C
Return Value
D
value is returned unchanged.
E F
Description
G
[Note: This method is provided for completeness.]
H
Example
I
using System;
J
namespace Samples { public class ConvertToInt32 { public static void Main() { int i = Int32.MaxValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToInt32(i)); i = Int32.MinValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToInt32(i)); } } }
K L M N O P Q R S T
The output is
U
From Int32 2147483647 yields 2147483647 From Int32 -2147483648 yields -2147483648
V W X
Convert.ToInt32(System.Int64) Method
Y
[ILASM]
Z
.method public hidebysig static int32 ToInt32(int64 value) [C#]
public static int ToInt32(long value)
775
Contents | Index
Convert
System
ToInt32() Method
Summary Converts a System.Int64 to a System.Int32. A
Parameters
B C
Parameter
Description
D
value
The 64-bit signed integer value to be converted.
E
Exceptions
F G
Exception
Condition
System.OverflowException
value is greater than System.Int32.MaxValue or less than System.Int32.MinValue.
H I J K
Example
L
using System;
M
namespace Samples { public class ConvertToInt32 { public static void Main() { try { long l = Int32.MaxValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToInt32(l)); l = Int32.MinValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToInt32(l)); l = Int64.MaxValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToInt32(l)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
N O P Q R S T U V W X Y Z
776
Contents | Index
System
Convert ToInt32() Method
The output is From Int64 2147483647 yields 2147483647 From Int64 -2147483648 yields -2147483648 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Convert.ToInt32(Int64 value) at Samples.ConvertToInt32.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt32\ToInt32(System.Int64)\Convert.cs:line 18
A B C D E
Convert.ToInt32(System.Object) Method
F
[ILASM]
G
.method public hidebysig static int32 ToInt32(object value)
H
[C#]
I
public static int ToInt32(object value)
J
Summary
K
Converts the value of the specified System.Object to a 32-bit signed integer.
L
Parameters
M N
Parameter
Description
value
A System.Object that implements the System.IConvertible interface or null.
O P Q R
Return Value
S
A 32-bit signed integer equivalent to the value of value, or zero if value is null.
T
Description
U
The return value is the result of invoking the IConvertible.ToInt32 method of the underlying type of value.
V W X
Exceptions
Y
Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
Z
777
Contents | Index
Convert
System
ToInt32() Method
Convert.ToInt32(System.Object, System.IFormatProvider) Method [ILASM]
A
.method public hidebysig static int32 ToInt32(object value, class System.IFormatProvider provider)
B
[C#]
public static int ToInt32(object value, IFormatProvider provider)
C D
Summary
E
Converts the value of the specified System.Object to a 32-bit signed integer using the specified culture-specific formatting information.
F G
Parameters
H I J
Parameter
Description
value
A System.Object that implements the System.IConvertible interface.
provider
A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
K L M N
Return Value
O
A 32-bit signed integer equivalent to the value of value, or zero if value is null.
P
Description
Q
The return value is the result of invoking the IConvertible.ToInt32 method of the underlying type of value. provider enables the user to specify culture-specific conversion information about the contents of value. For example, if value is a System.String that represents a number, provider could supply culture-specific information about the notation used to represent that number. The base types ignore provider; however, it is honored if value is a user-defined type that implements the System.IConvertible interface.
R S T U V W
Exceptions
X Y Z
Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
778
Contents | Index
System
Convert ToInt32() Method
Convert.ToInt32(System.SByte) Method [ILASM]
.method public hidebysig static int32 ToInt32(int8 value) [C#]
A
public static int ToInt32(sbyte value)
B C
Summary
D
Converts a System.SByte to a System.Int32.
E
Parameters
F
Parameter
Description
value
The System.SByte value to be converted.
G H I J
Description
K
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt32(System.Int16).
L M
Example
N
using System;
O
namespace Samples { public class ConvertToInt32 { public static void Main() { sbyte s = SByte.MaxValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToInt32(s)); s = SByte.MinValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToInt32(s)); } } }
P Q R S T U V W X Y
The output is
Z From Signed Byte 127 yields 127 From Signed Byte -128 yields -128
779
Contents | Index
Convert
System
ToInt32() Method
Convert.ToInt32(System.Int16) Method [ILASM]
.method public hidebysig static int32 ToInt32(int16 value)
A
[C#]
public static int ToInt32(short value)
B C
Summary
D
Converts a System.Int16 to a System.Int32.
E
Parameters
F G
Parameter
Description
value
The 16-bit signed integer value to be converted.
H I J K
Example
L
using System;
M
namespace Samples { public class ConvertToInt32 { public static void Main() { short i = Int16.MaxValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToInt32(i)); i = Int16.MinValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToInt32(i)); } } }
N O P Q R S T U V
The output is
W X
From Int16 32767 yields 32767 From Int16 -32768 yields -32768
Y Z
780
Contents | Index
System
Convert ToInt32() Method
Convert.ToInt32(System.String) Method [ILASM]
.method public hidebysig static int32 ToInt32(string value) [C#]
A
public static int ToInt32(string value)
B C
Summary
D
Converts a System.String to a System.Int32.
E
Parameters
F G
Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Integer style.
H I J K
Description
L
This method parses value using the information in a System.Globalization.NumberFormatInfo instance initialized for the current system culture.
M N
Exceptions
O P
Exception
Condition
System.ArgumentNullException
value is a null reference.
System.FormatException
value cannot be converted to a numeric value.
S
The numeric value of value is greater than System.Int32.MaxValue or less than System.Int32.MinValue.
T
System.OverflowException
Q R
U V W X Y Z
781
Contents | Index
Convert
System
ToInt32() Method
Example using System; namespace Samples { public class ConvertToInt32 { public static void Main() { string s; try { s = Int32.MaxValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt32(s)); s = "0"; Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt32(s)); s = Int32.MinValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt32(s)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt32(s)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = ((Int64)Int32.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt32(s)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P Q R S T U V W X Y
The output is
Z From String 2147483647 yields 2147483647 From String 0 yields 0 From String -2147483648 yields -2147483648
782
Contents | Index
System
Convert ToInt32() Method
Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt32(String value) at Samples.ConvertToInt32.Main() in C:\Books\BCL\Samples\System\Convert\ToInt32\ ToInt32(System.String)\Convert.cs:line 22 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt32(String value) at Samples.ConvertToInt32.Main() in C:\Books\BCL\Samples\System\Convert\ToInt32\ ToInt32(System.String)\Convert.cs:line 32
A B C D E F
Convert.ToInt32(System.String, System.Int32) Method
G
[ILASM]
H
.method public hidebysig static int32 ToInt32(string value, int32 fromBase)
I
[C#]
J
public static int ToInt32(string value, int fromBase)
K
Summary
L
Converts the System.String representation of a number in a specified base to an equivalent 32-bit signed integer.
M N
Parameters
O
Parameter
Description
value
A System.String containing a number.
fromBase
The base of the number in value, which must be 2, 8, 10, or 16.
P Q R S T
Return Value
U
A 32-bit signed integer equivalent to the number in value.
V W
Description
X
If fromBase is 16, you can prefix the number specified by the value parameter with “0x” or “0X”.
Y Z
783
Contents | Index
Convert
System
ToInt32() Method
Exceptions Exception
Condition
System.ArgumentException
fromBase is not 2, 8, 10, or 16.
A B C D
Convert.ToInt32(System.String, System.IFormatProvider) Method
E [ILASM]
F
.method public hidebysig static int32 ToInt32(string value, class System.IFormatProvider provider)
G
[C#]
public static int ToInt32(string value, IFormatProvider provider)
H I
Summary
J
Converts a System.String to a System.Int32.
K
Parameters
L M
Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Integer style.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
N O P Q R S
Description
T
This method parses value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is parsed using the formatting information of the current system culture.
U V W X Y Z
784
Contents | Index
System
Convert ToInt32() Method
Exceptions Exception
Condition
System.ArgumentNullException
value is a null reference.
System.FormatException
value cannot be converted to a numeric value.
C
The numeric value of value is greater than System.Int32.MaxValue or less than System.Int32.MinValue.
D
System.OverflowException
A B
E F G
Example
H
using System; using System.Globalization;
I J
namespace Samples { public class ConvertToInt32 { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; try { s = "~0"; Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt32(s, c)); s = Int32.MaxValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt32(s, c)); s = Int32.MinValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt32(s, c)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt32(s, c)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try {
K L M N O P Q R S T U V W X Y Z
785
Contents | Index
Convert
System
ToInt32() Method
s = ((Int64)Int32.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt32(s, c)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C }
D
} }
E
The output is
F G
From String ~0 yields 0 From String 2147483647 yields 2147483647 From String -2147483648 yields -2147483648 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt32(String value, IFormatProvider provider) at Samples.ConvertToInt32.Main() in C:\Books\BCL\Samples\System\Convert\ToInt32\ ToInt32(System.String,System.IFormatProvider)\Convert.cs:line 26 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt32(String value, IFormatProvider provider) at Samples.ConvertToInt32.Main() in C:\Books\BCL\Samples\System\Convert\ToInt32\ ToInt32(System.String,System.IFormatProvider)\Convert.cs:line 36
H I J K L M N O P Q
Convert.ToInt32(System.DateTime) Method
R
[ILASM]
.method public hidebysig static int32 ToInt32(valuetype System.DateTime value)
S
[C#]
T
public static int ToInt32(DateTime value)
U
Summary
V
Calling this method always throws System.InvalidCastException.
W X
Parameters
Y Z
Parameter
Description
value
A System.DateTime.
786
Contents | Index
System
Convert ToInt32() Method
Exceptions Exception
Condition
System.InvalidCastException
This conversion is not supported.
A B C D
Convert.ToInt32(System.UInt32) Method
E
[ILASM]
F
.method public hidebysig static int32 ToInt32(unsigned int32 value) [C#]
G
public static int ToInt32(uint value)
H
Summary
I
Converts a System.UInt32 to a System.Int32.
J K
Parameters
L
Parameter
Description
value
The 32-bit unsigned integer value to be converted.
M N O P
Description
Q
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt32(System.Int64).
R S
Exceptions
T
Exception
Condition
System.OverflowException
value is greater than System.Int32.MaxValue.
U V W X Y Z
787
Contents | Index
Convert
System
ToInt32() Method
Example using System; namespace Samples { public class ConvertToInt32 { public static void Main() { try { uint u = UInt32.MinValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToInt32(u)); u = UInt32.MaxValue / 2; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToInt32(u)); u = UInt32.MaxValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToInt32(u)); } catch(OverflowException e) { Console.WriteLine("Exception {0}", e); } } } }
A B C D E F G H I J K L M N O P
The output is
Q R
From UInt32 0 yields 0 From UInt32 2147483647 yields 2147483647 Exception System.OverflowException: Value was either too large or too small for an Int32. at System.Convert.ToInt32(UInt32 value) at Samples.ConvertToInt32.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt32\ToInt32(System.UInt32)\Convert.cs:line 18
S T U V W X
Convert.ToInt32(System.UInt64) Method
Y
[ILASM]
.method public hidebysig static int32 ToInt32(unsigned int64 value)
Z
[C#]
public static int ToInt32(ulong value)
788
Contents | Index
System
Convert ToInt32() Method
Summary Converts a System.UInt64 to a System.Int32. A
Parameters
B
Parameter
Description
C
value
The 64-bit unsigned integer value to be converted.
D E F
Description
G
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt32(System.Decimal).
H I
Exceptions
J
Exception
Condition
System.OverflowException
value is greater than System.Int32.MaxValue.
K L M N
Example
O
using System;
P namespace Samples { public class ConvertToInt32 { public static void Main() { try { ulong u = UInt64.MinValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToInt32(u)); u = (ulong) Int32.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToInt32(u)); u = UInt64.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToInt32(u)); } catch(OverflowException e)
Q R S T U V W X Y Z
789
Contents | Index
Convert
System
ToInt32() Method
{ Console.WriteLine("Exception: {0}", e); } }
A
} }
B C
The output is
D From UInt64 0 yields 0 From UInt64 2147483647 yields 2147483647 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Convert.ToInt32(UInt64 value) at Samples.ConvertToInt32.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt32\ToInt32(System.UInt64)\Convert.cs:line 18
E F G H I J
Convert.ToInt32(System.UInt16) Method
K [ILASM]
L
.method public hidebysig static int32 ToInt32(unsigned int16 value) [C#]
M
public static int ToInt32(ushort value)
N
Summary
O
Converts a System.UInt16 to a System.Int32.
P Q
Parameters
R S
Parameter
Description
T
value
The 16-bit unsigned integer value to be converted.
U V
Description
W
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt32(System.Int32).
X Y Z
790
Contents | Index
System
Convert ToInt64() Method
Example using System; namespace Samples { public class ConvertToInt32 { public static void Main() { try { ushort u = UInt16.MaxValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToInt32(u)); u = UInt16.MinValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToInt32(u)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N
The output is
O P
From UInt16 65535 yields 65535 From UInt16 0 yields 0
Q R
Convert.ToInt64(System.Boolean) Method
S
[ILASM]
T
.method public hidebysig static int64 ToInt64(bool value)
U
[C#]
V
public static long ToInt64(bool value)
W
Summary
X
Converts a System.Boolean to a System.Int64.
Y Z
791
Contents | Index
Convert
System
ToInt64() Method
Parameters Parameter
Description
value
The System.Boolean value to be converted.
A B C D
Return Value
E
If value is true, returns 1; if value is false, returns 0.
F
Example
G
using System;
H
namespace Samples { public class ConvertToInt64 { public static void Main() { bool b = true; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToInt64(b)); b = false; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToInt64(b)); } } }
I J K L M N O P Q R
The output is
S From Boolean True yields 1 From Boolean False yields 0
T U V
Convert.ToInt64(System.Byte) Method
W [ILASM]
X
.method public hidebysig static int64 ToInt64(unsigned int8 value) [C#]
Y
public static long ToInt64(byte value)
Z
Summary Converts a System.Byte to a System.Int64. 792
Contents | Index
System
Convert ToInt64() Method
Parameters Parameter
Description
value
The System.Byte value to be converted.
A B C
Example
D
using System;
E
namespace Samples { public class ConvertToInt64 { public static void Main() { byte b = Byte.MaxValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToInt64(b)); b = Byte.MinValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToInt64(b)); } } }
F G H I J K L M N O
The output is
P Q
From Byte 255 yields 255 From Byte 0 yields 0
R S
Convert.ToInt64(System.Char) Method
T
[ILASM]
U
.method public hidebysig static int64 ToInt64(valuetype System.Char value)
V
[C#]
public static long ToInt64(char value)
W X
Summary
Y
Converts a System.Char to a System.Int64.
Z
793
Contents | Index
Convert
System
ToInt64() Method
Parameters Parameter
Description
value
The System.Char to be converted interpreted as an unsigned value.
A B C
Example
D
using System;
E
namespace Samples { public class ConvertToInt64 { public static void Main() { Char c = 'A'; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToInt64(c)); c = 'a'; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToInt64(c)); c = Char.MinValue; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToInt64(c)); } } }
F G H I J K L M N O P Q
The output is
R
From Char A yields 65 From Char a yields 97 From Char yields 0
S T U V
Convert.ToInt64(System.Decimal) Method
W [ILASM]
X
.method public hidebysig static int64 ToInt64(decimal value) [C#]
Y
public static long ToInt64(decimal value)
Z
Summary Converts a System.Decimal to a System.Int64. 794
Contents | Index
System
Convert ToInt64() Method
Parameters Parameter
Description
value
The System.Decimal value to be converted.
A B C
Description
D
Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member must be implemented if the Extended Numerics Library is present in the implementation.
E F G
Exceptions
H I
Exception
Condition
System.OverflowException
value is greater than System.Int64.MaxValue or less than System.Int64.MinValue.
J K L M
Example
N
using System;
O namespace Samples { public class ConvertToInt64 { public static void Main() { try { Decimal d = Decimal.One; Console.WriteLine("From Decimal {0} yields d, Convert.ToInt64(d)); d = Decimal.Zero; Console.WriteLine("From Decimal {0} yields d, Convert.ToInt64(d)); d = 25.5m; Console.WriteLine("From Decimal {0} yields d, Convert.ToInt64(d)); d = -25.5m; Console.WriteLine("From Decimal {0} yields d, Convert.ToInt64(d)); d = Decimal.MaxValue;
P Q R S T U
{1}",
V {1}",
W X
{1}",
Y Z
{1}",
795
Contents | Index
Convert
System
ToInt64() Method
Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToInt64(d)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C
} }
D
}
E
The output is
F
From Decimal 1 yields 1 From Decimal 0 yields 0 From Decimal 25.5 yields 26 From Decimal -25.5 yields -26 Exception: System.OverflowException: Value was either too large or too small for an Int64. at System.Decimal.ToInt64(Decimal d) at System.Convert.ToInt64(Decimal value) at Samples.ConvertToInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt64\ToInt64(System.Decimal)\Convert.cs:line 24
G H I J K L M N
Convert.ToInt64(System.Double) Method
O
[ILASM]
P
.method public hidebysig static int64 ToInt64(float64 value)
Q
[C#]
public static long ToInt64(double value)
R S
Summary
T
Converts a System.Double to a System.Int64.
U
Parameters
V W X
Parameter
Description
value
The System.Double value to be converted.
Y Z
796
Contents | Index
System
Convert ToInt64() Method
Description Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member must be implemented if the Extended Numerics Library is present in the implementation.
A B
Exceptions
C
Exception
Condition
System.OverflowException
value is greater than System.Int64.MaxValue or less than System.Int64.MinValue.
D E F G
Example
H
using System;
I
namespace Samples { public class ConvertToInt64 { public static void Main() { try { double d = Double.Epsilon; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToInt64(d)); d = 0.0; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToInt64(d)); d = 5.5; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToInt64(d)); d = -5.5; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToInt64(d)); d = Double.MaxValue; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToInt64(d)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
J K L M N O P Q R S T U V W X Y Z
797
Contents | Index
Convert
System
ToInt64() Method
The output is From Double 4.94065645841247E-324 yields 0 From Double 0 yields 0 From Double 5.5 yields 6 From Double -5.5 yields -6 Exception: System.OverflowException: Value was either too large or too small for an Int64. at System.Convert.ToInt64(Double value) at Samples.ConvertToInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt64\ToInt64(System.Double)\Convert.cs:line 24
A B C D E F G
Convert.ToInt64(System.Single) Method
H
[ILASM]
.method public hidebysig static int64 ToInt64(float32 value)
I
[C#]
J
public static long ToInt64(float value)
K
Summary
L
Converts a System.Single to a System.Int64.
M
Parameters
N O
Parameter
Description
value
The System.Single value to be converted.
P Q R
Description
S
Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member must be implemented if the Extended Numerics Library is present in the implementation.
T U V
Exceptions
W X
Exception
Condition
System.OverflowException
value is greater than System.Int64.MaxValue or less than System.Int64.MinValue.
Y Z
798
Contents | Index
System
Convert ToInt64() Method
Example using System; namespace Samples { public class ConvertToInt64 { public static void Main() { float f; try { f = 0f; Console.WriteLine("From Single {0} yields f, Convert.ToInt64(f)); f = 25.5f; Console.WriteLine("From Single {0} yields f, Convert.ToInt64(f)); f = -25.5f; Console.WriteLine("From Single {0} yields f, Convert.ToInt64(f)); f = (float) Int64.MinValue; Console.WriteLine("From Single {0} yields f, Convert.ToInt64(f)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } try { f = Single.MaxValue; Console.WriteLine("From Single {0} yields f, Convert.ToInt64(f)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G
{1}",
H {1}",
I J
{1}",
K L
{1}",
M N O P Q R {1}",
S T U V W X Y
The output is
Z From Single 0 yields 0 From Single 25.5 yields 26 From Single -25.5 yields -26
799
Contents | Index
Convert
System
ToInt64() Method
Exception: System.OverflowException: Value was either too large or too small for an Int64. at System.Convert.ToInt64(Double value) at System.Convert.ToInt64(Single value) at Samples.ConvertToInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt64\ToInt64(System.Single)\Convert.cs:line 22 Exception: System.OverflowException: Value was either too large or too small for an Int64. at System.Convert.ToInt64(Double value) at System.Convert.ToInt64(Single value) at Samples.ConvertToInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt64\ToInt64(System.Single)\Convert.cs:line 32
A B C D E F G H
Convert.ToInt64(System.Int32) Method
I
[ILASM]
.method public hidebysig static int64 ToInt64(int32 value)
J
[C#]
public static long ToInt64(int value)
K L
Summary
M
Converts a System.Int32 to a System.Int64.
N
Parameters
O P
Parameter
Description
value
The 32-bit signed integer value to be converted.
Q R S
Example
T
using System;
U namespace Samples { public class ConvertToInt64 { public static void Main() { int i = Int32.MaxValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToInt64(i)); i = Int32.MinValue;
V W X Y Z
800
Contents | Index
System
Convert ToInt64() Method
Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToInt64(i)); } }
A
}
B
The output is
C
From Int32 2147483647 yields 2147483647 From Int32 -2147483648 yields -2147483648
D E F
Convert.ToInt64(System.Int64) Method
G
[ILASM]
H
.method public hidebysig static int64 ToInt64(int64 value)
I
[C#]
public static long ToInt64(long value)
J
Summary
K
Converts a System.Int64 to a System.Int64.
L M
Parameters
N
Parameter
Description
value
The 64-bit signed integer value to be converted.
O P Q R
Return Value
S
value is returned unchanged.
T
Description
U
[Note: This method is provided for completeness.]
V W X Y Z
801
Contents | Index
Convert
System
ToInt64() Method
Example using System; namespace Samples { public class ConvertToInt64 { public static void Main() { long l = Int64.MaxValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToInt64(l)); l = Int64.MinValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToInt64(l)); } } }
A B C D E F G H I J
The output is
K L
From Int64 9223372036854775807 yields 9223372036854775807 From Int64 -9223372036854775808 yields -9223372036854775808
M N O
Convert.ToInt64(System.Object) Method
P
[ILASM]
.method public hidebysig static int64 ToInt64(object value)
Q
[C#]
public static long ToInt64(object value)
R S
Summary
T
Converts the value of the specified System.Object to a 64-bit signed integer.
U
Parameters
V W
Parameter
Description
value
A System.Object that implements the System.IConvertible interface or null.
X Y Z
802
Contents | Index
System
Convert ToInt64() Method
Return Value A 64-bit signed integer equivalent to the value of value, or zero if value is null.
Description
A
The return value is the result of invoking the IConvertible.ToInt64 method of the underlying type of value.
B C D
Exceptions
E
Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
F G H I
Convert.ToInt64(System.Object, System.IFormatProvider) Method
J K
[ILASM]
.method public hidebysig static int64 ToInt64(object value, class System.IFormatProvider provider)
L
[C#]
M
public static long ToInt64(object value, IFormatProvider provider)
N
Summary
O
Converts the value of the specified System.Object to a 64-bit signed integer using the specified culture-specific formatting information.
P Q R
Parameters
S
Parameter
Description
value
A System.Object that implements the System.IConvertible interface.
provider
A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
T U V W X
Return Value
Y
A 64-bit signed integer equivalent to the value of value, or zero if value is null.
Z
803
Contents | Index
Convert
System
ToInt64() Method
Description The return value is the result of invoking the IConvertible.ToInt64 method of the underlying type of value. provider enables the user to specify culture-specific conversion information about the contents of value. For example, if value is a System.String that represents a number, provider could supply culture-specific information about the notation used to represent that number. The base types ignore provider; however, it is honored if value is a user-defined type that implements the System.IConvertible interface.
A B C D E
Exceptions
F G
Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
H I J K
Convert.ToInt64(System.SByte) Method
L [ILASM]
M
.method public hidebysig static int64 ToInt64(int8 value) [C#]
N
public static long ToInt64(sbyte value)
O
Summary
P
Converts a System.SByte to a System.Int64.
Q R
Parameters
S T
Parameter
Description
U
value
The System.SByte value to be converted.
V W
Description
X
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt64(System.Int16).
Y Z
804
Contents | Index
System
Convert ToInt64() Method
Example using System; namespace Samples { public class ConvertToInt64 { public static void Main() { sbyte s = SByte.MaxValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToInt64(s)); s = SByte.MinValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToInt64(s)); s = 0; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToInt64(s)); } } }
A B C D E F G H I J K L
The output is
M
From Signed Byte 127 yields 127 From Signed Byte -128 yields -128 From Signed Byte 0 yields 0
N O P Q
Convert.ToInt64(System.Int16) Method
R
[ILASM]
S
.method public hidebysig static int64 ToInt64(int16 value) [C#]
T
public static long ToInt64(short value)
U
Summary
V
Converts a System.Int16 to a System.Int64.
W X
Parameters
Y
Parameter
Description
value
The 16-bit signed integer value to be converted.
Z
805
Contents | Index
Convert
System
ToInt64() Method
Example using System; namespace Samples { public class ConvertToInt64 { public static void Main() { short i = Int16.MaxValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToInt64(i)); i = Int16.MinValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToInt64(i)); } } }
A B C D E F G H I J
The output is
K L
From Int16 32767 yields 32767 From Int16 -32768 yields -32768
M N O
Convert.ToInt64(System.String) Method
P
[ILASM]
.method public hidebysig static int64 ToInt64(string value)
Q
[C#]
public static long ToInt64(string value)
R S
Summary
T
Converts a System.String to a System.Int64.
U
Parameters
V W
Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Integer style.
X Y Z
806
Contents | Index
System
Convert ToInt64() Method
Description This method parses value using the information in a System.Globalization.NumberFormatInfo instance initialized for the current system culture. A
Exceptions
B C
Exception
Condition
System.ArgumentNullException
value is a null reference.
E
System.FormatException
value cannot be converted to a numeric value.
F
System.OverflowException
The numeric value of value is greater than System.Int64.MaxValue or less than System.Int64.MinValue.
D
G H I J
Example
K
using System;
L namespace Samples { public class ConvertToInt64 { public static void Main() { string s; try { s = Int64.MaxValue.ToString(); Console.WriteLine("From String {0} yields s, Convert.ToInt64(s)); s = " +0"; Console.WriteLine("From String {0} yields s, Convert.ToInt64(s)); s = Int64.MinValue.ToString(); Console.WriteLine("From String {0} yields s, Convert.ToInt64(s)); s = String.Empty; Console.WriteLine("From String {0} yields s, Convert.ToInt64(s)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e);
M N O P Q R {1}",
S T
{1}",
U V
{1}",
W X
{1}",
Y Z
807
Contents | Index
Convert
System
ToInt64() Method
} try { s = ((UInt64)Int64.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt64(s)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E }
F
} }
G
The output is
H I
From String 9223372036854775807 yields 9223372036854775807 From String +0 yields 0 From String -9223372036854775808 yields -9223372036854775808 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt64(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt64(String value) at Samples.ConvertToInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt64\ToInt64(System.String)\Convert.cs:line 22 Exception: System.OverflowException: Value was either too large or too small for an Int64. at System.Number.ParseInt64(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt64(String value) at Samples.ConvertToInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt64\ToInt64(System.String)\Convert.cs:line 32
J K L M N O P Q R S T
Convert.ToInt64(System.String, System.Int32) Method
U
[ILASM]
V
.method public hidebysig static int64 ToInt64(string value, int32 fromBase)
W
[C#]
public static long ToInt64(string value, int fromBase)
X Y
Summary
Z
Converts the System.String representation of a number in a specified base to an equivalent 64-bit signed integer.
808
Contents | Index
System
Convert ToInt64() Method
Parameters Parameter
Description
value
A System.String containing a number.
fromBase
The base of the number in value, which must be 2, 8, 10, or 16.
A B C D
Description
E
If fromBase is 16, you can prefix the number specified by the value parameter with “0x” or “0X”.
F G
Exceptions
H
Exception
Condition
System.ArgumentException
fromBase is not 2, 8, 10, or 16.
I J K L M
Convert.ToInt64(System.String, System.IFormatProvider) Method
N
[ILASM]
O
.method public hidebysig static int64 ToInt64(string value, class System.IFormatProvider provider)
P
[C#]
public static long ToInt64(string value, IFormatProvider provider)
Q R
Summary
S
Converts a System.String to a System.Int64.
T
Parameters
U
Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Integer style.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
V W X Y Z
809
Contents | Index
Convert
System
ToInt64() Method
Description This method parses value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is parsed using the formatting information of the current system culture.
A B C
Exceptions
D E F
Exception
Condition
System.ArgumentNullException
value is a null reference.
System.FormatException
value cannot be converted to a numeric value.
System.OverflowException
The numeric value of value is greater than System.Int64.MaxValue or less than System.Int64.MinValue.
G H I J K L
Example
M
using System; using System.Globalization;
N namespace Samples { public class ConvertToInt64 { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; try { s = " ~0"; Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt64(s, c)); s = Int64.MaxValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt64(s, c)); s = Int64.MinValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt64(s, c)); s = String.Empty;
O P Q R S T U V W X Y Z
810
Contents | Index
System
Convert ToInt64() Method
Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt64(s, c)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = ((UInt64)Int64.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToInt64(s, c)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E F G H I
} }
J
}
K
The output is
L M
From String ~0 yields 0 From String 9223372036854775807 yields 9223372036854775807 From String -9223372036854775808 yields -9223372036854775808 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt64(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt64(String value, IFormatProvider provider) at Samples.ConvertToInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt64\ToInt64(System.String,System.IFormatProvider)\Convert.cs:line 26 Exception: System.OverflowException: Value was either too large or too small for an Int64. at System.Number.ParseInt64(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt64(String value, IFormatProvider provider) at Samples.ConvertToInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt64\ToInt64(System.String,System.IFormatProvider)\Convert.cs:line 36
N O P Q R S T U V W
Convert.ToInt64(System.DateTime) Method [ILASM]
X
.method public hidebysig static int64 ToInt64(valuetype System.DateTime value)
Y
[C#]
Z
public static long ToInt64(DateTime value)
811
Contents | Index
Convert
System
ToInt64() Method
Summary Calling this method always throws System.InvalidCastException. A
Parameters
B C
Parameter
Description
D
value
A System.DateTime.
E F
Exceptions
G H I
Exception
Condition
System.InvalidCastException
This conversion is not supported.
J K L
Convert.ToInt64(System.UInt32) Method
M
[ILASM]
N
.method public hidebysig static int64 ToInt64(unsigned int32 value)
O
public static long ToInt64(uint value)
[C#]
P
Summary
Q
Converts a System.UInt32 to a System.Int64.
R
Parameters
S T
Parameter
Description
value
The 32-bit unsigned integer value to be converted.
U V W X
Description
Y
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt64(System.Int64).
Z
812
Contents | Index
System
Convert ToInt64() Method
Example using System; namespace Samples { public class ConvertToInt64 { public static void Main() { uint u = UInt32.MaxValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToInt64(u)); u = UInt32.MinValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToInt64(u)); } } }
A B C D E F G H I J
The output is
K L
From UInt32 4294967295 yields 4294967295 From UInt32 0 yields 0
M N
Convert.ToInt64(System.UInt64) Method
O
[ILASM]
P
.method public hidebysig static int64 ToInt64(unsigned int64 value)
Q
[C#]
public static long ToInt64(ulong value)
R
Summary
S
Converts a System.UInt64 to a System.Int64.
T U
Parameters
V
Parameter
Description
value
The 64-bit unsigned integer value to be converted.
W X Y Z
813
Contents | Index
Convert
System
ToInt64() Method
Description This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt64(System.Decimal). A
Exceptions
B C D E
Exception
Condition
System.OverflowException
value is greater than System.Int64.MaxValue.
F G
Example
H
using System;
I
namespace Samples { public class ConvertToInt64 { public static void Main() { try { ulong u = UInt64.MinValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToInt64(u)); u = (ulong) Int64.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToInt64(u)); u = UInt64.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToInt64(u)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
J K L M N O P Q R S T U V W X Y Z
814
Contents | Index
System
Convert ToInt64() Method
The output is From UInt64 0 yields 0 From UInt64 9223372036854775807 yields 9223372036854775807 Exception: System.OverflowException: Value was either too large or too small for an Int64. at System.Convert.ToInt64(UInt64 value) at Samples.ConvertToInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToInt64\ToInt64(System.UInt64)\Convert.cs:line 18
A B C D E
Convert.ToInt64(System.UInt16) Method
F
[ILASM]
G
.method public hidebysig static int64 ToInt64(unsigned int16 value)
H
[C#]
I
public static long ToInt64(ushort value)
J
Summary
K
Converts a System.UInt16 to a System.Int64.
L
Parameters
M N
Parameter
Description
value
The 16-bit unsigned integer value to be converted.
O P Q
Description
R
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt64(System.Int32).
S
Example
U
using System;
V
T
W
namespace Samples { public class ConvertToInt64 { public static void Main() { ushort u = UInt16.MaxValue; Console.WriteLine("From UInt16 {0} yields {1}",
X Y Z
815
Contents | Index
Convert
System
ToSByte() Method
u, Convert.ToInt64(u)); u = UInt16.MinValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToInt64(u));
A
} }
B }
C
The output is
D E
From UInt16 65535 yields 65535 From UInt16 0 yields 0
F G H
Convert.ToSByte(System.Boolean) Method
I
[ILASM]
.method public hidebysig static int8 ToSByte(bool value)
J
[C#]
public static sbyte ToSByte(bool value)
K L
Summary
M
Converts a System.Boolean to a System.SByte.
N
Parameters
O P
Parameter
Description
value
The System.Boolean value to be converted.
Q R S T
Return Value
U
If value is true, returns 1; if value is false, returns 0.
V
Description
W
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt16(System.Boolean).
X Y Z
816
Contents | Index
System
Convert ToSByte() Method
Example using System; namespace Samples { public class ConvertToSByte { public static void Main() { bool b = true; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToSByte(b)); b = false; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToSByte(b)); } } }
A B C D E F G H I J
The output is
K
From Boolean True yields 1 From Boolean False yields 0
L M N
Convert.ToSByte(System.Byte) Method
O [ILASM]
.method public hidebysig static int8 ToSByte(unsigned int8 value)
P
[C#]
Q
public static sbyte ToSByte(byte value)
R
Summary
S
Converts a System.Byte to a System.SByte.
T U
Parameters
V
Parameter
Description
value
The System.Byte value to be converted.
W X Y Z
817
Contents | Index
Convert
System
ToSByte() Method
Description This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt16(System.Byte). A
Exceptions
B C
Exception
Condition
System.OverflowException
value is greater than System.SByte.MaxValue.
D E F G
Example
H
using System;
I
namespace Samples { public class ConvertToSByte { public static void Main() { try { byte b = Byte.MinValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToSByte(b)); b = Byte.MaxValue / 2; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToSByte(b)); b = Byte.MaxValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToSByte(b)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
J K L M N O P Q R S T U V W X Y Z
818
Contents | Index
System
Convert ToSByte() Method
The output is From Byte 0 yields 0 From Byte 127 yields 127 Exception: System.OverflowException: Value was either too large or too small for a signed byte. at System.Convert.ToSByte(Byte value) at Samples.ConvertToSByte.Main() in C:\Books\BCL\Samples\System\Convert\ ToSByte\ToSByte(System.Byte)\Convert.cs:line 18
A B C D E
Convert.ToSByte(System.Char) Method
F
[ILASM]
G
.method public hidebysig static int8 ToSByte(valuetype System.Char value)
H
[C#]
I
public static sbyte ToSByte(char value)
J
Summary
K
Converts a System.Char to a System.SByte.
L
Parameters
M N
Parameter
Description
value
The System.Char to be converted is interpreted as an unsigned value.
O P Q
Description
R
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt16(System.Char).
S
Exceptions
U
T
V
Exception
Condition
W
System.OverflowException
The numeric value of value is greater than System.SByte.MaxValue.
X Y Z
819
Contents | Index
Convert
System
ToSByte() Method
Example using System; namespace Samples { public class ConvertToSByte { public static void Main() { try { Char c = Char.MinValue; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToSByte(c)); c = 'A'; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToSByte(c)); c = Char.MaxValue; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToSByte(c)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P
The output is
Q R
From Char yields 0 From Char A yields 65 Exception: System.OverflowException: Value was either too large or too small for a signed byte. at System.Convert.ToSByte(Char value) at Samples.ConvertToSByte.Main() in C:\Books\BCL\Samples\System\Convert\ ToSByte\ToSByte(System.Char)\Convert.cs:line 18
S T U V W X
Convert.ToSByte(System.Decimal) Method
Y
[ILASM]
.method public hidebysig static int8 ToSByte(decimal value)
Z
[C#]
public static sbyte ToSByte(decimal value)
820
Contents | Index
System
Convert ToSByte() Method
Summary Converts a System.Decimal to a System.SByte. A
Parameters
B
Parameter
Description
C
value
The System.Decimal value to be converted.
D E F
Description
G
Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt16(System.Decimal). This member must be implemented if the Extended Numerics Library is present in the implementation.
H I J K
Exceptions
L
Exception
Condition
System.OverflowException
value is greater than System.SByte.MaxValue or less than System.SByte.MinValue.
M N O P Q
Example
R
using System;
S
namespace Samples { public class ConvertToSByte { public static void Main() { try { Decimal d = Decimal.One; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToSByte(d)); d = Decimal.Zero; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToSByte(d));
T U V W X Y Z
821
Contents | Index
Convert
System
ToSByte() Method
d = SByte.MaxValue; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToSByte(d)); d = SByte.MinValue; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToSByte(d)); d = Decimal.MinValue; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToSByte(d));
A B C D
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
E F G
}
H
} }
I
The output is
J K
From Decimal 1 yields 1 From Decimal 0 yields 0 From Decimal 127 yields 127 From Decimal -128 yields -128 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Decimal.ToInt32(Decimal d) at System.Decimal.ToSByte(Decimal value) at System.Convert.ToSByte(Decimal value) at Samples.ConvertToSByte.Main() in C:\Books\BCL\Samples\System\Convert\ ToSByte\ToSByte(System.Decimal)\Convert.cs:line 24
L M N O P Q R S
Convert.ToSByte(System.Double) Method
T [ILASM]
U
.method public hidebysig static int8 ToSByte(float64 value)
V
[C#]
public static sbyte ToSByte(double value)
W X
Summary
Y
Converts a System.Double to a System.SByte.
Z
822
Contents | Index
System
Convert ToSByte() Method
Parameters Parameter
Description
value
The System.Double value to be converted.
A B C
Description
D
Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt16(System.Double). This member must be implemented if the Extended Numerics Library is present in the implementation.
E F G H I
Exceptions
J
Exception
Condition
K
value is greater than System.SByte.MaxValue or less than System.SByte.MinValue.
L
System.OverflowException
M N
Example
O
using System;
P
namespace Samples { public class ConvertToSByte { public static void Main() { try { double d = Double.Epsilon; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToSByte(d)); d = 0.0; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToSByte(d)); d = 5.5; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToSByte(d)); d = -5.5;
Q R S T U V W X Y Z
823
Contents | Index
Convert
System
ToSByte() Method
Console.WriteLine("From Double {0} yields {1}", d, Convert.ToSByte(d)); d = Double.PositiveInfinity; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToSByte(d));
A
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
B C D }
E }
F
}
G
The output is
H From Double 4.94065645841247E-324 yields 0 From Double 0 yields 0 From Double 5.5 yields 6 From Double -5.5 yields -6 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Convert.ToInt32(Double value) at System.Convert.ToSByte(Double value) at Samples.ConvertToSByte.Main() in C:\Books\BCL\Samples\System\Convert\ ToSByte\ToSByte(System.Double)\Convert.cs:line 24
I J K L M N O P
Convert.ToSByte(System.Single) Method
Q [ILASM]
R
.method public hidebysig static int8 ToSByte(float32 value)
S
[C#]
public static sbyte ToSByte(float value)
T U
Summary
V
Converts a System.Single to a System.SByte.
W
Parameters
X Y Z
Parameter
Description
value
The System.Single value to be converted.
824
Contents | Index
System
Convert ToSByte() Method
Description Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt16(System.Single). This member must be implemented if the Extended Numerics Library is present in the implementation.
A B C D
Exceptions
E
Exception
Condition
System.OverflowException
value is greater than System.SByte.MaxValue or less than System.SByte.MinValue.
F G H I
Example
J
using System; namespace Samples { public class ConvertToSByte { public static void Main() { try { float f = 0f; Console.WriteLine("From Single {0} yields f, Convert.ToSByte(f)); f = 25.5f; Console.WriteLine("From Single {0} yields f, Convert.ToSByte(f)); f = -25.5f; Console.WriteLine("From Single {0} yields f, Convert.ToSByte(f)); f = Single.MaxValue; Console.WriteLine("From Single {0} yields f, Convert.ToSByte(f)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
K L M N O P Q
{1}",
R {1}",
S T
{1}",
U V
{1}",
W X Y Z
825
Contents | Index
Convert
System
ToSByte() Method
The output is From Single 0 yields 0 From Single 25.5 yields 26 From Single -25.5 yields -26 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Convert.ToInt32(Double value) at System.Convert.ToSByte(Single value) at Samples.ConvertToSByte.Main() in C:\Books\BCL\Samples\System\Convert\ ToSByte\ToSByte(System.Single)\Convert.cs:line 21
A B C D E F G
Convert.ToSByte(System.Int32) Method
H
[ILASM]
I
.method public hidebysig static int8 ToSByte(int32 value) [C#]
J
public static sbyte ToSByte(int value)
K
Summary
L
Converts a System.Int32 to a System.SByte.
M N
Parameters
O P Q
Parameter
Description
value
The 32-bit signed integer value to be converted.
R S
Description
T
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt16(System.Int32).
U V
Exceptions
W X
Exception
Condition
System.OverflowException
value is greater than System.SByte.MaxValue or less than System.SByte.MinValue.
Y Z
826
Contents | Index
System
Convert ToSByte() Method
Example using System; namespace Samples { public class ConvertToSByte { public static void Main() { try { int i = SByte.MaxValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToSByte(i)); i = SByte.MinValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToSByte(i)); i = Int32.MinValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToSByte(i)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P
The output is
Q R
From Int32 127 yields 127 From Int32 -128 yields -128 Exception: System.OverflowException: Value was either too large or too small for a signed byte. at System.Convert.ToSByte(Int32 value) at Samples.ConvertToSByte.Main() in C:\Books\BCL\Samples\System\Convert\ ToSByte\ToSByte(System.Int32)\Convert.cs:line 18
S T U V W
Convert.ToSByte(System.Int64) Method
X
[ILASM]
Y
.method public hidebysig static int8 ToSByte(int64 value)
Z
[C#]
public static sbyte ToSByte(long value)
827
Contents | Index
Convert
System
ToSByte() Method
Summary Converts a System.Int64 to a System.SByte. A
Parameters
B C
Parameter
Description
D
value
The 64-bit signed integer value to be converted.
E F
Description
G
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt16(System.Int64).
H I
Exceptions
J K
Exception
Condition
System.OverflowException
value is greater than System.SByte.MaxValue or less than System.SByte.MinValue.
L M N O
Example
P
using System;
Q
namespace Samples { public class ConvertToSByte { public static void Main() { try { long l = SByte.MaxValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToSByte(l)); l = 0; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToSByte(l)); l = SByte.MinValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToSByte(l)); l = Int64.MaxValue;
R S T U V W X Y Z
828
Contents | Index
System
Convert ToSByte() Method
Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToSByte(l)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C
} }
D
}
E
The output is
F
From Int64 127 yields 127 From Int64 0 yields 0 From Int64 -128 yields -128 Exception: System.OverflowException: Value was either too large or too small for a signed byte. at System.Convert.ToSByte(Int64 value) at Samples.ConvertToSByte.Main() in C:\Books\BCL\Samples\System\Convert\ ToSByte\ToSByte(System.Int64)\Convert.cs:line 21
G H I J K L M
Convert.ToSByte(System.Object) Method
N [ILASM]
O
.method public hidebysig static int8 ToSByte(object value) [C#]
P
public static sbyte ToSByte(object value)
Q
Summary
R
Converts the value of the specified System.Object to an 8-bit signed integer.
S T
Parameters
U
Parameter
Description
V
A System.Object that implements the System.IConvertible interface or null.
W
value
X Y
Return Value
Z
An 8-bit signed integer equivalent to the value of value, or zero if value is null.
829
Contents | Index
Convert
System
ToSByte() Method
Description The return value is the result of invoking the IConvertible.ToSByte method of the underlying type of value. A
Exceptions
B C D E
Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
F G
Convert.ToSByte(System.Object, System.IFormatProvider) Method
H
[ILASM]
I
.method public hidebysig static int8 ToSByte(object value, class System.IFormatProvider provider)
J
[C#]
K
public static sbyte ToSByte(object value, IFormatProvider provider)
L M
Summary
N
Converts the value of the specified System.Object to an 8-bit signed integer using the specified culture-specific formatting information.
O
Parameters
P Q
Parameter
Description
value
A System.Object that implements the System.IConvertible interface.
provider
A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
R S T U V
Return Value
W
An 8-bit signed integer equivalent to the value of value, or zero if value is null.
X Y
Description
Z
provider enables the user to specify culture-specific conversion information about the contents of value. For example, if value is a System.String that represents a number, provider could supply culture-specific information about the notation used to represent that number. 830
Contents | Index
System
Convert ToSByte() Method
The base types ignore provider; however, it is honored if value is a user-defined type that implements the System.IConvertible interface. A
Convert.ToSByte(System.SByte) Method
B
[ILASM]
C
.method public hidebysig static int8 ToSByte(int8 value)
D
[C#]
public static sbyte ToSByte(sbyte value)
E F
Summary
G
Converts a System.SByte to a System.SByte.
H
Parameters
I
Parameter
Description
value
The System.SByte value to be converted.
J K L M
Return Value
N
value is returned unchanged.
O P
Description This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt16(System.Int16). [Note: This method is provided for completeness.]
Q
Example
T
using System;
U
R S
V
namespace Samples { public class ConvertToSByte { public static void Main() { sbyte s = SByte.MaxValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToSByte(s)); s = SByte.MinValue;
W X Y Z
831
Contents | Index
Convert
System
ToSByte() Method
Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToSByte(s)); } }
A
}
B
The output is
C
From Signed Byte 127 yields 127 From Signed Byte -128 yields -128
D E F
Convert.ToSByte(System.Int16) Method
G H
[ILASM]
I
[C#]
.method public hidebysig static int8 ToSByte(int16 value) public static sbyte ToSByte(short value)
J K
Summary
L
Converts a System.Int16 to a System.SByte.
M
Parameters
N O
Parameter
Description
value
The 16-bit signed integer value to be converted.
P Q R
Description
S
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt16(System.Int16).
T U
Exceptions
V W
Exception
Condition
System.OverflowException
value is greater than System.SByte.MaxValue or less than System.SByte.MinValue.
X Y Z
832
Contents | Index
System
Convert ToSByte() Method
Example using System; namespace Samples { public class ConvertToSByte { public static void Main() { try { short i = SByte.MaxValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToSByte(i)); i = 0; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToSByte(i)); i = SByte.MinValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToSByte(i)); i = Int16.MaxValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToSByte(i)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P Q R
The output is
S
From Int16 127 yields 127 From Int16 0 yields 0 From Int16 -128 yields -128 Exception: System.OverflowException: Value was either too large or too small for a signed byte. at System.Convert.ToSByte(Int16 value) at Samples.ConvertToSByte.Main() in C:\Books\BCL\Samples\System\Convert\ ToSByte\ToSByte(System.Int16)\Convert.cs:line 21
T U V W X Y Z
833
Contents | Index
Convert
System
ToSByte() Method
Convert.ToSByte(System.String) Method [ILASM]
.method public hidebysig static int8 ToSByte(string value)
A
[C#]
public static sbyte ToSByte(string value)
B C
Summary
D
Converts a System.String representation of a number to a System.SByte.
E
Parameters
F G
Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Integer style.
H I J K
Description
L
This method parses value using the information in a System.Globalization.NumberFormatInfo instance initialized for the current system culture. This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt16(System.String).
M N O P
Exceptions
Q R S
Exception
Condition
System.ArgumentNullException
value is a null reference.
System.FormatException
value cannot be converted to a numeric value in the specified format.
System.OverflowException
The numeric value of value is greater than System.SByte.MaxValue or less than System.SByte.MinValue.
T U V W X Y Z
834
Contents | Index
System
Convert ToSByte() Method
Example using System; namespace Samples { public class ConvertToSByte { public static void Main() { string s; try { s = SByte.MaxValue.ToString(); Console.WriteLine("From String {0} yields s, Convert.ToSByte(s)); s = SByte.MinValue.ToString(); Console.WriteLine("From String {0} yields s, Convert.ToSByte(s)); s = " +0"; Console.WriteLine("From String {0} yields s, Convert.ToSByte(s)); s = String.Empty; Console.WriteLine("From String {0} yields s, Convert.ToSByte(s)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = (SByte.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields s, Convert.ToSByte(s)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G
{1}",
H {1}",
I J
{1}",
K L
{1}",
M N O P Q R {1}",
S T U V W X Y Z
835
Contents | Index
Convert
System
ToSByte() Method
The output is From String 127 yields 127 From String -128 yields -128 From String +0 yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.SByte.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToSByte(String value) at Samples.ConvertToSByte.Main() in C:\Books\BCL\Samples\System\Convert\ ToSByte\ToSByte(System.String)\Convert.cs:line 22 Exception: System.OverflowException: Value was either too large or too small for a signed byte. at System.SByte.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToSByte(String value) at Samples.ConvertToSByte.Main() in C:\Books\BCL\Samples\System\Convert\ ToSByte\ToSByte(System.String)\Convert.cs:line 32
A B C D E F G H I J K
Convert.ToSByte(System.String, System.Int32) Method
L
[ILASM]
.method public hidebysig static int8 ToSByte(string value, int32 fromBase)
M
[C#]
public static sbyte ToSByte(string value, int fromBase)
N O
Summary
P
Converts the System.String representation of a number in a specified base to an equivalent 8-bit signed integer.
Q R
Parameters
S T
Parameter
Description
value
A System.String containing a number.
fromBase
The base of the number in value, which must be 2, 8, 10, or 16.
U V W X Y
Description
Z
If fromBase is 16, you can prefix the number specified by the value parameter with “0x” or “0X”.
836
Contents | Index
System
Convert ToSByte() Method
Exceptions Exception
Condition
System.ArgumentException
fromBase is not 2, 8, 10, or 16.
System.OverflowException
value is less than System.SByte.MinValue or greater than System.SByte.MaxValue.
A B C D E F
Convert.ToSByte(System.String, System.IFormatProvider) Method
G [ILASM]
H
.method public hidebysig static int8 ToSByte(string value, class System.IFormatProvider provider) [C#]
I
public static sbyte ToSByte(string value, IFormatProvider provider)
J K
Summary
L
Converts a System.String to a System.SByte.
M
Parameters
N
Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Integer style.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
O P Q R S T
Description
U
This method parses value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is parsed using the formatting information of the current system culture. This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt16(System.String, System.IFormatProvider).
V W X Y Z
837
Contents | Index
Convert
System
ToSByte() Method
Example using System; using System.Globalization;
A namespace Samples { public class ConvertToByteSample { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; try { s = " ~0"; Console.WriteLine("From String {0} yields {1}", s, Convert.ToSByte(s, c)); s = SByte.MaxValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToSByte(s, c)); s = SByte.MinValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToSByte(s, c)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToSByte(s, c)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = (SByte.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToSByte(s, c)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
B C D E F G H I J K L M N O P Q R S T U V W X Y Z
838
Contents | Index
System
Convert ToSByte() Method
The output is From String ~0 yields 0 From String 127 yields 127 From String -128 yields -128 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.SByte.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToSByte(String value, IFormatProvider provider) at Samples.ConvertToByteSample.Main() in C:\Books\BCL\Samples\System\Convert\ ToSByte\ToSByte(System.String,System.IFormatProvider)\Convert.cs:line 26 Exception: System.OverflowException: Value was either too large or too small for a signed byte. at System.SByte.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToSByte(String value, IFormatProvider provider) at Samples.ConvertToByteSample.Main() in C:\Books\BCL\Samples\System\Convert\ ToSByte\ToSByte(System.String,System.IFormatProvider)\Convert.cs:line 36
A B C D E F G H I J K
Convert.ToSByte(System.DateTime) Method
L
[ILASM]
.method public hidebysig static int8 ToSByte(valuetype System.DateTime value)
M
[C#]
N
public static sbyte ToSByte(DateTime value)
O
Summary
P
Calling this method always throws System.InvalidCastException.
Q R
Parameters
S
Parameter
Description
value
A System.DateTime.
T U V W
Exceptions
X
Exception
Condition
System.InvalidCastException
This conversion is not supported.
Y Z
839
Contents | Index
Convert
System
ToSByte() Method
Convert.ToSByte(System.UInt32) Method [ILASM]
.method public hidebysig static int8 ToSByte(unsigned int32 value)
A
[C#]
public static sbyte ToSByte(uint value)
B C
Summary
D
Converts a System.UInt32 to a System.SByte.
E
Parameters
F G H
Parameter
Description
value
The 32-bit unsigned integer value to be converted.
I J
Description
K
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt16(System.Int64).
L M
Exceptions
N O
Exception
Condition
P
System.OverflowException
value is greater than System.SByte.MaxValue.
Q R
Example
S
using System;
T
namespace Samples { public class ConvertToSByte { public static void Main() { try { uint u = (UInt32) SByte.MaxValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToSByte(u)); u = UInt32.MinValue; Console.WriteLine("From UInt32 {0} yields {1}",
U V W X Y Z
840
Contents | Index
System
Convert ToSByte() Method
u, Convert.ToSByte(u)); u = UInt32.MaxValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToSByte(u));
A
} catch(OverflowException e) { Console.WriteLine("Exception {0}", e); }
B C D
} }
E
}
F
The output is
G H
From UInt32 127 yields 127 From UInt32 0 yields 0 Exception System.OverflowException: Value was either too large or too small for a signed byte. at System.Convert.ToSByte(UInt32 value) at Samples.ConvertToSByte.Main() in C:\Books\BCL\Samples\System\Convert\ ToSByte\ToSByte(System.UInt32)\Convert.cs:line 18
I J K L M
Convert.ToSByte(System.UInt64) Method
N
[ILASM]
O
.method public hidebysig static int8 ToSByte(unsigned int64 value)
P
[C#]
public static sbyte ToSByte(ulong value)
Q R
Summary
S
Converts a System.UInt64 to a System.SByte.
T
Parameters
U
Parameter
Description
value
The 64-bit unsigned integer value to be converted.
V W X Y
Description
Z
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt16(System.Decimal). 841
Contents | Index
Convert
System
ToSByte() Method
Exceptions Exception
Condition
System.OverflowException
value is greater than System.SByte.MaxValue.
A B C
Example
D
using System;
E
namespace Samples { public class ConvertToSByte { public static void Main() { try { ulong u = (UInt64) SByte.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToSByte(u)); u = UInt64.MinValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToSByte(u)); u = UInt64.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToSByte(u)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
F G H I J K L M N O P Q R S T U
The output is
V W
From UInt64 127 yields 127 From UInt64 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for a signed byte. at System.Convert.ToSByte(UInt64 value) at Samples.ConvertToSByte.Main() in C:\Books\BCL\Samples\System\Convert\ ToSByte\ToSByte(System.UInt64)\Convert.cs:line 18
X Y Z
842
Contents | Index
System
Convert ToSByte() Method
Convert.ToSByte(System.UInt16) Method [ILASM]
.method public hidebysig static int8 ToSByte(unsigned int16 value) [C#]
A
public static sbyte ToSByte(ushort value)
B
Summary
C
Converts a System.UInt16 to a System.SByte.
D E
Parameters
F G
Parameter
Description
value
The 16-bit unsigned integer value to be converted.
H I J
Description
K
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt16(System.Int32).
L M
Exceptions
N
Exception
Condition
System.OverflowException
value is greater than System.SByte.MaxValue.
O P Q R
Example
S
using System;
T
namespace Samples { public class ConvertToSByte { public static void Main() { try { ushort u = (UInt16) SByte.MaxValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToSByte(u)); u = UInt16.MinValue;
U V W X Y Z
843
Contents | Index
Convert
System
ToSingle() Method
Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToSByte(u)); u = UInt16.MaxValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToSByte(u));
A
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
B C D }
E }
F
}
G
The output is
H From UInt16 127 yields 127 From UInt16 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for a signed byte. at System.Convert.ToSByte(UInt16 value) at Samples.ConvertToSByte.Main() in C:\Books\BCL\Samples\System\Convert\ ToSByte\ToSByte(System.UInt16)\Convert.cs:line 18
I J K L M N
Convert.ToSingle(System.Boolean) Method
O
[ILASM]
P
.method public hidebysig static float32 ToSingle(bool value)
Q
[C#]
public static float ToSingle(bool value)
R S
Summary
T
Converts a System.Boolean to a System.Single.
U
Parameters
V W
Parameter
Description
X
value
The System.Boolean value to be converted.
Y Z
Return Value If value is true, returns 1; if value is false, returns 0.
844
Contents | Index
System
Convert ToSingle() Method
Description This member must be implemented if the Extended Numerics Library is present in the implementation. A
Example
B
using System;
C
namespace Samples { public class ConvertToSingle { public static void Main() { bool b = true; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToSingle(b)); b = false; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToSingle(b)); } } }
D E F G H I J K L M
The output is
N
From Boolean True yields 1 From Boolean False yields 0
O P Q
Convert.ToSingle(System.Byte) Method
R
[ILASM]
.method public hidebysig static float32 ToSingle(unsigned int8 value)
S
[C#]
T
public static float ToSingle(byte value)
U
Summary
V
Converts a System.Byte to a System.Single.
W X
Parameters
Y
Parameter
Description
value
The System.Byte value to be converted.
Z
845
Contents | Index
Convert
System
ToSingle() Method
Description This member must be implemented if the Extended Numerics Library is present in the implementation. A B
Example
C
using System;
D
namespace Samples { public class ConvertToSingle { public static void Main() { byte b = Byte.MaxValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToSingle(b)); b = Byte.MinValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToSingle(b)); } } }
E F G H I J K L M
The output is
N From Byte 255 yields 255 From Byte 0 yields 0
O P Q
Convert.ToSingle(System.Char) Method
R [ILASM]
S
.method public hidebysig static float32 ToSingle(valuetype System.Char value) [C#]
T
public static float ToSingle(char value)
U V
Summary
W
Calling this method always throws System.InvalidCastException.
X
Parameters
Y Z
Parameter
Description
value
A Unicode character.
846
Contents | Index
System
Convert ToSingle() Method
Exceptions Exception
Condition
System.InvalidCastException
This conversion is not supported.
A B C D
Convert.ToSingle(System.Decimal) Method
E
[ILASM]
F
.method public hidebysig static float32 ToSingle(decimal value) [C#]
G
public static float ToSingle(decimal value)
H
Summary
I
Converts a System.Decimal to a System.Single.
J K
Parameters
L
Parameter
Description
value
The System.Decimal value to be converted.
M N O P
Return Value
Q
value as a System.Single. value is rounded using banker’s rounding.
R
Description
S
This member must be implemented if the Extended Numerics Library is present in the implementation.
T U
Example
V
using System;
W
namespace Samples { public class ConvertToSingle { public static void Main() {
X Y Z
847
Contents | Index
Convert
System
ToSingle() Method
Decimal d = Decimal.One; Console.WriteLine("From Decimal {0} yields d, Convert.ToSingle(d)); d = Decimal.Zero; Console.WriteLine("From Decimal {0} yields d, Convert.ToSingle(d)); d = Decimal.MaxValue; Console.WriteLine("From Decimal {0} yields d, Convert.ToSingle(d)); d = Decimal.MinValue; Console.WriteLine("From Decimal {0} yields d, Convert.ToSingle(d)); d = 25.5m; Console.WriteLine("From Decimal {0} yields d, Convert.ToSingle(d)); d = -25.5m; Console.WriteLine("From Decimal {0} yields d, Convert.ToSingle(d));
A B C D E F G H I
{1}",
{1}",
{1}",
{1}",
{1}",
{1}",
}
J }
K
}
L
The output is
M From From From From From From
N O P Q
Decimal Decimal Decimal Decimal Decimal Decimal
1 yields 1 0 yields 0 79228162514264337593543950335 yields 7.922816E+28 -79228162514264337593543950335 yields -7.922816E+28 25.5 yields 25.5 -25.5 yields -25.5
R S
Convert.ToSingle(System.Double) Method
T
[ILASM]
.method public hidebysig static float32 ToSingle(float64 value)
U
[C#]
public static float ToSingle(double value)
V W
Summary
X
Converts a System.Double to a System.Single.
Y Z
848
Contents | Index
System
Convert ToSingle() Method
Parameters Parameter
Description
value
The System.Double value to be converted.
A B C
Description
D
This member must be implemented if the Extended Numerics Library is present in the implementation.
E
Exceptions
G
F
H
Exception
Condition
System.OverflowException
value is greater than System.Single.MaxValue or less than System.Single.MinValue.
I J K L
Example
M
using System;
N namespace Samples { public class ConvertToSingle { public static void Main() { double d = Double.MaxValue; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToSingle(d)); d = Double.MinValue; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToSingle(d)); d = Double.PositiveInfinity; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToSingle(d)); d = Double.NegativeInfinity; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToSingle(d)); d = Double.Epsilon; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToSingle(d)); d = 0.0;
O P Q R S T U V W X Y Z
849
Contents | Index
Convert
System
ToSingle() Method
Console.WriteLine("From Double {0} yields {1}", d, Convert.ToSingle(d)); d = 5.5; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToSingle(d)); d = -5.5; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToSingle(d)); d = Double.NaN; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToSingle(d));
A B C D E }
F
} }
G
The output is
H I
From From From From From From From From From
J K L M N
Double Double Double Double Double Double Double Double Double
1.79769313486232E+308 yields Infinity -1.79769313486232E+308 yields -Infinity Infinity yields Infinity -Infinity yields -Infinity 4.94065645841247E-324 yields 0 0 yields 0 5.5 yields 5.5 -5.5 yields -5.5 NaN yields NaN
O P
Convert.ToSingle(System.Single) Method
Q [ILASM]
R
.method public hidebysig static float32 ToSingle(float32 value)
S
[C#]
public static float ToSingle(float value)
T U
Summary
V
Converts a System.Single to a System.Single.
W
Parameters
X Y Z
Parameter
Description
value
The System.Single value to be converted.
850
Contents | Index
System
Convert ToSingle() Method
Description [Note: This method is provided for completeness.] This member must be implemented if the Extended Numerics Library is present in the implementation. A
Example
B
using System;
C
namespace Samples { public class ConvertToSingle { public static void Main() { float f = Single.MaxValue; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToSingle(f)); f = Single.MinValue; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToSingle(f)); f = Single.Epsilon; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToSingle(f)); f = 0f; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToSingle(f)); f = 25.5f; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToSingle(f)); f = -25.5f; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToSingle(f)); } } }
D E F G H I J K L M N O P Q R S T U
The output is
V From From From From From From
Single Single Single Single Single Single
3.402823E+38 yields 3.402823E+38 -3.402823E+38 yields -3.402823E+38 1.401298E-45 yields 1.401298E-45 0 yields 0 25.5 yields 25.5 -25.5 yields -25.5
W X Y Z
851
Contents | Index
Convert
System
ToSingle() Method
Convert.ToSingle(System.Int32) Method [ILASM]
.method public hidebysig static float32 ToSingle(int32 value)
A
[C#]
public static float ToSingle(int value)
B C
Summary
D
Converts a System.Int32 to a System.Single.
E
Parameters
F G
Parameter
Description
value
The 32-bit signed integer value to be converted.
H I J K
Description
L
This member must be implemented if the Extended Numerics Library is present in the implementation.
M N
Example
O
using System;
P
namespace Samples { public class ConvertToSingle { public static void Main() { int i = Int32.MaxValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToSingle(i)); i = 0; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToSingle(i)); i = Int32.MinValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToSingle(i)); } } }
Q R S T U V W X Y Z
852
Contents | Index
System
Convert ToSingle() Method
The output is From Int32 2147483647 yields 2.147484E+09 From Int32 0 yields 0 From Int32 -2147483648 yields -2.147484E+09
A B C
Convert.ToSingle(System.Int64) Method
D
[ILASM]
E
.method public hidebysig static float32 ToSingle(int64 value)
F
[C#]
public static float ToSingle(long value)
G
Summary
H
Converts a System.Int64 to a System.Single.
I J
Parameters
K
Parameter
Description
value
The 64-bit signed integer value to be converted.
L M N O
Description
P
This member must be implemented if the Extended Numerics Library is present in the implementation.
Q R
Example
S
using System;
T namespace Samples { public class ConvertToSingle { public static void Main() { long l = Int64.MaxValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToSingle(l)); l = 0; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToSingle(l));
U V W X Y Z
853
Contents | Index
Convert
System
ToSingle() Method
l = Int64.MinValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToSingle(l)); }
A
} }
B C
The output is
D From Int64 9223372036854775807 yields 9.223372E+18 From Int64 0 yields 0 From Int64 -9223372036854775808 yields -9.223372E+18
E F G H
Convert.ToSingle(System.Object) Method
I
[ILASM]
.method public hidebysig static float32 ToSingle(object value)
J
[C#]
public static float ToSingle(object value)
K L
Summary
M
Converts the value of the specified System.Object to a single-precision floating-point number.
N O
Parameters
P Q
Parameter
Description
value
A System.Object that implements the System.IConvertible interface or null.
R S T U
Return Value
V
A single-precision floating-point number equivalent to the value of value, or zero if value is null.
W X
Description
Y
The return value is the result of invoking the IConvertible.ToSingle method of the underlying type of value.
Z
854
Contents | Index
System
Convert ToSingle() Method
Exceptions Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
A B C D
Convert.ToSingle(System.Object, System.IFormatProvider) Method
E
[ILASM]
F
.method public hidebysig static float32 ToSingle(object value, class System.IFormatProvider provider)
G
[C#]
H
public static float ToSingle(object value, IFormatProvider provider)
I
Summary
J
Converts the value of the specified System.Object to a single-precision floating-point number using the specified culture-specific formatting information.
K L
Parameters
M
Parameter
Description
value
A System.Object that implements the System.IConvertible interface.
provider
A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
N O P Q R S
Return Value
T
A single-precision floating-point number equivalent to the value of value, or zero if value is null.
U V
Description
W
The return value is the result of invoking the IConvertible.ToSingle method of the underlying type of value. provider enables the user to specify culture-specific conversion information about the contents of value. For example, if value is a System.String that represents a number, provider could supply culture-specific information about the notation used to represent that number.
X Y Z
855
Contents | Index
Convert
System
ToSingle() Method
The base types ignore provider; however, it is honored if value is a user-defined type that implements the System.IConvertible interface. A
Exceptions
B C D
Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
E F G
Convert.ToSingle(System.SByte) Method
H
[ILASM]
.method public hidebysig static float32 ToSingle(int8 value)
I
[C#]
public static float ToSingle(sbyte value)
J K
Summary
L
Converts a System.SByte to a System.Single.
M
Parameters
N O
Parameter
Description
value
The System.SByte value to be converted.
P Q R
Description
S
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToSingle(System.Int16). This member must be implemented if the Extended Numerics Library is present in the implementation.
T U V
Example
W
using System;
X namespace Samples { public class ConvertToSingle { public static void Main()
Y Z
856
Contents | Index
System
Convert ToSingle() Method
{ sbyte s = SByte.MaxValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToSingle(s)); s = 0; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToSingle(s)); s = SByte.MinValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToSingle(s));
A B C D
}
E
}
F
}
G
The output is
H From Signed Byte 127 yields 127 From Signed Byte 0 yields 0 From Signed Byte -128 yields -128
I J K
Convert.ToSingle(System.Int16) Method
L
[ILASM]
M
.method public hidebysig static float32 ToSingle(int16 value)
N
[C#]
public static float ToSingle(short value)
O P
Summary
Q
Converts a System.Int16 to a System.Single.
R
Parameters
S
Parameter
Description
value
The 16-bit signed integer value to be converted.
T U V W
Description
X
This member must be implemented if the Extended Numerics Library is present in the implementation.
Y Z
857
Contents | Index
Convert
System
ToSingle() Method
Example using System; namespace Samples { public class ConvertToSingle { public static void Main() { short i = Int16.MaxValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToSingle(i)); i = 0; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToSingle(i)); i = Int16.MinValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToSingle(i)); } } }
A B C D E F G H I J K
The output is
L M
From Int16 32767 yields 32767 From Int16 0 yields 0 From Int16 -32768 yields -32768
N O P
Convert.ToSingle(System.String) Method
Q [ILASM]
R
.method public hidebysig static float32 ToSingle(string value) [C#]
S
public static float ToSingle(string value)
T
Summary
U
Converts a System.String to a System.Single.
V
Parameters
W X Y
Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Float | System.Globalization.NumberStyles.AllowThousands style.
Z
858
Contents | Index
System
Convert ToSingle() Method
Description This method parses value using the information in a System.Globalization.NumberFormatInfo instance initialized for the current system culture. This member must be implemented if the Extended Numerics Library is present in the implementation.
A B
Exceptions
C D
Exception
Condition
System.ArgumentNullException
value is a null reference.
System.FormatException
value cannot be converted to a numeric value.
G
The numeric value of value is greater than System.Single.MaxValue or less than System.Single.MinValue.
H
System.OverflowException
E F
I J K
Example
L
using System;
M namespace Samples { public class ConvertToSingle { public static void Main() { string s; try { s = Single.MaxValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToSingle(s)); s = Single.MinValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToSingle(s)); s = Single.Epsilon.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToSingle(s)); s = Single.PositiveInfinity.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToSingle(s)); s = Single.NegativeInfinity.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToSingle(s));
N O P Q R S T U V W X Y Z
859
Contents | Index
Convert
System
ToSingle() Method
s = Single.NaN.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToSingle(s)); s = " +0"; Console.WriteLine("From String {0} yields {1}", s, Convert.ToSingle(s)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToSingle(s));
A B C D
} catch(FormatException e) { Console.WriteLine("Exception: {0}", e); }
E F G
}
H
} }
I
The output is
J K
From String 3.402823E+38 yields 3.402823E+38 From String -3.402823E+38 yields -3.402823E+38 From String 1.401298E-45 yields 1.401298E-45 From String Infinity yields Infinity From String -Infinity yields -Infinity From String NaN yields NaN From String +0 yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseSingle(String s, NumberStyles style, NumberFormatInfo info) at System.Single.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToSingle(String value) at Samples.ConvertToSingle.Main() in C:\Books\BCL\Samples\System\Convert\ ToSingle\ToSingle(System.String)\Convert.cs:line 34
L M N O P Q R S T
Convert.ToSingle(System.String, System.IFormatProvider) Method
U
[ILASM]
V
.method public hidebysig static float32 ToSingle(string value, class System.IFormatProvider provider)
W
[C#]
X
public static float ToSingle(string value, IFormatProvider provider)
Y
Summary
Z
Converts a System.String to a System.Single.
860
Contents | Index
System
Convert ToSingle() Method
Parameters Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Float | System.Globalization.NumberStyles.AllowThousands style.
B
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
D
A
provider
C
E F
Description
G
This method parses value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is parsed using the formatting information of the current system culture. This member must be implemented if the Extended Numerics Library is present in the implementation.
H I J K
Exceptions
L M
Exception
Condition N
System.ArgumentNullException
value is a null reference.
O
System.FormatException
value cannot be converted to a numeric value.
P
The numeric value of value is greater than System.Single.MaxValue or less than System.Single.MinValue.
Q
System.OverflowException
R S T
Example
U
using System; using System.Globalization;
V W
namespace Samples { public class ConvertToSingle { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU");
X Y Z
861
Contents | Index
Convert
System
ToSingle() Method
NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; try { s = " ~0"; Console.WriteLine("From String {0} yields {1}", s, Convert.ToSingle(s, c)); s = "~" + Double.Epsilon.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToSingle(s, c)); s = Double.PositiveInfinity.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToSingle(s, c)); s = Double.NegativeInfinity.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToSingle(s, c)); s = Double.NaN.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToSingle(s, c)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToSingle(s, c)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = Single.MaxValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToSingle(s, c)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E F G H I J K L M N O P Q R S T }
U
}
V
}
W
The output is
X From String ~0 yields 0 From String ~4.94065645841247E-324 yields 0 From String Infinity yields Infinity From String -Infinity yields -Infinity From String NaN yields NaN Exception: System.FormatException: Input string was not in a correct format.
Y Z
862
Contents | Index
System
Convert ToSingle() Method
at System.Number.ParseSingle(String s, NumberStyles style, NumberFormatInfo info) at System.Single.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToSingle(String value, IFormatProvider provider) at Samples.ConvertToSingle.Main() in C:\Books\BCL\Samples\System\Convert\ ToSingle\ToSingle(System.String,System.IFormatProvider)\Convert.cs:line 32 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseSingle(String s, NumberStyles style, NumberFormatInfo info) at System.Single.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToSingle(String value, IFormatProvider provider) at Samples.ConvertToSingle.Main() in C:\Books\BCL\Samples\System\Convert\ ToSingle\ToSingle(System.String,System.IFormatProvider)\Convert.cs:line 42
A B C D E F
Convert.ToSingle(System.DateTime) Method
G
[ILASM]
H
.method public hidebysig static float32 ToSingle(valuetype System.DateTime value)
I
[C#]
J
public static float ToSingle(DateTime value)
K
Summary
L
Calling this method always throws System.InvalidCastException.
M N
Parameters
O
Parameter
Description
value
A System.DateTime.
P Q R S
Exceptions
T
Exception
Condition
System.InvalidCastException
This conversion is not supported.
U V W X
Convert.ToSingle(System.UInt32) Method
Y
[ILASM]
Z
.method public hidebysig static float32 ToSingle(unsigned int32 value) [C#]
public static float ToSingle(uint value)
863
Contents | Index
Convert
System
ToSingle() Method
Summary Converts a System.UInt32 to a System.Single. A
Parameters
B C D
Parameter
Description
value
The 32-bit unsigned integer value to be converted.
E F
Description
G
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToSingle(System.Int64). This member must be implemented if the Extended Numerics Library is present in the implementation.
H I
Example
J
using System;
K
namespace Samples { public class ConvertToSingle { public static void Main() { uint u = UInt32.MaxValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToSingle(u)); u = UInt32.MinValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToSingle(u)); } } }
L M N O P Q R S T
The output is
U V
From UInt32 4294967295 yields 4.294967E+09 From UInt32 0 yields 0
W X Y
Convert.ToSingle(System.UInt64) Method
Z
[ILASM]
.method public hidebysig static float32 ToSingle(unsigned int64 value) [C#]
public static float ToSingle(ulong value)
864
Contents | Index
System
Convert ToSingle() Method
Summary Converts a System.UInt64 to a System.Single. A
Parameters
B
Parameter
Description
value
The 64-bit unsigned integer value to be converted.
C D E
Description
F
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToSingle(System.Decimal). This member must be implemented if the Extended Numerics Library is present in the implementation.
G H I
Example
J
using System;
K namespace Samples { public class ConvertToSingle { public static void Main() { ulong u = UInt64.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToSingle(u)); u = UInt64.MinValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToSingle(u)); } } }
L M N O P Q R S T U
The output is
V
From UInt64 18446744073709551615 yields 1.844674E+19 From UInt64 0 yields 0
W X
Convert.ToSingle(System.UInt16) Method
Y
[ILASM]
Z
.method public hidebysig static float32 ToSingle(unsigned int16 value) [C#]
public static float ToSingle(ushort value)
865
Contents | Index
Convert
System
ToString() Method
Summary Converts a System.UInt16 to a System.Single. A
Parameters
B C D
Parameter
Description
value
The 16-bit unsigned integer value to be converted.
E F
Description
G
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToSingle(System.Int32). This member must be implemented if the Extended Numerics Library is present in the implementation.
H I
Example
J
using System;
K
namespace Samples { public class ConvertToSingle { public static void Main() { ushort u = UInt16.MaxValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToSingle(u)); u = UInt16.MinValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToSingle(u)); } } }
L M N O P Q R S T
The output is
U V
From UInt16 65535 yields 65535 From UInt16 0 yields 0
W X
Convert.ToString(System.Boolean) Method
Y
[ILASM]
Z
.method public hidebysig static string ToString(bool value) [C#]
public static string ToString(bool value)
866
Contents | Index
System
Convert ToString() Method
Summary Converts a System.Boolean to a System.String. A
Parameters
B
Parameter
Description
value
The System.Boolean value to be converted.
C D E
Return Value
F
Returns the value returned by value.ToString().
G
Description
H
[Note: See System.Boolean.ToString.]
I J
Example
K
using System;
L
namespace Samples { public class ConvertToString { public static void Main() { bool b = true; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToString(b)); b = false; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToString(b)); } } }
M N O P Q R S T U
The output is
V From Boolean True yields True From Boolean False yields False
W X Y Z
867
Contents | Index
Convert
System
ToString() Method
Convert.ToString(System.Boolean, System.IFormatProvider) Method [ILASM]
A
.method public hidebysig static string ToString(bool value, class System.IFormatProvider provider)
B
[C#]
public static string ToString(bool value, IFormatProvider provider)
C D
Summary
E
Converts the value of the specified Boolean to its equivalent System.String representation.
F
Parameters
G H I
Parameter
Description
value
A Boolean value.
provider
(Reserved) An instance of a System.IFormatProvider interface implementation.
J K L M
Description
N
This implementation is identical to System.Boolean.ToString.
O P
Convert.ToString(System.Byte) Method
Q [ILASM]
R
.method public hidebysig static string ToString(unsigned int8 value)
S
[C#]
public static string ToString(byte value)
T U
Summary
V
Converts a System.Byte to a System.String.
W
Parameters
X Y Z
Parameter
Description
value
The System.Byte value to be converted.
868
Contents | Index
System
Convert ToString() Method
Return Value Returns the value returned by value.ToString().
Description
A
[Note: See System.Byte.ToString.]
B C
Example
D
using System;
E namespace Samples { public class ConvertToString { public static void Main() { byte b = Byte.MaxValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToString(b)); b = Byte.MinValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToString(b)); } } }
F G H I J K L M N O
The output is
P
From Byte 255 yields 255 From Byte 0 yields 0
Q R S
Convert.ToString(System.Byte, System.Int32) Method
T
[ILASM]
U
.method public hidebysig static string ToString(unsigned int8 value, int32 toBase)
V
[C#]
public static string ToString(byte value, int toBase)
W
Summary
X
Converts the value of an 8-bit unsigned integer to its equivalent System.String representation in a specified base.
Y Z
869
Contents | Index
Convert
System
ToString() Method
Parameters Parameter
Description
value
An 8-bit unsigned integer.
toBase
The base of the return value, which must be 2, 8, 10, or 16.
A B C D E
Exceptions
F G H
Exception
Condition
System.ArgumentException
toBase is not 2, 8, 10, or 16.
I J K
Convert.ToString(System.Byte, System.IFormatProvider) Method
L
[ILASM]
M
.method public hidebysig static string ToString(unsigned int8 value, class System.IFormatProvider provider) [C#]
N
public static string ToString(byte value, IFormatProvider provider)
O P
Summary
Q
Converts a System.Byte to a System.String.
R
Parameters
S T U
Parameter
Description
value
The System.Byte value to be converted.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
V W X Y
Return Value
Z
Returns the value returned by value.ToString(provider).
870
Contents | Index
System
Convert ToString() Method
Description This method converts value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is formatted in accordance with the current system culture. [Note: See System.Byte.ToString.]
A B C
Example
D
using System; using System.Globalization;
E F
namespace Samples { public class ConvertToString { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); byte b = Byte.MaxValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToString(b, c)); b = Byte.MinValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToString(b, c)); } } }
G H I J K L M N O P Q
The output is
R From Byte 255 yields 255 From Byte 0 yields 0
S T U
Convert.ToString(System.Char) Method
V [ILASM]
W
.method public hidebysig static string ToString(valuetype System.Char value) [C#]
X
public static string ToString(char value)
Y
Summary
Z
Converts a System.Char to a System.String.
871
Contents | Index
Convert
System
ToString() Method
Parameters Parameter
Description
value
The System.Char to be converted.
A B C
Example
D
using System;
E
namespace Samples { public class ConvertToString { public static void Main() { Char c = 'A'; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToString(c)); c = 'a'; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToString(c)); c = Char.MinValue; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToString(c)); } } }
F G H I J K L M N O P Q
The output is
R
From Char ? yields ? From Char A yields A From Char yields
S T U
Convert.ToString(System.Char, System.IFormatProvider) Method
V
[ILASM]
W
.method public hidebysig static string ToString(valuetype System.Char value, class System.IFormatProvider provider)
X
[C#]
Y
public static string ToString(char value, IFormatProvider provider)
Z
872
Contents | Index
System
Convert ToString() Method
Summary Converts the value of the specified Unicode character to its equivalent System.String representation. A
Parameters
B C
Parameter
Description
value
A Unicode character.
E
provider
A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
F
D
G H
Description
I
This implementation is identical to System.Char.ToString.
J K
Convert.ToString(System.Decimal) Method
L
[ILASM]
M
.method public hidebysig static string ToString(decimal value)
N
[C#]
public static string ToString(decimal value)
O
Summary
P
Converts a System.Decimal to a System.String.
Q R
Parameters
S
Parameter
Description
value
The System.Decimal value to be converted.
T U V W
Return Value
X
Returns the value returned by value.ToString().
Y
Description
Z
[Note: See System.Decimal.ToString.] This member must be implemented if the Extended Numerics Library is present in the implementation. 873
Contents | Index
Convert
System
ToString() Method
Example using System; namespace Samples { public class ConvertToString { public static void Main() { Decimal d = Decimal.MaxValue; Console.WriteLine("From Decimal {0} yields d, Convert.ToString(d)); d = Decimal.MinValue; Console.WriteLine("From Decimal {0} yields d, Convert.ToString(d)); d = Decimal.One; Console.WriteLine("From Decimal {0} yields d, Convert.ToString(d)); d = Decimal.Zero; Console.WriteLine("From Decimal {0} yields d, Convert.ToString(d)); d = Decimal.MinusOne; Console.WriteLine("From Decimal {0} yields d, Convert.ToString(d)); } } }
A B C D E F G H I J K L M N O P
{1}",
{1}",
{1}",
{1}",
{1}",
The output is
Q From From From From From
R S T
Decimal Decimal Decimal Decimal Decimal
79228162514264337593543950335 yields 79228162514264337593543950335 -79228162514264337593543950335 yields -79228162514264337593543950335 1 yields 1 0 yields 0 -1 yields -1
U V
Convert.ToString(System.Decimal, System.IFormatProvider) Method
W
[ILASM]
X
.method public hidebysig static string ToString(decimal value, class System.IFormatProvider provider)
Y
[C#]
public static string ToString(decimal value, IFormatProvider provider)
Z
874
Contents | Index
System
Convert ToString() Method
Summary Converts a System.Decimal to a System.String. A
Parameters
B
Parameter
Description
C
value
The System.Decimal value to be converted.
D
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
E F G
Return Value
H
Returns the value returned by value.ToString(provider).
I J
Description
K
This method converts value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is formatted in accordance with the current system culture. [Note: See System.Decimal.ToString.] This member must be implemented if the Extended Numerics Library is present in the implementation.
L M N O P
Example
Q
using System; using System.Globalization;
R S
namespace Samples { public class ConvertToString { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "!"; n.NegativeSign = "~"; Decimal d = Decimal.MaxValue; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToString(d, c)); d = Decimal.MinValue;
T U V W X Y Z
875
Contents | Index
Convert
System
ToString() Method
Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToString(d, c)); d = Decimal.One; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToString(d, c)); d = Decimal.Zero; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToString(d, c)); d = Decimal.MinusOne; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToString(d, c));
A B C D E }
F
} }
G
The output is
H I
From From From From From
J K L
Decimal Decimal Decimal Decimal Decimal
79228162514264337593543950335 yields 79228162514264337593543950335 -79228162514264337593543950335 yields ~79228162514264337593543950335 1 yields 1 0 yields 0 -1 yields ~1
M N
Convert.ToString(System.Double) Method
O
[ILASM]
.method public hidebysig static string ToString(float64 value)
P
[C#]
public static string ToString(double value)
Q R
Summary
S
Converts a System.Double to a System.String.
T
Parameters
U V
Parameter
Description
value
The System.Double value to be converted.
W X Y
Return Value
Z
Returns the value returned by value.ToString().
876
Contents | Index
System
Convert ToString() Method
Description [Note: See System.Double.ToString.] This member must be implemented if the Extended Numerics Library is present in the implementation. A
Example
B
using System;
C
namespace Samples { public class ConvertToString { public static void Main() { Double d = Double.MaxValue; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToString(d)); d = Double.MinValue; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToString(d)); d = Double.Epsilon; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToString(d)); d = Double.PositiveInfinity; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToString(d)); d = Double.NegativeInfinity; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToString(d)); d = 0.0; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToString(d)); d = Double.NaN; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToString(d)); } } }
D E F G H I J K L M N O P Q R S T U V
The output is From From From From From From From
Double Double Double Double Double Double Double
W X
1.79769313486232E+308 yields 1.79769313486232E+308 -1.79769313486232E+308 yields -1.79769313486232E+308 4.94065645841247E-324 yields 4.94065645841247E-324 Infinity yields Infinity -Infinity yields -Infinity 0 yields 0 NaN yields NaN
Y Z
877
Contents | Index
Convert
System
ToString() Method
Convert.ToString(System.Double, System.IFormatProvider) Method [ILASM]
A
.method public hidebysig static string ToString(float64 value, class System.IFormatProvider provider)
B
[C#]
public static string ToString(double value, IFormatProvider provider)
C D
Summary
E
Converts a System.Double to a System.String.
F
Parameters
G H I
Parameter
Description
value
The System.Double value to be converted.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
J K L M
Return Value
N
Returns the value returned by value.ToString(provider).
O
Description
P
This method converts value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is formatted in accordance with the current system culture. [Note: See System.Double.ToString.] This member must be implemented if the Extended Numerics Library is present in the implementation.
Q R S T U V
Example
W
using System; using System.Globalization;
X namespace Samples { public class ConvertToString { public static void Main() {
Y Z
878
Contents | Index
System
Convert ToString() Method
CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "!"; n.NegativeSign = "~"; Double d = Double.MaxValue; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToString(d, c)); d = Double.MinValue; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToString(d, c)); d = Double.Epsilon; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToString(d, c)); d = Double.PositiveInfinity; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToString(d, c)); d = Double.NegativeInfinity; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToString(d, c)); d = 0.0; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToString(d, c)); d = Double.NaN; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToString(d, c));
A B C D E F G H I J K L M N
} }
O
}
P
The output is From From From From From From From
Double Double Double Double Double Double Double
Q
1.79769313486232E+308 yields 1.79769313486232E!308 -1.79769313486232E+308 yields ~1.79769313486232E!308 4.94065645841247E-324 yields 4.94065645841247E~324 Infinity yields Infinity -Infinity yields -Infinity 0 yields 0 NaN yields NaN
R S T U V W
Convert.ToString(System.Single) Method
X
[ILASM]
Y
.method public hidebysig static string ToString(float32 value)
Z
[C#]
public static string ToString(float value)
879
Contents | Index
Convert
System
ToString() Method
Summary Converts a System.Single to a System.String. A
Parameters
B C D
Parameter
Description
value
The System.Single value to be converted.
E F
Return Value
G
Returns the value returned by value.ToString().
H
Description
I J
[Note: See System.Single.ToString.] This member must be implemented if the Extended Numerics Library is present in the implementation.
K
Example
L
using System;
M
namespace Samples { public class ConvertToString { public static void Main() { float f = Single.MaxValue; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToString(f)); f = Single.MinValue; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToString(f)); f = Single.PositiveInfinity; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToString(f)); f = Single.NegativeInfinity; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToString(f)); f = Single.NaN; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToString(f)); f = 0; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToString(f)); } } }
N O P Q R S T U V W X Y Z
880
Contents | Index
System
Convert ToString() Method
The output is From From From From From From
Single Single Single Single Single Single
3.402823E+38 yields 3.402823E+38 -3.402823E+38 yields -3.402823E+38 Infinity yields Infinity -Infinity yields -Infinity NaN yields NaN 0 yields 0
A B C D E
Convert.ToString(System.Single, System.IFormatProvider) Method
F [ILASM]
G
.method public hidebysig static string ToString(float32 value, class System.IFormatProvider provider)
H
[C#]
I
public static string ToString(float value, IFormatProvider provider)
J
Summary
K
Converts a System.Single to a System.String.
L
Parameters
M N
Parameter
Description
value
The System.Single value to be converted.
P
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
Q
O
R S
Return Value
T
Returns the value returned by value.ToString(provider).
U
Description
V
This method converts value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is formatted in accordance with the current system culture. [Note: See System.Single.ToString.] This member must be implemented if the Extended Numerics Library is present in the implementation.
W X Y Z
881
Contents | Index
Convert
System
ToString() Method
Example using System; using System.Globalization;
A namespace Samples { public class ConvertToString { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "!"; n.NegativeSign = "~"; float f = Single.MaxValue; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToString(f, c)); f = Single.MinValue; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToString(f, c)); f = Single.PositiveInfinity; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToString(f, c)); f = Single.NegativeInfinity; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToString(f, c)); f = Single.NaN; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToString(f, c)); f = 0; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToString(f, c)); } } }
B C D E F G H I J K L M N O P Q R S T U
The output is
V
From From From From From From
W X Y
Single Single Single Single Single Single
3.402823E+38 yields 3.402823E!38 -3.402823E+38 yields ~3.402823E!38 Infinity yields Infinity -Infinity yields -Infinity NaN yields NaN 0 yields 0
Z
882
Contents | Index
System
Convert ToString() Method
Convert.ToString(System.Int32) Method [ILASM]
.method public hidebysig static string ToString(int32 value) [C#]
A
public static string ToString(int value)
B C
Summary
D
Converts a System.Int32 to a System.String.
E
Parameters
F
Parameter
Description
value
The 32-bit signed integer value to be converted.
G H I J
Return Value
K
Returns the value returned by value.ToString().
L M
Description
N
[Note: See System.Int32.ToString.]
O
Example
P
using System;
Q
namespace Samples { public class ConvertToString { public static void Main() { int i = Int32.MaxValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToString(i)); i = 0; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToString(i)); i = Int32.MinValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToString(i)); } } }
R S T U V W X Y Z
883
Contents | Index
Convert
System
ToString() Method
The output is From Int32 2147483647 yields 2147483647 From Int32 0 yields 0 From Int32 -2147483648 yields -2147483648
A B C
Convert.ToString(System.Int32, System.Int32) Method
D
[ILASM]
E
.method public hidebysig static string ToString(int32 value, int32 toBase)
F
[C#]
public static string ToString(int value, int toBase)
G H
Summary
I
Converts the value of a 32-bit signed integer to its equivalent System.String representation in a specified base.
J K
Parameters
L M
Parameter
Description
N
value
A 32-bit signed integer.
toBase
The base of the return value, which must be 2, 8, 10, or 16.
O P Q
Exceptions
R S
Exception
Condition
System.ArgumentException
toBase is not 2, 8, 10, or 16.
T U V W
Convert.ToString(System.Int32, System.IFormatProvider) Method
X
[ILASM]
Y
.method public hidebysig static string ToString(int32 value, class System.IFormatProvider provider)
Z
[C#]
public static string ToString(int value, IFormatProvider provider)
884
Contents | Index
System
Convert ToString() Method
Summary Converts a System.Int32 to a System.String. A
Parameters
B
Parameter
Description
C
value
The 32-bit signed integer value to be converted.
D
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
E F G
Return Value
H
Returns the value returned by value.ToString(provider).
I J
Description
K
This method converts value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is formatted in accordance with the current system culture. [Note: See System.Int32.ToString.]
L M N O
Example
P
using System;
Q
namespace Samples { public class ConvertToString { public static void Main() { uint u = UInt32.MaxValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToString(u)); u = UInt32.MinValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToString(u)); } } }
R S T U V W X Y Z
885
Contents | Index
Convert
System
ToString() Method
The output is From UInt32 4294967295 yields 4294967295 From UInt32 0 yields 0
A B C
Convert.ToString(System.Int64) Method
D
[ILASM]
.method public hidebysig static string ToString(int64 value)
E
[C#]
public static string ToString(long value)
F G
Summary
H
Converts a System.Int64 to a System.String.
I
Parameters
J K
Parameter
Description
value
The 64-bit signed integer value to be converted.
L M N O
Return Value
P
Returns the value returned by value.ToString().
Q
Description
R
[Note: See System.Int64.ToString.]
S
Example
T
using System;
U namespace Samples { public class ConvertToString { public static void Main() { long l = Int64.MaxValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToString(l)); l = 0;
V W X Y Z
886
Contents | Index
System
Convert ToString() Method
Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToString(l)); l = Int64.MinValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToString(l));
A
}
B
}
C
}
D
The output is
E From Int64 9223372036854775807 yields 9223372036854775807 From Int64 0 yields 0 From Int64 -9223372036854775808 yields -9223372036854775808
F G H
Convert.ToString(System.Int64, System.Int32) Method
I
[ILASM]
J
.method public hidebysig static string ToString(int64 value, int32 toBase)
K
[C#]
L
public static string ToString(long value, int toBase)
M
Summary
N
Converts the value of a 64-bit signed integer to its equivalent System.String representation in a specified base.
O P
Parameters
Q
Parameter
Description
value
A 64-bit signed integer.
toBase
The base of the return value, which must be 2, 8, 10, or 16.
R S T U V
Return Value
W
The System.String representation of value in base toBase.
X Y Z
887
Contents | Index
Convert
System
ToString() Method
Exceptions Exception
Condition
System.ArgumentException
toBase is not 2, 8, 10, or 16.
A B C D
Convert.ToString(System.Int64, System.IFormatProvider) Method
E
[ILASM]
F
.method public hidebysig static string ToString(int64 value, class System.IFormatProvider provider)
G
[C#]
H
public static string ToString(long value, IFormatProvider provider)
I
Summary
J
Converts a System.Int64 to a System.String.
K
Parameters
L M N O
Parameter
Description
value
The 64-bit signed integer value to be converted.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
P Q R S
Return Value
T
Returns the value returned by value.ToString(provider).
U
Description
V
This method converts value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is formatted in accordance with the current system culture. [Note: See System.Int64.ToString.]
W X Y Z
888
Contents | Index
System
Convert ToString() Method
Example using System; using System.Globalization;
A namespace Samples { public class ConvertToString { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "!"; n.NegativeSign = "~"; long l = Int64.MaxValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToString(l, c)); l = 0; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToString(l, c)); l = Int64.MinValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToString(l, c)); } } }
B C D E F G H I J K L M N O
The output is
P
From Int64 9223372036854775807 yields 9223372036854775807 From Int64 0 yields 0 From Int64 -9223372036854775808 yields ~9223372036854775808
Q R S T
Convert.ToString(System.Object) Method
U [ILASM]
V
.method public hidebysig static string ToString(object value) [C#]
W
public static string ToString(object value)
X
Summary
Y
Converts the value of the specified System.Object to its System.String representation.
Z
889
Contents | Index
Convert
System
ToString() Method
Parameters Parameter
Description
value
A System.Object or null.
A B C D
Return Value
E
The System.String representation of the value of value, or System.String.Empty if value is null.
F G
Description
H
The return value is the result of invoking the ToString method of the underlying type of value.
I J K
Convert.ToString(System.Object, System.IFormatProvider) Method
L
[ILASM]
M
.method public hidebysig static string ToString(object value, class System.IFormatProvider provider)
N
[C#]
public static string ToString(object value, IFormatProvider provider)
O P
Summary
Q
Converts the value of the specified System.Object to its equivalent System.String representation using the specified culture-specific formatting information.
R S
Parameters
T U
Parameter
Description
V
value
A System.Object or null.
provider
A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
W X Y Z
890
Contents | Index
System
Convert ToString() Method
Return Value The System.String representation of the value of value, or System.String.Empty if value is null. A
Description
B
provider enables the user to specify culture-specific conversion information about the contents of value. For example, if value is a System.String that represents a number, provider could supply culture-specific information about the notation used to represent that number. The base types ignore provider; however, it is honored if value is a user-defined type that implements the System.IConvertible interface. The return value is the result of invoking the IConvertible.ToString method of the underlying type of value if the underlying type implements the IConvertible interface; otherwise, the return value is the result of invoking the ToString method of the underlying type.
C D E F G H I J
Convert.ToString(System.SByte) Method
K
[ILASM]
L
.method public hidebysig static string ToString(int8 value) [C#]
M
public static string ToString(sbyte value)
N
Summary
O
Converts a System.SByte to a System.String.
P Q
Parameters
R
Parameter
Description
value
The System.SByte value to be converted.
S T U V
Return Value
W
Returns the value returned by value.ToString().
X
Description
Y
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToString(System.Int16). [Note: See System.SByte.ToString.]
Z
891
Contents | Index
Convert
System
ToString() Method
Example using System; namespace Samples { public class ConvertToString { public static void Main() { sbyte s = SByte.MaxValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToString(s)); s = 0; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToString(s)); s = SByte.MinValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToString(s)); } } }
A B C D E F G H I J K L
The output is
M
From Signed Byte 127 yields 127 From Signed Byte 0 yields 0 From Signed Byte -128 yields -128
N O P Q
Convert.ToString(System.SByte, System.IFormatProvider) Method
R
[ILASM]
S
.method public hidebysig static string ToString(int8 value, class System.IFormatProvider provider)
T
[C#]
public static string ToString(sbyte value, IFormatProvider provider)
U V
Summary
W
Converts a System.SByte to a System.String.
X Y Z
892
Contents | Index
System
Convert ToString() Method
Parameters Parameter
Description
value
The System.SByte value to be converted.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
A B C D E
Return Value
F
Returns the value returned by value.ToString(provider).
G
Description
H
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToString(System.Int16, System.IFormatProvider). This method converts value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is formatted in accordance with the current system culture. [Note: See System.SByte.ToString.]
I J K L M N
Example
O
using System; using System.Globalization;
P Q
namespace Samples { public class ConvertToString { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "!"; n.NegativeSign = "~"; sbyte s = SByte.MaxValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToString(s, c)); s = 0; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToString(s, c)); s = SByte.MinValue;
R S T U V W X Y Z
893
Contents | Index
Convert
System
ToString() Method
Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToString(s, c)); } }
A
}
B
The output is
C
From Signed Byte 127 yields 127 From Signed Byte 0 yields 0 From Signed Byte -128 yields ~128
D E F G
Convert.ToString(System.Int16) Method
H
[ILASM]
I
.method public hidebysig static string ToString(int16 value) [C#]
J
public static string ToString(short value)
K
Summary
L
Converts a System.Int16 to a System.String.
M N
Parameters
O P Q
Parameter
Description
value
The 16-bit signed integer value to be converted.
R S
Return Value
T
Returns the value returned by value.ToString().
U
Description
V
[Note: See System.Int16.ToString.]
W X Y Z
894
Contents | Index
System
Convert ToString() Method
Example using System; namespace Samples { public class ConvertToString { public static void Main() { short i = Int16.MaxValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToString(i)); i = 0; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToString(i)); i = Int16.MinValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToString(i)); } } }
A B C D E F G H I J K L
The output is
M
From Int16 32767 yields 32767 From Int16 0 yields 0 From Int16 -32768 yields -32768
N O P Q
Convert.ToString(System.Int16, System.Int32) Method
R
[ILASM]
S
.method public hidebysig static string ToString(int16 value, int32 toBase) [C#]
T
public static string ToString(short value, int toBase)
U
Summary
V
Converts the value of a 16-bit signed integer to its equivalent System.String representation in a specified base.
W X Y Z
895
Contents | Index
Convert
System
ToString() Method
Parameters Parameter
Description
value
A 16-bit signed integer.
toBase
The base of the return value, which must be 2, 8, 10, or 16.
A B C D E
Exceptions
F G H
Exception
Condition
System.ArgumentException
toBase is not 2, 8, 10, or 16.
I J K
Convert.ToString(System.Int16, System.IFormatProvider) Method
L
[ILASM]
M
.method public hidebysig static string ToString(int16 value, class System.IFormatProvider provider) [C#]
N
public static string ToString(short value, IFormatProvider provider)
O P
Summary
Q
Converts a System.Int16 to a System.String.
R
Parameters
S T U
Parameter
Description
value
The 16-bit signed integer value to be converted.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
V W X Y
Return Value
Z
Returns the value returned by value.ToString(provider).
896
Contents | Index
System
Convert ToString() Method
Description This method converts value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is formatted in accordance with the current system culture. [Note: See System.Int16.ToString.]
A B C
Example
D
using System; using System.Globalization;
E F
namespace Samples { public class ConvertToString { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "!"; n.NegativeSign = "~"; short i = Int16.MaxValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToString(i, c)); i = 0; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToString(i, c)); i = Int16.MinValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToString(i, c)); } } }
G H I J K L M N O P Q R S T
The output is
U From Int16 32767 yields 32767 From Int16 0 yields 0 From Int16 -32768 yields ~32768
V W X
Convert.ToString(System.String) Method
Y
[ILASM]
Z
.method public hidebysig static string ToString(string value) [C#]
public static string ToString(string value)
897
Contents | Index
Convert
System
ToString() Method
Summary Returns the specified string. A
Parameters
B C
Parameter
Description
D
value
A System.String.
E F
Return Value
G
value is returned unchanged.
H
Description
I
[Note: This method is provided for completeness.]
J K
Example
L
using System;
M
namespace Samples { public class ConvertToString { public static void Main() { string s = Boolean.FalseString; Console.WriteLine("From String {0} yields {1}", s, Convert.ToString(s)); s = Boolean.TrueString; Console.WriteLine("From String {0} yields {1}", s, Convert.ToString(s)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToString(s)); s = DateTime.Now.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToString(s)); } } }
N O P Q R S T U V W X Y Z
898
Contents | Index
System
Convert ToString() Method
The output is From From From From
String False yields False String True yields True String yields String 6/06/2003 2:04:00 AM yields 6/06/2003 2:04:00 AM
A B C D
Convert.ToString(System.String, System.IFormatProvider) Method
E
[ILASM]
.method public hidebysig static string ToString(string value, class System.IFormatProvider provider)
F G
[C#]
public static string ToString(string value, IFormatProvider provider)
H
Summary
I
Returns the specified instance of System.String; no actual conversion is performed.
J K
Parameters
L
Parameter
Description
value
A System.String.
provider
A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
M N O P Q R
Return Value
S
Parameter value is returned unchanged.
T
Description
U
This method ignores the provider parameter.
V W X
Convert.ToString(System.DateTime) Method
Y
[ILASM]
.method public hidebysig static string ToString(valuetype System.DateTime value)
Z
[C#]
public static string ToString(DateTime value)
899
Contents | Index
Convert
System
ToString() Method
Summary Converts a System.DateTime value to a System.String. A
Parameters
B C
Parameter
Description
D
value
The System.DateTime value to be converted.
E F
Return Value
G
Returns the value returned by value.ToString().
H
Description
I
[Note: See System.DateTime.ToString.]
J K
Example
L
using System;
M
namespace Samples { public class ConvertToString { public static void Main() { DateTime dt = DateTime.MaxValue; Console.WriteLine("From DateTime {0} yields {1}", dt, Convert.ToString(dt)); dt = DateTime.Now; Console.WriteLine("From DateTime {0} yields {1}", dt, Convert.ToString(dt)); dt = DateTime.MinValue; Console.WriteLine("From DateTime {0} yields {1}", dt, Convert.ToString(dt)); } } }
N O P Q R S T U V W X
The output is
Y Z
From DateTime 31/12/9999 11:59:59 PM yields 31/12/9999 11:59:59 PM From DateTime 6/06/2003 1:43:34 AM yields 6/06/2003 1:43:34 AM From DateTime 1/01/0001 12:00:00 AM yields 1/01/0001 12:00:00 AM
900
Contents | Index
System
Convert ToString() Method
Convert.ToString(System.DateTime, System.IFormatProvider) Method [ILASM]
.method public hidebysig static string ToString(valuetype System.DateTime value, class System.IFormatProvider provider)
A
[C#]
B
public static string ToString(DateTime value, IFormatProvider provider)
C
Summary
D
Converts a System.DateTime value to a System.String.
E F
Parameters
G
Parameter
Description
value
The System.DateTime value to be converted.
provider
A System.IFormatProvider that supplies a System.Globalization.DateTimeFormatInfo containing culture-specific formatting information.
H I J K L M
Return Value
N
Returns the value returned by value.ToString(provider).
O P
Description
Q
This method converts value using the information in the System.Globalization.DateTimeFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.DateTimeFormatInfo cannot be obtained from provider, the string is formatted in accordance with the current system culture. [Note: See System.DateTime.ToString.]
R S T U
Example
V
using System; using System.Globalization;
W X
namespace Samples { public class ConvertToString { public static void Main() {
Y Z
901
Contents | Index
Convert
System
ToString() Method
CultureInfo c = new CultureInfo("en-AU"); DateTime dt = DateTime.MaxValue; Console.WriteLine("From DateTime {0} yields {1}", dt, Convert.ToString(dt, c)); dt = DateTime.Now; Console.WriteLine("From DateTime {0} yields {1}", dt, Convert.ToString(dt, c)); dt = DateTime.MinValue; Console.WriteLine("From DateTime {0} yields {1}", dt, Convert.ToString(dt, c));
A B C D }
E }
F
}
G
The output is
H From DateTime 31/12/9999 11:59:59 PM yields 12/31/9999 11:59:59 PM From DateTime 6/06/2003 1:46:33 AM yields 6/6/2003 1:46:33 AM From DateTime 1/01/0001 12:00:00 AM yields 1/1/0001 12:00:00 AM
I J K L
Convert.ToString(System.UInt32) Method
M
[ILASM]
N
.method public hidebysig static string ToString(unsigned int32 value) [C#]
O
public static string ToString(uint value)
P
Summary
Q
Converts a System.UInt32 to a System.String.
R S
Parameters
T U V
Parameter
Description
value
The 32-bit unsigned integer value to be converted.
W X
Return Value
Y
Returns the value returned by value.ToString().
Z
902
Contents | Index
System
Convert ToString() Method
Description This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToString(System.Int64). [Note: See System.UInt32.ToString.]
A B
Example
C
using System;
D namespace Samples { public class ConvertToString { public static void Main() { uint u = UInt32.MaxValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToString(u)); u = UInt32.MinValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToString(u)); } } }
E F G H I J K L M N
The output is
O
From UInt32 4294967295 yields 4294967295 From UInt32 0 yields 0
P Q R
Convert.ToString(System.UInt32, System.IFormatProvider) Method
S
[ILASM]
T
.method public hidebysig static string ToString(unsigned int32 value, class System.IFormatProvider provider)
U
[C#]
V
public static string ToString(uint value, IFormatProvider provider)
W
Summary
X
Converts a System.UInt32 to a System.String.
Y Z
903
Contents | Index
Convert
System
ToString() Method
Parameters Parameter
Description
value
The 32-bit unsigned integer value to be converted.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
A B C D E
Return Value
F
Returns the value returned by value.ToString(provider).
G H
Description
I
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToString(System.Int64, System.IFormatProvider). This method converts value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is formatted in accordance with the current system culture. [Note: See System.UInt32.ToString.]
J K L M N O
Example
P
using System; using System.Globalization;
Q namespace Samples { public class ConvertToString { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); uint u = UInt32.MaxValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToString(u, c)); u = UInt32.MinValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToString(u, c)); } } }
R S T U V W X Y Z
904
Contents | Index
System
Convert ToString() Method
The output is From UInt32 4294967295 yields 4294967295 From UInt32 0 yields 0
A B
Convert.ToString(System.UInt64) Method
C
[ILASM]
D
.method public hidebysig static string ToString(unsigned int64 value)
E
[C#]
public static string ToString(ulong value)
F G
Summary
H
Converts a System.UInt64 to a System.String.
I
Parameters Parameter
J K
Description
L
value
The 64-bit unsigned integer value to be converted.
M N
Return Value
O
Returns the value returned by value.ToString().
P Q
Description
R
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToString(System.Decimal). [Note: See System.UInt64.ToString.]
S T U
Example
V
using System;
W
namespace Samples { public class ConvertToString { public static void Main() { ulong u = UInt64.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}",
X Y Z
905
Contents | Index
Convert
System
ToString() Method
u, Convert.ToString(u)); u = UInt64.MinValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToString(u));
A
} }
B }
C
The output is
D E
From UInt64 18446744073709551615 yields 18446744073709551615 From UInt64 0 yields 0
F G H
Convert.ToString(System.UInt64, System.IFormatProvider) Method
I
[ILASM]
J
.method public hidebysig static string ToString(unsigned int64 value, class System.IFormatProvider provider)
K
[C#]
public static string ToString(ulong value, IFormatProvider provider)
L M
Summary
N
Converts a System.UInt64 to a System.String.
O
Parameters
P Q R
Parameter
Description
value
The 64-bit unsigned integer value to be converted.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
S T U V
Return Value
W
Returns the value returned by value.ToString(provider).
X Y
Description
Z
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToString(System.Decimal, System.IFormatProvider).
906
Contents | Index
System
Convert ToString() Method
This method converts value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is formatted in accordance with the current system culture. [Note: See System.UInt64.ToString.]
A B C
Example using System; using System.Globalization;
D
namespace Samples { public class ConvertToString { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); ulong u = UInt64.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToString(u, c)); u = UInt64.MinValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToString(u, c)); } } }
F
E
G H I J K L M N O P
The output is
Q From UInt64 18446744073709551615 yields 18446744073709551615 From UInt64 0 yields 0
R S T
Convert.ToString(System.UInt16) Method
U [ILASM]
V
.method public hidebysig static string ToString(unsigned int16 value) [C#]
W
public static string ToString(ushort value)
X
Summary
Y
Converts a System.UInt16 to a System.String.
Z
907
Contents | Index
Convert
System
ToString() Method
Parameters Parameter
Description
value
The 16-bit unsigned integer value to be converted.
A B C D
Return Value
E
Returns the value returned by value.ToString().
F
Description
G
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToString(System.Int32). [Note: See System.UInt16.ToString.]
H I J
Example
K
using System;
L
namespace Samples { public class ConvertToString { public static void Main() { ushort u = UInt16.MaxValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToString(u)); u = UInt16.MinValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToString(u)); } } }
M N O P Q R S T U V
The output is
W
From UInt16 65535 yields 65535 From UInt16 0 yields 0
X Y Z
908
Contents | Index
System
Convert ToString() Method
Convert.ToString(System.UInt16, System.IFormatProvider) Method [ILASM]
.method public hidebysig static string ToString(unsigned int16 value, class System.IFormatProvider provider)
A
[C#]
B
public static string ToString(ushort value, IFormatProvider provider)
C
Summary
D
Converts a System.UInt16 to a System.String.
E F
Parameters
G
Parameter
Description
value
The 16-bit unsigned integer value to be converted.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
H I J K L
Return Value
M
Returns the value returned by value.ToString(provider).
N O
Description
P
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToString(System.Int32, System.IFormatProvider). This method converts value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is formatted in accordance with the current system culture. [Note: See System.UInt16.ToString.]
Q R S T U
Example
V
using System; using System.Globalization;
W
namespace Samples { public class ConvertToString { public static void Main()
Y
X
Z
909
Contents | Index
Convert
System
ToUInt16() Method
{ CultureInfo c = new CultureInfo("en-AU"); ushort u = UInt16.MaxValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToString(u, c)); u = UInt16.MinValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToString(u, c));
A B C }
D
} }
E F
The output is
G From UInt16 65535 yields 65535 From UInt16 0 yields 0
H I J
Convert.ToUInt16(System.Boolean) Method
K [ILASM]
L
.method public hidebysig static unsigned int16 ToUInt16(bool value) [C#]
M
public static ushort ToUInt16(bool value)
N
Summary
O
Converts a System.Boolean to a System.UInt16.
P Q
Parameters
R S
Parameter
Description
T
value
The System.Boolean value to be converted.
U V
Return Value
W
If value is true, returns 1; if value is false, returns 0.
X Y
Description
Z
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt32(System.Boolean).
910
Contents | Index
System
Convert ToUInt16() Method
Example using System; namespace Samples { public class ConvertToUInt16 { public static void Main() { bool b = true; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToUInt16(b)); b = false; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToUInt16(b)); } } }
A B C D E F G H I J
The output is
K L
From Boolean True yields 1 From Boolean False yields 0
M N
Convert.ToUInt16(System.Byte) Method
O
[ILASM]
P
.method public hidebysig static unsigned int16 ToUInt16(unsigned int8 value)
Q
[C#]
public static ushort ToUInt16(byte value)
R
Summary
S
Converts a System.Byte to a System.UInt16.
T U
Parameters
V
Parameter
Description
value
The System.Byte value to be converted.
W X Y Z
911
Contents | Index
Convert
System
ToUInt16() Method
Description This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt32(System.Byte). A B
Example
C
using System;
D
namespace Samples { public class ConvertToUInt16 { public static void Main() { byte b = Byte.MaxValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToUInt16(b)); b = Byte.MinValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToUInt16(b)); } } }
E F G H I J K L M
The output is
N O
From Byte 255 yields 255 From Byte 0 yields 0
P Q R
Convert.ToUInt16(System.Char) Method
S
[ILASM]
T
.method public hidebysig static unsigned int16 ToUInt16(valuetype System.Char value)
U
[C#]
public static ushort ToUInt16(char value)
V W
Summary
X
Converts a System.Char to a System.UInt16.
Y Z
912
Contents | Index
System
Convert ToUInt16() Method
Parameters Parameter
Description
value
The System.Char to be converted interpreted as an unsigned value.
A B C
Description
D
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt32(System.Char).
E F
Example
G
using System;
H
namespace Samples { public class ConvertToUInt16 { public static void Main() { Char c = 'A'; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToUInt16(c)); c = 'a'; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToUInt16(c)); c = Char.MinValue; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToUInt16(c)); } } }
I J K L M N O P Q R S T
The output is
U
From Char A yields 65 From Char a yields 97 From Char yields 0
V W X
Convert.ToUInt16(System.Decimal) Method
Y
[ILASM]
Z
.method public hidebysig static unsigned int16 ToUInt16(decimal value) [C#]
public static ushort ToUInt16(decimal value)
913
Contents | Index
Convert
System
ToUInt16() Method
Summary Converts a System.Decimal to a System.UInt16. A
Parameters
B C
Parameter
Description
D
value
The System.Decimal value to be converted.
E F
Description
G
Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt32(System.Decimal). This member must be implemented if the Extended Numerics Library is present in the implementation.
H I J K
Exceptions
L M
Exception
Condition
System.OverflowException
value is greater than System.UInt16.MaxValue or less than System.UInt16.MinValue.
N O P Q
Example
R
using System;
S
namespace Samples { public class ConvertToUInt16 { public static void Main() { try { Decimal d = Decimal.One; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToUInt16(d)); d = Decimal.Zero; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToUInt16(d)); d = 25.5m;
T U V W X Y Z
914
Contents | Index
System
Convert ToUInt16() Method
Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToUInt16(d)); d = Decimal.MaxValue; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToUInt16(d));
A
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
B C D
}
E
}
F
}
G
The output is
H From Decimal 1 yields 1 From Decimal 0 yields 0 From Decimal 25.5 yields 26 Exception: System.OverflowException: Value was either too large or too small for a UInt32. at System.Decimal.ToUInt32(Decimal d) at System.Decimal.ToUInt16(Decimal value) at System.Convert.ToUInt16(Decimal value) at Samples.ConvertToUInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt16\ToUInt16(System.Decimal)\Convert.cs:line 21
I J K L M N O P
Convert.ToUInt16(System.Double) Method
Q [ILASM]
.method public hidebysig static unsigned int16 ToUInt16(float64 value)
R
[C#]
S
public static ushort ToUInt16(double value)
T
Summary
U
Converts a System.Double to a System.UInt16.
V W
Parameters
X
Parameter
Description
Y
value
The System.Double value to be converted.
Z
915
Contents | Index
Convert
System
ToUInt16() Method
Description Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt32(System.Double). This member must be implemented if the Extended Numerics Library is present in the implementation.
A B C D
Exceptions
E F G
Exception
Condition
System.OverflowException
value is greater than System.UInt16.MaxValue or less than System.UInt16.MinValue.
H I
Example
J
using System;
K namespace Samples { public class ConvertToUInt16 { public static void Main() { try { double d = Double.Epsilon; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToUInt16(d)); d = 0.0; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToUInt16(d)); d = 5.5; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToUInt16(d)); d = Double.PositiveInfinity; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToUInt16(d)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
L M N O P Q R S T U V W X Y Z
916
Contents | Index
System
Convert ToUInt16() Method
The output is From Double 4.94065645841247E-324 yields 0 From Double 0 yields 0 From Double 5.5 yields 6 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Convert.ToInt32(Double value) at System.Convert.ToUInt16(Double value) at Samples.ConvertToUInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt16\ToUInt16(System.Double)\Convert.cs:line 21
A B C D E F G
Convert.ToUInt16(System.Single) Method
H
[ILASM]
I
.method public hidebysig static unsigned int16 ToUInt16(float32 value) [C#]
J
public static ushort ToUInt16(float value)
K
Summary
L
Converts a System.Single to a System.UInt16.
M N
Parameters
O
Parameter
Description
value
The System.Single value to be converted.
P Q R
Description
S
Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt32(System.Single). This member must be implemented if the Extended Numerics Library is present in the implementation.
T U V W X Y Z
917
Contents | Index
Convert
System
ToUInt16() Method
Exceptions Exception
Condition
System.OverflowException
value is greater than System.UInt16.MaxValue or less than System.Uint16.MinValue.
A B C D
Example
E
using System;
F namespace Samples { public class ConvertToUInt16 { public static void Main() { try { float f = 0.0f; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToUInt16(f)); f = 25.5f; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToUInt16(f)); f = Single.MaxValue; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToUInt16(f)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
G H I J K L M N O P Q R S T U
The output is
V W
From Single 0 yields 0 From Single 25.5 yields 26 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Convert.ToInt32(Double value) at System.Convert.ToUInt16(Single value) at Samples.ConvertToUInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt16\ToUInt16(System.Single)\Convert.cs:line 18
X Y Z
918
Contents | Index
System
Convert ToUInt16() Method
Convert.ToUInt16(System.Int32) Method [ILASM]
.method public hidebysig static unsigned int16 ToUInt16(int32 value) [C#]
A
public static ushort ToUInt16(int value)
B
Summary
C
Converts a System.Int32 to a System.UInt16.
D E
Parameters
F G
Parameter
Description
value
The 32-bit signed integer value to be converted.
H I J
Description
K
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt32(System.Int32).
L M
Exceptions Exception
N O
Condition
P System.OverflowException
value is greater than System.UInt16.MaxValue or less than System.UInt16.MinValue.
Q R S
Example
T
using System;
U namespace Samples { public class ConvertToUInt16 { public static void Main() { try { int i = UInt16.MaxValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToUInt16(i));
V W X Y Z
919
Contents | Index
Convert
System
ToUInt16() Method
i = 0; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToUInt16(i)); i = Int32.MaxValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToUInt16(i));
A B
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
C D E }
F
} }
G
The output is
H I
From Int32 65535 yields 65535 From Int32 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for a UInt16. at System.Convert.ToUInt16(Int32 value) at Samples.ConvertToUInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt16\ToUInt16(System.Int32)\Convert.cs:line 18
J K L M N O
Convert.ToUInt16(System.Int64) Method
P
[ILASM]
.method public hidebysig static unsigned int16 ToUInt16(int64 value)
Q
[C#]
R
public static ushort ToUInt16(long value)
S
Summary
T
Converts a System.Int64 to a System.UInt16.
U V
Parameters
W X Y
Parameter
Description
value
The 64-bit signed integer value to be converted.
Z
920
Contents | Index
System
Convert ToUInt16() Method
Description This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt32(System.Int64). A
Exceptions
B C
Exception
Condition
System.OverflowException
value is greater than System.UInt16.MaxValue or less than System.UInt16.MinValue.
D E F G
Example
H
using System;
I namespace Samples { public class ConvertToUInt16 { public static void Main() { try { long l = UInt16.MaxValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToUInt16(l)); l = 0; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToUInt16(l)); l = Int64.MaxValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToUInt16(l)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
J K L M N O P Q R S T U V W X Y Z
921
Contents | Index
Convert
System
ToUInt16() Method
The output is From Int64 65535 yields 65535 From Int64 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for a UInt16. at System.Convert.ToUInt16(Int64 value) at Samples.ConvertToUInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt16\ToUInt16(System.Int64)\Convert.cs:line 18
A B C D E F
Convert.ToUInt16(System.Object) Method
G
[ILASM]
H
.method public hidebysig static unsigned int16 ToUInt16(object value)
I
public static ushort ToUInt16(object value)
[C#]
J
Summary
K
Converts the value of the specified System.Object to a 16-bit unsigned integer.
L
Parameters
M N
Parameter
Description
value
A System.Object that implements the System.IConvertible interface or null.
O P Q R
Return Value
S
A 16-bit unsigned integer equivalent to the value of value, or zero if value is null.
T U
Description
V
The return value is the result of invoking the IConvertible.ToUInt16 method of the underlying type of value.
W X
Exceptions
Y Z
Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
922
Contents | Index
System
Convert ToUInt16() Method
Convert.ToUInt16(System.Object, System.IFormatProvider) Method [ILASM]
.method public hidebysig static unsigned int16 ToUInt16(object value, class System.IFormatProvider provider)
A
[C#]
B
public static ushort ToUInt16(object value, IFormatProvider provider)
C
Summary
D
Converts the value of the specified System.Object to a 16-bit unsigned integer using the specified culture-specific formatting information.
E
Parameters
G
F
H
Parameter
Description
value
A System.Object that implements the System.IConvertible interface.
provider
A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
I J K L M
Return Value
N
A 16-bit unsigned integer equivalent to the value of value, or zero if value is null.
O P
Description
Q
The return value is the result of invoking the IConvertible.ToUInt16 method of the underlying type of value. provider enables the user to specify culture-specific conversion information about the contents of value. For example, if value is a System.String that represents a number, provider could supply culture-specific information about the notation used to represent that number. The base types ignore provider; however, it is honored if value is a user-defined type that implements the System.IConvertible interface.
R S T U V W
Convert.ToUInt16(System.SByte) Method
X
[ILASM]
Y
.method public hidebysig static unsigned int16 ToUInt16(int8 value)
Z
[C#]
public static ushort ToUInt16(sbyte value)
923
Contents | Index
Convert
System
ToUInt16() Method
Summary Converts a System.SByte to a System.UInt16. A
Parameters
B C
Parameter
Description
D
value
The System.SByte value to be converted.
E F
Description
G
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt32(System.Int16).
H I
Exceptions
J K
Exception
Condition
System.OverflowException
value is less than System.UInt16.MinValue.
L M N
Example
O
using System;
P namespace Samples { public class ConvertToUInt16 { public static void Main() { try { sbyte s = SByte.MaxValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToUInt16(s)); s = 0; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToUInt16(s)); s = SByte.MinValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToUInt16(s)); }
Q R S T U V W X Y Z
924
Contents | Index
System
Convert ToUInt16() Method
catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A
} }
B
}
C
The output is
D E
From Signed Byte 127 yields 127 From Signed Byte 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for a UInt16. at System.Convert.ToUInt16(SByte value) at Samples.ConvertToUInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt16\ToUInt16(System.SByte)\Convert.cs:line 18
F G H I J
Convert.ToUInt16(System.Int16) Method
K
[ILASM]
L
.method public hidebysig static unsigned int16 ToUInt16(int16 value)
M
[C#]
public static ushort ToUInt16(short value)
N
Summary
O
Converts a System.Int16 to a System.UInt16.
P Q
Parameters
R
Parameter
Description
value
The 16-bit signed integer value to be converted.
S T U V
Description
W
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt32(System.Int16).
X Y Z
925
Contents | Index
Convert
System
ToUInt16() Method
Exceptions Exception
Condition
System.OverflowException
value is less than System.UInt16.MinValue.
A B C
Example
D
using System;
E
namespace Samples { public class ConvertToUInt16 { public static void Main() { try { short i = Int16.MaxValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToUInt16(i)); i = 0; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToUInt16(i)); i = Int16.MinValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToUInt16(i)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
F G H I J K L M N O P Q R S T U
The output is
V W
From Int16 32767 yields 32767 From Int16 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for a UInt16. at System.Convert.ToUInt16(Int16 value) at Samples.ConvertToUInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt16\ToUInt16(System.Int16)\Convert.cs:line 18
X Y Z
926
Contents | Index
System
Convert ToUInt16() Method
Convert.ToUInt16(System.String) Method [ILASM]
.method public hidebysig static unsigned int16 ToUInt16(string value) [C#]
A
public static ushort ToUInt16(string value)
B C
Summary
D
Converts a System.String to a System.UInt16.
E
Parameters
F G
Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Integer style.
H I J K
Description
L
This method parses value using the information in a System.Globalization.NumberFormatInfo instance initialized for the current system culture. This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt32(System.String).
M N O P
Exceptions
Q
Exception
Condition
System.ArgumentNullException
value is a null reference.
S
System.FormatException
value cannot be converted to a numeric value.
T
System.OverflowException
The numeric value of value is greater than System.UInt16.MaxValue or less than System.UInt16.MinValue.
R
U V W X Y Z
927
Contents | Index
Convert
System
ToUInt16() Method
Example using System; namespace Samples { public class ConvertToUInt16 { public static void Main() { string s; try { s = (UInt16.MaxValue).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt16(s)); s = (UInt16.MinValue).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt16(s)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt16(s)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = (UInt16.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt16(s)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P Q R S T U V W
The output is
X
From String 65535 yields 65535 From String 0 yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseUInt32(String s, NumberStyles style, NumberFormatInfo info) at System.UInt16.Parse(String s, NumberStyles style, IFormatProvider provider)
Y Z
928
Contents | Index
System
Convert ToUInt16() Method
at System.Convert.ToUInt16(String value) at Samples.ConvertToUInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt16\ToUInt16(System.String)\Convert.cs:line 19 Exception: System.OverflowException: Value was either too large or too small for a UInt16. at System.UInt16.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToUInt16(String value) at Samples.ConvertToUInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt16\ToUInt16(System.String)\Convert.cs:line 29
A B C D E
Convert.ToUInt16(System.String, System.Int32) Method
F
[ILASM]
G
.method public hidebysig static unsigned int16 ToUInt16(string value, int32 fromBase) [C#]
H
public static ushort ToUInt16(string value, int fromBase)
I J
Summary
K
Converts the System.String representation of a number in a specified base to an equivalent 16-bit unsigned integer.
L M
Parameters
N O
Parameter
Description
value
A System.String containing a number.
fromBase
The base of the number in value, which must be 2, 8, 10, or 16.
P Q R S
Description
T
If fromBase is 16, you can prefix the number specified by the value parameter with “0x” or “0X”.
U V
Exceptions
W
Exception
Condition
X
System.ArgumentException
fromBase is not 2, 8, 10, or 16.
Y
System.OverflowException
value is less than System.UInt16.MinValue or greater than System.UInt16.MaxValue.
Z
929
Contents | Index
Convert
System
ToUInt16() Method
Convert.ToUInt16(System.String, System.IFormatProvider) Method [ILASM]
A
.method public hidebysig static unsigned int16 ToUInt16(string value, class System.IFormatProvider provider)
B
[C#]
public static ushort ToUInt16(string value, IFormatProvider provider)
C D
Summary
E
Converts a System.String to a System.UInt16.
F
Parameters
G H
Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Integer style.
provider
An object that implements the System.IFormatProvider interface and supplies a System.Globalization.NumberFormatInfo instance containing culture-specific formatting information.
I J K L M N
Description
O
This method parses value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is parsed using the formatting information of the current system culture. This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt32(System.String, System.IFormatProvider).
P Q R S T
Exceptions
U V
Exception
Condition
W
System.ArgumentNullException
value is a null reference.
System.FormatException
value cannot be converted to a numeric value.
System.OverflowException
The numeric value of value is greater than System.UInt16.MaxValue or less than System.UInt16.MinValue.
X Y Z
930
Contents | Index
System
Convert ToUInt16() Method
Example using System; using System.Globalization;
A namespace Samples { public class ConvertToUInt16 { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; try { s = "~0"; Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt16(s, n)); s = (UInt16.MaxValue).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt16(s, n)); s = (UInt16.MinValue).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt16(s, n)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt16(s, n)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = (UInt16.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt16(s)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
B C D E F G H I J K L M N O P Q R S T U V W X Y Z
931
Contents | Index
Convert
System
ToUInt16() Method
The output is From String ~0 yields 0 From String 65535 yields 65535 From String 0 yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseUInt32(String s, NumberStyles style, NumberFormatInfo info) at System.UInt16.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToUInt16(String value, IFormatProvider provider) at Samples.ConvertToUInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt16\ToUInt16(System.String,System.IFormatProvider)\Convert.cs:line 26 Exception: System.OverflowException: Value was either too large or too small for a UInt16. at System.UInt16.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Convert.ToUInt16(String value) at Samples.ConvertToUInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt16\ToUInt16(System.String,System.IFormatProvider)\Convert.cs:line 36
A B C D E F G H I J K
Convert.ToUInt16(System.DateTime) Method
L
[ILASM]
M
.method public hidebysig static unsigned int16 ToUInt16(valuetype System.DateTime value)
N
[C#]
public static ushort ToUInt16(DateTime value)
O P
Summary
Q
Calling this method always throws System.InvalidCastException.
R
Parameters
S T U
Parameter
Description
value
A System.DateTime.
V W
Exceptions
X Y
Exception
Condition
System.InvalidCastException
This conversion is not supported.
Z
932
Contents | Index
System
Convert ToUInt16() Method
Convert.ToUInt16(System.UInt32) Method [ILASM]
.method public hidebysig static unsigned int16 ToUInt16(unsigned int32 value) [C#]
A
public static ushort ToUInt16(uint value)
B C
Summary
D
Converts a System.UInt32 to a System.UInt16.
E
Parameters
F G
Parameter
Description
value
The 32-bit unsigned integer value to be converted.
H I J
Description
K
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt32(System.Int64).
L M N
Exceptions
O
Exception
Condition
System.OverflowException
value is greater than System.UInt16.MaxValue.
P Q R
Example
S
using System;
T U
namespace Samples { public class ConvertToUInt16 { public static void Main() { try { uint u = UInt32.MinValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToUInt16(u));
V W X Y Z
933
Contents | Index
Convert
System
ToUInt16() Method
u = UInt16.MaxValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToUInt16(u)); u = UInt32.MaxValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToUInt16(u));
A B
} catch(OverflowException e) { Console.WriteLine("Exception {0}", e); }
C D E }
F
} }
G
The output is
H I
From UInt32 0 yields 0 From UInt32 65535 yields 65535 Exception System.OverflowException: Value was either too large or too small for a UInt16. at System.Convert.ToUInt16(UInt32 value) at Samples.ConvertToUInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt16\ToUInt16(System.UInt32)\Convert.cs:line 18
J K L M N O
Convert.ToUInt16(System.UInt64) Method
P
[ILASM]
.method public hidebysig static unsigned int16 ToUInt16(unsigned int64 value)
Q
[C#]
R
public static ushort ToUInt16(ulong value)
S
Summary
T
Converts a System.UInt64 to a System.UInt16.
U V
Parameters
W X Y
Parameter
Description
value
The 64-bit unsigned integer value to be converted.
Z
934
Contents | Index
System
Convert ToUInt16() Method
Description This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt32(System.Decimal). A
Exceptions
B C
Exception
Condition
System.OverflowException
value is greater than System.UInt16.MaxValue.
D E F
Example
G
using System;
H
namespace Samples { public class ConvertToUInt16 { public static void Main() { try { ulong u = UInt64.MinValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToUInt16(u)); u = (ulong) UInt16.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToUInt16(u)); u = UInt64.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToUInt16(u)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
I J K L M N O P Q R S T U V W X Y Z
935
Contents | Index
Convert
System
ToUInt16() Method
The output is From UInt64 0 yields 0 From UInt64 65535 yields 65535 Exception: System.OverflowException: Value was either too large or too small for a UInt16. at System.Convert.ToUInt16(UInt64 value) at Samples.ConvertToUInt16.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt16\ToUInt16(System.UInt64)\Convert.cs:line 18
A B C D E F
Convert.ToUInt16(System.UInt16) Method
G
[ILASM]
H
.method public hidebysig static unsigned int16 ToUInt16(unsigned int16 value)
I
public static ushort ToUInt16(ushort value)
[C#]
J
Summary
K
Converts a System.UInt16 to a System.UInt16.
L
Parameters
M N
Parameter
Description
value
The 16-bit unsigned integer value to be converted.
O P Q R
Return Value
S
value is returned unchanged.
T
Description
U
[Note: This method is provided for completeness.] This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt32(System.Int32).
V W X Y Z
936
Contents | Index
System
Convert ToUInt32() Method
Example using System; namespace Samples { public class ConvertToUInt16 { public static void Main() { ushort u = UInt16.MaxValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToUInt16(u)); u = UInt16.MinValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToUInt16(u)); } } }
A B C D E F G H I J
The output is
K L
From UInt16 65535 yields 65535 From UInt16 0 yields 0
M N
Convert.ToUInt32(System.Boolean) Method
O
[ILASM]
P
.method public hidebysig static unsigned int32 ToUInt32(bool value)
Q
[C#]
public static uint ToUInt32(bool value)
R
Summary
S
Converts a System.Boolean to a System.UInt32.
T U
Parameters
V
Parameter
Description
value
The System.Boolean value to be converted.
W X Y Z
Return Value If value is true, returns 1; if value is false, returns 0. 937
Contents | Index
Convert
System
ToUInt32() Method
Description This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt64(System.Boolean). A B
Example
C
using System;
D
namespace Samples { public class ConvertToUInt32 { public static void Main() { bool b = true; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToUInt32(b)); b = false; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToUInt32(b)); } } }
E F G H I J K L M
The output is
N O
From Boolean True yields 1 From Boolean False yields 0
P Q R
Convert.ToUInt32(System.Byte) Method
S
[ILASM]
.method public hidebysig static unsigned int32 ToUInt32(unsigned int8 value)
T
[C#]
public static uint ToUInt32(byte value)
U V
Summary
W
Converts a System.Byte to a System.UInt32.
X Y Z
938
Contents | Index
System
Convert ToUInt32() Method
Parameters Parameter
Description
value
The System.Byte value to be converted.
A B C
Description
D
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt64(System.Byte).
E F
Example
G
using System;
H
namespace Samples { public class ConvertToUInt32 { public static void Main() { byte b = Byte.MaxValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToUInt32(b)); b = Byte.MinValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToUInt32(b)); } } }
I J K L M N O P Q R
The output is
S T
From Byte 255 yields 255 From Byte 0 yields 0
U V
Convert.ToUInt32(System.Char) Method
W
[ILASM]
X
.method public hidebysig static unsigned int32 ToUInt32(valuetype System.Char value)
Y
[C#]
Z
public static uint ToUInt32(char value)
939
Contents | Index
Convert
System
ToUInt32() Method
Summary Converts a System.Char to a System.UInt32. A
Parameters
B C
Parameter
Description
D
value
The System.Char to be converted interpreted as an unsigned value.
E F
Description
G
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt64(System.Char).
H I
Example
J
using System;
K namespace Samples { public class ConvertToUInt32 { public static void Main() { Char c = 'A'; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToUInt32(c)); c = 'a'; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToUInt32(c)); c = Char.MinValue; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToUInt32(c)); } } }
L M N O P Q R S T U V W
The output is
X From Char A yields 65 From Char a yields 97 From Char yields 0
Y Z
940
Contents | Index
System
Convert ToUInt32() Method
Convert.ToUInt32(System.Decimal) Method [ILASM]
.method public hidebysig static unsigned int32 ToUInt32(decimal value) [C#]
A
public static uint ToUInt32(decimal value)
B C
Summary
D
Converts a System.Decimal to a System.UInt32.
E
Parameters
F G
Parameter
Description
value
The System.Decimal value to be converted.
H I J
Description
K
Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt64(System.Decimal). This member must be implemented if the Extended Numerics Library is present in the implementation.
L M N O P
Exceptions
Q
Exception
Condition
R
value is greater than System.UInt32.MaxValue or less than System.UInt32.MinValue.
S
System.OverflowException
T U
Example
V
using System;
W
namespace Samples { public class ConvertToUInt32 { public static void Main() { try
X Y Z
941
Contents | Index
Convert
System
ToUInt32() Method
{ Decimal d = Decimal.One; Console.WriteLine("From Decimal {0} yields d, Convert.ToUInt32(d)); d = Decimal.Zero; Console.WriteLine("From Decimal {0} yields d, Convert.ToUInt32(d)); d = 25.5m; Console.WriteLine("From Decimal {0} yields d, Convert.ToUInt32(d)); d = Decimal.MaxValue; Console.WriteLine("From Decimal {0} yields d, Convert.ToUInt32(d));
A B C D E F
{1}",
{1}",
{1}",
{1}",
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
G H I }
J }
K
}
L
The output is
M From Decimal 1 yields 1 From Decimal 0 yields 0 From Decimal 25.5 yields 26 Exception: System.OverflowException: Value was either too large or too small for a UInt32. at System.Decimal.ToUInt32(Decimal d) at System.Convert.ToUInt32(Decimal value) at Samples.ConvertToUInt32.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt32\ToUInt32(System.Decimal)\Convert.cs:line 21
N O P Q R S T
Convert.ToUInt32(System.Double) Method
U V
[ILASM]
W
[C#]
.method public hidebysig static unsigned int32 ToUInt32(float64 value) public static uint ToUInt32(double value)
X Y
Summary
Z
Converts a System.Double to a System.UInt32.
942
Contents | Index
System
Convert ToUInt32() Method
Parameters Parameter
Description
value
The System.Double value to be converted.
A B C
Description
D
Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt64(System.Double). This member must be implemented if the Extended Numerics Library is present in the implementation.
E F G H I
Exceptions
J
Exception
Condition
K
value is greater than System.UInt32.MaxValue or less than System.UInt32.MinValue.
L
System.OverflowException
M N
Example
O
using System;
P
namespace Samples { public class ConvertToUInt32 { public static void Main() { try { double d = Double.Epsilon; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToUInt32(d)); d = 0.0; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToUInt32(d)); d = 5.5; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToUInt32(d)); d = Double.PositiveInfinity;
Q R S T U V W X Y Z
943
Contents | Index
Convert
System
ToUInt32() Method
Console.WriteLine("From Double {0} yields {1}", d, Convert.ToUInt32(d)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C
} }
D
}
E
The output is
F
From Double 4.94065645841247E-324 yields 0 From Double 0 yields 0 From Double 5.5 yields 6 Exception: System.OverflowException: Value was either too large or too small for a UInt32. at System.Convert.ToUInt32(Double value) at Samples.ConvertToUInt32.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt32\ToUInt32(System.Double)\Convert.cs:line 21
G H I J K L M
Convert.ToUInt32(System.Single) Method
N [ILASM]
O
.method public hidebysig static unsigned int32 ToUInt32(float32 value) [C#]
P
public static uint ToUInt32(float value)
Q R
Summary
S
Converts a System.Single to a System.UInt32.
T
Parameters
U V
Parameter
Description
W
value
The System.Single value to be converted.
X Y
Description
Z
Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6.
944
Contents | Index
System
Convert ToUInt32() Method
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt64(System.Single). This member must be implemented if the Extended Numerics Library is present in the implementation. A
Exceptions Exception
B C
Condition
D System.OverflowException
value is greater than System.UInt32.MaxValue or less than System.UInt32.MinValue.
E F G
Example
H
using System;
I namespace Samples { public class ConvertToUInt32 { public static void Main() { try { float f = 0.0f; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToUInt32(f)); f = 25.5f; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToUInt32(f)); f = Single.MaxValue; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToUInt32(f)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
J K L M N O P Q R S T U V W X Y Z
945
Contents | Index
Convert
System
ToUInt32() Method
The output is From Single 0 yields 0 From Single 25.5 yields 26 Exception: System.OverflowException: Value was either too large or too small for a UInt32. at System.Convert.ToUInt32(Double value) at System.Convert.ToUInt32(Single value) at Samples.ConvertToUInt32.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt32\ToUInt32(System.Single)\Convert.cs:line 18
A B C D E F
Convert.ToUInt32(System.Int32) Method
G H
[ILASM]
I
[C#]
.method public hidebysig static unsigned int32 ToUInt32(int32 value) public static uint ToUInt32(int value)
J K
Summary
L
Converts a System.Int32 to a System.UInt32.
M
Parameters
N O
Parameter
Description
value
The 32-bit signed integer value to be converted.
P Q R
Description
S
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt64(System.Int32).
T U
Exceptions
V W
Exception
Condition
System.OverflowException
value is less than System.UInt32.MinValue.
X Y Z
946
Contents | Index
System
Convert ToUInt32() Method
Example using System; namespace Samples { public class ConvertToUInt32 { public static void Main() { try { int i = Int32.MaxValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToUInt32(i)); i = 0; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToUInt32(i)); i = Int32.MinValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToUInt32(i)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P
The output is
Q R
From Int32 2147483647 yields 2147483647 From Int32 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for a UInt32. at System.Convert.ToUInt32(Int32 value) at Samples.ConvertToUInt32.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt32\ToUInt32(System.Int32)\Convert.cs:line 18
S T U V W
Convert.ToUInt32(System.Int64) Method
X
[ILASM]
Y
.method public hidebysig static unsigned int32 ToUInt32(int64 value)
Z
[C#]
public static uint ToUInt32(long value)
947
Contents | Index
Convert
System
ToUInt32() Method
Summary Converts a System.Int64 to a System.UInt32. A
Parameters
B C
Parameter
Description
D
value
The 64-bit signed integer value to be converted.
E F
Description
G
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt64(System.Int64).
H
Exceptions
I J
Exception
Condition
System.OverflowException
value is greater than System.UInt32.MaxValue or less than System.UInt32.MinValue.
K L M N
Example
O
using System;
P
namespace Samples { public class ConvertToUInt32 { public static void Main() { try { long l = UInt32.MaxValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToUInt32(l)); l = 0; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToUInt32(l)); l = Int64.MaxValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToUInt32(l)); } catch(OverflowException e)
Q R S T U V W X Y Z
948
Contents | Index
System
Convert ToUInt32() Method
{ Console.WriteLine("Exception: {0}", e); } }
A
} }
B
The output is
C D
From Int64 4294967295 yields 4294967295 From Int64 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for a UInt32. at System.Convert.ToUInt32(Int64 value) at Samples.ConvertToUInt32.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt32\ToUInt32(System.Int64)\Convert.cs:line 18
E F G H I
Convert.ToUInt32(System.Object) Method
J
[ILASM]
K
.method public hidebysig static unsigned int32 ToUInt32(object value)
L
[C#]
M
public static uint ToUInt32(object value)
N
Summary
O
Converts the value of the specified System.Object to a 32-bit unsigned integer.
P
Parameters
Q R
Parameter
Description
value
A System.Object that implements the System.IConvertible interface or null.
S T U V
Return Value
W
A 32-bit unsigned integer equivalent to the value of value, or zero if value is null.
X
Description
Y
The return value is the result of invoking the IConvertible.ToUInt32 method of the underlying type of value.
Z
949
Contents | Index
Convert
System
ToUInt32() Method
Exceptions Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
A B C D
Convert.ToUInt32(System.Object, System.IFormatProvider) Method
E [ILASM]
F
.method public hidebysig static unsigned int32 ToUInt32(object value, class System.IFormatProvider provider)
G
[C#]
public static uint ToUInt32(object value, IFormatProvider provider)
H I
Summary
J
Converts the value of the specified System.Object to a 32-bit unsigned integer using the specified culture-specific formatting information.
K L
Parameters
M N
Parameter
Description
value
A System.Object that implements the System.IConvertible interface.
provider
A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
O P Q R S
Return Value
T
A 32-bit unsigned integer equivalent to the value of value, or zero if value is null.
U
Description
V
The return value is the result of invoking the IConvertible.ToUInt32 method of the underlying type of value. provider enables the user to specify culture-specific conversion information about the contents of value. For example, if value is a System.String that represents a number, provider could supply culture-specific information about the notation used to represent that number. The base types ignore provider; however, it is honored if value is a user-defined type that implements the System.IConvertible interface.
W X Y Z
950
Contents | Index
System
Convert ToUInt32() Method
Convert.ToUInt32(System.SByte) Method [ILASM]
.method public hidebysig static unsigned int32 ToUInt32(int8 value) [C#]
A
public static uint ToUInt32(sbyte value)
B
Summary
C
Converts a System.SByte to a System.UInt32.
D E
Parameters
F G
Parameter
Description
value
The System.SByte value to be converted.
H I J
Description
K
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt64(System.Int16).
L M
Exceptions
N
Exception
Condition
System.OverflowException
value is less than System.UInt32.MinValue.
O P Q R
Example
S
using System;
T
namespace Samples { public class ConvertToUInt32 { public static void Main() { try { sbyte s = SByte.MaxValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToUInt32(s)); s = 0;
U V W X Y Z
951
Contents | Index
Convert
System
ToUInt32() Method
Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToUInt32(s)); s = SByte.MinValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToUInt32(s));
A
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
B C D }
E }
F
}
G
The output is
H From Signed Byte 127 yields 127 From Signed Byte 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for a UInt32. at System.Convert.ToUInt32(SByte value) at Samples.ConvertToUInt32.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt32\ToUInt32(System.SByte)\Convert.cs:line 18
I J K L M N
Convert.ToUInt32(System.Int16) Method
O
[ILASM]
P
.method public hidebysig static unsigned int32 ToUInt32(int16 value)
Q
[C#]
public static uint ToUInt32(short value)
R S
Summary
T
Converts a System.Int16 to a System.UInt32.
U
Parameters
V W X
Parameter
Description
value
The 16-bit signed integer value to be converted.
Y Z
952
Contents | Index
System
Convert ToUInt32() Method
Description This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt64(System.Int16). A
Exceptions
B C
Exception
Condition
System.OverflowException
value is less than System.UInt32.MinValue.
D E F
Example
G
using System;
H
namespace Samples { public class ConvertToUInt32 { public static void Main() { try { short i = Int16.MaxValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToUInt32(i)); i = 0; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToUInt32(i)); i = Int16.MinValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToUInt32(i)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
I J K L M N O P Q R S T U V W X Y Z
953
Contents | Index
Convert
System
ToUInt32() Method
The output is From Int16 32767 yields 32767 From Int16 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for a UInt32. at System.Convert.ToUInt32(Int16 value) at Samples.ConvertToUInt32.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt32\ToUInt32(System.Int16)\Convert.cs:line 18
A B C D E
Convert.ToUInt32(System.String) Method
F G
[ILASM]
H
[C#]
.method public hidebysig static unsigned int32 ToUInt32(string value) public static uint ToUInt32(string value)
I J
Summary
K
Converts a System.String to a System.UInt32.
L
Parameters
M N O
Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Integer style.
P Q
Description
R
This method parses value using the information in a System.Globalization.NumberFormatInfo instance initialized for the current system culture. This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt64(System.String).
S T U V W X Y Z
954
Contents | Index
System
Convert ToUInt32() Method
Exceptions Exception
Condition
System.ArgumentNullException
value is a null reference.
System.FormatException
value cannot be converted to a numeric value.
C
The numeric value of value is greater than System.UInt32.MaxValue or less than System.UInt32.MinValue.
D
System.OverflowException
A B
E F G
Example
H
using System;
I namespace Samples { public class ConvertToUInt32 { public static void Main() { string s; try { s = UInt32.MaxValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt32(s)); s = UInt32.MinValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt32(s)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt32(s)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = ((ulong) UInt32.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt32(s)); } catch(OverflowException e)
J K L M N O P Q R S T U V W X Y Z
955
Contents | Index
Convert
System
ToUInt32() Method
{ Console.WriteLine("Exception: {0}", e); } }
A
} }
B C
The output is
D From String 4294967295 yields 4294967295 From String 0 yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseUInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToUInt32(String value) at Samples.ConvertToUInt32.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt32\ToUInt32(System.String)\Convert.cs:line 19 Exception: System.OverflowException: Value was either too large or too small for a UInt32. at System.Number.ParseUInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToUInt32(String value) at Samples.ConvertToUInt32.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt32\ToUInt32(System.String)\Convert.cs:line 29
E F G H I J K L M N
Convert.ToUInt32(System.String, System.Int32) Method
O
[ILASM]
P
.method public hidebysig static unsigned int32 ToUInt32(string value, int32 fromBase)
Q
[C#]
public static uint ToUInt32(string value, int fromBase)
R S
Summary
T
Converts the System.String representation of a number in a specified base to an equivalent 32-bit unsigned integer.
U V
Parameters
W X
Parameter
Description
Y
value
A System.String containing a number.
fromBase
The base of the number in value, which must be 2, 8, 10, or 16.
Z
956
Contents | Index
System
Convert ToUInt32() Method
Description If fromBase is 16, you can prefix the number specified by the value parameter with “0x” or “0X”. A
Exceptions
B
Exception
Condition
C
System.ArgumentException
fromBase is not 2, 8, 10, or 16.
D E F
Convert.ToUInt32(System.String, System.IFormatProvider) Method
G
[ILASM]
H
.method public hidebysig static unsigned int32 ToUInt32(string value, class System.IFormatProvider provider)
I
[C#]
J
public static uint ToUInt32(string value, IFormatProvider provider)
K
Summary
L
Converts a System.String to a System.UInt32.
M N
Parameters
O
Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Integer style.
provider
An object that implements the System.IFormatProvider interface and supplies a System.Globalization.NumberFormatInfo instance containing culture-specific formatting information.
P Q R S T U V
Description
W
This method parses value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is parsed using the formatting information of the current system culture. This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt64(System.String, System.IFormatProvider).
X Y Z
957
Contents | Index
Convert
System
ToUInt32() Method
Exceptions Exception
Condition
System.ArgumentNullException
value is a null reference.
System.FormatException
value cannot be converted to a numeric value.
System.OverflowException
The numeric value of value is greater than System.UInt32.MaxValue or less than System.UInt32.MinValue.
A B C D E F G
Example
H
using System; using System.Globalization;
I
namespace Samples { public class ConvertToUInt32 { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; try { s = " ~0"; Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt32(s, c)); s = UInt32.MaxValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt32(s, c)); s = UInt32.MinValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt32(s, c)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt32(s, c)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try
J K L M N O P Q R S T U V W X Y Z
958
Contents | Index
System
Convert ToUInt32() Method
{ s = ((ulong) UInt32.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt32(s, c));
A
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
B C D
} }
E
}
F
The output is
G H
From String ~0 yields 0 From String 4294967295 yields 4294967295 From String 0 yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseUInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToUInt32(String value, IFormatProvider provider) at Samples.ConvertToUInt32.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt32\ToUInt32(System.String,System.IFormatProvider)\Convert.cs:line 26 Exception: System.OverflowException: Value was either too large or too small for a UInt32. at System.Number.ParseUInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToUInt32(String value, IFormatProvider provider) at Samples.ConvertToUInt32.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt32\ToUInt32(System.String,System.IFormatProvider)\Convert.cs:line 36
I J K L M N O P Q R S
Convert.ToUInt32(System.DateTime) Method
T [ILASM]
U
.method public hidebysig static unsigned int32 ToUInt32(valuetype System.DateTime value)
V
[C#]
W
public static uint ToUInt32(DateTime value)
X
Summary
Y
Calling this method always throws System.InvalidCastException.
Z
959
Contents | Index
Convert
System
ToUInt32() Method
Parameters Parameter
Description
value
A System.DateTime.
A B C
Exceptions
D E
Exception
Condition
System.InvalidCastException
This conversion is not supported.
F G H I
Convert.ToUInt32(System.UInt32) Method
J
[ILASM]
K
.method public hidebysig static unsigned int32 ToUInt32(unsigned int32 value)
L
[C#]
public static uint ToUInt32(uint value)
M N
Summary
O
Converts a System.UInt32 to a System.UInt32.
P
Parameters
Q R S
Parameter
Description
value
The 32-bit unsigned integer value to be converted.
T U
Description
V
[Note: This method is provided for completeness.] This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt64(System.Int64).
W X Y Z
960
Contents | Index
System
Convert ToUInt32() Method
Example using System; namespace Samples { public class ConvertToUInt32 { public static void Main() { uint u = UInt32.MaxValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToUInt32(u)); u = UInt16.MinValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToUInt32(u)); } } }
A B C D E F G H I J
The output is
K L
From UInt32 4294967295 yields 4294967295 From UInt32 0 yields 0
M N
Convert.ToUInt32(System.UInt64) Method
O
[ILASM]
P
.method public hidebysig static unsigned int32 ToUInt32(unsigned int64 value)
Q
[C#]
public static uint ToUInt32(ulong value)
R
Summary
S
Converts a System.UInt64 to a System.UInt32.
T U
Parameters
V
Parameter
Description
value
The 64-bit unsigned integer value to be converted.
W X Y Z
961
Contents | Index
Convert
System
ToUInt32() Method
Description This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt64(System.Decimal). A
Exceptions
B C D E
Exception
Condition
System.OverflowException
value is greater than System.UInt32.MaxValue.
F G
Example
H
using System;
I
namespace Samples { public class ConvertToUInt32 { public static void Main() { try { ulong u = UInt32.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToUInt32(u)); u = UInt32.MinValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToUInt32(u)); u = UInt64.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToUInt32(u)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
J K L M N O P Q R S T U V W X Y Z
962
Contents | Index
System
Convert ToUInt32() Method
The output is From UInt64 4294967295 yields 4294967295 From UInt64 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for a UInt32. at System.Convert.ToUInt32(UInt64 value) at Samples.ConvertToUInt32.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt32\ToUInt32(System.UInt64)\Convert.cs:line 18
A B C D E
Convert.ToUInt32(System.UInt16) Method
F
[ILASM]
G
.method public hidebysig static unsigned int32 ToUInt32(unsigned int16 value)
H
[C#]
I
public static uint ToUInt32(ushort value)
J
Summary
K
Converts a System.UInt16 to a System.UInt32.
L
Parameters
M N
Parameter
Description
value
The 16-bit unsigned integer value to be converted.
O P Q
Description
R
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToInt64(System.Int32).
S
Example
U
using System;
V
T
W
namespace Samples { public class ConvertToUInt32 { public static void Main() { ushort u = UInt16.MaxValue; Console.WriteLine("From UInt16 {0} yields {1}",
X Y Z
963
Contents | Index
Convert
System
ToUInt64() Method
u, Convert.ToUInt32(u)); u = UInt16.MinValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToUInt32(u));
A
} }
B }
C
The output is
D E
From UInt16 65535 yields 65535 From UInt16 0 yields 0
F G H
Convert.ToUInt64(System.Boolean) Method
I
[ILASM]
.method public hidebysig static unsigned int64 ToUInt64(bool value)
J
[C#]
public static ulong ToUInt64(bool value)
K L
Summary
M
Converts a System.Boolean to a System.UInt64.
N
Parameters
O P
Parameter
Description
value
The System.Boolean value to be converted.
Q R S T
Return Value
U
If value is true, returns 1; if value is false, returns 0.
V
Description
W
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDecimal(System.Boolean).
X Y Z
964
Contents | Index
System
Convert ToUInt64() Method
Example using System; namespace Samples { public class ConvertToUInt64 { public static void Main() { bool b = true; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToUInt64(b)); b = false; Console.WriteLine("From Boolean {0} yields {1}", b, Convert.ToUInt64(b)); } } }
A B C D E F G H I J
The output is
K L
From Boolean True yields 1 From Boolean False yields 0
M N
Convert.ToUInt64(System.Byte) Method
O
[ILASM]
P
.method public hidebysig static unsigned int64 ToUInt64(unsigned int8 value)
Q
[C#]
public static ulong ToUInt64(byte value)
R
Summary
S
Converts a System.Byte to a System.UInt64.
T U
Parameters
V
Parameter
Description
value
The System.Byte value to be converted.
W X Y Z
965
Contents | Index
Convert
System
ToUInt64() Method
Description This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDecimal(System.Byte). A B
Example
C
using System;
D
namespace Samples { public class ConvertToUInt64 { public static void Main() { byte b = Byte.MaxValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToUInt64(b)); b = Byte.MinValue; Console.WriteLine("From Byte {0} yields {1}", b, Convert.ToUInt64(b)); } } }
E F G H I J K L M
The output is
N
From Byte 255 yields 255 From Byte 0 yields 0
O P Q R
Convert.ToUInt64(System.Char) Method
S
[ILASM]
T
.method public hidebysig static unsigned int64 ToUInt64(valuetype System.Char value) [C#]
U
public static ulong ToUInt64(char value)
V W
Summary
X
Converts a System.Char to a System.UInt64.
Y Z
966
Contents | Index
System
Convert ToUInt64() Method
Parameters Parameter
Description
value
The System.Char to be converted interpreted as an unsigned value.
A B C
Description
D
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDecimal(System.Char).
E F
Example
G
using System;
H
namespace Samples { public class ConvertToUInt64 { public static void Main() { Char c = 'A'; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToUInt64(c)); c = 'a'; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToUInt64(c)); c = Char.MinValue; Console.WriteLine("From Char {0} yields {1}", c, Convert.ToUInt64(c)); } } }
I J K L M N O P Q R S T
The output is
U
From Char A yields 65 From Char a yields 97 From Char yields 0
V W X
Convert.ToUInt64(System.Decimal) Method
Y
[ILASM]
Z
.method public hidebysig static unsigned int64 ToUInt64(decimal value) [C#]
public static ulong ToUInt64(decimal value)
967
Contents | Index
Convert
System
ToUInt64() Method
Summary Converts a System.Decimal to a System.UInt64. A
Parameters
B C
Parameter
Description
D
value
The System.Decimal value to be converted.
E F
Description
G
Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDecimal(System.Decimal). This member must be implemented if the Extended Numerics Library is present in the implementation.
H I J K
Exceptions
L M
Exception
Condition
System.OverflowException
value is greater than System.UInt64.MaxValue or less than System.UInt64.MinValue.
N O P Q
Example
R
using System;
S
namespace Samples { public class ConvertToUInt64 { public static void Main() { try { Decimal d = Decimal.One; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToUInt64(d)); d = Decimal.Zero; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToUInt64(d));
T U V W X Y Z
968
Contents | Index
System
Convert ToUInt64() Method
d = 25.5m; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToUInt64(d)); d = Decimal.MaxValue; Console.WriteLine("From Decimal {0} yields {1}", d, Convert.ToUInt64(d));
A B
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
C D E
}
F
} }
G
The output is
H I
From Decimal 1 yields 1 From Decimal 0 yields 0 From Decimal 25.5 yields 26 Exception: System.OverflowException: Value was either too large or too small for a UInt64. at System.Decimal.ToUInt64(Decimal d) at System.Convert.ToUInt64(Decimal value) at Samples.ConvertToUInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt64\ToUInt64(System.Decimal)\Convert.cs:line 21
J K L M N O P
Convert.ToUInt64(System.Double) Method
Q [ILASM]
.method public hidebysig static unsigned int64 ToUInt64(float64 value)
R
[C#]
S
public static ulong ToUInt64(double value)
T
Summary
U
Converts a System.Double to a System.UInt64.
V W
Parameters
X
Parameter
Description
value
The System.Double value to be converted.
Y Z
969
Contents | Index
Convert
System
ToUInt64() Method
Description Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDecimal(System.Double). This member must be implemented if the Extended Numerics Library is present in the implementation.
A B C D
Exceptions
E F G
Exception
Condition
System.OverflowException
value is greater than System.UInt64.MaxValue or less than System.UInt64.MinValue.
H I
Example
J
using System;
K
namespace Samples { public class ConvertToUInt64 { public static void Main() { try { double d = Double.Epsilon; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToUInt64(d)); d = 0.0; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToUInt64(d)); d = 5.5; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToUInt64(d)); d = Double.PositiveInfinity; Console.WriteLine("From Double {0} yields {1}", d, Convert.ToUInt64(d)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
L M N O P Q R S T U V W X Y Z
970
Contents | Index
System
Convert ToUInt64() Method
The output is From Double 4.94065645841247E-324 yields 0 From Double 0 yields 0 From Double 5.5 yields 6 Exception: System.OverflowException: Value was either too large or too small for a UInt64. at System.Convert.ToUInt64(Double value) at Samples.ConvertToUInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt64\ToUInt64(System.Double)\Convert.cs:line 21
A B C D E F
Convert.ToUInt64(System.Single) Method
G
[ILASM]
.method public hidebysig static unsigned int64 ToUInt64(float32 value)
H
[C#]
I
public static ulong ToUInt64(float value)
J
Summary
K
Converts a System.Single to a System.UInt64.
L M
Parameters
N
Parameter
Description
O
value
The System.Single value to be converted.
P Q R
Description
S
Prior to the conversion, if value is halfway between two whole numbers, it is rounded to the nearest even integer. For example, 4.5 is rounded to 4, and 5.5 is rounded to 6. This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDecimal(System.Single). This member must be implemented if the Extended Numerics Library is present in the implementation.
T U V W
Exceptions
X
Exception
Condition
System.OverflowException
value is greater than System.UInt64.MaxValue or less than System.UInt64.MinValue.
Y Z
971
Contents | Index
Convert
System
ToUInt64() Method
Example using System; namespace Samples { public class ConvertToUInt64 { public static void Main() { try { float f = 0.0f; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToUInt64(f)); f = 25.5f; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToUInt64(f)); f = Single.MaxValue; Console.WriteLine("From Single {0} yields {1}", f, Convert.ToUInt64(f)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P
The output is
Q R
From Single 0 yields 0 From Single 25.5 yields 26 Exception: System.OverflowException: Value was either too large or too small for a UInt64. at System.Convert.ToUInt64(Double value) at System.Convert.ToUInt64(Single value) at Samples.ConvertToUInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt64\ToUInt64(System.Single)\Convert.cs:line 18
S T U V W X
Convert.ToUInt64(System.Int32) Method
Y
[ILASM]
Z
.method public hidebysig static unsigned int64 ToUInt64(int32 value) [C#]
public static ulong ToUInt64(int value)
972
Contents | Index
System
Convert ToUInt64() Method
Summary Converts a System.Int32 to a System.UInt64. A
Parameters
B
Parameter
Description
C
value
The 32-bit signed integer value to be converted.
D E F
Description
G
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDecimal(System.Int32).
H I
Exceptions
J
Exception
Condition
System.OverflowException
value is less than System.UInt64.MinValue.
K L M N
Example
O
using System;
P namespace Samples { public class ConvertToUInt64 { public static void Main() { try { int i = Int32.MaxValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToUInt64(i)); i = 0; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToUInt64(i)); i = Int32.MinValue; Console.WriteLine("From Int32 {0} yields {1}", i, Convert.ToUInt64(i)); } catch(OverflowException e)
Q R S T U V W X Y Z
973
Contents | Index
Convert
System
ToUInt64() Method
{ Console.WriteLine("Exception: {0}", e); } }
A
} }
B C
The output is
D From Int32 2147483647 yields 2147483647 From Int32 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for a UInt64. at System.Convert.ToUInt64(Int32 value) at Samples.ConvertToUInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt64\ToUInt64(System.Int32)\Convert.cs:line 18
E F G H I J
Convert.ToUInt64(System.Int64) Method
K [ILASM]
L
.method public hidebysig static unsigned int64 ToUInt64(int64 value) [C#]
M
public static ulong ToUInt64(long value)
N
Summary
O
Converts a System.Int64 to a System.UInt64.
P Q
Parameters
R S
Parameter
Description
T
value
The 64-bit signed integer value to be converted.
U V
Description
W
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDecimal(System.Int64).
X Y Z
974
Contents | Index
System
Convert ToUInt64() Method
Exceptions Exception
Condition
System.OverflowException
value is less than System.UInt64.MinValue.
A B C
Example
D
using System;
E
namespace Samples { public class ConvertToUInt64 { public static void Main() { try { long l = Int64.MaxValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToUInt64(l)); l = 0; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToUInt64(l)); l = Int64.MinValue; Console.WriteLine("From Int64 {0} yields {1}", l, Convert.ToUInt64(l)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
F G H I J K L M N O P Q R S T U
The output is
V W
From Int64 9223372036854775807 yields 9223372036854775807 From Int64 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for a UInt64. at System.Convert.ToUInt64(Int64 value) at Samples.ConvertToUInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt64\ToUInt64(System.Int64)\Convert.cs:line 18
X Y Z
975
Contents | Index
Convert
System
ToUInt64() Method
Convert.ToUInt64(System.Object) Method [ILASM]
.method public hidebysig static unsigned int64 ToUInt64(object value)
A
[C#]
public static ulong ToUInt64(object value)
B C
Summary
D
Converts the value of the specified System.Object to a 64-bit unsigned integer.
E
Parameters
F G
Parameter
Description
value
A System.Object that implements the System.IConvertible interface or null.
H I J K
Return Value
L
A 64-bit unsigned integer equivalent to the value of value, or zero if value is null.
M N
Description
O
The return value is the result of invoking the IConvertible.ToUInt64 method of the underlying type of value.
P Q
Exceptions
R S T
Exception
Condition
System.InvalidCastException
value does not implement System.IConvertible.
U V W
Convert.ToUInt64(System.Object, System.IFormatProvider) Method
X
[ILASM]
Y
.method public hidebysig static unsigned int64 ToUInt64(object value, class System.IFormatProvider provider) [C#]
Z
public static ulong ToUInt64(object value, IFormatProvider provider)
976
Contents | Index
System
Convert ToUInt64() Method
Summary Converts the value of the specified System.Object to a 64-bit unsigned integer using the specified culture-specific formatting information. A
Parameters
B C
Parameter
Description
value
A System.Object that implements the System.IConvertible interface.
E
provider
A System.IFormatProvider interface implementation that supplies culture-specific formatting information.
F
D
G H
Return Value
I
A 64-bit unsigned integer equivalent to the value of value, or zero if value is null.
J K
Description
L
The return value is the result of invoking the IConvertible.ToUInt64 method of the underlying type of value. provider enables the user to specify culture-specific conversion information about the contents of value. For example, if value is a System.String that represents a number, provider could supply culture-specific information about the notation used to represent that number. The base types ignore provider; however, it is honored if value is a user-defined type that implements the System.IConvertible interface.
M N O P Q R S
Convert.ToUInt64(System.SByte) Method
T
[ILASM]
.method public hidebysig static unsigned int64 ToUInt64(int8 value)
U
[C#]
V
public static ulong ToUInt64(sbyte value)
W
Summary
X
Converts a System.SByte to a System.UInt64.
Y Z
977
Contents | Index
Convert
System
ToUInt64() Method
Parameters Parameter
Description
value
The System.SByte value to be converted.
A B C
Description
D
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDecimal(System.Int16).
E F
Exceptions
G H
Exception
Condition
System.OverflowException
value is less than System.UInt64.MinValue.
I J K
Example
L
using System;
M namespace Samples { public class ConvertToUInt64 { public static void Main() { try { sbyte s = SByte.MaxValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToUInt64(s)); s = 0; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToUInt64(s)); s = SByte.MinValue; Console.WriteLine("From Signed Byte {0} yields {1}", s, Convert.ToUInt64(s)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
N O P Q R S T U V W X Y Z
978
Contents | Index
System
Convert ToUInt64() Method
The output is From Signed Byte 127 yields 127 From Signed Byte 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for a UInt64. at System.Convert.ToUInt64(SByte value) at Samples.ConvertToUInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt64\ToUInt64(System.SByte)\Convert.cs:line 18
A B C D E
Convert.ToUInt64(System.Int16) Method
F
[ILASM]
G
.method public hidebysig static unsigned int64 ToUInt64(int16 value)
H
[C#]
I
public static ulong ToUInt64(short value)
J
Summary
K
Converts a System.Int16 to a System.UInt64.
L
Parameters
M N
Parameter
Description
value
The 16-bit signed integer value to be converted.
O P Q
Description
R
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDecimal(System.Int16).
S
Exceptions
U
T
V
Exception
Condition
W
System.OverflowException
value is less than System.UInt64.MinValue.
X Y Z
979
Contents | Index
Convert
System
ToUInt64() Method
Example using System; namespace Samples { public class ConvertToUInt64 { public static void Main() { try { short i = Int16.MaxValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToUInt64(i)); i = 0; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToUInt64(i)); i = Int16.MinValue; Console.WriteLine("From Int16 {0} yields {1}", i, Convert.ToUInt64(i)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P
The output is
Q
From Int16 32767 yields 32767 From Int16 0 yields 0 Exception: System.OverflowException: Value was either too large or too small for a UInt64. at System.Convert.ToUInt64(Int16 value) at Samples.ConvertToUInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt64\ToUInt64(System.Int16)\Convert.cs:line 18
R S T U V W
Convert.ToUInt64(System.String) Method
X
[ILASM]
Y
.method public hidebysig static unsigned int64 ToUInt64(string value) [C#]
Z
public static ulong ToUInt64(string value)
980
Contents | Index
System
Convert ToUInt64() Method
Summary Converts a System.String to a System.UInt64. A
Parameters
B
Parameter
Description
C
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Integer style.
D E F
Description
G
This method parses value using the information in a System.Globalization.NumberFormatInfo instance initialized for the current system culture. This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDecimal(System.String).
H I J K
Exceptions
L
Exception
Condition
System.ArgumentNullException
value is null reference.
System.FormatException
value cannot be converted to a numeric value.
System.OverflowException
The numeric value of value is greater than System.UInt64.MaxValue or less than System.UInt64.MinValue.
M N O P Q R S
Example
T
using System;
U
namespace Samples { public class ConvertToUInt64 { public static void Main() { string s; try { s = UInt64.MaxValue.ToString();
V W X Y Z
981
Contents | Index
Convert
System
ToUInt64() Method
Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt64(s)); s = UInt64.MinValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt64(s)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt64(s));
A B C
} catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = ((Decimal) UInt64.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt64(s)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
D E F G H I J K L }
M }
N
}
O
The output is
P From String 18446744073709551615 yields 18446744073709551615 From String 0 yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseUInt64(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToUInt64(String value) at Samples.ConvertToUInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt64\ToUInt64(System.String)\Convert.cs:line 19 Exception: System.OverflowException: Value was either too large or too small for a UInt64. at System.Number.ParseUInt64(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToUInt64(String value) at Samples.ConvertToUInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt64\ToUInt64(System.String)\Convert.cs:line 29
Q R S T U V W X Y Z
982
Contents | Index
System
Convert ToUInt64() Method
Convert.ToUInt64(System.String, System.Int32) Method [ILASM]
.method public hidebysig static unsigned int64 ToUInt64(string value, int32 fromBase)
A
[C#]
B
public static ulong ToUInt64(string value, int fromBase)
C
Summary
D
Converts the System.String representation of a number in a specified base to an equivalent 64-bit unsigned integer.
E
Parameters
G
F
H
Parameter
Description
value
A System.String containing a number.
fromBase
The base of the number in value, which must be 2, 8, 10, or 16.
I J K L M
Return Value
N
A 64-bit unsigned integer equivalent to the number in value.
O
Description
P
If fromBase is 16, you can prefix the number specified by the value parameter with “0x” or “0X”.
Q R
Exceptions
S
Exception
Condition
System.ArgumentException
fromBase is not 2, 8, 10, or 16.
T U V W
Convert.ToUInt64(System.String, System.IFormatProvider) Method
X
[ILASM]
Y
.method public hidebysig static unsigned int64 ToUInt64(string value, class System.IFormatProvider provider)
Z
[C#]
public static ulong ToUInt64(string value, IFormatProvider provider)
983
Contents | Index
Convert
System
ToUInt64() Method
Summary Converts a System.String to a System.UInt64. A
Parameters
B C
Parameter
Description
value
The System.String to be converted. The string is in the System.Globalization.NumberStyles.Integer style.
provider
A System.Object that implements the System.IFormatProvider interface and supplies a System.Globalization.NumberFormatInfo instance containing culture-specific formatting information.
D E F G H I
Description
J
This method parses value using the information in the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the string is parsed using the formatting information of the current system culture. This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDecimal(System.Int64, System.IFormatProvider).
K L M N O
Exceptions
P Q
Exception
Condition
R
System.ArgumentNullException
value is a null reference.
System.FormatException
value cannot be converted to a numeric value.
System.OverflowException
The numeric value of value is greater than System.UInt64.MaxValue or less than System.UInt64.MinValue.
S T U V W X Y Z
984
Contents | Index
System
Convert ToUInt64() Method
Example using System; using System.Globalization;
A namespace Samples { public class ConvertToUInt64 { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; try { s = " ~0"; Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt64(s, c)); s = (UInt64.MaxValue).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt64(s, c)); s = (UInt64.MinValue).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt64(s, c)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt64(s, c)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = ((Decimal) UInt64.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Convert.ToUInt64(s, c)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
B C D E F G H I J K L M N O P Q R S T U V W X Y Z
985
Contents | Index
Convert
System
ToUInt64() Method
The output is From String ~0 yields 0 From String 18446744073709551615 yields 18446744073709551615 From String 0 yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseUInt64(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToUInt64(String value, IFormatProvider provider) at Samples.ConvertToUInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt64\ToUInt64(System.String,System.IFormatProvider)\Convert.cs:line 26 Exception: System.OverflowException: Value was either too large or too small for a UInt64. at System.Number.ParseUInt64(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToUInt64(String value, IFormatProvider provider) at Samples.ConvertToUInt64.Main() in C:\Books\BCL\Samples\System\Convert\ ToUInt64\ToUInt64(System.String,System.IFormatProvider)\Convert.cs:line 36
A B C D E F G H I J
Convert.ToUInt64(System.DateTime) Method
K
[ILASM]
L
.method public hidebysig static unsigned int64 ToUInt64(valuetype System.DateTime value)
M
[C#]
N
public static ulong ToUInt64(DateTime value)
O
Summary
P
Calling this method always throws System.InvalidCastException.
Q
Parameters
R S
Parameter
Description
value
A System.DateTime.
T U V
Exceptions
W X
Exception
Condition
System.InvalidCastException
This conversion is not supported.
Y Z
986
Contents | Index
System
Convert ToUInt64() Method
Convert.ToUInt64(System.UInt32) Method [ILASM]
.method public hidebysig static unsigned int64 ToUInt64(unsigned int32 value) [C#]
A
public static ulong ToUInt64(uint value)
B C
Summary
D
Converts a System.UInt32 to a System.UInt64.
E
Parameters
F
Parameter
Description
value
The 32-bit unsigned integer value to be converted.
G H I J
Description
K
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDecimal(System.Int64).
L M
Example
N
using System;
O
namespace Samples { public class ConvertToUInt64 { public static void Main() { uint u = UInt32.MaxValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToUInt64(u)); u = UInt16.MinValue; Console.WriteLine("From UInt32 {0} yields {1}", u, Convert.ToUInt64(u)); } } }
P Q R S T U V W X Y Z
987
Contents | Index
Convert
System
ToUInt64() Method
The output is From UInt32 4294967295 yields 4294967295 From UInt32 0 yields 0
A B C
Convert.ToUInt64(System.UInt64) Method
D
[ILASM]
.method public hidebysig static unsigned int64 ToUInt64(unsigned int64 value)
E
[C#]
public static ulong ToUInt64(ulong value)
F G
Summary
H
Converts a System.UInt64 to a System.UInt64.
I
Parameters
J K
Parameter
Description
value
The 64-bit unsigned integer value to be converted.
L M N O
Return Value
P
value is returned unchanged.
Q
Description
R
[Note: This method is provided for completeness.] This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDecimal(System.Decimal).
S T U
Example
V
using System;
W
namespace Samples { public class ConvertToUInt64 { public static void Main() { ulong u = UInt64.MaxValue; Console.WriteLine("From UInt64 {0} yields {1}",
X Y Z
988
Contents | Index
System
Convert ToUInt64() Method
u, Convert.ToUInt64(u)); u = UInt64.MinValue; Console.WriteLine("From UInt64 {0} yields {1}", u, Convert.ToUInt64(u));
A
} }
B
}
C
The output is
D E
From UInt64 18446744073709551615 yields 18446744073709551615 From UInt64 0 yields 0
F G
Convert.ToUInt64(System.UInt16) Method
H
[ILASM]
I
.method public hidebysig static unsigned int64 ToUInt64(unsigned int16 value)
J
[C#]
public static ulong ToUInt64(ushort value)
K L
Summary
M
Converts a System.UInt16 to a System.UInt64.
N
Parameters
O
Parameter
Description
value
The 16-bit unsigned integer value to be converted.
P Q R S
Description
T
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Convert.ToDecimal(System.Int32).
U V
Example
W
using System;
X
namespace Samples { public class ConvertToUInt64 { public static void Main()
Y Z
989
Contents | Index
Convert
System
ToUInt64() Method
{ ushort u = UInt16.MaxValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToUInt64(u)); u = UInt16.MinValue; Console.WriteLine("From UInt16 {0} yields {1}", u, Convert.ToUInt64(u));
A B C
} }
D
}
E
The output is
F
From UInt16 65535 yields 65535 From UInt16 0 yields 0
G H I J K L M N O P Q R S T U V W X Y Z
990
Contents | Index
System DateTime Structure
BCL
Object ValueType DateTime
A
IComparable
B
IFormattable IConvertible
NotStandardized
C D
Summary
E
Represents an instant in time, expressed as a date and time of day.
F
Type Summary
G
public struct DateTime : IComparable, IFormattable, IConvertible { // Constructors public DateTime (int year, int month, int day); public DateTime (int year, int month, int day, int hour, int minute, int second); public DateTime (int year, int month, int day, int hour, int minute, int second, int millisecond); MS public DateTime (int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar); MS public DateTime (int year, int month, int day, int hour, int minute, int second, Calendar calendar); MS public DateTime (int year, int month, int day, Calendar calendar); public DateTime (long ticks);
H I J K L M N O P Q R S T
// Fields public static readonly DateTime MaxValue = new DateTime (3155378975999999999); public static readonly DateTime MinValue = new DateTime (0);
U V
// Properties public DateTime Date { get; } public int Day { get; } MS public DayOfWeek DayOfWeek { get; } public int DayOfYear { get; } public int Hour { get; } public int Millisecond { get; } public int Minute { get; } public int Month { get; }
W X Y Z
991
Contents | Index
DateTime Structure
System
DateTime Structure
public public public public public public public
A B
static DateTime Now { get; } int Second { get; } long Ticks { get; } TimeSpan TimeOfDay { get; } static DateTime Today { get; } static DateTime UtcNow { get; } int Year { get; }
C // Methods public DateTime Add (TimeSpan value); public DateTime AddDays (double value); public DateTime AddHours (double value); public DateTime AddMilliseconds (double value); public DateTime AddMinutes (double value); public DateTime AddMonths (int months); public DateTime AddSeconds (double value); public DateTime AddTicks (long value); public DateTime AddYears (int value); public static int Compare (DateTime t1, DateTime t2); public int CompareTo (object value); public static int DaysInMonth (int year, int month); public override bool Equals (object value); public static bool Equals (DateTime t1, DateTime t2); MS public static DateTime FromFileTime (long fileTime); MS 1.1 public static DateTime FromFileTimeUtc (long fileTime); MS CF public static DateTime FromOADate (double d); MS public string[] GetDateTimeFormats (); MS public string[] GetDateTimeFormats (char format); MS public string[] GetDateTimeFormats (char format, IFormatProvider provider); MS public string[] GetDateTimeFormats (IFormatProvider provider); public override int GetHashCode (); MS public TypeCode GetTypeCode (); public static bool IsLeapYear (int year); public static DateTime operator +(DateTime d, TimeSpan t); public static bool operator ==(DateTime d1, DateTime d2); public static bool operator >(DateTime t1, DateTime t2); public static bool operator >=(DateTime t1, DateTime t2); public static bool operator !=(DateTime d1, DateTime d2); public static bool operator <(DateTime t1,
D E F G H I J K L M N O P Q R S T U V W X Y Z
992
Contents | Index
System
DateTime Structure DateTime Structure
DateTime t2); public static bool operator <=(DateTime t1, DateTime t2); public static TimeSpan operator -(DateTime d1, DateTime d2); public static DateTime operator -(DateTime d, TimeSpan t); public static DateTime Parse (string s); public static DateTime Parse (string s, IFormatProvider provider); public static DateTime Parse (string s, IFormatProvider provider, DateTimeStyles styles); public static DateTime ParseExact (string s, string format, IFormatProvider provider); public static DateTime ParseExact (string s, string format, IFormatProvider provider, DateTimeStyles style); public static DateTime ParseExact (string s, string[] formats, IFormatProvider provider, DateTimeStyles style); public TimeSpan Subtract (DateTime value); public DateTime Subtract (TimeSpan value); MS public long ToFileTime (); MS 1.1 public long ToFileTimeUtc (); public DateTime ToLocalTime (); public string ToLongDateString (); public string ToLongTimeString (); MS CF public double ToOADate (); public string ToShortDateString (); public string ToShortTimeString (); public override string ToString (); public string ToString (string format); public string ToString (string format, IFormatProvider provider); public string ToString (IFormatProvider provider); public DateTime ToUniversalTime () // MS MS MS MS MS MS MS
A B C D E F G H I J K L M N O P Q R S T U V W
Explicit Interface Members bool IConvertible.ToBoolean(IFormatProvider provider); byte IConvertible.ToByte(IFormatProvider provider); char IConvertible.ToChar(IFormatProvider provider); DateTime IConvertible.ToDateTime(IFormatProvider provider); decimal IConvertible.ToDecimal(IFormatProvider provider); double IConvertible.ToDouble(IFormatProvider provider); short IConvertible.ToInt16(IFormatProvider provider);
X Y Z
993
Contents | Index
DateTime Structure
System
DateTime Structure
MS MS MS MS MS MS MS MS
A B C
int IConvertible.ToInt32(IFormatProvider provider); long IConvertible.ToInt64(IFormatProvider provider); sbyte IConvertible.ToSByte(IFormatProvider provider); float IConvertible.ToSingle(IFormatProvider provider); object IConvertible.ToType(Type type,IFormatProvider provider); ushort IConvertible.ToUInt16(IFormatProvider provider); uint IConvertible.ToUInt32(IFormatProvider provider); ulong IConvertible.ToUInt64(IFormatProvider provider);
}
D E F
BA This is one of the few places in the library where we use operator overloading.
G
Traditionally, operator overloading has been a much-abused feature—almost all proposed usages for it in the BCL were rejected. But this one, I believe, is completely legitimate. DateTime can be considered a built-in type on the order of int and double. It is stack allocated and is immutable. Our usage of operator overloading in this class is not overly creative. The >= operator does exactly what a developer would expect. No guessing is required.
H I J K
Notice that we also provide nicely named methods for each of the operators for developers using languages that do not support operator overloading, since overloading is not required in the CLS.
L M N
KG It is surprising how difficult it can be to model a point in time. The DateTime type stores a point in time in Local or Universal Coordinated Time (abbreviated as UTC, a mix of the English and French acronyms). Just as we don’t store units such as Kilometers or degrees Celsius with the Int32, we do not store the “units” with the DateTime type such as Local, or UTC. By default, the DateTime object assumes local time. We made this decision because most uses of DateTime are interesting only in the current time zone. The DateTime type does not internally store the time zone offset it is in. An implication of that is that if you perform these operations:
O P Q R S T U
DateTime.Now.ToUniversalTime() DateTime.Now.ToUniversalTime().ToUniversalTime()
V
you get different results as each operation on DateTime assumes the value starts out in Local time.
W X
An outcome of this is that at the daylight savings time boundaries, times may not be represented accurately for the crossover hours. When using DateTime we suggest
Y Z
continued
994
Contents | Index
System
DateTime Structure DateTime Structure
you use Universal Times for comparing DateTime values from different sources. Of course for display purposes Local time is still the best bet. A
JR It’s interesting to note that DateTime’s Parse method defines the IFormat-
B
Provider parameter as the second parameter and its DateTimeStyles parameter as the third parameter. Contrast this to the Parse methods for Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, and Decimal. For the numeric types, their Parse methods define the IFormatProvider method as the third parameter and the NumberStyles parameter as the second parameter.
C D E F
Description
G
The System.DateTime value type represents dates and times with values ranging from 00:00:00, 1/1/0001 (Common Era) to 23:59:59 PM, 12/31/9999. [Note: Time values are measured in 100-nanosecond units, ticks, and a particular date is the number of ticks since 12:00 Midnight, January 1, 1 in the Gregorian calendar. For example, a ticks value of 31241376000000000L represents the date, Friday, January 01, 0100 12:00:00 AM. Time values can be added to, or subtracted from, an instance of System.DateTime. Time values can be negative or positive, and expressed in units such as ticks, seconds, or instances of System.TimeSpan. Methods and properties in this value type take into account details such as leap years and the number of days in a month. 12:00:00 AM is Midnight.]
H I J K L M N O
Example
P
using System; using System.Globalization; namespace Samples { public class DateTimeSample { public static void Main() { DateTime dt = DateTime.Now; string[] formats = {"d", "D", "f", "F", "g", "G", "m", "r", "s", "t", "T", "u", "U", "y", "dddd, MMMM dd yyyy", "ddd, MMM d \"'\"yy", "dddd, MMMM dd", "M/yy", "dd-MM-yy"}; foreach(string format in formats) {
Q R S T U V W X Y Z
995
Contents | Index
DateTime Structure
System
DateTime Structure
Console.WriteLine("Displayed using format {0} is: {1}", format, dt.ToString(format, DateTimeFormatInfo.InvariantInfo));
A
} DateTime d = new DateTime(1959, 9, 3); DateTime b = new DateTime(1973, 9, 25); Console.WriteLine("Today is {0:F}", dt); TimeSpan age = dt - d; Console.WriteLine("Damien is: {0:F}", age); Console.WriteLine("He has lived: {0,2:F} days", age.TotalDays); age = dt - b; Console.WriteLine("Brad is: {0:F}", age); Console.WriteLine("He has lived: {0,2:F} days", age.TotalDays);
B C D E F G H }
I
} }
J K
The output is
L
Displayed using format d is: 06/10/2003 Displayed using format D is: Tuesday, 10 June 2003 Displayed using format f is: Tuesday, 10 June 2003 09:00 Displayed using format F is: Tuesday, 10 June 2003 09:00:20 Displayed using format g is: 06/10/2003 09:00 Displayed using format G is: 06/10/2003 09:00:20 Displayed using format m is: June 10 Displayed using format r is: Tue, 10 Jun 2003 09:00:20 GMT Displayed using format s is: 2003-06-10T09:00:20 Displayed using format t is: 09:00 Displayed using format T is: 09:00:20 Displayed using format u is: 2003-06-10 09:00:20Z Displayed using format U is: Monday, 09 June 2003 23:00:20 Displayed using format y is: 2003 June Displayed using format dddd, MMMM dd yyyy is: Tuesday, June 10 2003 Displayed using format ddd, MMM d "'"yy is: Tue, Jun 10 '03 Displayed using format dddd, MMMM dd is: Tuesday, June 10 Displayed using format M/yy is: 6/03 Displayed using format dd-MM-yy is: 10-06-03 Today is Tuesday, 10 June 2003 9:00:20 AM Damien is: 15986.09:00:20.1009552 He has lived: 15986.38 days Brad is: 10850.09:00:20.1009552 He has lived: 10850.38 days
M N O P Q R S T U V W X Y Z
996
Contents | Index
System
DateTime Structure DateTime() Constructor
DateTime(System.Int32, System.Int32, System.Int32) Constructor [ILASM]
public rtspecialname specialname instance void .ctor(int32 year, int32 month, int32 day)
A
[C#]
B
public DateTime(int year, int month, int day)
C
Summary
D
Constructs and initializes a new instance of the System.DateTime structure with a specified year, month, and day.
E
Parameters
G
F
H
Parameter
Description
year
A System.Int32 containing the year (1 through 9999).
month
A System.Int32 containing the month (1 through 12).
day
A System.Int32 containing the day (1 through the number of days in month).
I J K L M N
Description
O
The time of day for the resulting System.DateTime is midnight (00:00:00).
P Q
Exceptions
R
Exception
System.ArgumentOutOfRangeException
Condition
S
year is less than 1 or greater than 9999.
T
-or-
U
month is less than 1 or greater than 12.
V
-or-
W
day is less than 1 or greater than the number of days in month.
X Y Z
997
Contents | Index
DateTime Structure
System
DateTime() Constructor
Example using System; namespace Samples { public class DateTimeConstructor { public static void Main() { DateTime d = new DateTime(2002, 11, 26); Console.WriteLine("This represents {0:d}", d); Console.WriteLine("It was a {0}", d.DayOfWeek); } } }
A B C D E F G H
The output is
I This represents 26/11/2002 It was a Tuesday
J K L M
DateTime(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) Constructor
N
[ILASM]
O
public rtspecialname specialname instance void .ctor(int32 year, int32 month, int32 day, int32 hour, int32 minute, int32 second)
P
[C#]
public DateTime(int year, int month, int day, int hour, int minute, int second)
Q R
Summary
S
Constructs and initializes a new instance of the System.DateTime structure with a specified year, month, day, hour, minute, and second.
T U V W X Y Z
998
Contents | Index
System
DateTime Structure DateTime() Constructor
Parameters Parameter
Description
year
A System.Int32 containing the year (1 through 9999).
month
A System.Int32 containing the month (1 through 12).
C
day
A System.Int32 containing the day (1 through the number of days in month).
D
hour
A System.Int32 containing the hours (0 through 23).
minute
A System.Int32 containing the minutes (0 through 59).
second
A System.Int32 containing the seconds (0 through 59).
A B
E F G H I J
Exceptions
K
Exception
Condition
L
year is less than 1 or greater than 9999.
M
-or-
N
month is less than 1 or greater than 12.
O
-orP
day is less than 1 or greater than the number of days in month. System.ArgumentOutOfRangeException
-or-
Q
hour is less than 0 or greater than 23.
R
-or-
S
minute is less than 0 or greater than 59.
T
-orU
second is less than 0 or greater than 59.
V W X Y Z
999
Contents | Index
DateTime Structure
System
DateTime() Constructor
Example using System; namespace Samples { public class DateTimeConstructor { public static void Main() { DateTime d = new DateTime(1959, 9, 3, 3, 30, 0); Console.WriteLine("This represents {0:d}", d); Console.WriteLine("It was a {0}", d.DayOfWeek); } } }
A B C D E F G H
The output is
I This represents 3/09/1959 It was a Thursday
J K L M
DateTime(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) Constructor
N
[ILASM]
O
public rtspecialname specialname instance void .ctor(int32 year, int32 month, int32 day, int32 hour, int32 minute, int32 second, int32 millisecond)
P
[C#]
Q
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)
R S
Summary
T
Constructs and initializes a new instance of the System.DateTime structure with a specified year, month, day, hour, minute, second, and millisecond.
U V W X Y Z
1000
Contents | Index
System
DateTime Structure DateTime() Constructor
Parameters Parameter
Description
year
A System.Int32 containing the year (1 through 9999).
month
A System.Int32 containing the month (1 through 12).
C
day
A System.Int32 containing the day (1 through the number of days in month).
D
hour
A System.Int32 containing the hours (0 through 23).
minute
A System.Int32 containing the minutes (0 through 59).
second
A System.Int32 containing the seconds (0 through 59).
H
millisecond
A System.Int32 containing the milliseconds.
I
A B
E F G
J K
Exceptions
L
Exception
Condition
M
year is less than 1 or greater than 9999.
N
-or-
O
month is less than 1 or greater than 12.
P
-or-
Q
day is less than 1 or greater than the number of days in month.
R
-orSystem.ArgumentOutOfRangeException
hour is less than 0 or greater than 23.
S
-or-
T
minute is less than 0 or greater than 59.
U
-or-
V
second is less than 0 or greater than 59.
W
-or-
X
millisecond is less than 0 or greater than 999.
Y System.ArgumentException
The specified parameters evaluate to a date less than System.DateTime.MinValue or greater than System.DateTime.MaxValue.
Z
1001
Contents | Index
DateTime Structure
System
DateTime() Constructor
Example using System; namespace Samples { public class DateTimeConstructor { public static void Main() { DateTime d = new DateTime(1959, 9, 3, 3, 30, 0, 0); Console.WriteLine("This represents {0:d}", d); Console.WriteLine("It was a {0}", d.DayOfWeek); } } }
A B C D E F G H
The output is
I This represents 3/09/1959 It was a Thursday
J K L
N
DateTime(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Globalization.Calendar) Constructor
O
[ILASM]
M
public rtspecialname specialname instance void .ctor(int32 year, int32 month, int32 day, int32 hour, int32 minute, int32 second, int32 millisecond, class System.Globalization.Calendar calendar)
P Q
[C#]
R
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar)
S T
Summary
U
Initializes a new instance of the System.DateTime structure to the specified year, month, day, hour, minute, second, and millisecond for the specified System.Globalization.Calendar.
V W X Y Z
1002
Contents | Index
System
DateTime Structure DateTime() Constructor
Parameters Parameter
Description
year
The year (1 through 9999).
month
The month (1 through the number of months in calendar).
C
day
The day (1 through the number of days in month).
D
hour
The hours (0 through 23).
minute
The minutes (0 through 59).
second
The seconds (0 through 59).
H
millisecond
The milliseconds (0 through 999).
I
calendar
The System.Globalization.Calendar that applies to this System.DateTime.
A B
E F G
J K L
Description
M
The allowable values for year, month, and day depend on the specified System.Globalization.Calendar. An exception is thrown if the specified date and time cannot be expressed using calendar. The System.Globalization namespace provides several calendars including System.Globalization.GregorianCalendar and System.Globalization.JulianCalendar.
N O P Q R S T U V W X Y Z
1003
Contents | Index
DateTime Structure
System
DateTime() Constructor
Exceptions Exception
Condition
System.ArgumentNullException
calendar is null.
A B C
year is less than 1 or greater than 9999.
D
-or-
E
month is less than 1 or greater than the number of months in calendar.
F
-or-
G
day is less than 1 or greater than the number of days in month.
H System.ArgumentOutOfRangeException
I
-orhour is less than 0 or greater than 23.
J
-or-
K
minute is less than 0 or greater than 59. -or-
L
second is less than 0 or greater than 59.
M
-or-
N
millisecond is less than 0 or greater than 999.
O System.ArgumentException
P
Specified parameters evaluate to less than System.DateTime.MinValue or more than System.DateTime.MaxValue.
Q R S T
DateTime(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Int32, System.Globalization.Calendar) Constructor
U
[ILASM]
public rtspecialname specialname instance void .ctor(int32 year, int32 month, int32 day, int32 hour, int32 minute, int32 second, class System.Globalization.Calendar calendar)
V W
[C#]
X
public DateTime(int year, int month, int day, int hour, int minute, int second, Calendar calendar)
Y Z
1004
Contents | Index
System
DateTime Structure DateTime() Constructor
Summary Initializes a new instance of the System.DateTime structure to the specified year, month, day, hour, minute, and second for the specified System.Globalization.Calendar. A
Parameters
B C
Parameter
Description
year
The year (1 through 9999).
E
month
The month (1 through the number of months in calendar).
F
day
The day (1 through the number of days in month).
hour
The hours (0 through 23).
minute
The minutes (0 through 59).
J
second
The seconds (0 through 59).
K
calendar
The System.Globalization.Calendar that applies to this System.DateTime.
D
G H I
L M N
Description
O
The allowable values for year, month, and day depend on the specified System.Globalization.Calendar. An exception is thrown if the specified date and time cannot be expressed using calendar. The System.Globalization namespace provides several calendars including System.Globalization.GregorianCalendar and System.Globalization.JulianCalendar.
P Q R S T U V W X Y Z
1005
Contents | Index
DateTime Structure
System
DateTime() Constructor
Exceptions Exception
Condition
System.ArgumentNullException
calendar is null.
A B C
year is less than 1 or greater than 9999.
D
-or-
E
month is less than 1 or greater than the number of months in calendar.
F
-or-
G System.ArgumentOutOfRangeException
H
day is less than 1 or greater than the number of days in month. -or-
I
hour is less than 0 or greater than 23.
J
-or-
K
minute is less than 0 or greater than 59. -or-
L
second is less than 0 or greater than 59.
M N
System.ArgumentException
O
Specified parameters evaluate to less than System.DateTime.MinValue or more than System.DateTime.MaxValue.
P Q
DateTime(System.Int32, System.Int32, System.Int32, System.Globalization.Calendar) Constructor
R S
[ILASM]
T
public rtspecialname specialname instance Mvoid .ctor(int32 year, int32 month, int32 day, class System.Globalization.Calendar calendar)
U
[C#]
public DateTime(int year, int month, int day, Calendar calendar)
V W
Summary
X
Initializes a new instance of the System.DateTime structure to the specified year, month, and day for the specified System.Globalization.Calendar.
Y Z
1006
Contents | Index
System
DateTime Structure DateTime() Constructor
Parameters Parameter
Description
year
The year (1 through 9999).
month
The month (1 through the number of months in calendar).
C
day
The day (1 through the number of days in month).
D
calendar
The System.Globalization.Calendar that applies to this System.DateTime.
A B
E F G
Description
H
The time of day for the resulting System.DateTime is midnight (00:00:00). The allowable values for year, month, and day depend on the specified System.Globalization.Calendar. An exception is thrown if the specified date and time cannot be expressed using calendar. The System.Globalization namespace provides several calendars including System.Globalization.GregorianCalendar and System.Globalization.JulianCalendar.
I J K L M N
Exceptions
O P
Exception
Condition Q
System.ArgumentNullException
R
calendar is null.
S
year is less than 1 or greater than 9999.
T
-orSystem.ArgumentOutOfRangeException
U
month is less than 1 or greater than the number of months in calendar.
V
-or-
W
day is less than 1 or greater than the number of days in month. System.ArgumentException
X
Specified parameters evaluate to less than System.DateTime.MinValue or more than System.DateTime.MaxValue.
Y Z
1007
Contents | Index
DateTime Structure
System
DateTime() Constructor
DateTime(System.Int64) Constructor [ILASM]
public rtspecialname specialname instance void .ctor(int64 ticks)
A
[C#]
public DateTime(long ticks)
B C
Summary
D
Constructs and initializes a new instance of the System.DateTime structure with the date and time expressed in 100-nanosecond units.
E F
Parameters
G H
Parameter
Description
ticks
A System.Int64 containing the date and time expressed in 100-nanosecond units.
I J K
Exceptions
L M
Exception
Condition
System.ArgumentOutOfRangeException
The date and time represented by ticks is less than System.DateTime.MinValue or greater than System.DateTime.MaxValue.
N O P Q
Example
R
using System; namespace Samples { public class DateTimeConstructor { public static void Main() { DateTime d1 = new DateTime(1959, 9, 3, 3, 30, 0); DateTime d2 = new DateTime(d1.Ticks); Console.WriteLine("This represents {0:d}", d2); Console.WriteLine("It was a {0}", d2.DayOfWeek); } } }
S T U V W X Y Z
1008
Contents | Index
System
DateTime Structure MaxValue Field
The output is This represents 3/09/1959 It was a Thursday
A B
DateTime.MaxValue Field
C
[ILASM]
D
.field public static initOnly valuetype System.DateTime MaxValue
E
[C#]
public static readonly DateTime MaxValue = new DateTime (3155378975999999999)
F G
Summary
H
A constant representing the largest possible value of System.DateTime.
I
Description
J
The value of this field is equivalent to 23:59:59.9999999, 12/31/9999, exactly one 100nanosecond tick before 00:00:00, 01/01/10000.
K L
Example
M
using System; namespace Samples { public class DateTimeMaxValue { public static void Main() { DateTime d1 = DateTime.MaxValue; DateTime d2 = DateTime.MinValue; Console.WriteLine("MaxValue {0:d}", d1); Console.WriteLine("MinValue {0:d}", d2); if(d1 > d2) Console.WriteLine("{0:F} is greater than {1:F}", d1, d2); } } }
N O P Q R S T U V W X
The output is
Y
MaxValue 31/12/9999 MinValue 1/01/0001 Friday, 31 December 9999 11:59:59 PM is greater than Monday, 1 January 0001 12:00:00 AM
Z
1009
Contents | Index
DateTime Structure
System
MinValue Field
DateTime.MinValue Field [ILASM]
.field public static initOnly valuetype System.DateTime MinValue
A
[C#]
public static readonly DateTime MinValue = new DateTime (0)
B C
Summary
D
A constant representing the smallest possible value of System.DateTime.
E F
Description
G
The value of this field is equivalent to 00:00:00.0000000, 1/1/0001.
H
Example
I
using System; namespace Samples { public class DateTimeMinValue { public static void Main() { DateTime d1 = DateTime.MaxValue; DateTime d2 = DateTime.MinValue; Console.WriteLine("MaxValue {0:d}", d1); Console.WriteLine("MinValue {0:d}", d2); if(d1 > d2) Console.WriteLine("{0:F} is greater than {1:F}", d1, d2); } } }
J K L M N O P Q R S T
The output is
U MaxValue 31/12/9999 MinValue 1/01/0001 Friday, 31 December 9999 11:59:59 PM is greater than Monday, 1 January 0001 12:00:00 AM
V W X Y Z
1010
Contents | Index
System
DateTime Structure Day Property
DateTime.Date Property [ILASM]
.property valuetype System.DateTime Date { public hidebysig specialname instance valuetype System.DateTime get_Date() }
A
[C#]
B
public DateTime Date { get; }
C
Summary
D
Gets the date component of the current instance.
E F
Property Value
G
A new System.DateTime instance with the same date as the current instance, and the time value set to midnight (00:00:00).
H I
Example
J
using System; namespace Samples { public class DateTimeDate { public static void Main() { DateTime d = DateTime.Now; Console.WriteLine("Date now is: {0}", d.Date); } } }
K L M N O P Q R
The output is
S T
Date now is: 10/06/2003 12:00:00 AM
U V
DateTime.Day Property
W
[ILASM]
X
.property int32 Day { public hidebysig specialname instance int32 get_Day() } [C#]
Y
public int Day { get; }
Z
1011
Contents | Index
DateTime Structure
System
DayOfWeek Property
Summary Gets the day of the month represented by the current instance. A
Property Value
B
A System.Int32 between 1 and 31 set to the day of the month component of the current instance.
C D
Example
E
using System; namespace Samples { public class DateTimeDay { public static void Main() { DateTime d = DateTime.Now; Console.WriteLine("Today is day {0} of the month", d.Day); } } }
F G H I J K L M
The output is
N O
Today is day 10 of the month
P Q
DateTime.DayOfWeek Property
R [ILASM]
S
.property valuetype System.DayOfWeek DayOfWeek { public hidebysig specialname instance valuetype System.DayOfWeek get_DayOfWeek() }
T
[C#]
public DayOfWeek DayOfWeek { get; }
U V
Summary
W
Gets the day of the week represented by this instance.
X Y
Property Value
Z
A System.DayOfWeek enumerated constant that indicates the day of the week. This property value ranges from zero, indicating Sunday, to six, indicating Saturday.
1012
Contents | Index
System
DateTime Structure Hour Property
DateTime.DayOfYear Property [ILASM]
.property int32 DayOfYear { public hidebysig specialname instance int32 get_DayOfYear() }
A
[C#]
B
public int DayOfYear { get; }
C
Summary
D
Gets the day of the year represented by the current instance.
E F
Property Value
G
A System.Int32 between 1 and 366 set to the day of the year component of the current instance.
H I
Example
J
using System; namespace Samples { public class DateTimeDayOfYear { public static void Main() { DateTime d = DateTime.Now; Console.WriteLine("Today is day {0} of the year", d.DayOfYear); } } }
K L M N O P Q R
The output is
S T
Today is day 161 of the year
U V
DateTime.Hour Property
W
[ILASM]
X
.property int32 Hour { public hidebysig specialname instance int32 get_Hour() } [C#]
Y
public int Hour { get; }
Z
1013
Contents | Index
DateTime Structure
System
Millisecond Property
Summary Gets the hour represented by the current instance. A
Property Value
B
A System.Int32 between 0 and 23 set to the hour component of the current instance.
C
Example
D
using System; namespace Samples { public class DateTimeHour { public static void Main() { DateTime d = DateTime.Now; Console.WriteLine("This is the {0} hour of the day", d.Hour); } } }
E F G H I J K L
The output is
M
This is the 10 hour of the day
N O
DateTime.Millisecond Property
P
[ILASM]
Q
.property int32 Millisecond { public hidebysig specialname instance int32 get_Millisecond() }
R
[C#]
S
public int Millisecond { get; }
T
Summary
U
Gets the milliseconds component of the date represented by the current instance.
V W
Property Value
X
A System.Int32 between 0 and 999 set to the milliseconds component of the current instance.
Y Z
1014
Contents | Index
System
DateTime Structure Minute Property
Example using System; namespace Samples { public class DateTimeMillisecond { public static void Main() { DateTime d = DateTime.Now; for(int i = 0; i < 10; i++) { Console.WriteLine("{0}", d.Millisecond); d = DateTime.Now; } } } }
A B C D E F G H I J
The output is
K
79 89 89 89 89 89 89 89 89 89
L M N O P Q R
DateTime.Minute Property
S
[ILASM]
T
.property int32 Minute { public hidebysig specialname instance int32 get_Minute() }
U
[C#]
V
public int Minute { get; }
W
Summary
X
Gets the minute component of the date represented by the current instance.
Y
Property Value
Z
A System.Int32 between 0 and 59 set to the minute component of the current instance.
1015
Contents | Index
DateTime Structure
System
Month Property
Example using System; namespace Samples { public class DateTimeMinutes { public static void Main() { DateTime d = DateTime.Now; Console.WriteLine("It is {0} minutes past the hour", d.Minute); } } }
A B C D E F G
The output is
H
It is 14 minutes past the hour
I J K
DateTime.Month Property
L
[ILASM]
.property int32 Month { public hidebysig specialname instance int32 get_Month() }
M
[C#]
N
public int Month { get; }
O
Summary
P
Gets the month component of the date represented by the current instance.
Q
Property Value
R
A System.Int32 between 1 and 12 set to the month component of the current instance.
S
Example
T
using System; namespace Samples { public class DateTimeMonth { public static void Main() { DateTime d = DateTime.Now; Console.WriteLine("It is the {0} month of the year", d.Month); } } }
U V W X Y Z
1016
Contents | Index
System
DateTime Structure Second Property
The output is It is the 6 month of the year
A
DateTime.Now Property
B
[ILASM] .property valuetype System.DateTime Now { public hidebysig static specialname valuetype System.DateTime get_Now() } [C#] public static DateTime Now { get; }
C D E F
Summary
G
Gets a System.DateTime representing the current local date and time.
H
Description
I
The resolution of this property depends on the system timer.
J
Example
K
using System; namespace Samples { public class DateTimeNow { public static void Main() { Console.WriteLine("It is {0}", DateTime.Now); } } }
L M N O P Q R S
The output is
T U
It is 10/06/2003 10:16:17 AM
V
DateTime.Second Property
W X
[ILASM] .property int32 Second { public hidebysig specialname instance int32 get_Second() } [C#] public int Second { get; }
Y Z
1017
Contents | Index
DateTime Structure
System
Ticks Property
Summary Gets the seconds component of the date represented by the current instance. A
Property Value
B
A System.Int32 between 0 and 59 set to the seconds component of the current instance.
C
Example
D
using System; namespace Samples { public class DateTimeSecond { public static void Main() { DateTime d = DateTime.Now; Console.WriteLine("It is {0} seconds into this minute", d.Second); } } }
E F G H I J K L M
The output is
N It is 12 seconds into this minute
O P
DateTime.Ticks Property
Q R
[ILASM]
S
[C#]
.property int64 Ticks { public hidebysig specialname instance int64 get_Ticks() } public long Ticks { get; }
T U
Summary
V
Gets the number of 100-nanosecond ticks that represent the date and time of the current instance.
W X
Description
Y
The value of this property is the number of 100-nanosecond intervals that have elapsed since 00:00:00, 1/1/0001. The value of the property is between System.DateTime.MinValue and System.DateTime.MaxValue.
Z
1018
Contents | Index
System
DateTime Structure TimeOfDay Property
Example using System; namespace Samples { public class DateTimeTicks { public static void Main() { DateTime d = DateTime.Now; Console.WriteLine("{0} is {1} ticks", d, d.Ticks); } } }
A B C D E F G H
The output is
I 10/06/2003 12:47:08 PM is 631908460281984384 ticks
J K
DateTime.TimeOfDay Property
L
[ILASM]
M
.property valuetype System.TimeSpan TimeOfDay { public hidebysig specialname instance valuetype System.TimeSpan get_TimeOfDay() }
N
[C#]
O
public TimeSpan TimeOfDay { get; }
P
Summary
Q
Gets the time of day of the current instance.
R S
Example
T
using System; namespace Samples { public class DateTimeTimeOfDay { public static void Main() { DateTime d = DateTime.Now; Console.WriteLine(d.TimeOfDay); } } }
U V W X Y Z
1019
Contents | Index
DateTime Structure
System
Today Property
The output is 12:47:53.1430656
A B
DateTime.Today Property
C
[ILASM]
D
.property valuetype System.DateTime Today { public hidebysig static specialname valuetype System.DateTime get_Today() }
E
[C#]
public static DateTime Today { get; }
F G
Summary
H
Gets the current date.
I
Property Value
J
A System.DateTime instance set to the date of the current instance, with the time set to 00:00:00.
K L
Example
M
using System; namespace Samples { public class DateTimeToday { public static void Main() { Console.WriteLine(DateTime.Today); } } }
N O P Q R S T
The output is
U V
10/06/2003 12:00:00 AM
W X
DateTime.UtcNow Property
Y
[ILASM]
.property valuetype System.DateTime UtcNow { public hidebysig static specialname valuetype System.DateTime get_UtcNow() }
Z
[C#]
public static DateTime UtcNow { get; }
1020
Contents | Index
System
DateTime Structure Year Property
Summary Gets the current time converted to coordinated universal time (UTC). A
Example
B
using System; namespace Samples { public class DateTimeUtcNow { public static void Main() { Console.WriteLine("GMT time is {0}", DateTime.UtcNow); } } }
C D E F G H I J
The output is
K
GMT time is 10/06/2003 2:49:35 AM
L M
DateTime.Year Property
N
[ILASM]
O
.property int32 Year { public hidebysig specialname instance int32 get_Year() }
P
[C#]
public int Year { get; }
Q
Summary
R
Gets the year component of the date represented by the current instance.
S
Property Value
T
A System.Int32 between 1 and 9999 set to the year component of the current instance.
U V
Example
W
using System; namespace Samples { public class DateTimeYear { public static void Main() { DateTime d = DateTime.Now;
X Y Z
1021
Contents | Index
DateTime Structure
System
Add() Method
Console.WriteLine(d.Year); } } }
A
The output is
B C
2003
D E
DateTime.Add(System.TimeSpan) Method
F
[ILASM]
G
.method public hidebysig instance valuetype System.DateTime Add(valuetype System.TimeSpan value)
H
[C#]
public DateTime Add(TimeSpan value)
I J
Summary
K
Adds the value of a specified System.TimeSpan instance to the current instance.
L
Parameters
M N
Parameter
Description
O
value
A System.TimeSpan instance.
P Q
Return Value
R
A System.DateTime instance set to the sum of the date and time of the current instance and the time interval represented by value.
S T
Description
U
A specified System.TimeSpan is added to the current instance of System.DateTime, and the result is returned as a new System.DateTime.
V W
Exceptions
X Y Z
Exception
Condition
System.ArgumentOutOfRangeException
The resulting System.DateTime is less than System.DateTime.MinValue or greater than System.DateTime.MaxValue.
1022
Contents | Index
System
DateTime Structure AddDays() Method
Example using System; namespace Samples { public class DateTimeAdd { public static void Main() { DateTime d = DateTime.Now; TimeSpan t = new TimeSpan(24, 0, 0); Console.WriteLine("TimeSpan is {0:F}", t); d = d.Add(t); Console.WriteLine("Tomorrow is {0:F}", d); } } }
A B C D E F G H I
The output is
J TimeSpan is 1.00:00:00 Tomorrow is Wednesday, 11 June 2003 9:08:56 AM
K L M
DateTime.AddDays(System.Double) Method
N
[ILASM]
O
.method public hidebysig instance valuetype System.DateTime AddDays(float64 value)
P
[C#]
public DateTime AddDays(double value)
Q
Summary
R
Adds a specified number of days to the value of the current instance.
S T
Parameters
U
Parameter
Description
value
A System.Double containing the number of whole and fractional days. For example, 4.5 is equivalent to 4 days, 12 hours, 0 minutes, 0 seconds, 0 milliseconds, and 0 ticks. value can be negative or positive.
V W X Y Z
1023
Contents | Index
DateTime Structure
System
AddDays() Method
Return Value A System.DateTime instance set to the sum of the date and time represented by the current instance and the number of days represented by value. A
Description
B
[Note: value is rounded to the nearest tick.] This member must be implemented if the Extended Numerics Library is present in the implementation.
C D E
Exceptions
F G
Exception
Condition
System.ArgumentOutOfRangeException
The resulting System.DateTime is less than System.DateTime.MinValue or greater than System.DateTime.MaxValue.
H I J K
Example
L
using System; namespace Samples { public class DateTimeAddDays { public static void Main() { DateTime dt = DateTime.Now; Console.WriteLine("Date is {0:F}", dt); double[] doubles = new double[]{ 0.5, 7, 14}; foreach(double d in doubles) Console.WriteLine("In {0} days it will be {1}", d, dt.AddDays(d)); } } }
M N O P Q R S T U V
The output is
W
Date is Tuesday, 10 June 2003 9:09:44 AM In 0.5 days it will be 10/06/2003 9:09:44 PM In 7 days it will be 17/06/2003 9:09:44 AM In 14 days it will be 24/06/2003 9:09:44 AM
X Y Z
1024
Contents | Index
System
DateTime Structure AddHours() Method
DateTime.AddHours(System.Double) Method [ILASM]
.method public hidebysig instance valuetype System.DateTime AddHours(float64 value)
A
[C#]
B
public DateTime AddHours(double value)
C
Summary
D
Adds a specified number of hours to the value of the current instance.
E F
Parameters
G H
Parameter
Description
value
A System.Double containing the number of whole and fractional hours. For example, 4.5 is equivalent to 4 hours, 30 minutes, 0 seconds, 0 milliseconds, and 0 ticks. value can be negative or positive.
I J K L
Return Value
M
A System.DateTime instance set to the sum of the date and time represented by the current instance and the number of hours represented by value.
N O
Description
P
[Note: value is rounded to the nearest tick.] This member must be implemented if the Extended Numerics Library is present in the implementation.
Q R S
Exceptions
T
Exception
Condition
System.ArgumentOutOfRangeException
The resulting System.DateTime is less than System.DateTime.MinValue or greater than System.DateTime.MaxValue.
U V W X Y Z
1025
Contents | Index
DateTime Structure
System
AddMilliseconds() Method
Example using System; namespace Samples { public class DateTimeAddHours { public static void Main() { DateTime dt = DateTime.Now; Console.WriteLine("Date is {0:F}", dt); double[] doubles = new double[]{ -0.5, 0.5, 12, 24}; foreach(double d in doubles) Console.WriteLine("In {0} hours it will be {1}", d, dt.AddHours(d)); } } }
A B C D E F G H I
The output is
J K
Date is Tuesday, 10 June 2003 9:10:44 AM In -0.5 hours it will be 10/06/2003 8:40:44 AM In 0.5 hours it will be 10/06/2003 9:40:44 AM In 12 hours it will be 10/06/2003 9:10:44 PM In 24 hours it will be 11/06/2003 9:10:44 AM
L M N O P
DateTime.AddMilliseconds(System.Double) Method
Q
[ILASM]
R
.method public hidebysig instance valuetype System.DateTime AddMilliseconds(float64 value) [C#]
S
public DateTime AddMilliseconds(double value)
T U
Summary
V
Adds a specified number of milliseconds to the value of the current instance.
W X Y Z
1026
Contents | Index
System
DateTime Structure AddMilliseconds() Method
Parameters Parameter
Description
value
A System.Double containing the number of whole and fractional milliseconds. For example, 4.5 is equivalent to 4 milliseconds and 5,000 ticks. value can be negative or positive.
A B C D
Return Value
E
A System.DateTime instance set to the sum of the date and time represented by the current instance and the number of milliseconds represented by value.
F G
Description
H
[Note: value is rounded to the nearest tick.] This member must be implemented if the Extended Numerics Library is present in the implementation.
I J K
Exceptions
L M
Exception
Condition N
System.ArgumentOutOfRangeException
The resulting System.DateTime is less than System.DateTime.MinValue or greater than System.DateTime.MaxValue.
O P Q
Example
R
using System; namespace Samples { public class DateTimeAddMilliseconds { public static void Main() { DateTime dt = DateTime.Now; Console.WriteLine("Date is {0:F}", dt); double[] doubles = new double[]{ 1, 1000, 1000000}; foreach(double d in doubles) Console.WriteLine("In {0} milliseconds it will be {1}", d, dt.AddMilliseconds(d)); } } }
S T U V W X Y Z
1027
Contents | Index
DateTime Structure
System
AddMinutes() Method
The output is Date is Tuesday, 10 June 2003 9:11:48 AM In 1 milliseconds it will be 10/06/2003 9:11:48 AM In 1000 milliseconds it will be 10/06/2003 9:11:49 AM In 1000000 milliseconds it will be 10/06/2003 9:28:28 AM
A B C D
DateTime.AddMinutes(System.Double) Method
E
[ILASM]
.method public hidebysig instance valuetype System.DateTime AddMinutes(float64 value)
F G
[C#]
public DateTime AddMinutes(double value)
H I
Summary
J
Adds a specified number of minutes to the value of the current instance.
K
Parameters
L M
Parameter
Description
value
A System.Double containing the number of whole and fractional minutes. For example, 4.5 is equivalent to 4 minutes, 30 seconds, 0 milliseconds, and 0 ticks. value can be negative or positive.
N O P Q R
Return Value
S
A System.DateTime instance set to the sum of the date and time represented by the current instance and the number of minutes represented by value.
T U
Description
V
[Note: value is rounded to the nearest tick.] This member must be implemented if the Extended Numerics Library is present in the implementation.
W X Y Z
1028
Contents | Index
System
DateTime Structure AddMonths() Method
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
The resulting System.DateTime is less than System.DateTime.MinValue or greater than System.DateTime.MaxValue.
A B C D
Example
E
using System; namespace Samples { public class DateTimeAddMinutes { public static void Main() { DateTime dt = DateTime.Now; Console.WriteLine("Date is {0:F}", dt); double[] doubles = new double[]{ -1, 30, 60, 1440}; foreach(double d in doubles) Console.WriteLine("In {0} minutes it will be {1}", d, dt.AddMinutes(d)); } } }
F G H I J K L M N O P
The output is
Q
Date is Tuesday, 10 June 2003 9:12:44 AM In -1 minutes it will be 10/06/2003 9:11:44 AM In 30 minutes it will be 10/06/2003 9:42:44 AM In 60 minutes it will be 10/06/2003 10:12:44 AM In 1440 minutes it will be 11/06/2003 9:12:44 AM
R S T U
DateTime.AddMonths(System.Int32) Method
V
[ILASM]
W
.method public hidebysig instance valuetype System.DateTime AddMonths(int32 months)
X
[C#]
public DateTime AddMonths(int months)
Y Z
Summary Adds a specified number of months to the value of the current instance.
1029
Contents | Index
DateTime Structure
System
AddMonths() Method
Parameters Parameter
Description
months
A System.Int32 containing the number of months. months can be positive or negative, and may be greater than the number of months in a year.
A B C D
Return Value
E
A System.DateTime instance set to the sum of the date and time represented by the current instance and months.
F G
Description
H
This method does not change the value of the current DateTime instance. Instead, a new DateTime instance is returned whose value is the result of this operation.
I J
Exceptions
K L
Exception
M N
System.ArgumentOutOfRangeException
O
Condition The resulting System.DateTime is less than System.DateTime.MinValue or greater than System.DateTime.MaxValue. -orThe months parameter is less than -120,000 or greater than 120,000.
P Q
Example
R
using System; namespace Samples { public class DateTimeAddMonths { public static void Main() { DateTime dt = DateTime.Now; Console.WriteLine("Date is {0:F}", dt); int[] ints = new int[]{ -12, 1, 12}; foreach(int i in ints) Console.WriteLine("In {0} months it will be {1}", i, dt.AddMonths(i)); } } }
S T U V W X Y Z
1030
Contents | Index
System
DateTime Structure AddSeconds() Method
The output is Date is Tuesday, 10 June 2003 9:13:32 AM In -12 months it will be 10/06/2002 9:13:32 AM In 1 months it will be 10/07/2003 9:13:32 AM In 12 months it will be 10/06/2004 9:13:32 AM
A B C D
DateTime.AddSeconds(System.Double) Method
E
[ILASM]
.method public hidebysig instance valuetype System.DateTime AddSeconds(float64 value)
F G
[C#]
public DateTime AddSeconds(double value)
H
Summary
I
Adds a specified number of seconds to the value of the current instance.
J K
Parameters
L
Parameter
Description
value
A System.Double containing the number of whole and fractional seconds. For example, 4.5 is equivalent to 4 seconds, 500 milliseconds, and 0 ticks. value can be positive or negative.
M N O P Q
Return Value
R
A System.DateTime instance set to the sum of the date and time represented by the current instance and the number of seconds represented by value.
S
Description
U
[Note: value is rounded to the nearest tick.] This member must be implemented if the Extended Numerics Library is present in the implementation.
V
T
W X Y Z
1031
Contents | Index
DateTime Structure
System
AddTicks() Method
Exceptions Exception
Condition
System.ArgumentException
The resulting System.DateTime is less than System.DateTime.MinValue or greater than System.DateTime.MaxValue.
A B C D
Example
E
using System; namespace Samples { public class DateTimeAddSeconds { public static void Main() { DateTime dt = DateTime.Now; Console.WriteLine("Date is {0:F}", dt); double[] doubles = new double[]{ -60, 60, 3600}; foreach(double d in doubles) Console.WriteLine("In {0} seconds it will be {1}", d, dt.AddSeconds(d)); } } }
F G H I J K L M N O
The output is
P Q
Date is Tuesday, 10 June 2003 9:14:44 AM In -60 seconds it will be 10/06/2003 9:13:44 AM In 60 seconds it will be 10/06/2003 9:15:44 AM In 3600 seconds it will be 10/06/2003 10:14:44 AM
R S T U
DateTime.AddTicks(System.Int64) Method
V
[ILASM]
.method public hidebysig instance valuetype System.DateTime AddTicks(int64 value)
W
[C#]
X
public DateTime AddTicks(long value)
Y
Summary
Z
Adds a specified number of ticks to the value of the current instance.
1032
Contents | Index
System
DateTime Structure AddTicks() Method
Parameters Parameter
Description
value
A System.Int64 containing the number of 100-nanosecond ticks. value can be positive or negative.
A B C D
Return Value
E
A System.DateTime instance set to the sum of the date and time represented by the current instance and the time represented by value.
F G
Exceptions
H
Exception
Condition
System.ArgumentOutOfRangeException
The resulting System.DateTime is less than System.DateTime.MinValue or greater than System.DateTime.MaxValue.
I J K L M
Example
N
using System; namespace Samples { public class DateTimeAddTicks { public static void Main() { DateTime dt = DateTime.Now; Console.WriteLine("Date is {0:F}", dt); long[] longs = new long[]{ -1000000000, 1000000000}; foreach(long l in longs) Console.WriteLine("In {0} ticks it will be {1}", l, dt.AddTicks(l)); } } }
O P Q R S T U V W X Y
The output is
Z
Date is Tuesday, 10 June 2003 9:15:47 AM In -1000000000 ticks it will be 10/06/2003 9:14:07 AM In 1000000000 ticks it will be 10/06/2003 9:17:27 AM
1033
Contents | Index
DateTime Structure
System
AddYears() Method
DateTime.AddYears(System.Int32) Method [ILASM]
.method public hidebysig instance valuetype System.DateTime AddYears(int32 value)
A
[C#]
public DateTime AddYears(int value)
B C
Summary
D
Adds a specified number of years to the value of the current instance.
E
Parameters
F G
Parameter
Description
value
A System.Int32 containing the number of years. value can be positive or negative.
H I J K
Return Value
L
A System.DateTime instance set to the sum of the date and time represented by the current instance and the number of years represented by value.
M N
Exceptions
O P
Exception
Condition
System.ArgumentOutOfRangeException
The resulting System.DateTime is less than System.DateTime.MinValue or greater than System.DateTime.MaxValue.
Q R S T
Example
U
using System; namespace Samples { public class DateTimeAddYears { public static void Main() { DateTime dt = DateTime.Now; Console.WriteLine("Date is {0:F}", dt); int[] ints = new int[]{ -10, 10, 100};
V W X Y Z
1034
Contents | Index
System
DateTime Structure Compare() Method
foreach(int i in ints) Console.WriteLine("In {0} years it will be {1}", i, dt.AddYears(i)); }
A
} }
B C
The output is
D Date is Tuesday, 10 June 2003 9:16:37 AM In -10 years it will be 10/06/1993 9:16:37 AM In 10 years it will be 10/06/2013 9:16:37 AM In 100 years it will be 10/06/2103 9:16:37 AM
E F G H
DateTime.Compare(System.DateTime, System.DateTime) Method
I [ILASM]
J
.method public hidebysig static int32 Compare(valuetype System.DateTime t1, valuetype System.DateTime t2)
K
[C#]
L
public static int Compare(DateTime t1, DateTime t2)
M
Summary
N
Returns the sort order of the two specified instances of System.DateTime.
O
Parameters
P Q
Parameter
Description
t1
The first System.DateTime.
S
t2
The second System.DateTime.
T
R
U V
Return Value
W
A System.Int32 containing a value that reflects the sort order of the two specified instances of System.DateTime. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number.
X Y Z
1035
Contents | Index
DateTime Structure
System
Compare() Method
Value Type
Condition
A
Any negative number
t1 < t2.
B
Zero
t1 == t2.
Any positive number
t1 > t2.
C D E
Example
F
using System; namespace Samples { public class DateTimeAddCompare { public static void Main() { DateTime d1 = DateTime.MinValue; DateTime d2 = DateTime.MaxValue; DoCompare(d1,d2); DoCompare(d2,DateTime.MinValue); DoCompare(DateTime.MaxValue, DateTime.MaxValue); } private static void DoCompare(DateTime d1, DateTime d2) { int compare = DateTime.Compare(d1, d2); if(compare == 0) Console.WriteLine("{0} is equal to {1}", d1, d2); else if(compare < 0) Console.WriteLine("{0} is less than {1}", d1, d2); else Console.WriteLine("{0} is greater than {1}", d1, d2); } } }
G H I J K L M N O P Q R S T U V W
The output is
X Y
1/01/0001 12:00:00 AM is less than 31/12/9999 11:59:59 PM 31/12/9999 11:59:59 PM is greater than 1/01/0001 12:00:00 AM 31/12/9999 11:59:59 PM is equal to 31/12/9999 11:59:59 PM
Z
1036
Contents | Index
System
DateTime Structure CompareTo() Method
DateTime.CompareTo(System.Object) Method [ILASM]
.method public final hidebysig virtual int32 CompareTo(object value) [C#]
A
public int CompareTo(object value)
B C
Summary
D
Returns the sort order of the current instance compared to the specified System.Object.
E
Parameters
F G
Parameter
Description
value
The System.Object to compare to the current instance.
H I J
Return Value
K
A System.Int32 containing a value that reflects the sort order of the current instance as compared to value. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number.
L M N O
Value
Description
Any negative number
Current instance < value.
Q
Zero
Current instance == value.
R
Any positive number
Current instance > value, or value is a null reference.
P
S T U
Description
V
Any instance of System.DateTime, regardless of its value, is considered greater than a null reference. [Note: This method is implemented to support the System.IComparable interface.]
W X Y Z
1037
Contents | Index
DateTime Structure
System
CompareTo() Method
Exceptions Exception
Condition
System.ArgumentException
value is not a System.DateTime and is not a null reference.
A B C
Example
D
using System; namespace Samples { public class DateTimeCompareTo { private static string CompareDateTimes(DateTime dt1, DateTime dt2) { int i = dt1.CompareTo(dt2); if(0 == i) return String.Format("{0} is equal to {1}", dt1, dt2); if(i > 0) return String.Format("{0} is greater than {1}", dt1, dt2); else return String.Format("{0} is less than {1}", dt1, dt2); } public static void Main() { DateTime dt1 = DateTime.MinValue; DateTime dt2 = DateTime.MaxValue; Console.WriteLine(CompareDateTimes(dt1, dt1)); Console.WriteLine(CompareDateTimes(dt1, dt2)); Console.WriteLine(CompareDateTimes(dt2, dt1)); } } }
E F G H I J K L M N O P Q R S T U
The output is
V 1/01/0001 12:00:00 AM is equal to 1/01/0001 12:00:00 AM 1/01/0001 12:00:00 AM is less than 31/12/9999 11:59:59 PM 31/12/9999 11:59:59 PM is greater than 1/01/0001 12:00:00 AM
W X Y Z
1038
Contents | Index
System
DateTime Structure DaysInMonth() Method
DateTime.DaysInMonth(System.Int32, System.Int32) Method [ILASM]
.method public hidebysig static int32 DaysInMonth(int32 year, int32 month) [C#]
A
public static int DaysInMonth(int year, int month)
B C
Summary
D
Returns the number of days in a specified month of a specified year.
E
Parameters
F G
Parameter
Description
year
A System.Int32 containing the year.
I
month
The month (a System.Int32 between 1 and 12).
J
H
K
Return Value
L
A System.Int32 set to the number of days in the specified month for the specified year. If the specified month is February, the return value is 28 or 29 depending upon whether the specified year is a leap year.
M N O P
Exceptions
Q
Exception
Condition
System.ArgumentOutOfRangeException
month is less than 1 or greater than 12.
R S T
Example
U
using System; namespace Samples { public class DateTimeDaysInMonth { public static void Main() { DateTime d = DateTime.Now; Console.WriteLine( "In year {0} in month {1} are {2} days",
V W X Y Z
1039
Contents | Index
DateTime Structure
System
Equals() Method
d.Year, d.Month, DateTime.DaysInMonth(d.Year, d.Month)); } }
A
}
B
The output is
C
In year 2003 in month 6 are 30 days
D E F
DateTime.Equals(System.Object) Method
G
[ILASM]
H
.method public hidebysig virtual bool Equals(object value)
I
public override bool Equals(object value)
[C#]
J
Summary
K
Returns a System.Boolean indicating whether the current instance is equal to a specified object.
L M
Parameters
N O
Parameter
Description
value
A System.Object to compare with the current instance.
P Q R
Return Value
S
true if value is a specified System.DateTime instance equal to the current instance; otherwise, false. [Note: This method overrides System.Object.Equals.]
T U V
Example
W
using System; namespace Samples { public class DateTimeEquals { public static void Main() { DateTime d1 = DateTime.MinValue;
X Y Z
1040
Contents | Index
System
DateTime Structure Equals() Method
DateTime d2 = DateTime.MaxValue; Console.WriteLine("Is {0} equal to {1}? {2}", d1, d1, d1.Equals(d1)); Console.WriteLine("Is {0} equal to {1}? {2}", d1, d2, d1.Equals(d2)); string s = "31/12/9999 11:59:59 PM"; Console.WriteLine("Is {0} equal to {1}? {2}", d2, s, d1.Equals(s));
A B C
}
D
} }
E F
The output is
G Is 1/01/0001 12:00:00 AM equal to 1/01/0001 12:00:00 AM? True Is 1/01/0001 12:00:00 AM equal to 31/12/9999 11:59:59 PM? False Is 31/12/9999 11:59:59 PM equal to 31/12/9999 11:59:59 PM? False
H I J
DateTime.Equals(System.DateTime, System.DateTime) Method
K
[ILASM]
L
.method public hidebysig static bool Equals(valuetype System.DateTime t1, valuetype System.DateTime t2)
M
[C#]
N
public static bool Equals(DateTime t1, DateTime t2)
O
Summary
P
Returns a System.Boolean indicating whether two specified instances of System.DateTime are equal.
Q
Parameters
S
R
T
Parameter
Description
t1
The first System.DateTime.
t2
The second System.DateTime.
U V W X Y
Return Value
Z
true if the two System.DateTime values are equal; otherwise, false.
1041
Contents | Index
DateTime Structure
System
FromFileTime() Method
Example using System; namespace Samples { public class DateTimeEquals { public static void Main() { DateTime d1 = DateTime.MinValue; DateTime d2 = DateTime.MaxValue; Console.WriteLine("Is {0} equal to {1}? {2}", d1, d1, DateTime.Equals(d1, d1)); Console.WriteLine("Is {0} equal to {1}? {2}", d1, d2, DateTime.Equals(d1, d2)); } } }
A B C D E F G H I J
The output is
K
Is 1/01/0001 12:00:00 AM equal to 1/01/0001 12:00:00 AM? True Is 1/01/0001 12:00:00 AM equal to 31/12/9999 11:59:59 PM? False
L M N
DateTime.FromFileTime(System.Int64) Method
O
[ILASM]
.method public hidebysig static valuetype System.DateTime FromFileTime(int64 fileTime)
P Q
[C#]
public static DateTime FromFileTime(long fileTime)
R S
Summary
T
Returns a System.DateTime equivalent to the specified operating system file time stamp.
U
Parameters
V W
Parameter
Description
fileTime
A Windows file time.
X Y Z
Return Value A System.DateTime value representing the date and time of fileTime, adjusted to local time. 1042
Contents | Index
System
DateTime Structure FromFileTimeUtc() Method
Description fileTime is a 64-bit signed integer value representing a Windows file timestamp. The time stamp is the number of 100-nanosecond intervals that have elapsed since January 1, 1601 A.D. (C.E.) 12:00 A.M. coordinated universal time (UTC).
A B
Exceptions
C
Exception
Condition
System.ArgumentOutOfRangeException
fileTime is not valid.
D E F G H
DateTime.FromFileTimeUtc(System.Int64) Method
I [ILASM]
J
.method public hidebysig static valuetype System.DateTime FromFileTimeUtc(int64 fileTime)
K
[C#]
public static DateTime FromFileTimeUtc(long fileTime)
L M
Summary
N
Returns a System.DateTime equivalent to the specified operating system file time stamp, adjusted to coordinated universal time (UTC).
O P
Parameters
Q
Parameter
Description
fileTime
A Windows file time expressed in ticks.
R S T U
Return Value
V
A System.DateTime value representing the date and time of fileTime, adjusted to coordinated universal time (UTC).
W X
Description
Y
fileTime is a 64-bit signed integer value representing a Windows file time stamp. The time stamp is the number of 100-nanosecond intervals that have elapsed since January 1, 1601 A.D. (C.E.)
Z
1043
Contents | Index
DateTime Structure
System
FromOADate() Method
12:00 A.M. coordinated universal time (UTC). The System.DateTime.FromFileTimeUtc method returns fileTime relative to January 1, 1 A.D. (C.E.) 12:00 A.M. A
Exceptions
B C D
Exception
Condition
System.ArgumentOutOfRangeException
fileTime is less than 0.
E F
DateTime.FromOADate(System.Double) Method
G H
[ILASM] .method public hidebysig static valuetype System.DateTime FromOADate(float64 d) [C#] public static DateTime FromOADate(double d)
I J K
Summary
L
Returns a System.DateTime equivalent to the specified OLE Automation Date.
M
Parameters
N O
Parameter
Description
d
An OLE Automation Date value.
P Q R
Description
S
d must be a value between negative 657435.0 through positive 2958466.0. It is stored as a double-precision floating-point number. See System.DateTime.ToOADate.
T U V
Exceptions
W X
Exception
Condition
System.ArgumentException
The date is not a valid OLE Automation Date value.
Y Z
1044
Contents | Index
System
DateTime Structure GetDateTimeFormats() Method
DateTime.GetDateTimeFormats() Method [ILASM] .method public hidebysig instance class System.String[] GetDateTimeFormats() [C#] public string[] GetDateTimeFormats()
A B C
Summary
D
Converts the value of this instance to all the string representations supported by the standard System.DateTime format specifiers.
E F
Return Value
G
A string array where each element is the representation of the value of this instance formatted with one of the standard System.DateTime formatting specifiers.
H I
Description
J
Each element of the return value is formatted using information from the current culture. For more information about culture-specific formatting information for the current culture, see System.Globalization.CultureInfo.CurrentCulture. For more information about the standard formatting specifiers, see System.Globalization.DateTimeFormatInfo.
K L M N O
DateTime.GetDateTimeFormats(System.Char) Method
P
[ILASM] .method public hidebysig instance class System.String[] GetDateTimeFormats(valuetype System.Char format) [C#] public string[] GetDateTimeFormats(char format)
Q R S T
Summary
U
Converts the value of this instance to all the string representations supported by the specified standard System.DateTime format specifier.
V W
Parameters
X Y
Parameter
Description
format
A Unicode character containing a format specifier.
Z
1045
Contents | Index
DateTime Structure
System
GetDateTimeFormats() Method
Return Value A string array where each element is the representation of the value of this instance formatted with the format standard System.DateTime formatting specifier. A B
Description
C
Each element of the return value is formatted using information from the current culture. For more information about culture-specific formatting information for the current culture, see System.Globalization.CultureInfo.CurrentCulture. For more information about the standard formatting specifiers, see System.Globalization.DateTimeFormatInfo.
D E F G
DateTime.GetDateTimeFormats(System.Char, System.IFormatProvider) Method
H I
[ILASM] .method public hidebysig instance class System.String[] GetDateTimeFormats (valuetype System.Char format, class System.IFormatProvider provider) [C#] public string[] GetDateTimeFormats(char format, IFormatProvider provider)
J K L M N
Summary
O
Converts the value of this instance to all the string representations supported by the specified standard System.DateTime format specifier and culture-specific formatting information.
P Q
Parameters
R S T
Parameter
Description
format
A Unicode character containing a format specifier.
provider
A System.IFormatProvider that supplies culture-specific formatting information about this instance.
U V W X
Return Value
Y
A string array where each element is the representation of the value of this instance formatted with one of the standard System.DateTime formatting specifiers.
Z
1046
Contents | Index
System
DateTime Structure GetDateTimeFormats() Method
Description Each element of the return value is formatted using culture-specific information supplied by provider. For more information about the standard formatting specifiers, see System.Globalization.DateTimeFormatInfo.
A B C D
DateTime.GetDateTimeFormats(System.IFormatProvider) Method
E
[ILASM] .method public hidebysig instance class System.String[] GetDateTimeFormats(class System.IFormatProvider provider) [C#] public string[] GetDateTimeFormats(IFormatProvider provider)
F G H
Summary
I
Converts the value of this instance to all the string representations supported by the standard System.DateTime format specifiers and the specified culture-specific formatting information.
J K
Parameters
M
L
N
Parameter
Description
provider
A System.IFormatProvider that supplies culture-specific formatting information about this instance.
O P Q R
Return Value
S
A string array where each element is the representation of the value of this instance formatted with one of the standard System.DateTime formatting specifiers.
T U
Description
V
Each element of the return value is formatted using culture-specific information supplied by provider. For more information about the standard formatting specifiers, see System.Globalization.DateTimeFormatInfo.
W X Y Z
1047
Contents | Index
DateTime Structure
System
GetHashCode() Method
DateTime.GetHashCode() Method [ILASM] .method public hidebysig virtual int32 GetHashCode() [C#] public override int GetHashCode()
A B C
Summary
D
Generates a hash code for the current instance.
E F
Description
G
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
H I
Example
J
using System; namespace Samples { public class DateTimeGetHashCode { public static void Main() { DateTime d1 = DateTime.MinValue; DateTime d2 = DateTime.Now; DateTime d3 = DateTime.MaxValue; Console.WriteLine("HashCode for {0} is: {1}", d1, d1.GetHashCode()); Console.WriteLine("HashCode for {0} is: {1}", d2, d2.GetHashCode()); Console.WriteLine("HashCode for {0} is: {1}", d3, d3.GetHashCode()); } } }
K L M N O P Q R S T U V
The output is
W
HashCode for 1/01/0001 12:00:00 AM is: 0 HashCode for 10/06/2003 9:30:07 AM is: 187274506 HashCode for 31/12/9999 11:59:59 PM is: -537061494
X Y Z
1048
Contents | Index
System
DateTime Structure IsLeapYear() Method
DateTime.GetTypeCode() Method [ILASM] .method public final hidebysig virtual valuetype System.TypeCode GetTypeCode() [C#] public TypeCode GetTypeCode()
A B C
Summary
D
Returns the System.TypeCode for value type System.DateTime.
E F
DateTime.IsLeapYear(System.Int32) Method
G
[ILASM] .method public hidebysig static bool IsLeapYear(int32 year) [C#] public static bool IsLeapYear(int year)
H I J
Summary
K
Returns a System.Boolean value indicating whether a specified year is a leap year.
L M
Parameters
N
Parameter
Description
year
A System.Int32 representing the year. year can be positive or negative.
O P Q R
Return Value
S
true if the specified year is a leap year; otherwise, false.
T
Example
U
using System; namespace Samples { public class DateTimeIsLeapYear { public static void Main() { DateTime d = DateTime.Now; for(DateTime end = d.AddYears(20); d < end; d = d.AddYears(1))
V W X Y Z
1049
Contents | Index
DateTime Structure
System
op_Addition() Method
{ if(DateTime.IsLeapYear(d.Year)) Console.WriteLine("Year {0} will be a leap year", d.Year);
A
} }
B }
C
}
D
The output is
E Year Year Year Year Year
F G H
2004 2008 2012 2016 2020
will will will will will
be be be be be
a a a a a
leap leap leap leap leap
year year year year year
I J
DateTime.op_Addition(System.DateTime, System.TimeSpan) Method
K [ILASM] .method public hidebysig static specialname valuetype System.DateTime op_Addition(valuetype System.DateTime d, valuetype System.TimeSpan t) [C#] public static DateTime operator +(DateTime d, TimeSpan t)
L M N O
Summary
P
Adds a specified System.TimeSpan value to a specified System.DateTime value.
Q
Parameters
R S
Parameter
Description
d
A System.DateTime value.
t
A System.TimeSpan value.
T U V W X
Return Value
Y
A System.DateTime instance that is the sum of the values of d and t.
Z
Description The returned value is equivalent to DateTime(d.Ticks + t.Ticks).
1050
Contents | Index
System
DateTime Structure op_Equality() Method
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
The resulting date and time is less than System.DateTime.MinValue or greater than System.DateTime.MaxValue.
A B C D
Example
E
using System; namespace Samples { public class DateTimeOperatorAddition { public static void Main() { DateTime d = new DateTime(1959, 9, 3); TimeSpan t = DateTime.Now - d; Console.WriteLine("I am {0} days old", t.Days); Console.WriteLine( "On {0:F} I will be twice my curent age", DateTime.Now + t); } } }
F G H I J K L M N O P
The output is
Q I am 15986 days old On Sunday, 17 March 2047 7:04:29 PM I will be twice my curent age
R S T
DateTime.op_Equality(System.DateTime, System.DateTime) Method
U [ILASM] .method public hidebysig static specialname bool op_Equality(valuetype System.DateTime d1, valuetype System.DateTime d2) [C#] public static bool operator ==(DateTime d1, DateTime d2)
V W X Y
Summary
Z
Returns a System.Boolean value indicating whether the two specified instances of System.DateTime are equal.
1051
Contents | Index
DateTime Structure
System
op_GreaterThan() Method
Parameters Parameter
Description
d1
The first System.DateTime to compare.
d2
The second System.DateTime to compare.
A B C D E
Return Value
F
true if d1.Ticks value is equal to the d2.Ticks value; otherwise, false.
G
Example
H
using System; namespace Samples { public class DateTimeOperatorEquality { public static void Main() { DateTime d1 = DateTime.MinValue; DateTime d2 = DateTime.MaxValue; Console.WriteLine("Is {0} equal to {1}: {2}", d1, d2, d1 == d2); Console.WriteLine("Is {0} equal to {1}: {2}", d1, d1, d1 == d1); } } }
I J K L M N O P Q R
The output is
S T
Is 1/01/0001 12:00:00 AM equal to 31/12/9999 11:59:59 PM: False Is 1/01/0001 12:00:00 AM equal to 1/01/0001 12:00:00 AM: True
U V W
DateTime.op_GreaterThan(System.DateTime, System.DateTime) Method
X
[ILASM] .method public hidebysig static specialname bool op_GreaterThan(valuetype System.DateTime t1, valuetype System.DateTime t2) [C#] public static bool operator >(DateTime t1, DateTime t2)
Y Z
1052
Contents | Index
System
DateTime Structure op_GreaterThan() Method
Summary Returns a System.Boolean value indicating whether one specified System.DateTime is greater than another specified System.DateTime. A
Parameters
B C
Parameter
Description
t1
A System.DateTime.
E
t2
A System.DateTime.
F
D
G H
Return Value
I
true if t1.Ticks value is greater than the t2.Ticks value; otherwise, false.
J
Example
K
using System; namespace Samples { public class DateTimeOperatorGreaterThan { public static void Main() { DateTime d1 = DateTime.MinValue; DateTime d2 = DateTime.MaxValue; Console.WriteLine("Is {0} greater than {1}: {2}", d1, d2, d1 > d2); Console.WriteLine("Is {0} greater than {1}: {2}", d2, d1, d2 > d1); Console.WriteLine("Is {0} greater than {1}: {2}", d1, d1, d1 > d1); } } }
L M N O P Q R S T U V
The output is
W X
Is 1/01/0001 12:00:00 AM greater than 31/12/9999 11:59:59 PM: False Is 31/12/9999 11:59:59 PM greater than 1/01/0001 12:00:00 AM: True Is 1/01/0001 12:00:00 AM greater than 1/01/0001 12:00:00 AM: False
Y Z
1053
Contents | Index
DateTime Structure
System
op_GreaterThanOrEqual() Method
DateTime.op_GreaterThanOrEqual(System.DateTime, System.DateTime) Method [ILASM] .method public hidebysig static specialname bool op_GreaterThanOrEqual(valuetype System.DateTime t1, valuetype System.DateTime t2) [C#] public static bool operator >=(DateTime t1, DateTime t2)
A B C D E
Summary
F
Returns a System.Boolean value indicating whether one specified System.DateTime is greater than or equal to another specified System.DateTime.
G
Parameters
H I
Parameter
Description
K
t1
A System.DateTime.
L
t2
A System.DateTime.
J
M N
Return Value
O
true if t1.Ticks value is greater than or equal to t2.Ticks value; otherwise, false.
P
Example
Q
using System; namespace Samples { public class DateTimeOperatorGreaterThanOrEqual { public static void Main() { DateTime d1 = DateTime.MinValue; DateTime d2 = DateTime.MaxValue; Console.WriteLine( "Is {0} greater than or equal to {1}: {2}", d1, d2, d1 >= d2); Console.WriteLine( "Is {0} greater than or equal to {1}: {2}", d2, d1, d2 >= d1);
R S T U V W X Y Z
1054
Contents | Index
System
DateTime Structure op_Inequality() Method
Console.WriteLine( "Is {0} greater than or equal to {1}: {2}", d1, d1, d1 >= d1); }
A
} }
B C
The output is
D Is 1/01/0001 12:00:00 AM greater than or equal to 31/12/9999 11:59:59 PM: False Is 31/12/9999 11:59:59 PM greater than or equal to 1/01/0001 12:00:00 AM: True Is 1/01/0001 12:00:00 AM greater than or equal to 1/01/0001 12:00:00 AM: True
E F G
DateTime.op_Inequality(System.DateTime, System.DateTime) Method
H I
[ILASM] .method public hidebysig static specialname bool op_Inequality(valuetype System.DateTime d1, valuetype System.DateTime d2) [C#] public static bool operator !=(DateTime d1, DateTime d2)
J K L
Summary
M
Returns a System.Boolean value indicating whether two specified instances of System.DateTime are not equal.
N O P
Parameters
Q
Parameter
Description
d1
A System.DateTime.
d2
A System.DateTime.
R S T U V
Return Value
W
true if d1.Ticks value is not equal to d2.Ticks value; otherwise, false.
X Y Z
1055
Contents | Index
DateTime Structure
System
op_LessThan() Method
Example using System; namespace Samples { public class DateTimeOperatorInequality { public static void Main() { DateTime d1 = DateTime.MinValue; DateTime d2 = DateTime.MaxValue; Console.WriteLine("Is {0} not equal to {1}: {2}", d1, d2, d1 != d2); Console.WriteLine("Is {0} not equal to {1}: {2}", d1, d1, d1 != d1); } } }
A B C D E F G H I J
The output is
K
Is 1/01/0001 12:00:00 AM not equal to 31/12/9999 11:59:59 PM: True Is 1/01/0001 12:00:00 AM not equal to 1/01/0001 12:00:00 AM: False
L M N
DateTime.op_LessThan(System.DateTime, System.DateTime) Method
O
[ILASM] .method public hidebysig static specialname bool op_LessThan(valuetype System.DateTime t1, valuetype System.DateTime t2) [C#] public static bool operator <(DateTime t1, DateTime t2)
P Q R S
Summary
T
Returns a System.Boolean value indicating whether one specified System.DateTime is less than another specified System.DateTime.
U V
Parameters
W X Y
Parameter
Description
t1
A System.DateTime.
t2
A System.DateTime.
Z
1056
Contents | Index
System
DateTime Structure op_LessThanOrEqual() Method
Return Value true if t1.Ticks value is less than t2.Ticks value; otherwise, false. A
Example
B
using System; namespace Samples { public class DateTimeOperatorLessThan { public static void Main() { DateTime d1 = DateTime.MinValue; DateTime d2 = DateTime.MaxValue; Console.WriteLine("Is {0} less than {1}: {2}", d1, d2, d1 < d2); Console.WriteLine("Is {0} less than {1}: {2}", d2, d1, d2 < d1); Console.WriteLine("Is {0} less than {1}: {2}", d1, d1, d1 < d1); } } }
C D E F G H I J K L M
The output is
N O
Is 1/01/0001 12:00:00 AM less than 31/12/9999 11:59:59 PM: True Is 31/12/9999 11:59:59 PM less than 1/01/0001 12:00:00 AM: False Is 1/01/0001 12:00:00 AM less than 1/01/0001 12:00:00 AM: False
P Q R
DateTime.op_LessThanOrEqual(System.DateTime, System.DateTime) Method
S T
[ILASM] .method public hidebysig static specialname bool op_LessThanOrEqual(valuetype System.DateTime t1, valuetype System.DateTime t2) [C#] public static bool operator <=(DateTime t1, DateTime t2)
U V W X
Summary
Y
Returns a System.Boolean value indicating whether one specified System.DateTime is less than or equal to another specified System.DateTime.
Z
1057
Contents | Index
DateTime Structure
System
op_LessThanOrEqual() Method
Parameters Parameter
Description
t1
A System.DateTime.
t2
A System.DateTime.
A B C D E
Return Value
F
true if t1.Ticks value is less than or equal to t2.Ticks value; otherwise, false.
G
Example
H
using System; namespace Samples { public class DateTimeOperatorLessThanOrEqual { public static void Main() { DateTime d1 = DateTime.MinValue; DateTime d2 = DateTime.MaxValue; Console.WriteLine( "Is {0} less than or equal to {1}: {2}", d1, d2, d1 <= d2); Console.WriteLine( "Is {0} less than or equal to {1}: {2}", d2, d1, d2 <= d1); Console.WriteLine( "Is {0} less than or equal to {1}: {2}", d1, d1, d1 <= d1); } } }
I J K L M N O P Q R S T U
The output is
V W
Is 1/01/0001 12:00:00 AM less than or equal to 31/12/9999 11:59:59 PM: True Is 31/12/9999 11:59:59 PM less than or equal to 1/01/0001 12:00:00 AM: False Is 1/01/0001 12:00:00 AM less than or equal to 1/01/0001 12:00:00 AM: True
X Y Z
1058
Contents | Index
System
DateTime Structure op_Subtraction() Method
DateTime.op_Subtraction(System.DateTime, System.DateTime) Method [ILASM] .method public hidebysig static specialname valuetype System.TimeSpan op_Subtraction(valuetype System.DateTime d1, valuetype System.DateTime d2) [C#] public static TimeSpan operator -(DateTime d1, DateTime d2)
A B C
Summary
D
Subtracts a specified System.DateTime from another specified System.DateTime value, producing a time interval.
E
Parameters
G
F
H
Parameter
Description
d1
A System.DateTime (the minuend).
d2
A System.DateTime (the subtrahend).
I J K L M
Return Value
N
A System.TimeSpan that is the time interval between d1 and d2.
O
Description
P
The returned value is equivalent to System.TimeSpan(d1.Ticks–d2.Ticks).
Q R
Exceptions
S
Exception
Condition
System.ArgumentOutOfRangeException
The resulting date and time is less than System.DateTime.MinValue or greater than System.DateTime.MaxValue.
T U V W X Y Z
1059
Contents | Index
DateTime Structure
System
op_Subtraction() Method
Example using System; namespace Samples { public class DateTimeOperatorSubtraction { public static void Main() { DateTime d = new DateTime(1959, 9, 3); TimeSpan t = DateTime.Now - d; Console.WriteLine("I am {0} days old", t.Days); Console.WriteLine("I was born on {0:F}", DateTime.Now - t); } } }
A B C D E F G H I
The output is
J I am 15986 days old
K L
DateTime.op_Subtraction(System.DateTime, System.TimeSpan) Method
M
[ILASM] .method public hidebysig static specialname valuetype System.DateTime op_Subtraction(valuetype System.DateTime d, valuetype System.TimeSpan t) [C#] public static DateTime operator -(DateTime d, TimeSpan t)
N O P Q
Summary
R
Subtracts a specified System.TimeSpan from a specified System.DateTime.
S T
Parameters
U V
Parameter
Description
W
d
A System.DateTime.
t
A System.TimeSpan.
X Y Z
Return Value A System.DateTime whose value is the value of d minus the value of t. 1060
Contents | Index
System
DateTime Structure Parse() Method
Description The returned value is equivalent to System.DateTime(d.Ticks–t.Ticks). A
Exceptions
B
Exception
Condition
C
The resulting date and time is less than System.DateTime.MinValue or greater than System.DateTime.MaxValue.
D
System.ArgumentOutOfRangeException
E F G
Example
H
using System; namespace Samples { public class DateTimeOperatorSubtraction { public static void Main() { DateTime d = new DateTime(1959, 9, 3); TimeSpan t = DateTime.Now - d; Console.WriteLine("I am {0} days old", t.Days); Console.WriteLine("I was born on {0:F}", DateTime.Now - t); } } }
I J K L M N O P Q R
The output is
S
I am 15986 days old I was born on Thursday, 3 September 1959 12:00:00 AM
T U V
DateTime.Parse(System.String) Method
W
[ILASM] .method public hidebysig static valuetype System.DateTime Parse(string s) [C#] public static DateTime Parse(string s)
X Y Z
Summary Returns the specified System.String converted to a System.DateTime value. 1061
Contents | Index
DateTime Structure
System
Parse() Method
Parameters Parameter
Description
s
A System.String containing a value to convert. The string is interpreted using the System.Globalization.DateTimeStyles.None style.
A B C D
Description
E
This version of System.DateTime.Parse is equivalent to System.DateTime.Parse(s, null, System.Globalization.DateTimeStyles.None ). The string s is parsed using the formatting information in a System.Globalization.DateTimeFormatInfo initialized for the current system culture. In order for the string to be successfully parsed, it is required to represent a date and time value in one of the standard System.DateTime patterns described in System.Globalization.DateTimeFormatInfo. If the string contains only a time, and no date, then the current date (System.DateTime.Now ) is used. If the string contains only a date and no time, this method assumes 12 A.M. Any leading, trailing, and inner white space characters are ignored.
F G H I J K L M
Exceptions
N O P
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s does not contain a valid string representation of a time or date and time.
Q R S T
Example
U
using System; namespace Samples { public class DateTimeParse { public static void Main() { try { string s = DateTime.Now.ToString(); DateTime d = DateTime.Parse(s);
V W X Y Z
1062
Contents | Index
System
DateTime Structure Parse() Method
Console.WriteLine("DateTime is {0:F}", d); d = DateTime.Parse(s.Substring(0, 10)); Console.WriteLine("DateTime is {0:F}", d); d = DateTime.Parse(String.Empty);
A
} catch(FormatException e) { Console.WriteLine("Exception: {0}", e); }
B C D
} }
E
}
F
The output is
G H
DateTime is Tuesday, 10 June 2003 9:41:10 AM DateTime is Tuesday, 10 June 2003 12:00:00 AM Exception: System.FormatException: String was not recognized as a valid DateTime. at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) at System.DateTime.Parse(String s, IFormatProvider provider, DateTimeStyles styles) at System.DateTime.Parse(String s, IFormatProvider provider) at System.DateTime.Parse(String s) at Samples.DateTimeParse.Main() in C:\Books\BCL\Samples\System\DateTime\ Parse(System.String)\DateTime.cs:line 16
I J K L M N O P
DateTime.Parse(System.String, System.IFormatProvider) Method
Q [ILASM] .method public hidebysig static valuetype System.DateTime Parse(string s, class System.IFormatProvider provider) [C#] public static DateTime Parse(string s, IFormatProvider provider)
R S T U
Summary
V
Returns the specified System.String converted to a System.DateTime value.
W X Y Z
1063
Contents | Index
DateTime Structure
System
Parse() Method
Parameters Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.DateTimeStyles.None style.
provider
A System.IFormatProvider that supplies a System.Globalization.DateTimeFormatInfo object containing culture-specific format information about s.
A B C D E F
Description
G
This version of System.DateTime.Parse is equivalent to System.DateTime.Parse(s, provider, DateTimeStyles.None). The string s is parsed using the culture-specific formatting information from the System.Globalization.DateTimeFormatInfo instance supplied by provider. If provider is null or a System.Globalization.DateTimeFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. In order for the string to be successfully parsed, it is required to represent a date and time value in one of the standard System.DateTime patterns described in System.Globalization.DateTimeFormatInfo. If the string contains only a time, and no date, then the current date (System.DateTime.Now) is used. If the string contains only a date and no time, this method assumes 12 A.M. Any leading, trailing, and inner white space characters are ignored.
H I J K L M N O P Q
Exceptions
R S
Exception
Condition
System.ArgumentException
s is a null reference.
System.FormatException
s does not contain a valid string representation of a time or date and time.
T U V W X Y Z
1064
Contents | Index
System
DateTime Structure Parse() Method
Example using System; using System.Globalization; namespace Samples { public class DateTimeParse { public static void Main() { IFormatProvider f = new CultureInfo("en-AU", true); string s1 = DateTime.Now.ToString(f); DateTime d = DateTime.Parse(s1, f); Console.WriteLine(d.ToString(f)); int first = s1.IndexOf('/'); int second = s1.IndexOf('/', first + 1); string s2 = s1.Substring(first + 1, second - (first + 1)) + "/" + s1.Substring(0, first) + "/" + s1.Substring(second + 1); Console.WriteLine(s2); f = new CultureInfo("en-US", true); DateTime d2 = DateTime.Parse(s2, f); Console.WriteLine(d2.ToString(f)); } } }
A B C D E F G H I J K L M N O P
The output is
Q R
10/06/2003 9:43:36 AM 06/10/2003 9:43:36 AM 6/10/2003 9:43:36 AM
S T U
DateTime.Parse(System.String, System.IFormatProvider, System.Globalization.DateTimeStyles) Method
V W
[ILASM] .method public hidebysig static valuetype System.DateTime Parse(string s, class System.IFormatProvider provider, valuetype System.Globalization.DateTimeStyles styles) [C#] public static DateTime Parse(string s, IFormatProvider provider, DateTimeStyles styles)
X Y Z
1065
Contents | Index
DateTime Structure
System
Parse() Method
Summary Returns the specified System.String converted to a System.DateTime value. A
Parameters
B C
Parameter
Description
D
s
A System.String containing the value to convert.
provider
A System.IFormatProvider that supplies a System.Globalization.DateTimeFormatInfo object containing culture-specific format information about s.
styles
One or more System.Globalization.DateTimeStyles values that specify the style of s. Specify multiple values for styles using the bitwise OR operator.
E F G H I J
Description
K
The string s is parsed using the culture-specific formatting information from the System.Globalization.DateTimeFormatInfo instance supplied by provider. If provider is null or a System.Globalization.DateTimeFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. In order for the string to be successfully parsed, it is required to represent a date and time value in one of the standard System.DateTime patterns described in System.Globalization.DateTimeFormatInfo. If the string contains only a time, and no date, and if the styles parameter is set to System.Globalization.DateTimeStyles.NoCurrentDateDefault the Gregorian year 1, month 1, day 1 are used. In all other cases where a date is not specified, the current date (System.DateTime.Now ) is used. If the string contains only a date and no time, this method assumes 12 A.M. For all settings of the styles parameter, any leading, trailing, and inner white space characters are ignored.
L M N O P Q R S T U
Exceptions
V W X Y
Exception
Condition
System.ArgumentException
s is a null reference.
System.FormatException
s does not contain a valid string representation of a time or date and time.
Z
1066
Contents | Index
System
DateTime Structure ParseExact() Method
Example using System; using System.Globalization; namespace Samples { public class DateTimeParse { public static void Main() { IFormatProvider f = new CultureInfo("en-AU", true); string s = String.Format("\t {0} ", DateTime.Now.ToString(f)); DateTime d = DateTime.Parse(s, f, DateTimeStyles.AllowWhiteSpaces); Console.WriteLine(d); f = new CultureInfo("en-US", true); s = String.Format(" \t{0} ", DateTime.Now.ToString(f)); d = DateTime.Parse(s, f, DateTimeStyles.AllowWhiteSpaces); Console.WriteLine(d); } } }
A B C D E F G H I J K L M N
The output is
O 10/06/2003 9:45:05 AM 10/06/2003 9:45:05 AM
P Q R
DateTime.ParseExact(System.String, System.String, System.IFormatProvider) Method
S T
[ILASM] .method public hidebysig static valuetype System.DateTime ParseExact(string s, string format, class System.IFormatProvider provider) [C#] public static DateTime ParseExact(string s, string format, IFormatProvider provider)
U V W X
Summary
Y
Converts the specified System.String representation of a date and time to its System.DateTime equivalent using a specified format and System.IFormatProvider.
Z
1067
Contents | Index
DateTime Structure
System
ParseExact() Method
Parameters Parameter
Description
s
A System.String containing a date and time to convert. The format of the string is required to match the specified format exactly.
format
A System.String containing the expected format of s. [Note: For a list of valid format values, see System.Globalization.DateTimeFormatInfo.]
provider
A System.IFormatProvider that supplies a System.Globalization.DateTimeFormatInfo object containing culture-specific format information about s.
A B C D E F G H
Description
I
System.DateTime.ParseExact constructs a System.DateTime from the string s. The string is required to specify a date and, optionally, a time in the specified format. The string s is parsed using the culture-specific formatting information from the System.Globalization.DateTimeFormatInfo instance supplied by provider. If provider is null or a System.Globalization.DateTimeFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. If the s string contains only a time, and no date, then the current date (System.DateTime.Now) is used. If the string contains only a date and no time, this method assumes 12 A.M. Leading, trailing, and inner white space characters are not allowed. [Note: For information on formatting system-supplied data types, see the System.IFormattable interface.]
J K L M N O P Q R
Exceptions
S T U V
Exception
Condition
System.ArgumentNullException
s or format is a null reference.
W
s or format is an empty string.
X
System.FormatException
-ors does not contain a date and time that were recognized as the pattern specified in format.
Y Z
1068
Contents | Index
System
DateTime Structure ParseExact() Method
Example using System; using System.Globalization; namespace Samples { public class DateTimeParseExact { public static void Main() { CultureInfo c = new CultureInfo("en-AU", true); DateTimeFormatInfo i = c.DateTimeFormat; DateTime d = DateTime.ParseExact("3/09/1959", i.ShortDatePattern, c); Console.WriteLine(d.ToString(c)); d = DateTime.ParseExact("12:00 0", i.ShortTimePattern, c); Console.WriteLine(d.ToString(c)); } } }
A B C D E F G H I J K L M
The output is
N 3/09/1959 12:00:00 AM 10/06/2003 12:00:00 AM
O P
DateTime.ParseExact(System.String, System.String, System.IFormatProvider, System.Globalization.DateTimeStyles) Method
Q
[ILASM] .method public hidebysig static valuetype System.DateTime ParseExact(string s, string format, class System.IFormatProvider provider, valuetype System.Globalization.DateTimeStyles style) [C#] public static DateTime ParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style)
S
R
T U V W X
Summary
Y
Converts the System.String representation of a date and time to its System.DateTime equivalent using a specified style, the expected format, and culture-specific format information.
Z
1069
Contents | Index
DateTime Structure
System
ParseExact() Method
Parameters Parameter
Description
s
A System.String containing a date and time to convert. The format of the string is required to match the specified format exactly.
format
A System.String containing the expected format of s. [Note: For a list of valid format values, see System.Globalization.DateTimeFormatInfo.]
provider
A System.IFormatProvider that supplies a System.Globalization.DateTimeFormatInfo object containing culture-specific format information about s.
style
One or more System.Globalization.DateTimeStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator.
A B C D E F G H I J
Description
K
System.DateTime.ParseExact constructs a System.DateTime from the string s. The string is required to specify a date and, optionally, a time in the provided format. The string s is parsed using the culture-specific formatting information from the System.Globalization.DateTimeFormatInfo instance supplied by provider. If provider is null or a System.Globalization.DateTimeFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. If the s string contains only a time, and no date, and if the style parameter is set to System.Globalization.DateTimeStyles.NoCurrentDateDefault the Gregorian year 1, month 1, day 1 are used, and no leading, trailing, or inner white space characters are allowed. In all other cases where a date is not specified, the current date (System.DateTime.Now) is used. If the s string contains only a date and no time, this method assumes 12 A.M. [Note: For information on formatting system-supplied data types, see the System.IFormattable interface.]
L M N O P Q R S T U V W X Y Z
1070
Contents | Index
System
DateTime Structure ParseExact() Method
Exceptions Exception
Condition
System.ArgumentNullException
s or format is a null reference.
A
System.FormatException
B
s or format is an empty string.
C
-or-
D
s does not contain a date and time that were recognized as the pattern specified in format.
E F G
Example
H
using System; using System.Globalization; namespace Samples { public class DateTimeParseExact { public static void Main() { CultureInfo c = new CultureInfo("en-AU", true); DateTimeFormatInfo i = c.DateTimeFormat; DateTime d = DateTime.ParseExact(" 3/09/1959 ", i.ShortDatePattern, c, DateTimeStyles.AllowWhiteSpaces); Console.WriteLine(d.ToString(c)); d = DateTime.ParseExact(" 12:00 0 ", i.ShortTimePattern, c, DateTimeStyles.AllowWhiteSpaces); Console.WriteLine(d.ToString(c)); } } }
I J K L M N O P Q R S T U V
The output is
W X
3/09/1959 12:00:00 AM 10/06/2003 12:00:00 AM
Y Z
1071
Contents | Index
DateTime Structure
System
ParseExact() Method
DateTime.ParseExact(System.String, System.String[], System.IFormatProvider, System.Globalization.DateTimeStyles) Method [ILASM] .method public hidebysig static valuetype System.DateTime ParseExact(string s, class System.String[] formats, class System.IFormatProvider provider, valuetype System.Globalization.DateTimeStyles style) [C#] public static DateTime ParseExact(string s, string[] formats, IFormatProvider provider, DateTimeStyles style)
A B C D E F
Summary
G
Converts the System.String representation of a date and time to its System.DateTime equivalent using a specified style, an array of expected formats, and culture-specific format information.
H I
Parameters
J K
Parameter
Description
s
A System.String containing one or more dates and times to convert. The format of the string is required to match the specified format exactly.
formats
A System.String array containing the expected formats of s. [Note: For a list of valid formats values, see System.Globalization.DateTimeFormatInfo.]
provider
A System.IFormatProvider that supplies a System.Globalization.DateTimeFormatInfo object containing culture-specific format information about s.
style
One or more System.Globalization.DateTimeStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator.
L M N O P Q R S T U
Return Value
V
A System.DateTime equivalent to the date and time contained in s.
W
Description
X
System.DateTime.ParseExact constructs a System.DateTime from the s System.String. The string is required to specify a date and, optionally, a time in the provided format. The string s is parsed using the culture-specific formatting information from the System.Globalization.DateTimeFormatInfo instance supplied by provider. If
Y Z
1072
Contents | Index
System
DateTime Structure ParseExact() Method
provider is null or a System.Globalization.DateTimeFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. If the s string contains only a time, and no date, and if the style parameter is set to System.Globalization.DateTimeStyles.NoCurrentDateDefault the Gregorian year 1, month 1, day 1 are used, and no leading, trailing, or inner white space characters are allowed. In all other cases where a date is not specified, the current date (System.DateTime.Now) is used. If the s string contains only a date and no time, this method assumes 12 A.M. [Note: For information on formatting system-supplied data types, see the System.IFormattable interface.]
A B C D E F
Exceptions
G
Exception
Condition
System.ArgumentNullException
s or formats is a null reference.
System.FormatException
s or formats is an empty string. -ors does not contain a date and time that were recognized as the pattern specified in formats.
H I J K L M N
Example
O
using System; using System.Globalization; namespace Samples { public class DateTimeParseExact { public static void Main() { CultureInfo c = new CultureInfo("en-AU", true); DateTimeFormatInfo i = c.DateTimeFormat; string[] s = { i.ShortDatePattern, i.ShortTimePattern}; DateTime d = DateTime.ParseExact(" 3/09/1959 ", s, c, DateTimeStyles.AllowWhiteSpaces); Console.WriteLine(d.ToString(c)); d = DateTime.ParseExact(" 12:00 0 ", s, c,
P Q R S T U V W X Y Z
1073
Contents | Index
DateTime Structure
System
Subtract() Method
DateTimeStyles.AllowWhiteSpaces); Console.WriteLine(d.ToString(c)); } }
A
}
B
The output is
C
3/09/1959 12:00:00 AM 10/06/2003 12:00:00 AM
D E F
DateTime.Subtract(System.DateTime) Method
G
[ILASM] .method public hidebysig instance valuetype System.TimeSpan Subtract(valuetype System.DateTime value)
H I
[C#]
J
public TimeSpan Subtract(DateTime value)
K
Summary
L
Subtracts a specified date and time from the current instance.
M N
Parameters
O P Q
Parameter
Description
value
An instance of System.DateTime.
R S
Return Value
T
A System.TimeSpan interval equal to the date and time represented by the current instance minus the date and time represented by the specified System.DateTime.
U V
Example
W
using System; namespace Samples { public class DateTimeSubtract { public static void Main() { DateTime d1 = DateTime.Now;
X Y Z
1074
Contents | Index
System
DateTime Structure Subtract() Method
DateTime d2 = new DateTime(1959, 9, 3); Console.WriteLine( "There has been {0} days since my birthday", d1.Subtract(d2).Days);
A
} }
B
}
C
The output is
D
2 Days, 0 hours before 10/06/2003 9:50:29 AM was: 8/06/2003 9:50:29 AM
E F
DateTime.Subtract(System.TimeSpan) Method
G
[ILASM] .method public hidebysig instance valuetype System.DateTime Subtract(valuetype System.TimeSpan value) [C#] public DateTime Subtract(TimeSpan value)
H
Summary
L
Subtracts a specified System.TimeSpan from the current instance.
M
I J K
N
Parameters
O
Parameter
Description
value
An instance of System.TimeSpan.
P Q R S
Return Value
T
A new System.DateTime instance equal to the date and time represented by the current instance minus the time interval of the specified System.TimeSpan.
U V
Exceptions
W
Exception
Condition
System.ArgumentOutOfRangeException
The resulting date and time is less than System.DateTime.MinValue or greater than System.DateTime.MaxValue.
X Y Z
1075
Contents | Index
DateTime Structure
System
ToFileTime() Method
Example using System; namespace Samples { public class DateTimeSubtract { public static void Main() { DateTime d = DateTime.Now; TimeSpan t = new TimeSpan(48, 0, 0); Console.WriteLine( "{0} Days, {1} hours before {2} was: {3}", t.Days, t.Hours, d, d.Subtract(t)); } } }
A B C D E F G H I
The output is
J 2 Days, 0 hours before 10/06/2003 9:50:29 AM was: 8/06/2003 9:50:29 AM
K L
DateTime.ToFileTime() Method
M
[ILASM] .method public hidebysig instance int64 ToFileTime() [C#] public long ToFileTime()
N O P Q
Summary
R
Converts the value of this instance to the format of a local operating system file time.
S
Description
T
A system file time is a 64-bit unsigned value representing the date and time as the number of 100-nanosecond intervals that have elapsed since January 1, 1601 12:00 A.M. An exception is thrown if you attempt to convert a date earlier than January 1, 1601 12:00:00 A.M. coordinated universal time (UTC).
U V W
Exceptions
X Y
Exception
Condition
System.ArgumentOutOfRangeException
The value of this instance cannot be converted to a system file time.
Z
1076
Contents | Index
System
DateTime Structure ToLocalTime() Method
DateTime.ToFileTimeUtc() Method [ILASM] .method public hidebysig instance int64 ToFileTimeUtc() [C#] public long ToFileTimeUtc()
A B C
Summary
D
Converts the value of this instance to the format of operating system file time, ignoring the local time zone.
E F
Description
G
The file time is a 64-bit signed integer value representing a Windows file time stamp. The time stamp is the number of 100-nanosecond intervals that have elapsed since January 1, 1601 A.D. (C.E.) 12:00 A.M. coordinated universal time (UTC). The System.DateTime.ToFileTimeUtc method returns the value of this System.DateTime relative to January 1, 1601 A.D. (C.E.) 12:00 A.M., but does not adjust the file time to account for the local time zone.
H I J K L
Exceptions
M
Exception
Condition
System.ArgumentOutOfRangeException
The resulting file time would be less than 0.
N O P Q R
DateTime.ToLocalTime() Method
S [ILASM] .method public hidebysig instance valuetype System.DateTime ToLocalTime() [C#] public DateTime ToLocalTime()
T U V
Summary
W
Converts the universal time coordinate (UTC) time value in the current instance to local time.
X
Return Value
Y
An instance of System.DateTime equivalent of the time value in the current instance, adjusted to the local time zone and daylight saving time. If the result is too large or too
Z
1077
Contents | Index
DateTime Structure
System
ToLongDateString() Method
small to be represented as a System.DateTime, this method returns a System.DateTime set to System.DateTime.MaxValue or System.DateTime.MinValue. A
Description
B
This method assumes that the current instance of System.DateTime holds the UTC time value, and not a local time. Each time it is invoked, this method performs the necessary modifications on the System.DateTime to derive the local time, whether the current System.DateTime holds the UTC time or not. The local time zone information is obtained from the operating system.
C D E F
Example
G
using System; namespace Samples { public class DateTimeToLocalTime { public static void Main() { DateTime d = DateTime.UtcNow; Console.WriteLine("UTC Now is: {0}", d); Console.WriteLine("At local is: {0}", d.ToLocalTime()); } } }
H I J K L M N O P
The output is
Q
UTC Now is: 9/06/2003 11:53:07 PM At local is: 10/06/2003 9:53:07 AM
R S T
DateTime.ToLongDateString() Method
U
[ILASM] .method public hidebysig instance string ToLongDateString() [C#] public string ToLongDateString()
V W X Y
Summary
Z
Converts the date denoted by the current instance to its equivalent long date System.String representation.
1078
Contents | Index
System
DateTime Structure ToLongTimeString() Method
Return Value A System.String containing the same value as a System.String returned by System.DateTime.ToString("D", null). A
Description
B
The value of the current instance is formatted using the long date format specifier, “D”. [Note: This format uses the culture of the current thread. To specify formatting using a different culture, use System.DateTime.ToString. For more information regarding the long date specifier, see System.Globalization.DateTimeFormatInfo.]
C D E F
Example
G
using System; namespace Samples { public class DateTimeToLongDateString { public static void Main() { DateTime d = DateTime.Now; Console.WriteLine("ToString : {0}", d); Console.WriteLine("ToLongDateString: {0}", d.ToLongDateString()); } } }
H I J K L M N O P
The output is
Q
ToString : 10/06/2003 9:54:02 AM ToLongDateString: Tuesday, 10 June 2003
R S T
DateTime.ToLongTimeString() Method
U
[ILASM] .method public hidebysig instance string ToLongTimeString() [C#] public string ToLongTimeString()
V W X
Summary
Y
Converts the time denoted by the current instance to its equivalent long time System.String representation.
Z
1079
Contents | Index
DateTime Structure
System
ToOADate() Method
Return Value A System.String containing the same value as a System.String returned by System.DateTime.ToString("T", null). A B
Description
C
The value of the current instance is formatted using the long time format specifier, “T”. [Note: This format uses the culture of the current thread. To specify formatting using a different culture, use System.DateTime.ToString. For more information regarding the long time specifier, see System.Globalization.DateTimeFormatInfo.]
D E F
Example
G
using System; namespace Samples { public class DateTimeToLongTimeString { public static void Main() { DateTime d = DateTime.Now; Console.WriteLine("ToString : {0}", d); Console.WriteLine("ToLongTimeString: {0}", d.ToLongTimeString()); } } }
H I J K L M N O P
The output is
Q
ToString : 10/06/2003 9:54:57 AM ToLongTimeString: 9:54:57 AM
R S T
DateTime.ToOADate() Method
U
[ILASM] .method public hidebysig instance float64 ToOADate() [C#] public double ToOADate()
V W X Y
Summary
Z
Converts the value of this instance to the equivalent OLE Automation Date.
1080
Contents | Index
System
DateTime Structure ToShortDateString() Method
Description An OLE Automation Date is implemented as a floating-point number whose value is the number of days from midnight, 30 December 1899. For example, midnight, 31 December 1899 is represented by 1.0; 6 A.M., 1 January 1900 is represented by 2.25; midnight, 29 December 1899 is represented by –1.0; and 6 A.M., 29 December 1899 is represented by –1.25. Only System.DateTime objects with a tick value that is greater than or equal to positive or negative 31241376000000000 can be represented as an OLE Automation Date. An uninitialized System.DateTime, that is, an instance with a tick value of 0, is converted to the equivalent uninitialized OLE Automation Date, that is, a date with a value of 0.0 which represents midnight, 30 December 1899. The System.DateTime.Ticks value of a System.DateTime is between System.DateTime.MinValue and System.DateTime.MaxValue. The maximum value of a System.DateTime is equal to the maximum value of an OLE Automation Date. See System.DateTime.FromOADate.
A B C D E F G H I
Exceptions
J K
Exception
Condition L
System.OverflowException
The value of this instance cannot be represented as an OLE Automation Date.
M N O P
DateTime.ToShortDateString() Method
Q
[ILASM] .method public hidebysig instance string ToShortDateString() [C#] public string ToShortDateString()
R S T
Summary
U
Converts the date denoted by the current instance to its equivalent short date System.String representation.
V W
Return Value
X
A System.String containing the same value as a System.String returned by System.DateTime.ToString("d", null).
Y Z
1081
Contents | Index
DateTime Structure
System
ToShortTimeString() Method
Description The value of the current instance is formatted using the short date format specifier, “d”. [Note: This format uses the culture of the current thread. To specify formatting using a different culture, use System.DateTime.ToString. For more information regarding the short date specifier, see System.Globalization.DateTimeFormatInfo.]
A B C
Example
D
using System; namespace Samples { public class DateTimeToShortDateString { public static void Main() { DateTime d = DateTime.Now; Console.WriteLine("ToString : {0}", d); Console.WriteLine("ToShortDateString: {0}", d.ToShortDateString()); } } }
E F G H I J K L M
The output is
N ToString : 10/06/2003 9:56:21 AM ToShortDateString: 10/06/2003
O P Q
DateTime.ToShortTimeString() Method
R
[ILASM] .method public hidebysig instance string ToShortTimeString() [C#] public string ToShortTimeString()
S T U V
Summary
W
Converts the time denoted by this instance to its equivalent short time System.String representation.
X Y
Return Value
Z
A System.String containing the same value as a System.String returned by System.DateTime.ToString("t", null).
1082
Contents | Index
System
DateTime Structure ToString() Method
Description The value of the current instance is formatted using the short time format specifier, “t”. [Note: This format uses the culture of the current thread. To specify formatting using a different culture, use System.DateTime.ToString. For more information regarding the short time specifier, see System.Globalization.DateTimeFormatInfo.]
A B C
Example
D
using System; namespace Samples { public class DateTimeToShortTimeString { public static void Main() { DateTime d = DateTime.Now; Console.WriteLine("ToString : {0}", d); Console.WriteLine("ToShortTimeString: {0}", d.ToShortTimeString()); } } }
E F G H I J K L M
The output is
N ToString : 10/06/2003 9:57:13 AM ToShortTimeString: 9:57 AM
O P Q
DateTime.ToString() Method
R
[ILASM] .method public hidebysig virtual string ToString() [C#] public override string ToString()
S T U
Summary
V
Returns a System.String representation of the value of the current instance.
W X
Return Value
Y
A System.String representation of the current instance formatted using the general format specifier, (“G”). The string takes into account the current system culture.
Z
1083
Contents | Index
DateTime Structure
System
ToString() Method
Description This version of System.DateTime.ToString is equivalent to System.DateTime.ToString("G", null). [Note: For more information about the general format specifier (“G”) see System.Globalization.DateTimeFormatInfo. This method overrides System.Object.ToString.]
A B C D
Example
E
using System; namespace Samples { public class DateTimeToString { public static void Main() { DateTime d = DateTime.Now; Console.WriteLine("ToString: {0}", d); Console.WriteLine("ToString: {0}", d.ToString()); Console.WriteLine("ToString: {0}", d.ToString("G", null)); } } }
F G H I J K L M N
The output is
O P
ToString: 10/06/2003 10:01:11 AM ToString: 10/06/2003 10:01:11 AM ToString: 10/06/2003 10:01:11 AM
Q R S
DateTime.ToString(System.String) Method
T
[ILASM] .method public hidebysig instance string ToString(string format) [C#] public string ToString(string format)
U V W
Summary
X
Returns a System.String representation of the value of the current instance.
Y Z
1084
Contents | Index
System
DateTime Structure ToString() Method
Parameters Parameter
Description
format
A System.String that specifies the format of the returned string. [Note: For a list of valid values, see System.Globalization.DateTimeFormatInfo.]
A B C D
Return Value
E
A System.String representation of the current instance formatted as specified by format. The string takes into account the current system culture.
F G
Description
H
This version of System.DateTime.ToString is equivalent to System.DateTime.ToString(format, null). If format is a null reference, the general format specifier “G” is used. [Note: This method uses the culture information of the current thread. For information on formatting system-supplied data types, see the System.IFormattable interface.]
I J K L
Exceptions
M N
Exception
Condition O
System.FormatException
The length of the format string is 1, and it is not one of the format specifier characters defined for System.Globalization.DateTimeFormatInfo.
Q
-or-
R
The format string does not contain a valid custom format pattern.
S
P
T U
Example using System; namespace Samples { public class DateTimeToShortTimeString { public static void Main() { DateTime d = DateTime.Now; Console.WriteLine("ToString
V W X Y Z : {0}", d);
1085
Contents | Index
DateTime Structure
System
ToString() Method
Console.WriteLine("ToShortTimeString: {0}", d.ToShortTimeString()); } }
A
}
B
The output is
C ToString("d/MM/yyyy") yields: 10/06/2003 ToString("d/MM/yy") yields: 10/06/03 ToString("d/M/yy") yields: 10/6/03 ToString("d/M/yyyy") yields: 10/6/2003 ToString("dd/MM/yy") yields: 10/06/03 ToString("dd/MM/yyyy") yields: 10/06/2003 ToString("dd-MMM-yy") yields: 10-Jun-03 ToString("dd-MMMM-yyyy") yields: 10-June-2003 ToString("yyyy-MM-dd") yields: 2003-06-10 ToString("yy/MM/dd") yields: 03/06/10 ... ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'") yields: Tue, 10 Jun 2003 09:58:13 GMT ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'") yields: Tue, 10 Jun 2003 09:58:13 GMT ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss") yields: 2003-06-10T09:58:13 ToString("h:mm tt") yields: 9:58 AM ToString("H:mm") yields: 9:58 ToString("HH:mm") yields: 09:58 ToString("h:mm:ss tt") yields: 9:58:13 AM ToString("H:mm:ss") yields: 9:58:13 ToString("HH:mm:ss") yields: 09:58:13 ToString("yyyy'-'MM'-'dd HH':'mm':'ss'Z'") yields: 2003-06-10 09:58:13Z ToString("dddd, d MMMM yyyy h:mm:ss tt") yields: Tuesday, 10 June 2003 9:58:13 AM ToString("dddd, d MMMM yyyy H:mm:ss") yields: Tuesday, 10 June 2003 9:58:13 ToString("dddd, d MMMM yyyy HH:mm:ss") yields: Tuesday, 10 June 2003 09:58:13 ToString("d MMMM yyyy h:mm:ss tt") yields: 10 June 2003 9:58:13 AM ToString("d MMMM yyyy H:mm:ss") yields: 10 June 2003 9:58:13 ToString("d MMMM yyyy HH:mm:ss") yields: 10 June 2003 09:58:13 ToString("MMMM yyyy") yields: June 2003 ToString("MMMM yyyy") yields: June 2003
D E F G H I J K L M N O P Q R S T U V W
DateTime.ToString(System.String, System.IFormatProvider) Method
X
[ILASM] .method public final hidebysig virtual string ToString(string format, class System.IFormatProvider provider) [C#] public string ToString(string format, IFormatProvider provider)
Y Z
1086
Contents | Index
System
DateTime Structure ToString() Method
Summary Returns a System.String representation of the value of the current instance. A
Parameters
B
Parameter
Description
C
A System.String containing a character that specifies the format of the returned string. [Note: For a list of valid values, see System.Globalization.DateTimeFormatInfo.]
D
format
provider
A System.IFormatProvider that supplies a System.Globalization.DateTimeFormatInfo instance containing culture-specific formatting information.
E F G H I
Return Value
J
A System.String representation of the current instance formatted as specified by format. The string takes into account the information in the System.Globalization.DateTimeFormatInfo supplied by provider.
K L M
Description
N
If provider is null or System.Globalization.DateTimeFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. If format is a null reference, the general format specifier “G” is used. [Note: For more information regarding the standard format specifier, see System.Globalization.DateTimeFormatInfo. For information on formatting system-supplied data types, see the System.IFormattable interface. This method is implemented to support the System.IFormattable interface.]
O P Q R S T
Exceptions Exception
System.FormatException
U
Condition
V
The length of the format string is 1, and it is not one of the format specifier characters defined for System.Globalization.DateTimeFormatInfo.
W
-or-
Y
The format string does not contain a valid custom format pattern.
Z
X
1087
Contents | Index
DateTime Structure
System
ToString() Method
Example using System; using System.Globalization; namespace Samples { public class DateTimeToString { public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo i = new CultureInfo("fr-FR").DateTimeFormat; string[] strings = i.GetAllDateTimePatterns(); foreach(string s in strings) Console.WriteLine("ToString(\"{0}\", i) yields: {1}", s, d.ToString(s, i)); } } }
A B C D E F G H I J K
The output is
L M
ToString("dd/MM/yyyy", i) yields: 10/06/2003 ToString("dd/MM/yy", i) yields: 10/06/03 ToString("dd.MM.yy", i) yields: 10.06.03 ToString("dd-MM-yy", i) yields: 10-06-03 ToString("yyyy-MM-dd", i) yields: 2003-06-10 ToString("dddd d MMMM yyyy", i) yields: mardi 10 juin 2003 ToString("d MMM yy", i) yields: 10 juin 03 ToString("d MMMM yyyy", i) yields: 10 juin 2003 ToString("dddd d MMMM yyyy HH:mm", i) yields: mardi 10 juin 2003 10:02 ToString("dddd d MMMM yyyy H:mm", i) yields: mardi 10 juin 2003 10:02 ToString("dddd d MMMM yyyy HH.mm", i) yields: mardi 10 juin 2003 10.02 ToString("dddd d MMMM yyyy HH' h 'mm", i) yields: mardi 10 juin 2003 10 h 02 ... ToString("yyyy'-'MM'-'dd HH':'mm':'ss'Z'", i) yields: 2003-06-10 10:02:20Z ToString("dddd d MMMM yyyy HH:mm:ss", i) yields: mardi 10 juin 2003 10:02:20 ToString("dddd d MMMM yyyy H:mm:ss", i) yields: mardi 10 juin 2003 10:02:20 ToString("dddd d MMMM yyyy HH.mm", i) yields: mardi 10 juin 2003 10.02 ToString("dddd d MMMM yyyy HH' h 'mm", i) yields: mardi 10 juin 2003 10 h 02 ToString("d MMM yy HH:mm:ss", i) yields: 10 juin 03 10:02:20 ToString("d MMM yy H:mm:ss", i) yields: 10 juin 03 10:02:20 ToString("d MMM yy HH.mm", i) yields: 10 juin 03 10.02 ToString("d MMM yy HH' h 'mm", i) yields: 10 juin 03 10 h 02 ToString("d MMMM yyyy HH:mm:ss", i) yields: 10 juin 2003 10:02:20 ToString("d MMMM yyyy H:mm:ss", i) yields: 10 juin 2003 10:02:20
N O P Q R S T U V W X Y Z
1088
Contents | Index
System
DateTime Structure ToString() Method
ToString("d MMMM yyyy ToString("d MMMM yyyy ToString("MMMM yyyy", ToString("MMMM yyyy",
HH.mm", i) yields: 10 juin 2003 10.02 HH' h 'mm", i) yields: 10 juin 2003 10 h 02 i) yields: juin 2003 i) yields: juin 2003
A B
DateTime.ToString(System.IFormatProvider) Method
C D
[ILASM] .method public final hidebysig virtual string ToString(class System.IFormatProvider provider) [C#] public string ToString(IFormatProvider provider)
E F G
Summary
H
Returns a System.String representation of the value of the current instance.
I J
Parameters
K
Parameter
Description
provider
A System.IFormatProvider that supplies a System.Globalization.DateTimeFormatInfo containing culture-specific formatting information.
L M N O
Return Value
P
A System.String representation of the current instance formatted using the general format specifier, (“G”). The string takes into account the formatting information in the System.Globalization.DateTimeFormatInfo instance supplied by provider.
Q R S
Description
T
This version of System.DateTime.ToString is equivalent to System.DateTime.ToString(“G”, provider). If provider is null or the System.Globalization.DateTimeFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. [Note: The general format specifier “G” provides the general date pattern including the long time form, equivalent to System.Globalization.DateTimeFormatInfo.ShortDatePattern combined with System.Globalization.DateTimeFormatInfo.LongTimePattern. For more information on format specifiers, see System.Globalization.DateTimeFormatInfo. For information on formatting system-supplied data types, see the System.IFormattable interface.]
U V W X Y Z
1089
Contents | Index
DateTime Structure
System
ToUniversalTime() Method
Example using System; using System.Globalization; namespace Samples { public class DateTimeToString { public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo i = new CultureInfo("fr-FR").DateTimeFormat; Console.WriteLine("ToString(i) yields: {0}", d.ToString(i)); i = new CultureInfo("en-US").DateTimeFormat; Console.WriteLine("ToString(i) yields: {0}", d.ToString(i)); } } }
A B C D E F G H I J K
The output is
L M
ToString(i) yields: 10/06/2003 10:07:42 ToString(i) yields: 6/10/2003 10:07:42 AM
N O
DateTime.ToUniversalTime() Method
P
[ILASM] .method public hidebysig instance valuetype System.DateTime ToUniversalTime() [C#] public DateTime ToUniversalTime()
Q R S T
Summary
U
Converts the current System.DateTime value to coordinated universal time (UTC).
V
Return Value
W
The UTC System.DateTime equivalent of the current System.DateTime value. If the result is too large or too small to be represented as a System.DateTime, the current function returns a System.DateTime set to System.DateTime.MaxValue or System.DateTime.MinValue.
X Y Z
1090
Contents | Index
System
DateTime Structure ToBoolean() Method
Description This method assumes that the current instance of System.DateTime holds the local time value, and not a UTC time. Therefore each time it is run, this method performs the necessary modifications on the System.DateTime to derive the UTC time, whether the current System.DateTime holds the local time or not. The local time zone information is obtained from the operating system.
A B C
Example
D
using System; namespace Samples { public class DateTimeToUniversalTime { public static void Main() { DateTime d = DateTime.Now; Console.WriteLine("Local time is: {0}", d); Console.WriteLine("UTC is: {0}", d.ToUniversalTime()); } } }
E F G H I J K L M N
The output is
O Local time is: 10/06/2003 10:09:04 AM UTC is: 10/06/2003 12:09:04 AM
P Q R
IConvertible.ToBoolean(System.IFormatProvider) Method
S [ILASM]
T
.method private final hidebysig virtual bool System.IConvertible.ToBoolean(class System.IFormatProvider provider) [C#]
U
bool IConvertible.ToBoolean(IFormatProvider provider)
V W
Summary
X
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToBoolean.]
Y Z
1091
Contents | Index
DateTime Structure
System
ToByte() Method
IConvertible.ToByte(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual unsigned int8 System.IConvertible.ToByte(class System.IFormatProvider provider)
B
[C#]
byte IConvertible.ToByte(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToByte.]
F G H
IConvertible.ToChar(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual valuetype System.Char System.IConvertible.ToChar(class System.IFormatProvider provider)
K
[C#]
char IConvertible.ToChar(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToChar.]
O P Q
IConvertible.ToDateTime(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual valuetype System.DateTime System.IConvertible.ToDateTime(class System.IFormatProvider provider)
T
[C#]
DateTime IConvertible.ToDateTime(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDateTime.]
X Y Z
1092
Contents | Index
System
DateTime Structure ToInt16() Method
IConvertible.ToDecimal(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual decimal System.IConvertible.ToDecimal(class System.IFormatProvider provider)
A
[C#]
B
decimal IConvertible.ToDecimal(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDecimal.]
E F G
IConvertible.ToDouble(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual float64 System.IConvertible.ToDouble(class System.IFormatProvider provider)
J
[C#]
K
double IConvertible.ToDouble(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDouble.]
N O P
IConvertible.ToInt16(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual int16 System.IConvertible.ToInt16(class System.IFormatProvider provider)
S
[C#]
T
short IConvertible.ToInt16(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt16.]
W X Y Z
1093
Contents | Index
DateTime Structure
System
ToInt32() Method
IConvertible.ToInt32(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual int32 System.IConvertible.ToInt32(class System.IFormatProvider provider)
B
[C#]
int IConvertible.ToInt32(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt32.]
F G H
IConvertible.ToInt64(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual int64 System.IConvertible.ToInt64(class System.IFormatProvider provider)
K
[C#]
long IConvertible.ToInt64(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt64.]
O P Q
IConvertible.ToSByte(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual int8 System.IConvertible.ToSByte(class System.IFormatProvider provider)
T
[C#]
sbyte IConvertible.ToSByte(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSByte.]
X Y Z
1094
Contents | Index
System
DateTime Structure ToUInt16() Method
IConvertible.ToSingle(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual float32 System.IConvertible.ToSingle(class System.IFormatProvider provider)
A
[C#]
B
float IConvertible.ToSingle(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSingle.]
E F G
IConvertible.ToType(System.Type, System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual object System.IConvertible.ToType(class System.Type type, class System.IFormatProvider provider)
J
[C#]
K
object IConvertible.ToType(Type type, IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToType.]
N O P
IConvertible.ToUInt16(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual unsigned int16 System.IConvertible.ToUInt16(class System.IFormatProvider provider)
S
[C#]
T
ushort IConvertible.ToUInt16(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt16.] This member is not CLS-compliant.
W X Y Z
1095
Contents | Index
DateTime Structure
System
ToUInt32() Method
IConvertible.ToUInt32(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual unsigned int32 System.IConvertible.ToUInt32(class System.IFormatProvider provider)
B
[C#]
uint IConvertible.ToUInt32(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt32.] This member is not CLS-compliant.
F G H
IConvertible.ToUInt64(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual unsigned int64 System.IConvertible.ToUInt64(class System.IFormatProvider provider)
K
[C#]
ulong IConvertible.ToUInt64(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt64.] This member is not CLS-compliant.
O P Q R S T U V W X Y Z
1096
Contents | Index
System.Globalization DateTimeFormatInfo
BCL
Object ICloneable
A
DateTimeFormatInfo IFormatProvider
B
Summary
C
Defines culture-specific formats and patterns for System.DateTime values.
D E
Type Summary
F
public sealed class DateTimeFormatInfo : ICloneable, IFormatProvider { // Constructors public DateTimeFormatInfo ();
G H I J
// Properties public string[] AbbreviatedDayNames { set; get; } public string[] AbbreviatedMonthNames { set; get; } public string AMDesignator { set; get; } MS public Calendar Calendar { set; get; } MS public CalendarWeekRule CalendarWeekRule { set; get; } public static DateTimeFormatInfo CurrentInfo { get; } public string DateSeparator { set; get; } public string[] DayNames { set; get; } MS public DayOfWeek FirstDayOfWeek { set; get; } public string FullDateTimePattern { set; get; } public static DateTimeFormatInfo InvariantInfo { get; } public bool IsReadOnly { get; } public string LongDatePattern { set; get; } public string LongTimePattern { set; get; } public string MonthDayPattern { set; get; } public string[] MonthNames { set; get; } public string PMDesignator { set; get; } MS public string RFC1123Pattern { get; } public string ShortDatePattern { set; get; } public string ShortTimePattern { set; get; } MS public string SortableDateTimePattern { get; } public string TimeSeparator { set; get; } MS public string UniversalSortableDateTimePattern { get; } public string YearMonthPattern { set; get; }
K L M N O P Q R S T U V W X Y
// Methods public object Clone (); MS public string GetAbbreviatedDayName (DayOfWeek dayofweek); MS public string GetAbbreviatedEraName (int era);
Z
1097
Contents | Index
DateTimeFormatInfo
System.Globalization
DateTimeFormatInfo Class
public string GetAbbreviatedMonthName (int month); MS public string[] GetAllDateTimePatterns (); MS public string[] GetAllDateTimePatterns (char format); MS public string GetDayName (DayOfWeek dayofweek); public int GetEra (string eraName); public string GetEraName (int era); public object GetFormat (Type formatType); MS public static DateTimeFormatInfo GetInstance (IFormatProvider provider); public string GetMonthName (int month); public static DateTimeFormatInfo ReadOnly (DateTimeFormatInfo dtfi)
A B C D }
E F G
BA In general I am not a big fan of properties that return arrays; they are just too easy to get wrong. In this case, for example, in the early days of the .NET Framework we had a bug such that we were returning the internal instance from one of these properties which allowed a malicious or careless developer to change the names of the days of the week for the entire process!
H I J K
Highly simplified code from the DateTimeFormatInfo with the bug:
L
private string[] dayNames = new string[]{“Monday”, “Tuesday”}; public string[] DayNames { get { return dayNames; } }
M N O P
Code that exploits the bug:
Q R
DateTimeFormatInfo.InvariantInfo.DayNames[0] = “UpperDay”; Console.WriteLine (DateTimeFormatInfo.InvariantInfo.DayNames[0]);
S
From any process this will return “UpperDay”.
T U
The fix is simple:
V public string[] DayNames { get { return (string[]) dayNames.Clone(); } }
W X Y Z
continued
1098
Contents | Index
System.Globalization
DateTimeFormatInfo DateTimeFormatInfo Class
But then the down side is you create a copy of the array every time it is asked for. That may not be so bad in this example, but if the array is large it could be a big issue. A
Consider the code:
B
for (int i = 0; i < DateTimeFormatInfo.InvariantInfo.DayNames.Length; i++){ Console.WriteLine (DateTimeFormatInfo.InvariantInfo.DayNames[i]); }
C D E
It creates a copy of the array every time through the loop. Because of the property syntax that fact would be easy to miss in a code review. In general it would be better to return a collection from properties of this type, or turn the member into a method.
G
BG One note on this type of security bug—many people may incorrectly assume
H
that the CLI’s initonly keyword (exposed as C#’s readonly keyword) means that an array is not modifiable. They might try writing their code like this:
I
private readonly String[] dayNames = new String[]{“Monday”, “Tuesday”};
K
That’s not sufficient. This means the reference to the array is readonly, but arrays are always mutable. You can’t assign a different array to the dayNames field, but you can call a method like Array::Clear on that array, or simply assign a different value to the array, like this:
L
F
J
M N O
dayNames[0] = “Yesterday”;
P Q
Description
R
System.DateTime values are formatted by the System.DateTime.ParseExact and System.DateTime.ToString methods according to standard or custom patterns stored in the properties of a System.Globalization.DateTimeFormatInfo instance. The standard patterns can be accessed and modified through the associated System.Globalization.DateTimeFormatInfo properties. [Note: The format patterns and properties of a read-only System.Globalization.DateTimeFormatInfo instance cannot be changed. To determine whether a System.Globalization.DateTimeFormatInfo instance is read-only, use the System.Globalization.DateTimeFormatInfo.IsReadOnly property.] Date and time format patterns are specified using strings called format specifiers. A string is interpreted as a standard format specifier if it contains exactly one standard format specifier character. If the string contains a single character and that character is not one of the standard format specifiers, an exception is thrown. If the string contains two or more
S T U V W X Y Z
1099
Contents | Index
DateTimeFormatInfo
System.Globalization
DateTimeFormatInfo Class
characters, even if the extra characters are white spaces, the string is interpreted as a custom format specifier. Format specifiers and format patterns are case-sensitive; for example, ’g’ and ’G’ represent different patterns. The following table shows the standard format specifiers and the associated format pattern defined for the invariant culture. The exact pattern produced by a format specifier is influenced by culture-specific date and/or time settings on the current system; computers with different date and time settings might display different patterns. The asterisk at the end of a format pattern indicates that the preceding character may be repeated without changing the meaning of the pattern. For example, the pattern “HH*” indicates that the strings “HH”, “HHH”, “HHHH”, and “HHHHH” produce the same result when used with System.DateTime.ParseExact and System.DateTime.ToString methods.
A B C D E F G H I
Format Specifier
Format Pattern
Description
d
MM/dd/yyyy
The full date in numeric format ( System.Globalization.DateTimeFormatInfo.ShortDatePattern ).
D
dddd*, dd MMMM* yyyy
The full date including the day of the week and the name of the month (System.Globalization.DateTimeFormatInfo.LongDatePattern ).
f
dddd*, dd MMMM* yyyy HH*:mm*
The full date and time, including the day of the week and the name of the month (System.Globalization.DateTimeFormatInfo.LongDatePattern combined with System.Globalization.DateTimeFormatInfo.Short TimePattern ).
F
dddd*, dd MMMM* yyyy HH*:mm*:ss*
The full date and time, including the seconds ( System.Globalization.DateTimeFormatInfo.FullDateTimePatt ern equivalent to System.Globalization.Date-TimeFormatInfo.LongDatePattern combined with System.Globalization.DateTimeFormatInfo.LongTime Pattern ).
g
MM/dd/yyyy HH*:mm*
A general date pattern including the short time form (System.Globalization.DateTimeFormatInfo.ShortDatePattern combined with System.Globalization.DateTimeFormatInfo.ShortTimePattern ).
G
MM/dd/yyyy HH*:mm*:ss*
A general date pattern including the long time form ( System.Globalization.DateTimeFormatInfo.ShortDatePattern combined with System.Globalization.DateTimeFormatInfo.LongTimePattern ).
J K L M N O P Q R S T U V W X Y Z
1100
Contents | Index
System.Globalization
DateTimeFormatInfo DateTimeFormatInfo Class
Format Specifier
Format Pattern
Description
m, M
MMMM* dd
The full name of the month and the date ( System.Globalization.DateTimeFormatInfo.MonthDayPattern ).
t
HH*:mm*
The time in short format (System.Globalization.DateTimeFormatInfo.ShortTimePattern ).
T
HH*:mm*:ss*
The time in long format (System.Globalization.DateTimeFormatInfo.LongTimePattern ).
U
dddd*, dd MMMM* yyyy HH*:mm*:ss*
The full date and time, including the seconds, in the Gregorian calendar (System.Globalization.DateTimeFormatInfo.FullDateTimePattern ).
yyyy MMMM*
The full name of the month and the year in four-digit format (System.Globalization.DateTimeFormatInfo.YearMonthPattern ).
A B C D E F
y, Y
G H I J K
The following table lists custom format specifiers that can be combined to construct custom patterns. If the custom pattern contains white space characters, characters enclosed in single or double quotation marks, or characters not defined in the following table, these characters are considered literals and are included in the output string unchanged. [Note: See the System.String class for the list of white space characters.]
L M N O P
Format Pattern
Q
Description
Examples
The day of the month as a value in the range 1-31, inclusive. Single-digit days do not have a leading zero.
1 22
dd
The day of the month as a value in the range 1-31, inclusive. Single-digit days have a leading zero.
01 22
ddd
The abbreviated name of the day of the week, as defined in System.Globalization.DateTimeFormatInfo.AbbreviatedDayNames.
Mon
The full name of the day of the week, as defined in System.Globalization.DateTimeFormatInfo.DayNames.
Monday
d
R S T U V
dddd*
W X Y Z
1101
Contents | Index
DateTimeFormatInfo
System.Globalization
DateTimeFormatInfo Class
Format Pattern
Description
Examples
M
The numeric month as a value in the range 1-12, inclusive. Single-digit months do not have a leading zero.
2 11
MM
The numeric month as a value in the range 1-12, inclusive. Single-digit months have a leading zero.
02 11
MMM
The abbreviated name of the month, as defined in System.Globalization.DateTimeFormatInfo.AbbreviatedMonthNames.
Feb
MMMM*
The full name of the month, as defined in System.Globalization.DateTimeFormatInfo.MonthNames.
February
y
The year without the century (two-digit). If the value is less than 10, the year is displayed with no leading zero.
0 3
yy
The year without the century (two-digit). If the year without the century is less than 10, the year is displayed with a leading zero.
00 03
yyyy
The year including the century in four digits.
2000 2003
g*
The name of a period or era (such as "A.D." or "B.C."). This pattern is ignored if the date to be formatted does not have an associated period or era string.
A.D.
h
The hour within a 12-hour range as a value in the range 1-12, inclusive. Single-digit hours do not have a leading zero. [Note: The value represents whole hours passed since either midnight (12) or noon (12). To distinguish between values occurring before and after noon, include the "t" or "tt*" custom format specifier.]
3 11
hh*
The hour within a 12-hour range as a value in the range 1-12, inclusive. Single-digit hours have a leading zero. [Note: The value represents whole hours passed since either midnight (12) or noon (12). To distinguish between values occurring before and after noon, include the "t" or "tt*" custom format specifier.]
03 11
H
The hour as a value in the range 0-23, inclusive. Single-digit hours do not have a leading zero. [Note: The value represents whole hours passed since midnight.]
3 13
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1102
Contents | Index
System.Globalization
DateTimeFormatInfo DateTimeFormatInfo Class
Format Pattern
Description
Examples
HH*
The hour as a value in the range 0 and 23, inclusive. Singledigit hours have a leading zero. [Note: The value represents whole hours passed since midnight.]
03 13
m
The minute as a value in the range 0-59, inclusive. Single-digit minutes do not have a leading zero. [Note: The value represents whole minutes passed since the last hour.]
5 15
mm*
The minute as a value in the range 0-59, inclusive. Single-digit minutes have a leading zero. [Note: The value represents whole minutes passed since the last hour.]
05 15
s
The second as a value in the range 0-59, inclusive. Single-digit seconds do not have a leading zero. [Note: The value represents whole seconds passed since the last minute.]
1 30
ss*
The second as a value in the range 0-59, inclusive. Single-digit seconds have a leading zero. [Note: The value represents whole seconds passed since the last minute.]
01 30
f
Displays fractional seconds represented in one digit.
1
M
ff
Displays fractional seconds represented in two digits.
01
N
fff
Displays fractional seconds represented in three digits.
001
ffff
Displays fractional seconds represented in four digits.
0001
Q
fffff
Displays fractional seconds represented in five digits.
00001
R
ffffff
Displays fractional seconds represented in six digits.
000001
S
fffffff
Displays fractional seconds represented in seven digits.
0000001
T
t
The first character of the AM/PM designator defined in the System.Globalization.DateTimeFormatInfo property System.Globalization.DateTimeFormatInfo.AMDesignator or System.Globalization.DateTimeFormatInfo.PMDesignator. [Note: If the total number of hours passed since midnight is less than 12, the A.M. designator is used; otherwise the P.M. designator is used.]
A B C D E F G H I J K L
O P
U V
A P
W X Y Z
1103
Contents | Index
DateTimeFormatInfo
System.Globalization
DateTimeFormatInfo Class
Format Pattern
Description
Examples
tt*
The AM/PM designator defined in the System.Globalization.DateTimeFormatInfo property System.Globalization.DateTimeFormatInfo.AMDesignator or System.Globalization.DateTimeFormatInfo.PMDesignator. [Note: If the total number of hours passed since midnight is less than 12, the A.M. designator is used; otherwise the P.M. designator is used.]
AM PM
z
The time zone offset (hour only) from the universal time coordinate (UTC) time (Greenwich Mean Time) as a value in the range –12 to +13, inclusive. Single-digit hours do not have a leading zero. [Note: The value always includes a leading sign (zero is '+0'), indicating hours ahead of UTC time (+) or hours behind UTC time (–). The offset takes Daylight Savings Time into account.]
–8
zz
The time zone offset (hour only) from the UTC time (Greenwich Mean Time) as a value in the range –12 to +13, inclusive. Single-digit hours have a leading zero. [Note: The value always includes a leading sign (zero is '+0'), indicating hours ahead of UTC time (+) or hours behind UTC time (–). The offset takes Daylight Savings Time into account.]
–08
zzz*
The full time zone offset (hour and minutes) from the UTC time (Greenwich Mean Time) as a value in the range –12:00 to +13:00, inclusive. Single-digit hours and minutes have leading zeros. [Note: The value always includes a leading sign (zero is '+0'), indicating hours ahead of UTC time (+) or hours behind UTC time (–). The offset takes Daylight Savings Time into account.]
–08:00
:
The invariant culture time separator defined in System.Globalization.DateTimeFormatInfo.TimeSeparator.
:
/
The invariant culture date separator defined in the System.Globalization.DateTimeFormatInfo.DateSeparator.
/
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1104
Contents | Index
System.Globalization
DateTimeFormatInfo DateTimeFormatInfo Class
Format Pattern
%c
\c
'xx' or "xx"
Description
Examples A
c represents a single custom format character. Produces the custom format pattern associated with the format character c. The %c specifier provides a mechanism for specifying a single custom format character and having it recognized as a custom specifier. This format is intended for characters that define both a custom and a standard format. Note that a format string containing exactly one such character will be interpreted as a standard format specifier unless prefaced with the %. [Note: For example, for the invariant culture, "%d" produces the single or double digit date, while "d" produces the date in "MM/ dd/yyyy" format. Without the %, a format string containing one character would have to include leading or trailing white space to be interpreted as a custom specifier because custom formats are required to have two or more characters.]
"%y" produces a two-digit year without a leading zero, and not the "MMMM, yyyy" pattern.
c represents any character predefined as part of a format specifier. Prevents the character from being interpreted as a format specifier (the character is treated as a literal). [Note: In programming languages where the backslash ('\') character is used to specify control sequences such as newline (\n), the backslash character is required to be specified twice. For example, in C#, "\d" is coded as "\\d".]
"\d" produces the character 'd', and not the day of the month.
xx represents a string of characters of any length. The characters are treated as literals.
"'d'" produces the character 'd', and not the day of the month.
B C D E F G H I J K L M N O P Q R
Example
S
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoSample { public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo i = new CultureInfo("fr-FR").DateTimeFormat; string[] f = i.GetAllDateTimePatterns(); foreach(string s in f) Console.WriteLine("ToString(\"{0}\") yields: {1}",
T U V W X Y Z
1105
Contents | Index
DateTimeFormatInfo
System.Globalization
DateTimeFormatInfo Class
s, d.ToString(s, i)); i = new CultureInfo("en-AU").DateTimeFormat; f = i.GetAllDateTimePatterns(); foreach(string s in f) Console.WriteLine("ToString(\"{0}\") yields: {1}", s, d.ToString(s, i));
A B }
C
} }
D
The output is
E F
ToString("dd/MM/yyyy") yields: 10/06/2003 ToString("dd/MM/yy") yields: 10/06/03 ToString("dd.MM.yy") yields: 10.06.03 ToString("dd-MM-yy") yields: 10-06-03 ToString("yyyy-MM-dd") yields: 2003-06-10 ToString("dddd d MMMM yyyy") yields: mardi 10 juin 2003 ToString("d MMM yy") yields: 10 juin 03 ToString("d MMMM yyyy") yields: 10 juin 2003 ToString("dddd d MMMM yyyy HH:mm") yields: mardi 10 juin 2003 12:57 ToString("dddd d MMMM yyyy H:mm") yields: mardi 10 juin 2003 12:57 ToString("dddd d MMMM yyyy HH.mm") yields: mardi 10 juin 2003 12.57 ToString("dddd d MMMM yyyy HH' h 'mm") yields: mardi 10 juin 2003 12 h 57 ... ToString("d/MM/yyyy") yields: 10/06/2003 ToString("d/MM/yy") yields: 10/06/03 ToString("d/M/yy") yields: 10/6/03 ToString("d/M/yyyy") yields: 10/6/2003 ToString("dd/MM/yy") yields: 10/06/03 ToString("dd/MM/yyyy") yields: 10/06/2003 ToString("dd-MMM-yy") yields: 10-Jun-03 ToString("dd-MMMM-yyyy") yields: 10-June-2003 ToString("yyyy-MM-dd") yields: 2003-06-10 ToString("yy/MM/dd") yields: 03/06/10 ToString("yyyy/MM/dd") yields: 2003/06/10 ToString("dddd, d MMMM yyyy") yields: Tuesday, 10 June 2003 ToString("d MMMM yyyy") yields: 10 June 2003 ToString("dddd, d MMMM yyyy h:mm tt") yields: Tuesday, 10 June 2003 12:57 PM ToString("dddd, d MMMM yyyy H:mm") yields: Tuesday, 10 June 2003 12:57 ToString("dddd, d MMMM yyyy HH:mm") yields: Tuesday, 10 June 2003 12:57 ...
G H I J K L M N O P Q R S T U V W X Y Z
1106
Contents | Index
System.Globalization
DateTimeFormatInfo DateTimeFormatInfo() Constructor
DateTimeFormatInfo() Constructor [ILASM] public rtspecialname specialname instance void .ctor() [C#] public DateTimeFormatInfo()
A B C
Summary
D
Constructs and initializes a new instance of the System.Globalization.DateTimeFormatInfo class that is culture-independent (invariant).
E F
Description
G
The new instance of System.Globalization.DateTimeFormatInfo is not read-only, and its properties can be modified with user-defined patterns.
H I
Example
J
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoConstructor { public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo i = new DateTimeFormatInfo(); string[] f = i.GetAllDateTimePatterns(); foreach(string s in f) Console.WriteLine("ToString(\"{0}\") yields: {1}", s, d.ToString(s, i)); } } }
K L M N O P Q R S T U
The output is
V
ToString("MM/dd/yyyy") yields: 06/10/2003 ToString("dddd, dd MMMM yyyy") yields: Tuesday, 10 June 2003 ToString("dddd, dd MMMM yyyy HH:mm") yields: Tuesday, 10 June 2003 13:00 ToString("dddd, dd MMMM yyyy hh:mm tt") yields: Tuesday, 10 June 2003 01:00 PM ToString("dddd, dd MMMM yyyy H:mm") yields: Tuesday, 10 June 2003 13:00 ToString("dddd, dd MMMM yyyy h:mm tt") yields: Tuesday, 10 June 2003 1:00 PM ToString("dddd, dd MMMM yyyy HH:mm:ss") yields: Tuesday, 10 June 2003 13:00:48 ToString("MM/dd/yyyy HH:mm") yields: 06/10/2003 13:00
W X Y Z
1107
Contents | Index
DateTimeFormatInfo
System.Globalization
AbbreviatedDayNames Property
ToString("MM/dd/yyyy hh:mm tt") yields: 06/10/2003 01:00 PM ToString("MM/dd/yyyy H:mm") yields: 06/10/2003 13:00 ToString("MM/dd/yyyy h:mm tt") yields: 06/10/2003 1:00 PM ToString("MM/dd/yyyy HH:mm:ss") yields: 06/10/2003 13:00:48 ToString("MMMM dd") yields: June 10 ToString("MMMM dd") yields: June 10 ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'") yields: Tue, 10 Jun 2003 13:00:48 GMT ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'") yields: Tue, 10 Jun 2003 13:00:48 GMT ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss") yields: 2003-06-10T13:00:48 ToString("HH:mm") yields: 13:00 ToString("hh:mm tt") yields: 01:00 PM ToString("H:mm") yields: 13:00 ToString("h:mm tt") yields: 1:00 PM ToString("HH:mm:ss") yields: 13:00:48 ToString("yyyy'-'MM'-'dd HH':'mm':'ss'Z'") yields: 2003-06-10 13:00:48Z ToString("dddd, dd MMMM yyyy HH:mm:ss") yields: Tuesday, 10 June 2003 13:00:48 ToString("yyyy MMMM") yields: 2003 June ToString("yyyy MMMM") yields: 2003 June
A B C D E F G H I J K
DateTimeFormatInfo.AbbreviatedDayNames Property
L [ILASM] .property class System.String[] AbbreviatedDayNames { public hidebysig specialname instance class System.String[] get_AbbreviatedDayNames() public hidebysig specialname instance void set_AbbreviatedDayNames(class System.String[] value) } [C#] public string[] AbbreviatedDayNames { get; set; }
M N O P Q
Summary
R
Gets or sets a one-dimensional array of type System.String containing the culturespecific abbreviated names of the days of the week.
S T
Description
U
The array specified in a set operation is required to be one-dimensional and have exactly seven elements. The first element of the array is the abbreviated day name for Sunday, and the last element is the name for Saturday. The property value of the culture invariant System.Globalization.DateTimeFormatInfo.AbbreviatedDayNames is a System.String array that contains “Sun”, “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, and “Sat”.
V W X Y Z
1108
Contents | Index
System.Globalization
DateTimeFormatInfo AbbreviatedDayNames Property
Exceptions Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.ArgumentException
The value specified for a set operation is not an array with exactly 7 elements.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
A B C D E F G
Example
H
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoAbbreviatedDayNames { public static void Main() { DateTimeFormatInfo f = CultureInfo.CurrentCulture.DateTimeFormat; foreach (string s in f.AbbreviatedDayNames) Console.WriteLine (s); f = new DateTimeFormatInfo(); string[] names = {"Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"}; f.AbbreviatedDayNames = names; foreach (string s in f.AbbreviatedDayNames) Console.WriteLine (s); } } }
I J K L M N O P Q R S T U V
The output is
W
Sun Mon Tue Wed Thu Fri Sat Mo
X Y Z
1109
Contents | Index
DateTimeFormatInfo
System.Globalization
AbbreviatedMonthNames Property
Tu We Th Fr Sa Su
A B C
DateTimeFormatInfo.AbbreviatedMonthNames Property
D
[ILASM] .property class System.String[] AbbreviatedMonthNames { public hidebysig specialname instance class System.String[] get_AbbreviatedMonthNames() public hidebysig specialname instance void set_AbbreviatedMonthNames(class System.String[] value) } [C#] public string[] AbbreviatedMonthNames { get; set; }
E F G H I J
Summary
K
Gets or sets a one-dimensional array of type System.String containing the culturespecific abbreviated names of the months.
L M
Property Value
N
A one-dimensional array of type System.String containing the abbreviated names of the months. For cultures with 12-month calendars the 13th element of the array is an empty string.
O P Q
Description
R
The System.Array specified in a set operation is required to be one-dimensional and have exactly 13 elements. The property value of the culture invariant System.Globalization.DateTimeFormatInfo.AbbreviatedMonthNames is a System.String array that contains “Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”, and “ “. [Note: The array returned by this property has 13 elements to support calendars with 13 months.]
S T U V W X Y Z
1110
Contents | Index
System.Globalization
DateTimeFormatInfo AbbreviatedMonthNames Property
Exceptions Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.ArgumentException
The value specified for a set operation is not an array with exactly 13 elements.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
A B C D E F G
Example
H
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoAbbreviatedMonthNames { public static void Main() { DateTimeFormatInfo f = CultureInfo.CurrentCulture.DateTimeFormat; foreach(string s in f.AbbreviatedMonthNames) Console.WriteLine(s); f = new DateTimeFormatInfo(); string[] names = {"JA", "FE", "MAr", "AP", "MAy", "JUn", "JUl", "AU", "SE", "OC", "NO", "DE", ""}; f.AbbreviatedMonthNames = names; foreach(string s in f.AbbreviatedMonthNames) Console.WriteLine(s); } } }
I J K L M N O P Q R S T U V W
The output is
X
Jan Feb Mar Apr May
Y Z
1111
Contents | Index
DateTimeFormatInfo
System.Globalization
AMDesignator Property
Jun Jul Aug Sep Oct Nov Dec JA FE MAr AP MAy JUn JUl AU SE OC NO DE
A B C D E F G H I J K L
DateTimeFormatInfo.AMDesignator Property
M
[ILASM] .property string AMDesignator { public hidebysig specialname instance string get_AMDesignator() public hidebysig specialname instance void set_AMDesignator(string value) } [C#] public string AMDesignator { get; set; }
N O P Q R
Summary
S
Gets or sets the System.String culture-specific designator for hours that are “ante meridiem” (before noon).
T U
Description
V
The property value of the culture invariant System.Globalization.DateTimeFormatInfo.AMDesignator returns the System.String “AM”.
W X Y Z
1112
Contents | Index
System.Globalization
DateTimeFormatInfo Calendar Property
Exceptions Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
A B C D E
Example
F
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoAMDesignator { public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo i = new DateTimeFormatInfo(); Console.WriteLine(i.AMDesignator); Console.WriteLine(i.PMDesignator); i.AMDesignator = "am"; i.PMDesignator = "pm"; Console.WriteLine(d.ToString("hh mm tt", i)); } } }
G H I J K L M N O P Q
The output is
R S
AM PM 01 13 am
T U V
DateTimeFormatInfo.Calendar Property
W
[ILASM] .property class System.Globalization.Calendar Calendar { public hidebysig specialname instance class System.Globalization.Calendar get_Calendar() public hidebysig specialname instance void set_Calendar(class System.Globalization.Calendar value) } [C#] public Calendar Calendar { get; set; }
X Y Z
1113
Contents | Index
DateTimeFormatInfo
System.Globalization
Calendar Property
Summary Gets or sets the calendar to use for the current culture. A
Property Value
B
The System.Globalization.Calendar indicating the calendar to use for the current culture. The default for System.Globalization.DateTimeFormatInfo.InvariantInfo is the System.Globalization.GregorianCalendar.
C D E
Description
F
The System.Globalization.DateTimeFormatInfo.Calendar property only accepts calendars that are valid for the current culture of the current thread. The System.Globalization.CultureInfo.Calendar property specifies the default calendar for the culture and the System.Globalization.CultureInfo.OptionalCalendars property specifies other calendars supported by the culture. Changing the value of this property affects the following properties as well: System.Globalization.DateTimeFormatInfo.MonthNames, System.Globalization.DateTimeFormatInfo.AbbreviatedMonthNames, System.Globalization.DateTimeFormatInfo.DayNames, System.Globalization.DateTimeFormatInfo.AbbreviatedDayNames, System.Globalization.DateTimeFormatInfo.CalendarWeekRule, System.Globalization.DateTimeFormatInfo.FirstDayOfWeek, System.Globalization.DateTimeFormatInfo.FullDateTimePattern, System.Globalization.DateTimeFormatInfo.LongDatePattern, System.Globalization.DateTimeFormatInfo.ShortDatePattern, System.Globalization.DateTimeFormatInfo.YearMonthPattern, and System.Globalization.DateTimeFormatInfo.MonthDayPattern. For example, if the culture of the current thread is Japanese, this property accepts System.Globalization.JapaneseCalendar, System.Globalization.GregorianCalendarTypes.LocalizedSystem.Globalization.GregorianCalendar, or System.Globalization.GregorianCalendarTypes.USEnglishSystem.Globalization.GregorianCalendar. When the System.Globalization.JapaneseCalendar is used, the default long date pattern is "gg y'\x5e74'M'\x6708'd'\x65e5'". When the System.Globalization.GregorianCalendarTypes.LocalizedSystem.Globalization.GregorianCalendar is used, the default long date pattern is "yyyy'\x5e74'M'\x6708'd'\x65e5'".
G H I J K L M N O P Q R S T U V W X Y Z
1114
Contents | Index
System.Globalization
DateTimeFormatInfo CalendarWeekRule Property
Exceptions Exception
Condition
System.ArgumentNullException
The property is being set to null.
System.ArgumentException
The property is being set to a System.Globalization.Calendar that is not valid for the current culture.
A
System.InvalidOperationException
B C D E
The property is being set and the System.Globalization.DateTimeFormatInfo is read-only.
F G H
DateTimeFormatInfo.CalendarWeekRule Property
I
[ILASM] .property valuetype System.Globalization.CalendarWeekRule CalendarWeekRule { public hidebysig specialname instance valuetype System.Globalization.CalendarWeekRule get_CalendarWeekRule() public hidebysig specialname instance void set_CalendarWeekRule(valuetype System.Globalization.CalendarWeekRule value) } [C#] public CalendarWeekRule CalendarWeekRule { get; set; }
J K L M N O
Summary
P
Gets or sets a value that specifies which rule is used to determine the first calendar week of the year.
Q R
Property Value
S
A System.Globalization.CalendarWeekRule value that determines the first calendar week of the year. The default for System.Globalization.DateTimeFormatInfo.InvariantInfo is System.Globalization.CalendarWeekRule.FirstDay.
T U V
Description
W
This property is affected if the value of the System.Globalization.DateTimeFormatInfo.Calendar property changes.
X Y Z
1115
Contents | Index
DateTimeFormatInfo
System.Globalization
CurrentInfo Property
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
The property is being set to a value that is not a valid System.Globalization.CalendarWeekRule value.
A B C D E
DateTimeFormatInfo.CurrentInfo Property
F [ILASM] .property class System.Globalization.DateTimeFormatInfo CurrentInfo { public hidebysig static specialname class System.Globalization.DateTimeFormatInfo get_CurrentInfo() } [C#] public static DateTimeFormatInfo CurrentInfo { get; }
G H I J K
Summary
L
Gets a read-only System.Globalization.DateTimeFormatInfo instance that formats values based on the current culture.
M N
Example
O
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoCurrentInfo { public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo i = DateTimeFormatInfo.CurrentInfo; Console.WriteLine(i.DateSeparator); try { i.DateSeparator = ":"; } catch(InvalidOperationException e) { Console.WriteLine("Exception: {0}", e); } } } }
P Q R S T U V W X Y Z
1116
Contents | Index
System.Globalization
DateTimeFormatInfo DateSeparator Property
The output is Exception: System.InvalidOperationException: Instance is read-only. at System.Globalization.DateTimeFormatInfo.set_DateSeparator(String value) at Samples.DateTimeFormatInfoCurrentInfo.Main() in C:\Books\BCL\Samples\ System.Globalization\DateTimeFormatInfo\CurrentInfo\DateTimeFormatInfo.cs:line 15
A B C D
DateTimeFormatInfo.DateSeparator Property
E
[ILASM] .property string DateSeparator { public hidebysig specialname instance string get_DateSeparator() public hidebysig specialname instance void set_DateSeparator(string value) } [C#] public string DateSeparator { get; set; }
F G H I
Summary
J
Gets or sets the culture-specific System.String to use to separate the year, month, and day components of a date.
K L
Description
M
The property value of the culture invariant System.Globalization.DateTimeFormatInfo.DateSeparator is “/”.
N O P
Exceptions
Q
Exception
Condition
R
The value specified for a set operation is a null reference.
S
System.ArgumentNullException
The current instance is read-only and a set operation was attempted.
U
System.InvalidOperationException
T
V W
Example
X
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoDateSeparator {
Y Z
1117
Contents | Index
DateTimeFormatInfo
System.Globalization
DayNames Property
public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo i = new DateTimeFormatInfo(); Console.WriteLine(i.DateSeparator); i.DateSeparator = "-"; Console.WriteLine(d.ToString(i)); }
A B C }
D
}
E
The output is
F / 06-10-2003 13:15:29
G H I
DateTimeFormatInfo.DayNames Property
J [ILASM] .property class System.String[] DayNames { public hidebysig specialname instance class System.String[] get_DayNames() public hidebysig specialname instance void set_DayNames(class System.String[] value) } [C#] public string[] DayNames { get; set; }
K L M N O
Summary
P
Gets or sets a one-dimensional array of type System.String containing the culturespecific full names of the days of the week.
Q R
Description
S
The array specified in a set operation is required to be one-dimensional and have exactly seven elements. The first element of the array is the abbreviated day name for Sunday, and the last element is the name for Saturday. The property value of the culture invariant System.Globalization.DateTimeFormatInfo.DayNames is a System.String array that contains “Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, and “Saturday”.
T U V W X Y Z
1118
Contents | Index
System.Globalization
DateTimeFormatInfo DayNames Property
Exceptions Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.ArgumentException
The value specified for a set operation is not an array with exactly 7 elements.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
A B C D E F G
Example
H
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoDayNames { public static void Main() { DateTimeFormatInfo f = new DateTimeFormatInfo(); DisplayDayNames(f); string[] names = {"Monday.", "Tuesday.", "Wednesday.", "Thursday.", "Friday.", "Saturday.", "Sunday."}; f.DayNames = names; DisplayDayNames(f); } public static void DisplayDayNames( DateTimeFormatInfo f) { string[] names = f.DayNames; foreach(string s in names) Console.WriteLine(s); } } }
I J K L M N O P Q R S T U V W X
The output is
Y
Sunday Monday Tuesday Wednesday
Z
1119
Contents | Index
DateTimeFormatInfo
System.Globalization
FirstDayOfWeek Property
Thursday Friday Saturday Monday. Tuesday. Wednesday. Thursday. Friday. Saturday. Sunday.
A B C D E F
DateTimeFormatInfo.FirstDayOfWeek Property
G
[ILASM] .property valuetype System.DayOfWeek FirstDayOfWeek { public hidebysig specialname instance valuetype System.DayOfWeek get_FirstDayOfWeek() public hidebysig specialname instance void set_FirstDayOfWeek(valuetype System.DayOfWeek value) } [C#] public DayOfWeek FirstDayOfWeek { get; set; }
H I J K L
Summary
M
Gets or sets the first day of the week.
N
Property Value
O
A System.DayOfWeek value representing the first day of the week. The default for System.Globalization.DateTimeFormatInfo.InvariantInfo is System.DayOfWeek.Sunday.
P Q R
Description
S
This property is affected if the value of the System.Globalization.DateTimeFormatInfo.Calendar property changes.
T U
Exceptions
V W
Exception
Condition
System.ArgumentOutOfRangeException
The property is being set to a value that is not a valid System.DayOfWeek value.
System.InvalidOperationException
The property is being set and the System.Globalization.DateTimeFormatInfo is read-only.
X Y Z
1120
Contents | Index
System.Globalization
DateTimeFormatInfo FullDateTimePattern Property
DateTimeFormatInfo.FullDateTimePattern Property [ILASM] .property string FullDateTimePattern { public hidebysig specialname instance string get_FullDateTimePattern() public hidebysig specialname instance void set_FullDateTimePattern(string value) } [C#] public string FullDateTimePattern { get; set; }
A B C
Summary
D
Gets or sets the format pattern for a long date and long time value.
E F
Description
G
The System.DateTime.ParseExact and System.DateTime.ToString methods associate the format pattern returned by this property with the ’F’ format character. The property value of the culture invariant System.Globalization.DateTimeFormatInfo.FullDateTimePattern is “dddd, dd MMMM yyyy HH:mm:ss”.
H I J
Exceptions
K
Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
L M N O P Q
Example
R
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoFullDateTimePattern { public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo i = new DateTimeFormatInfo(); Console.WriteLine(i.FullDateTimePattern); Console.WriteLine(d.ToString("F", i)); i.FullDateTimePattern = "dddd, dd MMMM yyyy hh:mm:ss tt"; Console.WriteLine(d.ToString("F", i)); } } }
S T U V W X Y Z
1121
Contents | Index
DateTimeFormatInfo
System.Globalization
InvariantInfo Property
The output is dddd, dd MMMM yyyy HH:mm:ss Tuesday, 10 June 2003 13:17:42 Tuesday, 10 June 2003 01:17:42 PM
A B C
DateTimeFormatInfo.InvariantInfo Property
D
[ILASM] .property class System.Globalization.DateTimeFormatInfo InvariantInfo { public hidebysig static specialname class System.Globalization.DateTimeFormatInfo get_InvariantInfo() } [C#] public static DateTimeFormatInfo InvariantInfo { get; }
E F G H I
Summary
J
Gets a culture invariant instance of System.Globalization.DateTimeFormatInfo that is read-only.
K L
Example
M
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoInvariantInfo { public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo i = DateTimeFormatInfo.InvariantInfo; Console.WriteLine(d.ToString(i)); Console.WriteLine(i.DateSeparator); try { i.DateSeparator = "-"; } catch(InvalidOperationException e) { Console.WriteLine("Exception: {0}", e); } } } }
N O P Q R S T U V W X Y Z
1122
Contents | Index
System.Globalization
DateTimeFormatInfo IsReadOnly Property
The output is 06/10/2003 13:18:43 / Exception: System.InvalidOperationException: Instance is read-only. at System.Globalization.DateTimeFormatInfo.set_DateSeparator(String value) at Samples.DateTimeFormatInfoInvariantInfo.Main() in C:\Books\BCL\Samples\ System.Globalization\DateTimeFormatInfo\InvariantInfo\DateTimeFormatInfo.cs:line 16
A B C D
DateTimeFormatInfo.IsReadOnly Property
E
[ILASM] .property bool IsReadOnly { public hidebysig specialname instance bool get_IsReadOnly() } [C#] public bool IsReadOnly { get; }
F G H I
Summary
J
Gets a System.Boolean value indicating whether the current System.Globalization.DateTimeFormatInfo instance is read-only.
K
Property Value
M
true if the System.Globalization.DateTimeFormatInfo is read-only; otherwise, false.
N
L
O
Example
P
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoIsReadOnly { public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo i = new DateTimeFormatInfo(); if(!i.IsReadOnly) i.DateSeparator = "-"; Console.WriteLine(d.ToString(i)); i = DateTimeFormatInfo.InvariantInfo; if(!i.IsReadOnly) i.DateSeparator = "-"; Console.WriteLine(d.ToString(i)); } } }
Q R S T U V W X Y Z
1123
Contents | Index
DateTimeFormatInfo
System.Globalization
LongDatePattern Property
The output is 06-10-2003 13:19:42 06/10/2003 13:19:42
A B C
DateTimeFormatInfo.LongDatePattern Property
D
[ILASM] .property string LongDatePattern { public hidebysig specialname instance string get_LongDatePattern() public hidebysig specialname instance void set_LongDatePattern(string value) } [C#] public string LongDatePattern { get; set; }
E F G H
Summary
I
Gets or sets the format pattern for a long date value.
J K
Description
L
The System.DateTime.ParseExact and System.DateTime.ToString methods associate the format pattern returned by this property with the ’D’ format character. The property value of the culture invariant System.Globalization.DateTimeFormatInfo.LongDatePattern is “dddd, dd MMMM yyyy”.
M N O
Exceptions
P Q
Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
R S T U V W
Example
X
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoLongDatePattern { public static void Main()
Y Z
1124
Contents | Index
System.Globalization
DateTimeFormatInfo LongTimePattern Property
{ DateTime d = DateTime.Now; DateTimeFormatInfo i = new DateTimeFormatInfo(); Console.WriteLine(i.LongDatePattern); Console.WriteLine(d.ToString("D", i)); i.LongDatePattern = "ddd, dd MMMM yyyy"; Console.WriteLine(d.ToString("D", i));
A B C
} }
D
}
E
The output is
F
dddd, dd MMMM yyyy Tuesday, 10 June 2003 Tue, 10 June 2003
G H I J
DateTimeFormatInfo.LongTimePattern Property
K [ILASM] .property string LongTimePattern { public hidebysig specialname instance string get_LongTimePattern() public hidebysig specialname instance void set_LongTimePattern(string value) } [C#] public string LongTimePattern { get; set; }
L M N O
Summary
P
Gets or sets the format pattern for a long time value.
Q R
Description
S
The System.DateTime.ParseExact and System.DateTime.ToString methods associate the format pattern returned by this property with the ’T’ format character. The property value of the culture invariant System.Globalization.DateTimeFormatInfo.LongTimePattern is “HH:mm:ss”.
T U V W X Y Z
1125
Contents | Index
DateTimeFormatInfo
System.Globalization
MonthDayPattern Property
Exceptions Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
A B C D E F
Example
G
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoLongTimePattern { public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo i = new DateTimeFormatInfo(); Console.WriteLine(i.LongTimePattern); Console.WriteLine(d.ToString("T", i)); i.LongTimePattern = "hh:mm:ss tt"; Console.WriteLine(d.ToString("T", i)); } } }
H I J K L M N O P Q R
The output is
S
HH:mm:ss 13:21:42 01:21:42 PM
T U V
DateTimeFormatInfo.MonthDayPattern Property
W X
[ILASM] .property string MonthDayPattern { public hidebysig specialname instance string get_MonthDayPattern() public hidebysig specialname instance void set_MonthDayPattern(string value) } [C#] public string MonthDayPattern { get; set; }
Y Z
1126
Contents | Index
System.Globalization
DateTimeFormatInfo MonthDayPattern Property
Summary Gets or sets the format pattern for a month and day value.
Description
A
The System.DateTime.ParseExact and System.DateTime.ToString methods associate the format pattern returned by this property with the ’m’ and ’M’ format characters. The property value of the culture invariant System.Globalization.DateTimeFormatInfo.MonthDayPattern is “MMMM dd”.
B C D E
Exceptions
F
Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
G H I J K L
Example
M
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoMonthDayPattern { public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo i = new DateTimeFormatInfo(); Console.WriteLine(i.MonthDayPattern); Console.WriteLine(d.ToString("m", i)); i.MonthDayPattern = "dd, MMMM"; Console.WriteLine(d.ToString("m", i)); } } }
N O P Q R S T U V W X
The output is
Y Z
MMMM dd June 10 10, June
1127
Contents | Index
DateTimeFormatInfo
System.Globalization
MonthNames Property
DateTimeFormatInfo.MonthNames Property [ILASM] .property class System.String[] MonthNames { public hidebysig specialname instance class System.String[] get_MonthNames() public hidebysig specialname instance void set_MonthNames(class System.String[] value) } [C#] public string[] MonthNames { get; set; }
A B C D
Summary
E
Gets or sets a one-dimensional array of type System.String containing the culturespecific full names of the months.
F G
Property Value
H
A one-dimensional array of type System.String containing the full names of the months. For cultures with 12-month calendars the 13th element of the array is an empty string.
I J K
Description
L
The array specified in a set operation is required to be one-dimensional and have exactly 13 elements. The property value of the culture invariant System.Globalization.DateTimeFormatInfo.MonthNames is a System.String array that contains “January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”, and “ “. [Note: The array returned by this property has 13 elements to support calendars with 13 months.]
M N O P Q R S
Exceptions
T U V
Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.ArgumentException
The value specified for a set operation is not an array with exactly 13 elements.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
W X Y Z
1128
Contents | Index
System.Globalization
DateTimeFormatInfo MonthNames Property
Example using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoMonthNames { public static void Main() { DateTimeFormatInfo f = new DateTimeFormatInfo(); DisplayMonthNames(f); string[] names = { "Jan.", "Feb.", "Mar.", "Apr.", "May.", "Jun.", "Jul.", "Aug.", "Sep.","Oct.", "Nov.", "Dec.", String.Empty}; f.MonthNames = names; DisplayMonthNames(f); } public static void DisplayMonthNames( DateTimeFormatInfo f) { string[] names = f.MonthNames; foreach(string s in names) Console.WriteLine(s); } } }
A B C D E F G H I J K L M N O P
The output is
Q January February March April May June July August September October November December
R S T U V W X Y
Jan. Feb. Mar. Apr.
Z
1129
Contents | Index
DateTimeFormatInfo
System.Globalization
PMDesignator Property
May. Jun. Jul. Aug. Sep. Oct. Nov. Dec.
A B C D E
DateTimeFormatInfo.PMDesignator Property
F [ILASM] .property string PMDesignator { public hidebysig specialname instance string get_PMDesignator() public hidebysig specialname instance void set_PMDesignator(string value) } [C#] public string PMDesignator { get; set; }
G H I J K
Summary
L
Gets or sets the culture-specific System.String designator for hours that are “post meridiem” (after noon).
M N
Description
O
The property value of the culture invariant System.Globalization.DateTimeFormatInfo.PMDesignator is “PM”.
P Q
Exceptions
R S
Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
T U V W X Y Z
1130
Contents | Index
System.Globalization
DateTimeFormatInfo RFC1123Pattern Property
Example using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoAMDesignator { public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo i = new DateTimeFormatInfo(); Console.WriteLine(i.AMDesignator); Console.WriteLine(i.PMDesignator); i.AMDesignator = "am"; i.PMDesignator = "pm"; Console.WriteLine(d.ToString("hh mm tt", i)); } } }
A B C D E F G H I J K
The output is
L AM PM 01 25 pm
M N O
DateTimeFormatInfo.RFC1123Pattern Property
P
[ILASM] .property string RFC1123Pattern { public hidebysig specialname instance string get_RFC1123Pattern() } [C#] public string RFC1123Pattern { get; }
Q
Summary
U
Gets the format pattern for a time value, which is based on the Internet Engineering Task Force (IETF) Request for Comments (RFC) 1123 specification and is associated with the ’r’ and ’R’ format characters.
V
R S T
W X Y Z
1131
Contents | Index
DateTimeFormatInfo
System.Globalization
ShortDatePattern Property
DateTimeFormatInfo.ShortDatePattern Property [ILASM] .property string ShortDatePattern { public hidebysig specialname instance string get_ShortDatePattern() public hidebysig specialname instance void set_ShortDatePattern(string value) } [C#] public string ShortDatePattern { get; set; }
A B C D
Summary
E
Gets or sets the format pattern for a short date value.
F G
Description
H
The System.DateTime.ParseExact and System.DateTime.ToString methods associate the format pattern returned by this property with the ’d’ format character. The property value of the culture invariant System.Globalization.DateTimeFormatInfo.ShortDatePattern is “MM/dd/yyyy”.
I J K
Exceptions
L M
Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
N O P Q R S
Example
T
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoShortDatePattern { public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo i = new DateTimeFormatInfo(); Console.WriteLine(i.ShortDatePattern); Console.WriteLine(d.ToString("d", i)); i.ShortDatePattern = "dd/MM/yyyy";
U V W X Y Z
1132
Contents | Index
System.Globalization
DateTimeFormatInfo ShortTimePattern Property
Console.WriteLine(d.ToString("d", i)); } } }
A
The output is
B C
MM/dd/yyyy 06/10/2003 10/06/2003
D E F
DateTimeFormatInfo.ShortTimePattern Property
G
[ILASM] .property string ShortTimePattern { public hidebysig specialname instance string get_ShortTimePattern() public hidebysig specialname instance void set_ShortTimePattern(string value) } [C#] public string ShortTimePattern { get; set; }
H I J K L
Summary
M
Gets or sets the format pattern for a short time value.
N
Description
O
The System.DateTime.ParseExact and System.DateTime.ToString methods associate the format pattern returned by this property with the ’t’ format character. The property value of the culture invariant System.Globalization.DateTimeFormatInfo.ShortTimePattern is “HH:mm”.
P Q R S
Exceptions
T
Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
U V W X Y Z
1133
Contents | Index
DateTimeFormatInfo
System.Globalization
SortableDateTimePattern Property
Example using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoShortTimePattern { public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo i = new DateTimeFormatInfo(); Console.WriteLine(i.ShortTimePattern); Console.WriteLine(d.ToString("t", i)); i.ShortTimePattern = "hh:mm tt"; Console.WriteLine(d.ToString("t", i)); } } }
A B C D E F G H I J
The output is
K HH:mm 13:27 01:27 PM
L M N O
DateTimeFormatInfo.SortableDateTimePattern Property
P
[ILASM]
Q
.property string SortableDateTimePattern { public hidebysig specialname instance string get_SortableDateTimePattern() } [C#]
R
public string SortableDateTimePattern { get; }
S T
Summary
U
Gets the format pattern for a sortable date and time value, which is associated with the ’s’ format character.
V W
DateTimeFormatInfo.TimeSeparator Property
X [ILASM] .property string TimeSeparator { public hidebysig specialname instance string get_TimeSeparator() public hidebysig specialname instance void set_TimeSeparator(string value) } [C#] public string TimeSeparator { get; set; }
Y Z
1134
Contents | Index
System.Globalization
DateTimeFormatInfo TimeSeparator Property
Summary Gets or sets the culture-specific System.String to use to separate the components of time values (hour, minutes, seconds). A
Description
B
The property value of the culture invariant System.Globalization.DateTimeFormatInfo.TimeSeparator is “:”.
C D E
Exceptions
F
Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
H
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
J
G
I
K L
Example
M
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoTimeSeparator { public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo i = new DateTimeFormatInfo(); Console.WriteLine(i.TimeSeparator); i.TimeSeparator = "-"; Console.WriteLine(d.ToString(i)); } } }
N O P Q R S T U V W
The output is
X
: 06/10/2003 13-27-50
Y Z
1135
Contents | Index
DateTimeFormatInfo
System.Globalization
UniversalSortableDateTimePattern Property
DateTimeFormatInfo.UniversalSortableDateTimePattern Property [ILASM]
A
.property string UniversalSortableDateTimePattern { public hidebysig specialname instance string get_UniversalSortableDateTimePattern() }
B
[C#]
public string UniversalSortableDateTimePattern { get; }
C D
Summary
E
Gets the format pattern for a universal sortable date and time value, which is associated with the ’u’ and ’U’ format characters.
F G
Description
H
System.Globalization.DateTimeFormatInfo.UniversalSortableDateTimePattern can be used to display time in a sortable format with the universal time designator “Z” at the end. The format is sortable because it uses leading zeros for year, month, day, hour, minute, and second. The pattern (“yyyy'-'MM'-'dd HH':'mm':'ss'Z'”) is the same regardless of culture or format provider.
I J K L M
DateTimeFormatInfo.YearMonthPattern Property
N
[ILASM] .property string YearMonthPattern { public hidebysig specialname instance string get_YearMonthPattern() public hidebysig specialname instance void set_YearMonthPattern(string value) } [C#] public string YearMonthPattern { get; set; }
O P Q R S
Summary
T
Gets or sets the format pattern for a year and month value.
U
Description
V
The System.DateTime.ParseExact and System.DateTime.ToString methods associate the format pattern returned by this property with the ’y’ and ’Y’ format character. The property value of the culture invariant System.Globalization.DateTimeFormatInfo.YearMonthPattern is “yyyy MMMM”.
W X Y Z
1136
Contents | Index
System.Globalization
DateTimeFormatInfo Clone() Method
Exceptions Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
A B C D E
Example
F
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoYearMonthPattern { public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo i = new DateTimeFormatInfo(); Console.WriteLine(i.YearMonthPattern); Console.WriteLine(d.ToString("Y", i)); i.YearMonthPattern = "yyyy, MM"; Console.WriteLine(d.ToString("Y", i)); } } }
G H I J K L M N O P Q R
The output is
S
yyyy MMMM 2003 June 2003, 06
T U V
DateTimeFormatInfo.Clone() Method
W X
[ILASM] .method public final hidebysig virtual object Clone() [C#] public object Clone()
Y Z
1137
Contents | Index
DateTimeFormatInfo
System.Globalization
Clone() Method
Summary Creates a copy of the current instance. A
Return Value
B
A new System.Globalization.DateTimeFormatInfo instance with property values equal to the property values of the original System.Globalization.DateTimeFormatInfo instance.
C D E
Description
F
The System.Globalization.DateTimeFormatInfo.Clone method creates a new instance of the same type as the current instance, and then copies the contents of each of the current instance’s non-static fields. The new instance is not read-only, and its properties can be modified with userdefined patterns. [Note: This method is implemented to support the System.ICloneable interface.]
G H I J K
Example
L
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoCLone { public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo i1 = new DateTimeFormatInfo(); DateTimeFormatInfo i2 = i1; Console.WriteLine(i1.DateSeparator); i1.DateSeparator = "-"; Console.WriteLine(i2.DateSeparator); Console.WriteLine(d.ToString(i2)); } } }
M N O P Q R S T U V W
The output is
X Y
/ 06-10-2003 13:02:13
Z
1138
Contents | Index
System.Globalization
DateTimeFormatInfo GetAbbreviatedDayName() Method
DateTimeFormatInfo.GetAbbreviatedDayName(System.DayOfWeek) Method [ILASM] .method public hidebysig instance string GetAbbreviatedDayName(valuetype System.DayOfWeek dayofweek) [C#] public string GetAbbreviatedDayName(DayOfWeek dayofweek)
A B C
Summary
D
Returns the culture-specific abbreviated name of the specified day of the week based on the System.Globalization.CultureInfo of the current thread.
E
Parameters
G
F
H
Parameter
Description
dayofweek
A System.DayOfWeek value.
I J K
Return Value
L
The culture-specific abbreviated name of the day of the week represented by dayofweek.
M N
Description
O
For the default invariant System.Globalization.DateTimeFormatInfo, this method returns a string from the System.Globalization.GregorianCalendar:
P Q
Return Value
R
Return Value
S
Sunday
"Sun"
Thursday
"Thu"
T
Monday
"Mon"
Friday
"Fri"
U
Tuesday
"Tue"
Saturday
"Sat"
Wednesday
"Wed"
V W X Y Z
1139
Contents | Index
DateTimeFormatInfo
System.Globalization
GetAbbreviatedEraName() Method
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
dayofweek is not a valid System.DayOfWeek value.
A B C D
DateTimeFormatInfo.GetAbbreviatedEraName(System.Int32) Method
E F
[ILASM] .method public hidebysig instance string GetAbbreviatedEraName(int32 era) [C#] public string GetAbbreviatedEraName(int era)
G H I
Summary
J
Returns the string containing the abbreviated name of the specified era, if an abbreviation exists.
K L
Parameters
M N
Parameter
Description
O
era
The integer representing the era.
P Q
Return Value
R
A string containing the abbreviated name of the specified era, if an abbreviation exists or a string containing the full name of the era, if an abbreviation does not exist.
S T
Description
U
The era name is the name a calendar uses to refer to a period of time reckoned from a fixed point or event. For example, “A.D.” or “C.E.” is the current era in the Gregorian calendar. The valid values for era are listed in the System.Globalization.Calendar.Eras property of the appropriate class derived from System.Globalization.Calendar. For example: System.Globalization.JapaneseCalendar.Eras displays a list of eras that are supported by this implementation. In the System.Globalization.JapaneseCalendar, the abbreviated era name is the first character of the full era name; that is, either the single-character case-insensitive Latin alphabet abbreviation or the single-character Kanji abbreviation.
V W X Y Z
1140
Contents | Index
System.Globalization
DateTimeFormatInfo GetAbbreviatedMonthName() Method
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
era does not represent a valid era in the calendar specified in the System.Globalization.DateTimeFormatInfo.Calendar property.
A B C D E
DateTimeFormatInfo.GetAbbreviatedMonthName(System.Int32) Method
F
[ILASM] .method public hidebysig instance string GetAbbreviatedMonthName(int32 month) [C#] public string GetAbbreviatedMonthName(int month)
G H I
Summary
J
Gets the abbreviated name of the specified month based on the culture of the current thread.
K L
Parameters
M
Parameter
Description
N
month
A System.Int32 from 1 through 13 representing the month name to retrieve.
O P Q
Return Value A System.String containing the abbreviated name of the month represented by month. For cultures with 12-month calendars, the empty string is returned as the name of the 13th month.
R
Description
U
For the default (culture-invariant) System.Globalization.DateTimeFormatInfo instance, this method returns one of the following strings:
V
S T
W X Y Z
1141
Contents | Index
DateTimeFormatInfo
System.Globalization
GetAbbreviatedMonthName() Method
Return Value
Return Value
A
1
"Jan"
8
"Aug"
B
2
"Feb"
9
"Sep"
C
3
"Mar"
10
"Oct"
4
"Apr"
11
"Nov"
F
5
"May"
12
"Dec"
G
6
"Jun"
13
""
H
7
"Jul"
D E
I J
[Note: This method supports calendars with 13 months.]
K
Exceptions
L M
Exception
Condition
System.ArgumentOutOfRangeException
month is less than 1 or greater than 13.
N O P Q
Example
R
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoGetAbbreviatedMonthName { public static void Main() { DateTimeFormatInfo f = new DateTimeFormatInfo(); for(int i = 1; i <= 13; i++) Console.WriteLine( f.GetAbbreviatedMonthName(i)); } } }
S T U V W X Y Z
1142
Contents | Index
System.Globalization
DateTimeFormatInfo GetAllDateTimePatterns() Method
The output is Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
A B C D E F G H
DateTimeFormatInfo.GetAllDateTimePatterns() Method
I J
[ILASM] .method public hidebysig instance class System.String[] GetAllDateTimePatterns() [C#] public string[] GetAllDateTimePatterns()
K L M
Summary
N
Returns all the standard patterns in which System.DateTime values can be formatted.
O
Description
P
See the summary page of the System.Globalization.DateTimeFormatInfo class for a list of the standard format characters and their associated patterns.
Q R S
DateTimeFormatInfo.GetAllDateTimePatterns(System.Char) Method
T
[ILASM]
U
.method public hidebysig instance class System.String[] GetAllDateTimePatterns(valuetype System.Char format)
V
[C#]
W
public string[] GetAllDateTimePatterns(char format)
X
Summary
Y
Returns all the standard patterns in which System.DateTime values can be formatted using the specified format character.
Z
1143
Contents | Index
DateTimeFormatInfo
System.Globalization
GetDayName() Method
Parameters Parameter
Description
format
A standard format character.
A B C D
Description
E
See the summary page of the System.Globalization.DateTimeFormatInfo class for a list of the standard format characters and their associated patterns.
F G
Exceptions
H I J
Exception
Condition
System.ArgumentException
format is not a valid standard format character.
K L
DateTimeFormatInfo.GetDayName(System.DayOfWeek) Method
M
[ILASM] .method public hidebysig instance string GetDayName(valuetype System.DayOfWeek dayofweek) [C#] public string GetDayName(DayOfWeek dayofweek)
N O P Q R
Summary
S
Returns the culture-specific full name of the specified day of the week based on the System.Globalization.CultureInfo of the current thread.
T
Parameters
U V W X
Parameter
Description
dayofweek
A System.DayOfWeek value.
Y Z
Description For the default invariant System.Globalization.DateTimeFormatInfo, this method returns a string from the System.Globalization.GregorianCalendar: 1144
Contents | Index
System.Globalization
DateTimeFormatInfo GetEra() Method
Return Value
Return Value
Sunday
"Sunday"
Thursday
"Thursday"
A
Monday
"Monday"
Friday
"Friday"
B
Tuesday
"Tuesday"
Saturday
"Saturday"
Wednesday
"Wednesday"
C D E F
Exceptions
G
Exception
Condition
System.ArgumentOutOfRangeException
dayofweek is not a valid System.DayOfWeek value.
H I J K L
DateTimeFormatInfo.GetEra(System.String) Method
M N
[ILASM] .method public hidebysig instance int32 GetEra(string eraName) [C#] public int GetEra(string eraName)
O P Q
Summary
R
Gets a System.Int32 representing the specified era.
S
Parameters
T
Parameter
Description
eraName
A System.String containing the name of the era.
U V W X
Return Value
Y
A System.Int32 representing the era. If eraName is invalid, returns –1.
Z
1145
Contents | Index
DateTimeFormatInfo
System.Globalization
GetEraName() Method
Description The value specified for eraName is case-insensitive. [Note: An era name is a culturally specific name for a period of time marked by a distinctive character or reckoned from a fixed point or event. For example “A.D.” and “B.C.” are two eras of the Gregorian calendar.]
A B C
Exceptions
D E
Exception
Condition
F
System.ArgumentNullException
eraName is a null reference.
G H
Example
I
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoGetEra { public static void Main() { DateTimeFormatInfo f = new DateTimeFormatInfo(); Console.WriteLine(f.GetEra("B.C.")); Console.WriteLine(f.GetEra("A.D.")); Console.WriteLine(f.GetEra("C.E.")); } } }
J K L M N O P Q R
The output is
S
-1 1 -1
T U V
DateTimeFormatInfo.GetEraName(System.Int32) Method
W
[ILASM] .method public hidebysig instance string GetEraName(int32 era) [C#] public string GetEraName(int era)
X Y Z
Summary Gets the System.String containing the name of the specified era. 1146
Contents | Index
System.Globalization
DateTimeFormatInfo GetEraName() Method
Parameters Parameter
Description
era
A System.Int32 representing the era.
A B C
Description
D
[Note: An era name is a culturally specific name for a period of time marked by a distinctive character or reckoned from a fixed point or event. For example “A.D.” and “B.C.” are two eras of the Gregorian calendar.]
E F G
Exceptions
H
Exception
Condition
System.ArgumentOutOfRangeException
era does not represent a valid era in the calendar for the current thread.
I J K L M
Example
N
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoGetEraName { public static void Main() { try { DateTimeFormatInfo f = new DateTimeFormatInfo(); Console.WriteLine(f.GetEraName(0)); Console.WriteLine(f.GetEraName(1)); Console.WriteLine(f.GetEraName(f.GetEra("B.C."))); } catch(ArgumentOutOfRangeException e) { Console.WriteLine("Exception: {0}", e); } } } }
O P Q R S T U V W X Y Z
1147
Contents | Index
DateTimeFormatInfo
System.Globalization
GetFormat() Method
The output is A.D. A.D. Exception: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: Era value was not valid. at System.Globalization.DateTimeFormatInfo.GetEraName(Int32 era) at Samples.DateTimeFormatInfoGetEraName.Main() in C:\Books\BCL\Samples\ System.Globalization\DateTimeFormatInfo\GetEraName(System.Int32)\DateTimeFormatInf o.cs:line 15
A B C D E F G
DateTimeFormatInfo.GetFormat(System.Type) Method
H
[ILASM] .method public final hidebysig virtual object GetFormat(class System.Type formatType) [C#] public object GetFormat(Type formatType)
I J K L
Summary
M
Returns an object of the specified type that provides System.DateTime formatting services.
N
Parameters
O P
Parameter
Description
formatType
The System.Type of the formatting object to be returned.
Q R S
Return Value
T
A formatting object of the specified System.Type. If no formatting object of the specified type is available, or formatType is a null reference, returns the formatting object for the current culture.
U V W
Description
X
[Note: This method is implemented to support the System.IFormatProvider interface.]
Y Z
1148
Contents | Index
System.Globalization
DateTimeFormatInfo GetInstance() Method
Example using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoGetFormat { public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo f = new DateTimeFormatInfo(); IFormatProvider i = (IFormatProvider) f.GetFormat(typeof(DateTimeFormatInfo)); Console.WriteLine(i); } } }
A B C D E F G H I J
The output is
K
System.Globalization.DateTimeFormatInfo
L M
DateTimeFormatInfo.GetInstance(System.IFormatProvider) Method
N
[ILASM] .method public hidebysig static class System.Globalization.DateTimeFormatInfo GetInstance(class System.IFormatProvider provider) [C#] public static DateTimeFormatInfo GetInstance(IFormatProvider provider)
O P Q R
Summary
S
Returns the System.Globalization.DateTimeFormatInfo associated with the specified System.IFormatProvider.
T U
Parameters
V
Parameter
Description
provider
The System.IFormatProvider that gets the System.Globalization.DateTimeFormatInfo. -ornull to get System.Globalization.DateTimeFormatInfo.CurrentInfo.
W X Y Z
1149
Contents | Index
DateTimeFormatInfo
System.Globalization
GetMonthName() Method
Description This method uses the System.IFormatProvider.GetFormat method of provider using System.Globalization.DateTimeFormatInfo as the Type parameter. If provider is null or if System.IFormatProvider.GetFormat returns null, this method returns System.Globalization.DateTimeFormatInfo.CurrentInfo. You can get a System.Globalization.DateTimeFormatInfo for a specific culture using one of the following methods:
A B C D
•
E F
•
G H
Through the System.Globalization.CultureInfo.DateTimeFormat property. Through the System.Globalization.DateTimeFormatInfo.GetInstance method where provider is a System.Globalization.CultureInfo.
A System.Globalization.DateTimeFormatInfo can be created only for the invariant culture or for specific cultures, not for neutral cultures. For more information about the invariant culture, specific cultures, and neutral cultures, see the System.Globalization.CultureInfo class.
I J K L
DateTimeFormatInfo.GetMonthName(System.Int32) Method
M
[ILASM] .method public hidebysig instance string GetMonthName(int32 month) [C#] public string GetMonthName(int month)
N O P Q
Summary
R
Gets the full name of the specified month based on the culture of the current thread.
S
Parameters
T U
Parameter
Description
month
A System.Int32 from 1 through 13 representing the month name to retrieve.
V W X
Return Value
Y
A System.String containing the full name of the month represented by month. For cultures with 12-month calendars the empty string is returned as the name of the 13th month.
Z
1150
Contents | Index
System.Globalization
DateTimeFormatInfo GetMonthName() Method
Description For the default (culture invariant) System.Globalization.DateTimeFormatInfo instance, this method returns one of the following strings: A B
Return Value
Return Value
C D
1
"January"
8
"August"
2
"February"
9
"September"
3
"March"
10
"October"
4
"April"
11
"November"
H
5
"May"
12
"December"
I
6
"June"
13
""
7
"July"
E F G
J K L M
[Note: This method supports calendars with 13 months.]
N O
Exceptions
P
Exception
Condition
Q
System.ArgumentOutOfRangeException
month is less than 1 or greater than 13.
R S T
Example
U
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoGetMonthName { public static void Main() { DateTimeFormatInfo f = new DateTimeFormatInfo(); for(int i = 1; i <= 13; i++) Console.WriteLine(
V W X Y Z
1151
Contents | Index
DateTimeFormatInfo
System.Globalization
ReadOnly() Method
f.GetMonthName(i)); } } }
A
The output is
B C
January February March April May June July August September October November December
D E F G H I J K
DateTimeFormatInfo.ReadOnly(System.Globalization.DateTimeFormatInfo) Method
L M
[ILASM] .method public hidebysig static class System.Globalization.DateTimeFormatInfo ReadOnly(class System.Globalization.DateTimeFormatInfo dtfi) [C#] public static DateTimeFormatInfo ReadOnly(DateTimeFormatInfo dtfi)
N O P Q
Summary
R
Returns a read-only copy of the specified instance of System.Globalization.DateTimeFormatInfo.
S T
Parameters
U V
Parameter
Description
dtfi
The System.Globalization.DateTimeFormatInfo to copy.
W X Y
Description
Z
[Note: Use a read-only System.Globalization.DateTimeFormatInfo copy to prevent modifications to the specified instance.]
1152
Contents | Index
System.Globalization
DateTimeFormatInfo ReadOnly() Method
Exceptions Exception
Condition
System.ArgumentNullException
dtfi is a null reference.
A B C
Example
D
using System; using System.Globalization; namespace Samples { public class DateTimeFormatInfoReadOnly { public static void Main() { DateTime d = DateTime.Now; DateTimeFormatInfo i1 = new DateTimeFormatInfo(); DateTimeFormatInfo i2 = DateTimeFormatInfo.ReadOnly(i1); Console.WriteLine(i1.DateSeparator); i1.DateSeparator = "-"; Console.WriteLine(i2.DateSeparator); Console.WriteLine(d.ToString(i2)); try { i2.DateSeparator = ":"; } catch(InvalidOperationException e) { Console.WriteLine("Exception: {0}", e); } } } }
E F G H I J K L M N O P Q R S T U
The output is
V / / 06/10/2003 13:09:45 Exception: System.InvalidOperationException: Instance is read-only. at System.Globalization.DateTimeFormatInfo.set_DateSeparator(String value) at Samples.DateTimeFormatInfoReadOnly.Main() in C:\Books\BCL\Samples\ System.Globalization\DateTimeFormatInfo\ReadOnly(System.Globalization.DateTimeForm atInfo)\DateTimeFormatInfo.cs:line 19 .
W X Y Z
1153
Contents | Index
System.Globalization DateTimeStyles Enum
BCL
Object
A
IComparable
ValueType
B
Enum
IFormattable DateTimeStyles
C
IConvertible
NotStandardized
D
Summary
E
Defines the formatting options that customize how the System.DateTime.Parse and System.DateTime.ParseExact methods parse a string.
F G
Type Summary
H
public enum DateTimeStyles { AdjustToUniversal = 0x10, AllowInnerWhite = 0x4, AllowLeadingWhite = 0x1, AllowTrailingWhite = 0x2, AllowWhiteSpaces = AllowLeadingWhite | AllowTrailingWhite | AllowInnerWhite, NoCurrentDateDefault = 0x8, None = 0x0, }
I J K L M N O
Description
P
[Note: See the System.String class for the list of white space characters. Only the System.Globalization.DateTimeStyles.NoCurrentDateDefault option affects the System.DateTime.Parse method. System.DateTime.Parse always ignores leading, inner, and trailing white spaces.]
Q R S
Example
T
using System; using System.Globalization; namespace Samples { public class DateTimeStylesSample { public static void Main() { IFormatProvider f = new CultureInfo("en-AU", true); string s = String.Format("\t {0} ", DateTime.Now.ToString(f)); DateTime d = DateTime.Parse(s, f,
U V W X Y Z
1154
Contents | Index
System.Globalization
DateTimeStyles Enum AdjustToUniversal Field
DateTimeStyles.AllowWhiteSpaces); Console.WriteLine("String: {0} yields date {1}", s, d); d = DateTime.Parse(s, f, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowInnerWhite | DateTimeStyles.AllowTrailingWhite); Console.WriteLine("String: {0} yields date {1}", s, d); s = String.Format(" {0} \t", DateTime.Now.ToString("T", f)); d = DateTime.Parse(s, f, DateTimeStyles.NoCurrentDateDefault); Console.WriteLine("String: {0} yields date {1}", s, d);
A B C D E F
} }
G
}
H
The output is String: String: String:
10/06/2003 1:30:25 PM 10/06/2003 1:30:25 PM 1:30:25 PM
I yields date 10/06/2003 1:30:25 PM yields date 10/06/2003 1:30:25 PM yields date 1/01/0001 1:30:25 PM
J K L M
DateTimeStyles.AdjustToUniversal Field
N
[ILASM] .field public static literal valuetype System.Globalization.DateTimeStyles AdjustToUniversal [C#] AdjustToUniversal = 0x10
O P Q
Summary
R
Specifies that the date and time must be converted to universal time coordinate time or Greenwich mean time (GMT).
S T U
Example
V
using System; using System.Globalization; namespace Samples { public class DateTimeStylesAdjustToUniversal { public static void Main() { IFormatProvider f = new CultureInfo("en-AU", true); string s = DateTime.Now.ToString(
W X Y Z
1155
Contents | Index
DateTimeStyles Enum
System.Globalization
AllowInnerWhite Field
"dd/MM/yyyy hh:mmzzz", f); DateTime d = DateTime.Parse(s, f, DateTimeStyles.AdjustToUniversal); Console.WriteLine("String: {0} yields date {1}", s, d);
A }
B }
C
}
D
The output is
E String: 10/06/2003 01:32+10:00 yields date 9/06/2003 3:32:00 PM
F G
DateTimeStyles.AllowInnerWhite Field
H I
[ILASM] .field public static literal valuetype System.Globalization.DateTimeStyles AllowInnerWhite [C#] AllowInnerWhite = 0x4
J K L M
Summary
N
Specifies that extra white space characters not specified in the System.Globalization.DateTimeFormatInfo format patterns are allowed.
O P
Example
Q
using System; using System.Globalization; namespace Samples { public class DateTimeStylesAllowInnerWhite { public static void Main() { IFormatProvider f = new CultureInfo("en-AU", true); string s = DateTime.Now.ToString( "dd/MM/ yyyy \t hh:mm", f); DateTime d = DateTime.Parse(s, f, DateTimeStyles.AllowInnerWhite); Console.WriteLine("String: {0} yields date {1}", s, d); } } }
R S T U V W X Y Z
1156
Contents | Index
System.Globalization
DateTimeStyles Enum AllowLeadingWhite Field
The output is String: 10/06/
2003
01:33 yields date 10/06/2003 1:33:00 AM
A B
DateTimeStyles.AllowLeadingWhite Field
C [ILASM] .field public static literal valuetype System.Globalization.DateTimeStyles AllowLeadingWhite [C#] AllowLeadingWhite = 0x1
D E F G
Summary
H
Specifies that leading white space characters are allowed.
I
Example
J
using System; using System.Globalization; namespace Samples { public class DateTimeStylesAllowLeadingWhite { public static void Main() { IFormatProvider f = new CultureInfo("en-AU", true); string s = DateTime.Now.ToString( "\t\n dd/MM/yyyy hh:mm", f); DateTime d = DateTime.Parse(s, f, DateTimeStyles.AllowLeadingWhite); Console.WriteLine("String: {0} yields date {1}", s, d); } } }
K L M N O P Q R S T U V
The output is
W String: 10/06/2003 01:36 yields date 10/06/2003 1:36:00 AM
X Y Z
1157
Contents | Index
DateTimeStyles Enum
System.Globalization
AllowTrailingWhite Field
DateTimeStyles.AllowTrailingWhite Field [ILASM] .field public static literal valuetype System.Globalization.DateTimeStyles AllowTrailingWhite [C#] AllowTrailingWhite = 0x2
A B C D
Summary
E
Specifies that trailing white space characters are allowed.
F
Example
G
using System; using System.Globalization; namespace Samples { public class DateTimeStylesAllowTrailingWhite { public static void Main() { IFormatProvider f = new CultureInfo("en-AU", true); string s = DateTime.Now.ToString( "dd/MM/yyyy hh:mm\t\n ", f); DateTime d = DateTime.Parse(s, f, DateTimeStyles.AllowTrailingWhite); Console.WriteLine("String: {0} yields date {1}", s, d); } } }
H I J K L M N O P Q R
The output is
S T
String: 10/06/2003 01:37 yields date 10/06/2003 1:37:00 AM
U V W
DateTimeStyles.AllowWhiteSpaces Field
X
[ILASM] .field public static literal valuetype System.Globalization.DateTimeStyles AllowWhiteSpaces [C#] AllowWhiteSpaces = AllowLeadingWhite | AllowTrailingWhite | AllowInnerWhite
Y Z
1158
Contents | Index
System.Globalization
DateTimeStyles Enum NoCurrentDateDefault Field
Summary Specifies that white space characters anywhere in the string are allowed. A
Example
B
using System; using System.Globalization; namespace Samples { public class DateTimeStylesAllowWhiteSpaces { public static void Main() { IFormatProvider f = new CultureInfo("en-AU", true); string s = DateTime.Now.ToString( "\t dd/MM/yyyy \t hh:mm\t ", f); DateTime d = DateTime.Parse(s, f, DateTimeStyles.AllowWhiteSpaces); Console.WriteLine("String: {0} yields date {1}", s, d); } } }
C D E F G H I J K L M
The output is String:
10/06/2003
N 01:42
O
yields date 10/06/2003 1:42:00 AM
P Q
DateTimeStyles.NoCurrentDateDefault Field
R
[ILASM] .field public static literal valuetype System.Globalization.DateTimeStyles NoCurrentDateDefault [C#] NoCurrentDateDefault = 0x8
S T U V
Summary
W
Specifies that there is no current date default. If a string contains only the time and not the date, and this option is used with the System.DateTime.Parse or System.DateTime.ParseExact methods, a Gregorian year 1, month 1, day 1 date is assumed. In all other cases the methods assume the current local system date.
X Y Z
1159
Contents | Index
DateTimeStyles Enum
System.Globalization
None Field
Example using System; using System.Globalization; namespace Samples { public class DateTimeStylesNoCurrentDateDefault { public static void Main() { IFormatProvider f = new CultureInfo("en-AU", true); string s = String.Format("{0}", DateTime.Now.ToString("T", f)); DateTime d = DateTime.Parse(s, f, DateTimeStyles.NoCurrentDateDefault); Console.WriteLine("String: {0} yields date {1}", s, d); } } }
A B C D E F G H I J
The output is
K L
String: 1:44:05 PM yields date 1/01/0001 1:44:05 PM
M N
DateTimeStyles.None Field
O
[ILASM] .field public static literal valuetype System.Globalization.DateTimeStyles None [C#] None = 0x0
P Q R
Summary
S
Specifies that the default formatting options are to be used.
T U
Example
V
using System; using System.Globalization; namespace Samples { public class DateTimeStylesNone { public static void Main() { IFormatProvider f = new CultureInfo("en-AU", true); string s = String.Format("\t{0} \n",
W X Y Z
1160
Contents | Index
System.Globalization
DateTimeStyles Enum None Field
DateTime.Now.ToString("T", f)); DateTime d = DateTime.Parse(s, f, DateTimeStyles.None); Console.WriteLine("String: {0} yields date {1}", s, d);
A
} }
B
}
C
The output is
D E
String: 1:44:56 PM yields date 10/06/2003 1:44:56 PM
F G H I J K L M N O P Q R S T U V W X Y Z
1161
Contents | Index
System Decimal Structure
Extended Numerics
Object
A
IFormattable
ValueType
B
Decimal
ExtendedNumerics
C
IComparable IConvertible
NotStandardized
D
Summary
E
Represents a floating-point decimal data type with up to 29 significant digits, suitable for financial and commercial calculations.
F G
Type Summary
H
public struct Decimal : IFormattable, IComparable, IConvertible { // Constructors public Decimal (double value); public Decimal (float value); public Decimal (int value); MS public Decimal (int lo, int mid, int hi, bool isNegative, byte scale); public Decimal (int[] bits); public Decimal (long value); public Decimal (uint value); public Decimal (ulong value);
I J K L M N O P
// Fields public static readonly decimal MaxValue = 79228162514264337593543950335; public static readonly decimal MinusOne = -1; public static readonly decimal MinValue = -79228162514264337593543950335; public static readonly decimal One = 1; public static readonly decimal Zero = 0;
Q R S T U V
// Methods public static decimal Add (decimal d1, decimal d2); public static int Compare (decimal d1, decimal d2); public int CompareTo (object value); public static decimal Divide (decimal d1, decimal d2); public static bool Equals (decimal d1, decimal d2); public override bool Equals (object value); public static decimal Floor (decimal d); MS CF public static decimal FromOACurrency (long cy);
W X Y Z
1162
Contents | Index
System
Decimal Structure Decimal Structure
public public MS public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public public
static int[] GetBits (decimal d); override int GetHashCode (); TypeCode GetTypeCode (); static decimal Multiply (decimal d1, decimal d2); static decimal Negate (decimal d); static decimal operator +(decimal d1, decimal d2); static decimal operator --(decimal d); static decimal operator /(decimal d1, decimal d2); static bool operator ==(decimal d1, decimal d2); static explicit operator byte(decimal value); static explicit operator char(decimal value); static explicit operator decimal (double value); static explicit operator decimal (float value); static explicit operator double (decimal value); static explicit operator float(decimal value); static explicit operator int(decimal value); static explicit operator long(decimal value); static explicit operator sbyte(decimal value); static explicit operator short(decimal value); static explicit operator uint(decimal value); static explicit operator ulong(decimal value); static explicit operator ushort(decimal value); static bool operator >(decimal d1, decimal d2); static bool operator >=(decimal d1, decimal d2); static implicit operator decimal (byte value); static implicit operator decimal (char value); static implicit operator decimal (int value); static implicit operator decimal (long value); static implicit operator decimal (sbyte value); static implicit operator decimal (short value); static implicit operator decimal (uint value); static implicit operator decimal (ulong value); static implicit operator decimal (ushort value); static decimal operator ++(decimal d); static bool operator !=(decimal d1, decimal d2); static bool operator <(decimal d1, decimal d2); static bool operator <=(decimal d1, decimal d2); static decimal operator %(decimal d1, decimal d2); static decimal operator *(decimal d1, decimal d2);
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1163
Contents | Index
Decimal Structure
System
Decimal Structure
A B C D E F G MS MS MS MS MS MS CF MS MS
H I J K L M N
MS MS MS
O P
public static decimal operator -(decimal d1, decimal d2); public static decimal operator -(decimal d); public static decimal operator +(decimal d); public static decimal Parse (string s); public static decimal Parse (string s, NumberStyles style); public static decimal Parse (string s, NumberStyles style, IFormatProvider provider); public static decimal Parse (string s, IFormatProvider provider); public static decimal Remainder (decimal d1, decimal d2); public static decimal Round (decimal d, int decimals); public static decimal Subtract (decimal d1, decimal d2); public static byte ToByte (decimal value); public static double ToDouble (decimal d); public static short ToInt16(decimal value); public static int ToInt32(decimal d); public static long ToInt64(decimal d); public static long ToOACurrency (decimal value); public static sbyte ToSByte (decimal value); public static float ToSingle (decimal d); public override string ToString (); public string ToString (string format); public string ToString (string format, IFormatProvider provider); public string ToString (IFormatProvider provider); public static ushort ToUInt16(decimal value); public static uint ToUInt32(decimal d); public static ulong ToUInt64(decimal d); public static decimal Truncate (decimal d);
Q // MS MS MS MS MS MS MS MS MS MS MS MS MS MS MS
R S T U V W X Y Z
Explicit Interface Members bool IConvertible.ToBoolean(IFormatProvider provider); byte IConvertible.ToByte(IFormatProvider provider); char IConvertible.ToChar(IFormatProvider provider); DateTime IConvertible.ToDateTime(IFormatProvider provider); decimal IConvertible.ToDecimal(IFormatProvider provider); double IConvertible.ToDouble(IFormatProvider provider); short IConvertible.ToInt16(IFormatProvider provider); int IConvertible.ToInt32(IFormatProvider provider); long IConvertible.ToInt64(IFormatProvider provider); sbyte IConvertible.ToSByte(IFormatProvider provider); float IConvertible.ToSingle(IFormatProvider provider); object IConvertible.ToType(Type type,IFormatProvider provider); ushort IConvertible.ToUInt16(IFormatProvider provider); uint IConvertible.ToUInt32(IFormatProvider provider); ulong IConvertible.ToUInt64(IFormatProvider provider);
}
1164
Contents | Index
System
Decimal Structure Decimal Structure
BA This is another good example of use of operator overloading. Clearly Decimal is a built-in type and it should behave that way. All the operators do exactly what you would expect. See DateTime for more notes on operator overloading.
A B
Throughout the standardization process we were very fortunate to have the input of experts in their field. In the case of this decimal we benefited from having the world’s leading expert assist us. Mike Cowlishaw, an IBM Fellow, has devoted much of his career to the study and implementation of Decimal on a wide range of systems. Although the debates around the changes to Decimal were at times heated, his input caused us to produce a better standard and better product. See more information on Mike’s work with Decimal at http://www2.hursley.ibm.com/decimal.
C D E F G
JM Wow! Decimal sure drummed up some discussion and controversy. A codebreaking change in a certain implementation of the CLI was even made where the ToString method behavior was changed to preserve the scale, which is the right thing to do. This even had cross-task-group ramifications as the change affected the C# folks. Just goes to show that standardization can be exciting!
H
KG Decimal used to truncate trailing zeroes but the ECMA standardization pro-
L
cess required that trailing zeroes be preserved on Decimal operations. So in version 1.1, we changed Decimal to preserve trailing zeroes. This has interesting serialization consequences for some scenarios (such as storing numeric information in a database), but the new behavior is far more appropriate for general situations.
M
I J K
N O P
BG Our original design for Decimal came straight from OLE Automation’s
Q
Decimal type. About the only thing that changed was the behavior of ToString in some cases. In fact, the types have the same memory layout, which is convenient for COM Interop.
R S
JR Decimal is a very interesting class. It is considered a primitive type by the C#
T
compiler but it is not considered a primitive type by the CLI. This is why Decimal provides methods to add, subtract, multiple, and divide values. Notice that these methods do not exist for the other numeric types, such as Int32. So, when compiling code that adds two Decimal values together, the C# compiler emits code to call the overloaded operator methods but, when compiling code that adds two Int32 values together, the C# compiler emits code that knows how to add two Int32 values together—no method call is performed. Another side effect of this is that C#’s checked and unchecked code feature has no effect on Decimal values—operations on Decimal values are always checked.
U V W X Y Z
1165
Contents | Index
Decimal Structure
System
Decimal Structure
Description The System.Decimal type can represent values from approximately –7.9 × 1028 to 7.9 × 1028, with 28 or 29 significant digits. The System.Decimal data type is ideally suited to financial calculations that require a large number of significant digits and no round-off errors. The finite set of values of type decimal are of the form –1s × c × 10-f, where the sign s is 0 or 1, the coefficient c is given by 0 <= c < 296, and the scale f is such that 0 <= f <= 28. A System.Decimal is represented as a 96-bit integer scaled by a power of ten. For a System.Decimal with an absolute value less than 1.0, the value is exact to the 28th decimal place, but no further. For a System.Decimal with an absolute value greater than or equal to 1.0, the value is exact to 28 or 29 digits. The result of an operation on values of type System.Decimal is that which would result from calculating an exact result (preserving scale, as defined for each operator) and then rounding to fit the representation. That is, results are exact to 28 or 29 digits, but to no more than 28 decimal places. A zero result has a sign of 0 and a scale of 0. Results are rounded to the nearest representable value, and, when a result is equally close to two representable values, to the value that has an even number in the least significant digit position (banker’s rounding). [Note: Unlike the System.Single and System.Double data types, decimal fractional numbers such as 0.1 can be represented exactly in the System.Decimal representation. In the System.Single and System.Double representations, such numbers are often infinite fractions, making those representations prone to round-off errors. Further, the System.Decimal representation preserves scale, so that 1.23 + 1.27 will give the answer 2.50, not 2.5.] If a System.Decimal arithmetic operation produces a value that is too small for the System.Decimal format after rounding, the result of the operation is zero. If a System.Decimal arithmetic operation produces a result that is too large for the System.Decimal format, a System.OverflowException is thrown. [Note: The System.Decimal class implements implicit conversions from the System.SByte, System.Byte, System.Int16, System.UInt16, System.Int32, System.UInt32, System.Int64, and System.UInt64 types to System.Decimal. These implicit conversions never lose information and never throw exceptions. The System.Decimal class also implements explicit conversions from System.Decimal to System.Byte, System.SByte, System.Int16, System.UInt16, System.Int32, System.UInt32, System.Int64, and System.UInt64. These explicit conversions round the System.Decimal value towards zero to the nearest integer, and then convert that integer to the destination type. A System.OverflowException is thrown if the result is not within the range of the destination type. The System.Decimal class provides narrowing conversions to and from the System.Single and System.Double types. A conversion from System.Decimal to System.Single or System.Double may lose precision, but will not lose information about the overall magnitude of the numeric value, and will never throw an exception. A conversion from System.Single or System.Double to System.Decimal
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1166
Contents | Index
System
Decimal Structure Decimal Structure
throws a System.OverflowException if the value is not within the range of the System.Decimal type.]
Example
A
using System;
B C
namespace Samples { public class DecimalSample { public static void Main() { Decimal max = Decimal.MaxValue, min = Decimal.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); Console.WriteLine("Is {0} equal to {1}: {2}", max, max, max.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", max, min, max.Equals(min)); Console.WriteLine("{0} has hashcode of: {1}", max, max.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", min, min.GetHashCode()); string s = max.ToString(); Console.WriteLine("\"{0}\" parsed from string yields: {1}", s, Decimal.Parse(s)); s = min.ToString(); Console.WriteLine("\"{0}\" parsed from string yields: {1}", s, Decimal.Parse(s)); string[] formats = {"C","E","F","G","N","P"}; foreach(string f in formats) Console.WriteLine("Format {0}: {1}", f, max.ToString(f)); } } }
D E F G H I J K L M N O P Q R S T U V
The output is
W MaxValue: 79228162514264337593543950335 MinValue: -79228162514264337593543950335 Is 79228162514264337593543950335 equal to 79228162514264337593543950335: True Is 79228162514264337593543950335 equal to -79228162514264337593543950335: False 79228162514264337593543950335 has hashcode of: 1173356544 -79228162514264337593543950335 has hashcode of: -974127104 "79228162514264337593543950335" parsed from string yields: 79228162514264337593543950335
X Y Z
1167
Contents | Index
Decimal Structure
System
Decimal() Constructor
"-79228162514264337593543950335" parsed from string yields: -79228162514264337593543950335 Format C: $79,228,162,514,264,337,593,543,950,335.00 Format E: 7.922816E+028 Format F: 79228162514264337593543950335.00 Format G: 79228162514264337593543950335 Format N: 79,228,162,514,264,337,593,543,950,335.00 Format P: 7,922,816,251,426,433,759,354,395,033,500.00 %
A B C D E
Decimal(System.Double) Constructor
F [ILASM]
G
public rtspecialname specialname instance void .ctor(float64 value) [C#]
H
public Decimal(double value)
I
Summary
J
Constructs and initializes a new System.Decimal value.
K L
Parameters
M N O
Parameter
Description
value
The System.Double value used to initialize the new System.Decimal.
P Q
Description
R
This constructor initializes the new System.Decimal to the value specified by value. This constructor rounds value to 15 significant digits using banker’s rounding.
S T
Exceptions
U
Exception
V
Condition
W
value is one of the following:
X
greater than System.Decimal.MaxValue less than System.Decimal.MinValue
Y
System.OverflowException
Z
equal to System.Double.NaN equal to System.Double.PositiveInfinity equal to System.Double.NegativeInfinity
1168
Contents | Index
System
Decimal Structure Decimal() Constructor
Example using System; namespace Samples { public class DecimalConstructor { public static void Main() { try { Decimal d = new Decimal(42d); Console.WriteLine("d is: {0}", d); d = new Decimal(double.MaxValue); Console.WriteLine("d is: {0}", d); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M
The output is
N O
d is: 42 Exception: System.OverflowException: Value was either too large or too small for a Decimal. at System.Decimal..ctor(Double value) at Samples.DecimalConstructor.Main() in C:\Books\BCL\Samples\System\Decimal\ Decimal(System.Double)\Decimal.cs:line 13
P Q R S T
Decimal(System.Single) Constructor
U [ILASM]
V
public rtspecialname specialname instance void .ctor(float32 value) [C#]
W
public Decimal(float value)
X
Summary
Y
Constructs and initializes a new System.Decimal value.
Z
1169
Contents | Index
Decimal Structure
System
Decimal() Constructor
Parameters Parameter
Description
value
The System.Single value used to initialize the new System.Decimal.
A B C D
Description
E
This constructor initializes the new System.Decimal to the value specified by value. This constructor rounds value to 7 significant digits using banker’s rounding.
F G
Exceptions
H
Exception
I
Condition
J
value is one of the following:
K
greater than System.Decimal.MaxValue less than System.Decimal.MinValue
L
System.OverflowException
M
equal to System.Single.NaN equal to System.Single.PositiveInfinity
N
equal to System.Single.NegativeInfinity
O P
Example
Q
using System;
R
namespace Samples { public class DecimalConstructor { public static void Main() { try { Decimal d = new Decimal(42f); Console.WriteLine("d is: {0}", d); d = new Decimal(float.MaxValue); Console.WriteLine("d is: {0}", d); } catch(OverflowException e) {
S T U V W X Y Z
1170
Contents | Index
System
Decimal Structure Decimal() Constructor
Console.WriteLine("Exception: {0}", e); } } }
A
}
B
The output is
C
d is: 42 Exception: System.OverflowException: Value was either too large or too small for a Decimal. at System.Decimal..ctor(Single value) at Samples.DecimalConstructor.Main() in C:\Books\BCL\Samples\System\Decimal\ Decimal(System.Single)\Decimal.cs:line 13
D E F G H
Decimal(System.Int32) Constructor
I
[ILASM]
J
public rtspecialname specialname instance void .ctor(int32 value)
K
[C#]
public Decimal(int value)
L M
Summary
N
Constructs and initializes a new System.Decimal value.
O
Parameters
P
Parameter
Description
value
The System.Int32 value used to initialize the new System.Decimal.
Q R S T
Description
U
This constructor initializes the new System.Decimal to the value specified by value.
V
Example
W
using System;
X Y
namespace Samples { public class DecimalConstructor { public static void Main()
Z
1171
Contents | Index
Decimal Structure
System
Decimal() Constructor
{ Decimal d = new Decimal(42); Console.WriteLine("d is: {0}", d); }
A
} }
B C
The output is
D d is: 42
E F
Decimal(System.Int32, System.Int32, System.Int32, System.Boolean, System.Byte) Constructor
G H
[ILASM]
I
public rtspecialname specialname instance void .ctor(int32 lo, int32 mid, int32 hi, bool isNegative, unsigned int8 scale)
J
[C#]
K
public Decimal(int lo, int mid, int hi, bool isNegative, byte scale)
L
Summary
M
Initializes a new instance of System.Decimal from parameters specifying the instance’s constituent parts.
N O
Parameters
P Q
Parameter
Description
lo
The low 32 bits of a 96-bit integer.
T
mid
The middle 32 bits of a 96-bit integer.
U
hi
The high 32 bits of a 96-bit integer.
isNegative
The sign of the number; 1 is negative, 0 is positive.
scale
A power of 10 ranging from 0 to 28.
R S
V W X Y
Description
Z
The binary representation of a System.Decimal number consists of a 1-bit sign, a 96-bit integer number, and a scaling factor used to divide the integer number and specify what
1172
Contents | Index
System
Decimal Structure Decimal() Constructor
portion of it is a decimal fraction. The scaling factor is implicitly the number 10 raised to an exponent ranging from 0 to 28. A
Exceptions
B
Exception
Condition
System.ArgumentOutOfRangeException
scale is greater than 28.
C D E F
Decimal(System.Int32[]) Constructor
G
[ILASM]
H
public rtspecialname specialname instance void .ctor(class System.Int32[] bits)
I
[C#]
public Decimal(int[] bits)
J K
Summary
L
Constructs and initializes a new System.Decimal value.
M
Parameters Parameter
N O
Description
P
bits
A System.Int32 array containing a bit representation of a System.Decimal. bits contains the following four elements:
Q
Index 0 (bits 0–31) contains the low-order 32 bits of the decimal’s coefficient.
R
Index 1 (bits 32–63) contains the middle 32 bits of the decimal’s coefficient.
S
Index 2 (bits 64–95) contains the high-order 32 bits of the decimal’s coefficient.
T
Index 3 (bits 96–127) contains the sign bit and scale. See below.
U V
Description
W
This constructor initializes the new System.Decimal to the value represented by the elements of bits. [Note: The elements of bits represent a System.Decimal as a coefficient c, a scale f, and sign bit s. The decimal value is computed as –1s × c × 10–f. The coefficient c is divided into three 32-bit integer values.] The sign and scale occupy a total of 32 bits as follows:
X Y Z
1173
Contents | Index
Decimal Structure
System
Decimal() Constructor
Bit Positions
Name
Description
A
0–15
(None)
Zero.
B
16–23
Scale
Contains a value between 0 and 28.
C
24–30
(None)
Zero.
D
31
Sign
0 (positive) or 1 (negative).
E F
[Note: A numeric value may have several possible binary representations; they are numerically equal but have different scales. Also, the bit representation differentiates between –0, 0.00, and 0; these are all treated as 0 in operations, and any zero result will have a sign of 0 and a scale of 0.]
G H I
Exceptions
J K
Exception
Condition
System.ArgumentNullException
bits is a null reference.
System.ArgumentException
bits does not contain four elements.
L M N O
Example
P
using System;
Q
namespace Samples { public class DecimalConstructor { public static void Main() { int negativeBit = unchecked((int)0x80000000); decimal d = new Decimal(new int[]{-1, -1, -1, 0}); Console.WriteLine("{{-1, -1, -1, 0}}: {0}",d); Console.WriteLine("MaxValue is: {0}", Decimal.MaxValue); d = new Decimal(new int[]{-1, -1, -1, negativeBit}); Console.WriteLine("{{-1, -1, -1, negativeBit}}: {0}",d); Console.WriteLine("MinValue is: {0}", Decimal.MinValue); d = new Decimal(new int[]{0, 0, 0, 0}); Console.WriteLine("{{0, 0, 0, 0}} = {0}",d);
R S T U V W X Y Z
1174
Contents | Index
System
Decimal Structure Decimal() Constructor
d = new Decimal(new int[]{1, 0, 0, 0}); Console.WriteLine("{{1, 0, 0, 0}} = {0}",d); d = new Decimal(new int[]{0, 1, 0, 0}); Console.WriteLine("{{0, 1, 0, 0}} = {0}",d); d = new Decimal(new int[]{0, 0, 1, 0}); Console.WriteLine("{{0, 0, 1, 0}} = {0}",d); d = new Decimal(new int[]{42, 0, 0, negativeBit}); Console.WriteLine("{{42, 0, 0, negativeBit}} = {0}",d);
A B C
}
D
} }
E F
The output is
G {-1, -1, -1, 0}: 79228162514264337593543950335 MaxValue is: 79228162514264337593543950335 {-1, -1, -1, negativeBit}: -79228162514264337593543950335 MinValue is: -79228162514264337593543950335 {0, 0, 0, 0} = 0 {1, 0, 0, 0} = 1 {0, 1, 0, 0} = 4294967296 {0, 0, 1, 0} = 18446744073709551616 {42, 0, 0, negativeBit} = -42
H I J K L M N
Decimal(System.Int64) Constructor
O
[ILASM]
P
public rtspecialname specialname instance void .ctor(int64 value)
Q
[C#]
public Decimal(long value)
R
Summary
S
Constructs and initializes a new System.Decimal value.
T U
Parameters
V
Parameter
Description
value
The System.Int64 value used to initialize the new System.Decimal.
W X Y Z
Description This constructor initializes the new System.Decimal to the value specified by value. 1175
Contents | Index
Decimal Structure
System
Decimal() Constructor
Example using System; namespace Samples { public class DecimalConstructor { public static void Main() { Decimal d = new Decimal(long.MaxValue); Console.WriteLine("d is: {0}", d); } } }
A B C D E F G H
The output is
I d is: 9223372036854775807
J K L
Decimal(System.UInt32) Constructor
M
[ILASM]
public rtspecialname specialname instance void .ctor(unsigned int32 value)
N
[C#]
public Decimal(uint value)
O P
Summary
Q
Constructs and initializes a new System.Decimal value.
R
Parameters
S T
Parameter
Description
value
The System.UInt32 value used to initialize the new System.Decimal.
U V W
Description
X
This member is not CLS-compliant. For a CLS-compliant alternative, use the System.Decimal(System.Int64) constructor. This constructor initializes the new System.Decimal to the value specified by value.
Y Z
1176
Contents | Index
System
Decimal Structure Decimal() Constructor
Example using System; namespace Samples { public class DecimalConstructor { public static void Main() { Decimal d = new Decimal(uint.MaxValue); Console.WriteLine("d is: {0}", d); } } }
A B C D E F G H
The output is
I d is: 4294967295
J K
Decimal(System.UInt64) Constructor
L
[ILASM]
M
public rtspecialname specialname instance void .ctor(unsigned int64 value)
N
[C#]
public Decimal(ulong value)
O
Summary
P
Constructs and initializes a new System.Decimal value.
Q R
Parameters
S
Parameter
Description
value
The System.UInt64 value used to initialize the new System.Decimal.
T U V W
Description
X
This constructor initializes the new System.Decimal to the value specified by value. This member is not CLS-compliant. For a CLS-compliant alternative, use the System.Decimal(System.Int64) constructor.
Y Z
1177
Contents | Index
Decimal Structure
System
MaxValue Field
Example using System; namespace Samples { public class DecimalConstructor { public static void Main() { Decimal d = new Decimal(ulong.MaxValue); Console.WriteLine("d is: {0}", d); } } }
A B C D E F G H
The output is
I d is: 18446744073709551615
J K L
Decimal.MaxValue Field
M
[ILASM]
.field public static initOnly decimal MaxValue
N
[C#]
public static readonly decimal MaxValue = 79228162514264337593543950335
O P
Summary
Q
Contains the maximum positive value for the System.Decimal type.
R
Description
S
The value of this constant is 79228162514264337593543950335.
T U
Example
V
using System;
W
namespace Samples { public class DecimalMaxValue { public static void Main() { Decimal max = Decimal.MaxValue, one = Decimal.One,
X Y Z
1178
Contents | Index
System
Decimal Structure MinusOne Field
zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("One: {0}", one); Console.WriteLine("Zero: {0}", zero); Console.WriteLine("MinusOne: {0}", minusOne); Console.WriteLine("MinValue: {0}", min);
A B C
}
D
} }
E F
The output is
G MaxValue: 79228162514264337593543950335 One: 1 Zero: 0 MinusOne: -1 MinValue: -79228162514264337593543950335
H I J K
Decimal.MinusOne Field
L
[ILASM]
M
.field public static initOnly decimal MinusOne
N
[C#]
O
public static readonly decimal MinusOne = -1
P
Summary
Q
Contains negative one (–1).
R
Example
S
using System;
T
namespace Samples { public class DecimalMinusOne { public static void Main() { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue;
U V W X Y Z
1179
Contents | Index
Decimal Structure
System
MinValue Field
Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("One: {0}", one); Console.WriteLine("Zero: {0}", zero); Console.WriteLine("MinusOne: {0}", minusOne); Console.WriteLine("MinValue: {0}", min);
A }
B }
C
}
D
The output is
E MaxValue: 79228162514264337593543950335 One: 1 Zero: 0 MinusOne: -1 MinValue: -79228162514264337593543950335
F G H I J
Decimal.MinValue Field
K [ILASM]
L
.field public static initOnly decimal MinValue [C#]
M
public static readonly decimal MinValue = -79228162514264337593543950335
N
Summary
O
Contains the minimum (most negative) value for the System.Decimal type.
P Q
Description
R
The value of this constant is –79228162514264337593543950335.
S
Example
T
using System;
U namespace Samples { public class DecimalMinValue { public static void Main() { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne,
V W X Y Z
1180
Contents | Index
System
Decimal Structure One Field
min = Decimal.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("One: {0}", one); Console.WriteLine("Zero: {0}", zero); Console.WriteLine("MinusOne: {0}", minusOne); Console.WriteLine("MinValue: {0}", min);
A B
}
C
} }
D
The output is
E F
MaxValue: 79228162514264337593543950335 One: 1 Zero: 0 MinusOne: -1 MinValue: -79228162514264337593543950335
G H I J
Decimal.One Field
K
[ILASM]
L
.field public static initOnly decimal One
M
[C#]
public static readonly decimal One = 1
N
Summary
O
Contains one (1).
P Q
Example
R
using System;
S namespace Samples { public class DecimalOne { public static void Main() { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("One: {0}", one); Console.WriteLine("Zero: {0}", zero);
T U V W X Y Z
1181
Contents | Index
Decimal Structure
System
Zero Field
Console.WriteLine("MinusOne: {0}", minusOne); Console.WriteLine("MinValue: {0}", min); } }
A
}
The output is
B
MaxValue: 79228162514264337593543950335 One: 1 Zero: 0 MinusOne: -1 MinValue: -79228162514264337593543950335
C D E F G
Decimal.Zero Field
H
[ILASM]
I
.field public static initOnly decimal Zero [C#]
J
public static readonly decimal Zero = 0
K
Summary
L
Contains zero (0).
M N
Example
O
using System;
P
namespace Samples { public class DecimalZero { public static void Main() { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("One: {0}", one); Console.WriteLine("Zero: {0}", zero); Console.WriteLine("MinusOne: {0}", minusOne); Console.WriteLine("MinValue: {0}", min); } } }
Q R S T U V W X Y Z
1182
Contents | Index
System
Decimal Structure Add() Method
The output is MaxValue: 79228162514264337593543950335 One: 1 Zero: 0 MinusOne: -1 MinValue: -79228162514264337593543950335
A B C D
Decimal.Add(System.Decimal, System.Decimal) Method
E
[ILASM]
F
.method public hidebysig static decimal Add(decimal d1, decimal d2)
G
[C#]
public static decimal Add(decimal d1, decimal d2)
H
Summary
I
Adds two System.Decimal values together.
J K
Parameters
L
Parameter
Description
d1
The first value to add.
d2
The second value to add.
M N O P Q
Return Value
R
A System.Decimal containing the sum of d1 and d2. The scale of the result, before any rounding, is the larger of the scales of d1 and d2. For example, 1.1 + 2.22 gives 3.32, and 2.50 + 1 gives 3.50.
S T U
Exceptions
V W
Exception
Condition X
System.OverflowException
The sum of d1 and d2 is less than System.Decimal.MinValue or greater than System.Decimal.MaxValue.
Y Z
1183
Contents | Index
Decimal Structure
System
Add() Method
Example using System; namespace Samples { public class DecimalAdd { public static void Main() { try { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue; Console.WriteLine("Add({0}, {1}): {2}", max, minusOne, Decimal.Add(max, minusOne)); Console.WriteLine("Add({0}, {1}): {2}", one, zero, Decimal.Add(one, zero)); Console.WriteLine("Add({0}, {1}): {2}", max, min, Decimal.Add(max, min)); Console.WriteLine("Add({0}, {1}): {2}", max, one, Decimal.Add(max, one)); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P Q R S
The output is
T Add(79228162514264337593543950335, -1): 79228162514264337593543950334 Add(1, 0): 1 Add(79228162514264337593543950335, -79228162514264337593543950335): 0 Exception: System.OverflowException: Value was either too large or too small for a Decimal. at System.Decimal.Add(Decimal d1, Decimal d2) at Samples.DecimalAdd.Main() in C:\Books\BCL\Samples\System\Decimal\ Add(System.Decimal,System.Decimal)\Decimal.cs:line 22
U V W X Y Z
1184
Contents | Index
System
Decimal Structure Compare() Method
Decimal.Compare(System.Decimal, System.Decimal) Method [ILASM]
.method public hidebysig static int32 Compare(decimal d1, decimal d2) [C#]
A
public static int Compare(decimal d1, decimal d2)
B
Summary
C
Compares the values of two System.Decimal values and returns sort order information.
D E
Parameters
F G
Parameter
Description
d1
The first value to compare.
d2
The second value to compare.
H I J K
Return Value
L
A System.Int32 containing a value that reflects the sort order of d1 and d2. The exact value returned by this method is implementation defined. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number. Each comparison compares the numerical values of d1 and d2.
M N O P
Return Value
Meaning
Q
any negative number
d1 < d2
R
zero
d1 == d2
any positive number
d1 > d2
S T U V
Example
W
using System;
X namespace Samples { public class DecimalCompare { public static void Main() {
Y Z
1185
Contents | Index
Decimal Structure
System
CompareTo() Method
DoCompare(Decimal.MaxValue, Decimal.MaxValue); DoCompare(Decimal.One, Decimal.Zero); DoCompare(Decimal.Zero, Decimal.MinusOne); DoCompare(Decimal.MinValue, Decimal.MinusOne);
A
} private static void DoCompare(Decimal d1, Decimal d2) { int compare = Decimal.Compare(d1, d2); if(compare == 0) Console.WriteLine("{0} is equal to {1}", d1, d2); else if(compare < 0) Console.WriteLine("{0} is less than {1}", d1, d2); else Console.WriteLine("{0} is greater than {1}", d1, d2); }
B C D E F G H I }
J }
K
The output is
L M
79228162514264337593543950335 is equal to 79228162514264337593543950335 1 is greater than 0 0 is greater than -1 -79228162514264337593543950335 is less than -1
N O P Q
Decimal.CompareTo(System.Object) Method
R
[ILASM]
S
.method public final hidebysig virtual int32 CompareTo(object value)
T
public int CompareTo(object value)
[C#]
U
Summary
V
Returns the sort order of the current instance compared to the specified System.Object.
W
Parameters
X Y
Parameter
Description
value
The System.Object to compare to the current instance.
Z
1186
Contents | Index
System
Decimal Structure CompareTo() Method
Return Value A System.Int32 containing a value that reflects the sort order of the current instance as compared to value. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number. Each comparison compares the numerical values of d1 and d2.
A B C D
Return Value
Description
any negative number
Current instance < value.
zero
Current instance == value.
G
any positive number
Current instance > value, or value is a null reference.
H
E F
I
Description
J
[Note: This method is implemented to support the System.IComparable interface.]
K L
Exceptions
M
Exception
Condition
System.ArgumentException
value is not a System.Decimal and is not a null reference.
N O P Q
Example
R
using System;
S namespace Samples { public class DateTimeCompareTo { private static string CompareDecimals(Decimal d1, Decimal d2) { int i = d1.CompareTo(d2); if(0 == i) return String.Format("{0} is equal to {1}", d1, d2); if(i > 0) return String.Format("{0} is greater than {1}", d1, d2); else return String.Format("{0} is less than {1}", d1, d2);
T U V W X Y Z
1187
Contents | Index
Decimal Structure
System
Divide() Method
} public static void Main() { Decimal d1 = Decimal.MinValue; Decimal d2 = Decimal.MaxValue; Console.WriteLine(CompareDecimals(d1, d1)); Console.WriteLine(CompareDecimals(d1, d2)); Console.WriteLine(CompareDecimals(d2, d1)); }
A B C D
} }
E F
The output is
G -79228162514264337593543950335 is equal to -79228162514264337593543950335 -79228162514264337593543950335 is less than 79228162514264337593543950335 79228162514264337593543950335 is greater than -79228162514264337593543950335
H I J K
Decimal.Divide(System.Decimal, System.Decimal) Method
L
[ILASM]
.method public hidebysig static decimal Divide(decimal d1, decimal d2)
M
[C#]
public static decimal Divide(decimal d1, decimal d2)
N O
Summary
P
Divides the value of one System.Decimal by another.
Q
Parameters
R S
Parameter
Description
U
d1
The dividend.
V
d2
The divisor.
T
W X
Return Value
Y
A System.Decimal containing the result of dividing d1 by d2. The scale of the result, before any rounding, is the smallest scale that will preserve a result equal to the exact result. For example, 2.22/2 gives 1.11.
Z
1188
Contents | Index
System
Decimal Structure Divide() Method
Exceptions Exception
Condition
System.DivideByZeroException
d2 is zero.
System.OverflowException
The result is greater than System.Decimal.MaxValue or less than System.Decimal.MinValue.
A B C D E
Example
F
using System;
G
namespace Samples { public class DecimalDivide { public static void Main() { try { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue; Console.WriteLine("Divide({0}, {1}): {2}", max, minusOne, Decimal.Divide(max, minusOne)); Console.WriteLine("Divide({0}, {1}): {2}", max, min, Decimal.Divide(max, min)); Console.WriteLine("Divide({0}, {1}): {2}", max, one, Decimal.Divide(max, one)); Console.WriteLine("Divide({0}, {1}): {2}", one, zero, Decimal.Divide(one, zero)); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
H I J K L M N O P Q R S T U V W X
The output is
Y
Divide(79228162514264337593543950335, -1): -79228162514264337593543950335 Divide(79228162514264337593543950335, -79228162514264337593543950335): -1 Divide(79228162514264337593543950335, 1): 79228162514264337593543950335 Exception: System.DivideByZeroException: Attempted to divide by zero.
Z
1189
Contents | Index
Decimal Structure
System
Equals() Method
at System.Decimal.Divide(Decimal d1, Decimal d2) at Samples.DecimalDivide.Main() in C:\Books\BCL\Samples\System\Decimal\ Divide(System.Decimal,System.Decimal)\Decimal.cs:line 22
A B
Decimal.Equals(System.Decimal, System.Decimal) Method
C
[ILASM]
D
.method public hidebysig static bool Equals(decimal d1, decimal d2)
E
public static bool Equals(decimal d1, decimal d2)
[C#]
F
Summary
G
Determines whether two System.Decimal values have the same value.
H
Parameters
I J
Parameter
Description
d1
The first System.Decimal to compare.
d2
The second System.Decimal to compare.
K L M N
Return Value
O
true if d1 and d2 are numerically equal (have the same value) otherwise, false.
P Q
Example
R
using System;
S
namespace Samples { public class DecimalEquals { public static void Main() { Decimal d1 = Decimal.MinValue; Decimal d2 = Decimal.MaxValue; Console.WriteLine("Is {0} equal to {1}? {2}", d1, d1, Decimal.Equals(d1, d1)); Console.WriteLine("Is {0} equal to {1}? {2}", d1, d2, Decimal.Equals(d1, d2)); } } }
T U V W X Y Z
1190
Contents | Index
System
Decimal Structure Equals() Method
The output is Is -79228162514264337593543950335 equal to -79228162514264337593543950335? True Is -79228162514264337593543950335 equal to 79228162514264337593543950335? False
A B
Decimal.Equals(System.Object) Method
C
[ILASM]
D
.method public hidebysig virtual bool Equals(object value)
E
[C#]
public override bool Equals(object value)
F G
Summary
H
Determines whether the current instance and the specified System.Object have the same type and value.
I J
Parameters
K
Parameter
Description
value
The System.Object to compare to the current instance.
L M N O
Return Value
P
true if value has the same type and is numerically equal to (has the same value as) the current instance. If value is a null reference or is not an instance of System.Decimal, returns false.
Q R S
Description
T
[Note: This method overrides System.Object.Equals.]
U
Example
V
using System;
W
namespace Samples { public class DecimalEquals { public static void Main() { Decimal d1 = Decimal.MinValue;
X Y Z
1191
Contents | Index
Decimal Structure
System
Floor() Method
Decimal d2 = Decimal.MaxValue; Console.WriteLine("Is {0} equal to {1}? {2}", d1, d1, d1.Equals(d1)); Console.WriteLine("Is {0} equal to {1}? {2}", d1, d2, d1.Equals(d2)); string s = Decimal.MaxValue.ToString(); Console.WriteLine("Is {0} equal to {1}? {2}", d2, s, d1.Equals(s));
A B C }
D
} }
E F
The output is
G Is -79228162514264337593543950335 equal to -79228162514264337593543950335? True Is -79228162514264337593543950335 equal to 79228162514264337593543950335? False Is 79228162514264337593543950335 equal to 79228162514264337593543950335? False
H I J K
Decimal.Floor(System.Decimal) Method
L
[ILASM]
.method public hidebysig static decimal Floor(decimal d)
M
[C#]
public static decimal Floor(decimal d)
N O
Summary
P
Rounds a System.Decimal value to the closest integer towards negative infinity.
Q
Parameters
R S
Parameter
Description
d
The System.Decimal to round downward.
T U V W
Return Value
X
A System.Decimal value v such that v is a whole number and d – 1 < v <= d. The scale of the result will be zero.
Y Z
1192
Contents | Index
System
Decimal Structure FromOACurrency() Method
Example using System; namespace Samples { public class DecimalFloor { public static void Main() { Decimal d1 = Decimal.MinusOne, d2 = Decimal.Zero, d3 = 42.42M, d4 = -d3; Console.WriteLine("Floor({0}): {1}", d1, Decimal.Floor(d1)); Console.WriteLine("Floor({0}): {1}", d2, Decimal.Floor(d2)); Console.WriteLine("Floor({0}): {1}", d3, Decimal.Floor(d3)); Console.WriteLine("Floor({0}): {1}", d4, Decimal.Floor(d4)); } } }
A B C D E F G H I J K L M
The output is
N O
Floor(-1): -1 Floor(0): 0 Floor(42.42): 42 Floor(-42.42): -43
P Q R
Decimal.FromOACurrency(System.Int64) Method
S
[ILASM]
T
.method public hidebysig static decimal FromOACurrency(int64 cy)
U
[C#]
V
public static decimal FromOACurrency(long cy)
W
Summary
X
Converts the specified 64-bit signed integer, which contains an OLE Automation Currency value, to the equivalent System.Decimal value.
Y Z
1193
Contents | Index
Decimal Structure
System
GetBits() Method
Parameters Parameter
Description
cy
An OLE Automation Currency value.
A B C D
Return Value
E
A System.Decimal that contains the equivalent of cy.
F G
Decimal.GetBits(System.Decimal) Method
H
[ILASM]
.method public hidebysig static class System.Int32[] GetBits(decimal d)
I
[C#]
J
public static int[] GetBits(decimal d)
K
Summary
L
Returns a binary representation of the specified System.Decimal value.
M
Parameters
N O P Q
Parameter
Description
d
The System.Decimal value for which a binary representation is returned.
R S
Return Value
T
An array of type System.Int32 containing the following four elements:
U V
Index
Description
0
Low-order 32 bits of the decimal’s coefficient, c.
Y
1
Middle 32 bits of c.
Z
2
High-order 32 bits of c.
3
Sign bit and scale. See below.
W X
1194
Contents | Index
System
Decimal Structure GetBits() Method
The sign bit and scale occupy 32 bits as follows:
Bit Positions
Description
A
0–15
Unused.
B
Contains the scale f, a value between 0 and 28 which indicates the power of 10 to divide c by, to produce the System.Decimal value.
C
16–23
D
24–30
Unused.
E
31
The sign, s, of the System.Decimal value. 0 (zero or positive) or 1 (negative).
F G
Description
H
[Note: The elements of the returned array contain a binary representation of d as a coefficient c, a scale f, and sign bit s. The value of d is computed as –1s × c × 10–f. c occupies the first three elements of the returned array. The fourth element contains f and s.] A numeric value may have several possible binary representations; they are numerically equal but have different scales. Also, the bit representation differentiates between –0, 0.00, and 0; these are all treated as 0 in operations, and any zero result will have a sign of 0 and a scale of 0.
I J K L M
Example
N
using System; using System.Collections.Specialized;
O P
namespace Samples { public class DecimalGetBits { public static void Main() { Display(Decimal.MaxValue); Display(Decimal.One); Display(Decimal.Zero); Display(Decimal.MinusOne); Display(Decimal.MinValue); } public static void Display(Decimal d) { Console.WriteLine("Value: {0}", d); Console.WriteLine("Value as int[]:"); int[] ints = Decimal.GetBits(d); foreach(int i in ints) Console.Write("[{0}] ", i);
Q R S T U V W X Y Z
1195
Contents | Index
Decimal Structure
System
GetBits() Method
Console.WriteLine(); foreach(int i in ints) Console.WriteLine("[{0}] ", new BitVector32(i)); Console.WriteLine();
A
} }
B }
C
The output is
D E
Value: 79228162514264337593543950335 Value as int[]: [-1] [-1] [-1] [0] [BitVector32{11111111111111111111111111111111}] [BitVector32{11111111111111111111111111111111}] [BitVector32{11111111111111111111111111111111}] [BitVector32{00000000000000000000000000000000}]
F G H I
Value: 1 Value as int[]: [1] [0] [0] [0] [BitVector32{00000000000000000000000000000001}] [BitVector32{00000000000000000000000000000000}] [BitVector32{00000000000000000000000000000000}] [BitVector32{00000000000000000000000000000000}]
J K L M N
Value: 0 Value as int[]: [0] [0] [0] [0] [BitVector32{00000000000000000000000000000000}] [BitVector32{00000000000000000000000000000000}] [BitVector32{00000000000000000000000000000000}] [BitVector32{00000000000000000000000000000000}]
O P Q R S
Value: -1 Value as int[]: [1] [0] [0] [-2147483648] [BitVector32{00000000000000000000000000000001}] [BitVector32{00000000000000000000000000000000}] [BitVector32{00000000000000000000000000000000}] [BitVector32{10000000000000000000000000000000}]
T U V W X
Value: -79228162514264337593543950335 Value as int[]: [-1] [-1] [-1] [-2147483648] [BitVector32{11111111111111111111111111111111}] [BitVector32{11111111111111111111111111111111}] [BitVector32{11111111111111111111111111111111}] [BitVector32{10000000000000000000000000000000}]
Y Z
1196
Contents | Index
System
Decimal Structure GetHashCode() Method
Decimal.GetHashCode() Method [ILASM]
.method public hidebysig virtual int32 GetHashCode() [C#]
A
public override int GetHashCode()
B C
Summary
D
Generates a hash code for the current instance.
E
Return Value
F
A System.Int32 containing the hash code for this instance.
G
Description
H
The algorithm used to generate the hash code value is unspecified. [Note: This method overrides System.Object.GetHashCode.]
I J K
Example
L
using System;
M namespace Samples { public class DecimalGetBits { public static void Main() { Console.WriteLine("Value: {0}, HashCode: {1}", Decimal.MaxValue, Decimal.MaxValue.GetHashCode()); Console.WriteLine("Value: {0}, HashCode: {1}", Decimal.One, Decimal.One.GetHashCode()); Console.WriteLine("Value: {0}, HashCode: {1}", Decimal.Zero, Decimal.Zero.GetHashCode()); Console.WriteLine("Value: {0}, HashCode: {1}", Decimal.MinusOne, Decimal.MinusOne.GetHashCode()); Console.WriteLine("Value: {0}, HashCode: {1}", Decimal.MinValue, Decimal.MinValue.GetHashCode()); } } }
N O P Q R S T U V W X Y Z
1197
Contents | Index
Decimal Structure
System
GetTypeCode() Method
The output is Value: Value: Value: Value: Value:
A B
79228162514264337593543950335, HashCode: 1173356544 1, HashCode: 1072693248 0, HashCode: 0 -1, HashCode: -1074790400 -79228162514264337593543950335, HashCode: -974127104
C D E
Decimal.GetTypeCode() Method
F
[ILASM]
.method public final hidebysig virtual valuetype System.TypeCode GetTypeCode()
G
[C#]
public TypeCode GetTypeCode()
H I
Summary
J
Returns the System.TypeCode for value type System.Decimal.
K L
Decimal.Multiply(System.Decimal, System.Decimal) Method
M [ILASM]
N
.method public hidebysig static decimal Multiply(decimal d1, decimal d2) [C#]
O
public static decimal Multiply(decimal d1, decimal d2)
P Q
Summary
R
Returns the result of multiplying two System.Decimal values.
S
Parameters
T U V
Parameter
Description
d1
The first value to multiply.
d2
The second value to multiply.
W X Y Z
1198
Contents | Index
System
Decimal Structure Multiply() Method
Return Value The result of multiplying d1 and d2. The scale of the result, before any rounding, is the sum of the scales of d1 and d2. For example, 123 × 3 gives 369, and 2.2 × 1.35 gives 2.970.
A B
Exceptions
C
Exception
Condition
System.OverflowException
The result is greater than System.Decimal.MaxValue or less than System.Decimal.MinValue.
D E F G H
Example
I
using System;
J
namespace Samples { public class DecimalMultiply { public static void Main() { try { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue; Console.WriteLine("Multiply({0}, {1}): {2}", max, minusOne, Decimal.Multiply(max, minusOne)); Console.WriteLine("Multiply({0}, {1}): {2}", max, one, Decimal.Multiply(max, one)); Console.WriteLine("Multiply({0}, {1}): {2}", one, zero, Decimal.Multiply(one, zero)); Console.WriteLine("Multiply({0}, {1}): {2}", max, min, Decimal.Multiply(max, min)); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
K L M N O P Q R S T U V W X Y Z
1199
Contents | Index
Decimal Structure
System
Negate() Method
The output is Multiply(79228162514264337593543950335, -1): -79228162514264337593543950335 Multiply(79228162514264337593543950335, 1): 79228162514264337593543950335 Multiply(1, 0): 0 Exception: System.OverflowException: Value was either too large or too small for a Decimal. at System.Decimal.Multiply(Decimal d1, Decimal d2) at Samples.DecimalMultiply.Main() in C:\Books\BCL\Samples\System\Decimal\ Multiply(System.Decimal,System.Decimal)\Decimal.cs:line 23
A B C D E F
Decimal.Negate(System.Decimal) Method
G H
[ILASM]
I
[C#]
.method public hidebysig static decimal Negate(decimal d) public static decimal Negate(decimal d)
J K
Summary
L
Returns the result of multiplying a System.Decimal value by –1.
M
Parameters
N O
Parameter
Description
d
The value to negate.
P Q R
Return Value
S
The negated value of d. If d is zero, then zero is returned (with 0 sign and scale); otherwise, the scale of the result is the same as the scale of d.
T U
Example
V
using System;
W namespace Samples { public class DecimalNegate { public static void Main() { Decimal max = Decimal.MaxValue,
X Y Z
1200
Contents | Index
System
Decimal Structure op_Addition() Method
one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue; Console.WriteLine("Value: {0}, Negated: {1}", max, Decimal.Negate(max)); Console.WriteLine("Value: {0}, Negated: {1}", one, Decimal.Negate(one)); Console.WriteLine("Value: {0}, Negated: {1}", zero, Decimal.Negate(zero)); Console.WriteLine("Value: {0}, Negated: {1}", minusOne, Decimal.Negate(minusOne)); Console.WriteLine("Value: {0}, Negated: {1}", min, Decimal.Negate(min));
A B C D E F G
} }
H
}
I
The output is
J Value: Value: Value: Value: Value:
79228162514264337593543950335, Negated: -79228162514264337593543950335 1, Negated: -1 0, Negated: 0 -1, Negated: 1 -79228162514264337593543950335, Negated: 79228162514264337593543950335
K L M N
Decimal.op_Addition(System.Decimal, System.Decimal) Method
O
[ILASM]
P
.method public hidebysig static specialname decimal op_Addition(decimal d1, decimal d2)
Q
[C#]
R
public static decimal operator +(decimal d1, decimal d2)
S
Summary
T
Adds two System.Decimal values together.
U V
Parameters
W
Parameter
Description
d1
The first value to add.
d2
The second value to add.
X Y Z
1201
Contents | Index
Decimal Structure
System
op_Addition() Method
Return Value The value returned by System.Decimal.Add(d1,d2). A
Exceptions
B C
Exception
Condition
D
System.OverflowException
The sum of d1 and d2 is greater than System.Decimal.MaxValue or less than System.Decimal.MinValue.
E F
Example
G
using System;
H
namespace Samples { public class DecimalOp_Addition { public static void Main() { try { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue; Console.WriteLine("{0} + {1}: {2}", max, minusOne, max + minusOne); Console.WriteLine("{0} + {1}: {2}", one, zero, one + zero); Console.WriteLine("{0} + {1}: {2}", max, min, max + min); Console.WriteLine("{0} + {1}: {2}", max, one, max + one); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
I J K L M N O P Q R S T U V W X Y Z
1202
Contents | Index
System
Decimal Structure op_Decrement() Method
The output is 79228162514264337593543950335 + -1: 79228162514264337593543950334 1 + 0: 1 79228162514264337593543950335 + -79228162514264337593543950335: 0 Exception: System.OverflowException: Value was either too large or too small for a Decimal. at System.Decimal.Add(Decimal d1, Decimal d2) at System.Decimal.op_Addition(Decimal d1, Decimal d2) at Samples.DecimalOp_Addition.Main() in C:\Books\BCL\Samples\System\Decimal\ Op_Addition(System.Decimal,System.Decimal)\Decimal.cs:line 22
A B C D E F G
Decimal.op_Decrement(System.Decimal) Method
H
[ILASM]
I
.method public hidebysig static specialname decimal op_Decrement(decimal d) [C#]
J
public static decimal operator --(decimal d)
K
Summary
L
Returns the specified value decremented by one.
M N
Parameters
O
Parameter
Description
d
A System.Decimal value.
P Q R
Return Value
S
The value returned by System.Decimal.Subtract(d, System.Decimal.One).
T U
Exceptions
V
Exception
Condition
System.OverflowException
The result is greater than System.Decimal.MaxValue or less than System.Decimal.MinValue.
W X Y Z
1203
Contents | Index
Decimal Structure
System
op_Decrement() Method
Example using System; namespace Samples { public class DecimalOp_Decrement { public static void Main() { try { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue; Console.WriteLine("Value: {0}, Decremented: max, --max); Console.WriteLine("Value: {0}, Decremented: one, --one); Console.WriteLine("Value: {0}, Decremented: zero, --zero); Console.WriteLine("Value: {0}, Decremented: minusOne, --minusOne); Console.WriteLine("Value: {0}, Decremented: min, --min); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P Q R S T
{1}", {1}", {1}", {1}", {1}",
The output is
U Value: 79228162514264337593543950335, Decremented: 79228162514264337593543950334 Value: 1, Decremented: 0 Value: 0, Decremented: -1 Value: -1, Decremented: -2 Exception: System.OverflowException: Value was either too large or too small for a Decimal. at System.Decimal.Subtract(Decimal d1, Decimal d2) at System.Decimal.op_Decrement(Decimal d) at Samples.DecimalOp_Decrement.Main() in C:\Books\BCL\Samples\System\Decimal\ Op_Decrement(System.Decimal)\Decimal.cs:line 24
V W X Y Z
1204
Contents | Index
System
Decimal Structure op_Division() Method
Decimal.op_Division(System.Decimal, System.Decimal) Method [ILASM]
.method public hidebysig static specialname decimal op_Division(decimal d1, decimal d2)
A
[C#]
B
public static decimal operator /(decimal d1, decimal d2)
C
Summary
D
Divides one System.Decimal value by another System.Decimal.
E F
Parameters
G
Parameter
Description
d1
The dividend.
d2
The divisor.
H I J K L
Return Value
M
The value returned by System.Decimal.Divide(d1, d2).
N O
Exceptions
P
Exception
Condition
Q
System.DivideByZeroException
The divisor is zero.
R
System.OverflowException
The result is greater than System.Decimal.MaxValue or less than System.Decimal.MinValue.
S T U
Example
V
using System;
W
namespace Samples { public class DecimalOp_Division { public static void Main() {
X Y Z
1205
Contents | Index
Decimal Structure
System
op_Equality() Method
try { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue; Console.WriteLine("{0} / {1}: {2}", max, max, max / max); Console.WriteLine("{0} / {1}: {2}", max, min, max / min); Console.WriteLine("{0} / {1}: {2}", max, one, max / one); Console.WriteLine("{0} / {1}: {2}", max, minusOne, max / minusOne); Console.WriteLine("{0} / {1}: {2}", max, zero, max / zero); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); }
A B C D E F G H I J K L
} }
M }
N
The output is
O P
79228162514264337593543950335 / 79228162514264337593543950335: 1 79228162514264337593543950335 / -79228162514264337593543950335: -1 79228162514264337593543950335 / 1: 79228162514264337593543950335 79228162514264337593543950335 / -1: -79228162514264337593543950335 Exception: System.DivideByZeroException: Attempted to divide by zero. at System.Decimal.Divide(Decimal d1, Decimal d2) at System.Decimal.op_Division(Decimal d1, Decimal d2) at Samples.DecimalOp_Division.Main() in C:\Books\BCL\Samples\System\Decimal\ Op_Division(System.Decimal,System.Decimal)\Decimal.cs:line 24
Q R S T U V W
Decimal.op_Equality(System.Decimal, System.Decimal) Method
X
[ILASM]
Y
.method public hidebysig static specialname bool op_Equality(decimal d1, decimal d2) [C#]
Z
public static bool operator ==(decimal d1, decimal d2)
1206
Contents | Index
System
Decimal Structure op_Equality() Method
Summary Determines whether two decimals have the same value. A
Parameters
B
Parameter
Description
C
d1
The first System.Decimal to compare.
D
d2
The second System.Decimal to compare.
E F G
Return Value
H
true if System.Decimal.Compare(d1, d2) returns zero; otherwise, false.
I
Example
J
using System;
K
namespace Samples { public class DecimalOp_Equality { public static void Main() { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue; Console.WriteLine("{0} == {1}: {2}", max, minusOne, max == minusOne); Console.WriteLine("{0} == {1}: {2}", max, zero, max == zero); Console.WriteLine("{0} == {1}: {2}", max, one, max == one); Console.WriteLine("{0} == {1}: {2}", max, min, max == min); Console.WriteLine("{0} == {1}: {2}", max, max, max == max); } } }
L M N O P Q R S T U V W X Y Z
1207
Contents | Index
Decimal Structure
System
op_Explicit() Method
The output is 79228162514264337593543950335 79228162514264337593543950335 79228162514264337593543950335 79228162514264337593543950335 79228162514264337593543950335
A B
== == == == ==
-1: False 0: False 1: False -79228162514264337593543950335: False 79228162514264337593543950335: True
C D E
Decimal.op_Explicit(System.Decimal) Method
F
[ILASM]
.method public hidebysig static specialname unsigned int8 op_Explicit(decimal value)
G
[C#]
public static explicit operator byte(decimal value)
H I
Summary
J
Performs an explicit conversion of a System.Decimal value to System.Byte.
K
Parameters
L M
Parameter
Description
value
The System.Decimal value to convert to System.Byte.
N O P
Return Value
Q
A System.Byte containing value rounded towards zero to the nearest integer.
R
Exceptions
S T
Exception
Condition
System.OverflowException
The resulting integer value is greater than System.Byte.MaxValue or less than System.Byte.MinValue.
U V W X
Example
Y
using System;
Z
namespace Samples { public class DecimalOp_Explicit
1208
Contents | Index
System
Decimal Structure op_Explicit() Method
{ public static void Main() { try { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero; Console.WriteLine("{0} is {1}", one, (byte) one); Console.WriteLine("{0} is {1}", zero, (byte) zero); Console.WriteLine("{0} is {1}", max, (byte) max); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } }
A B C D E F G H I J
}
K
}
L
The output is
M
1 is 1 0 is 0 Exception: System.OverflowException: Value was either too large or too small for a UInt32. at System.Decimal.ToUInt32(Decimal d) at System.Decimal.ToByte(Decimal value) at System.Decimal.op_Explicit(Decimal value) at Samples.DecimalOp_Explicit.Main() in C:\Books\BCL\Samples\System\Decimal\ Op_ExplicitUInt8(System.Decimal)\Decimal.cs:line 18
N O P Q R S T
Decimal.op_Explicit(System.Decimal) Method
U
[ILASM]
V
.method public hidebysig static specialname valuetype System.Char op_Explicit(decimal value)
W
[C#]
X
public static explicit operator char(decimal value)
Y
Summary
Z
Performs an explicit conversion of a System.Decimal value to System.Char.
1209
Contents | Index
Decimal Structure
System
op_Explicit() Method
Parameters Parameter
Description
value
The System.Decimal value to convert to System.Char.
A B C D
Return Value
E
A System.Char containing value rounded towards zero to the nearest integer.
F
Exceptions
G H I J
Exception
Condition
System.OverflowException
The resulting integer value is greater than System.Char.MaxValue or less than System.Char.MinValue.
K L
Example
M
using System;
N
namespace Samples { public class DecimalOp_Explicit { public static void Main() { try { char max = char.MaxValue, min = char.MinValue; Console.WriteLine("{0} is {1}", max, (Decimal) max); Console.WriteLine("{0} is {1}", min, (Decimal) min); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
O P Q R S T U V W X Y Z
1210
Contents | Index
System
Decimal Structure op_Explicit() Method
The output is ? is 65535 is 0
A B
Decimal.op_Explicit(System.Double) Method
C
[ILASM]
D
.method public hidebysig static specialname decimal op_Explicit(float64 value)
E
[C#]
public static explicit operator decimal(double value)
F G
Summary
H
Performs an explicit conversion of a System.Double value to System.Decimal.
I
Parameters Parameter
J K
Description
L
value
The System.Double value to convert to System.Decimal.
M N
Return Value
O
A System.Decimal with the specified value.
P Q
Exceptions Exception
R
Condition
S T
value is one of the following:
System.OverflowException
greater than System.Decimal.MaxValue
U
less than System.Decimal.MinValue
V
equal to System.Double.NaN
W
equal to System.Double.PositiveInfinity
X
equal to System.Double.NegativeInfinity Y Z
1211
Contents | Index
Decimal Structure
System
op_Explicit() Method
Example using System; namespace Samples { public class DecimalOp_Explicit { public static void Main() { try { Double max = Double.MaxValue, epsilon = Double.Epsilon; Console.WriteLine("{0} is {1}", epsilon, (Decimal) epsilon); Console.WriteLine("{0} is {1}", max, (Decimal) max); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N
The output is
O P
4.94065645841247E-324 is 0 Exception: System.OverflowException: Value was either too large or too small for a Decimal. at System.Decimal..ctor(Double value) at System.Decimal.op_Explicit(Double value) at Samples.DecimalOp_Explicit.Main() in C:\Books\BCL\Samples\System\Decimal\ Op_Explicit(System.Double)\Decimal.cs:line 15
Q R S T U V
Decimal.op_Explicit(System.Single) Method
W
[ILASM]
X
.method public hidebysig static specialname decimal op_Explicit(float32 value) [C#]
Y
public static explicit operator decimal(float value)
Z
Summary Performs an explicit conversion of a System.Single value to System.Decimal. 1212
Contents | Index
System
Decimal Structure op_Explicit() Method
Parameters Parameter
Description
value
The System.Single value to convert to System.Decimal.
A B C
Return Value
D
A System.Decimal with the specified value.
E
Exceptions
F
Exception
Condition
System.OverflowException
value is one of the following: greater than System.Decimal.MaxValue less than System.Decimal.MinValue equal to System.Single.NaN equal to System.Single.PositiveInfinity equal to System.Single.NegativeInfinity
G H I J K L M
Example
N
using System;
O
namespace Samples { public class DecimalOp_Explicit { public static void Main() { try { float max = float.MaxValue, epsilon = float.Epsilon; Console.WriteLine("{0} is {1}", epsilon, (Decimal) epsilon); Console.WriteLine("{0} is {1}", max, (Decimal) max); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
P Q R S T U V W X Y Z
1213
Contents | Index
Decimal Structure
System
op_Explicit() Method
The output is 1.401298E-45 is 0 Exception: System.OverflowException: Value was either too large or too small for a Decimal. at System.Decimal..ctor(Single value) at System.Decimal.op_Explicit(Single value) at Samples.DecimalOp_Explicit.Main() in C:\Books\BCL\Samples\System\Decimal\ Op_Explicit(System.Single)\Decimal.cs:line 15
A B C D E
Decimal.op_Explicit(System.Decimal) Method
F
[ILASM]
G
.method public hidebysig static specialname float64 op_Explicit(decimal value)
H
[C#]
public static explicit operator double(decimal value)
I J
Summary
K
Performs an explicit conversion of a System.Decimal value to System.Double.
L
Parameters
M N O
Parameter
Description
value
The System.Decimal value to convert to System.Double.
P Q
Return Value
R
A System.Double with the specified value.
S T
Description
U
[Note: This operation can produce round-off errors due to the fact that System.Double has fewer significant digits than System.Decimal.]
V W
Example
X
using System;
Y
namespace Samples { public class DecimalOp_Explicit { public static void Main()
Z
1214
Contents | Index
System
Decimal Structure op_Explicit() Method
{ Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue; Console.WriteLine("{0} is {1}", max, (double) max); Console.WriteLine("{0} is {1}", one, (double) one); Console.WriteLine("{0} is {1}", zero, (double) zero); Console.WriteLine("{0} is {1}", minusOne, (double) minusOne); Console.WriteLine("{0} is {1}", min, (double) min);
A B C D E F G H
}
I
} }
J K
The output is
L
79228162514264337593543950335 is 7.92281625142643E+28 1 is 1 0 is 0 -1 is -1 -79228162514264337593543950335 is -7.92281625142643E+28
M N O P
Decimal.op_Explicit(System.Decimal) Method
Q
[ILASM]
R
.method public hidebysig static specialname float32 op_Explicit(decimal value)
S
[C#]
T
public static explicit operator float(decimal value)
U
Summary
V
Performs an explicit conversion of a System.Decimal value to System.Single.
W
Parameters
X Y
Parameter
Description Z
value
The System.Decimal value to convert to System.Single.
1215
Contents | Index
Decimal Structure
System
op_Explicit() Method
Return Value A System.Single with the specified value. [Note: This operation can produce round-off errors due to the fact that System.Single has fewer significant digits than System.Decimal.]
A B
Example
C
using System;
D namespace Samples { public class DecimalOp_Explicit { public static void Main() { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue; Console.WriteLine("{0} is {1}", max, (float) max); Console.WriteLine("{0} is {1}", one, (float) one); Console.WriteLine("{0} is {1}", zero, (float) zero); Console.WriteLine("{0} is {1}", minusOne, (float) minusOne); Console.WriteLine("{0} is {1}", min, (float) min); } } }
E F G H I J K L M N O P Q R
The output is
S T
79228162514264337593543950335 is 7.922816E+28 1 is 1 0 is 0 -1 is -1 -79228162514264337593543950335 is -7.922816E+28
U V W X Y
Decimal.op_Explicit(System.Decimal) Method
Z
[ILASM]
.method public hidebysig static specialname int32 op_Explicit(decimal value) [C#]
public static explicit operator int(decimal value)
1216
Contents | Index
System
Decimal Structure op_Explicit() Method
Summary Performs an explicit conversion of a System.Decimal value to System.Int32. A
Parameters
B
Parameter
Description
C
value
The System.Decimal value to convert to System.Int32.
D E F
Return Value
G
A System.Int32 containing value rounded towards zero to the nearest integer.
H
Exceptions
I
Exception
Condition
System.OverflowException
The resulting integer value is greater than System.Int32.MaxValue or less than System.Int32.MinValue.
J K L M N
Example
O
using System;
P namespace Samples { public class DecimalOp_Explicit { public static void Main() { try { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne; Console.WriteLine("{0} is {1}", one, (int) one); Console.WriteLine("{0} is {1}", zero, (int) zero); Console.WriteLine("{0} is {1}", minusOne, (int) minusOne);
Q R S T U V W X Y Z
1217
Contents | Index
Decimal Structure
System
op_Explicit() Method
Console.WriteLine("{0} is {1}", max, (int) max); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); }
A B C
} }
D
}
E
The output is
F
1 is 1 0 is 0 -1 is -1 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Decimal.ToInt32(Decimal d) at System.Decimal.op_Explicit(Decimal value) at Samples.DecimalOp_Explicit.Main() in C:\Books\BCL\Samples\System\Decimal\ Op_ExplicitInt32(System.Decimal)\Decimal.cs:line 21
G H I J K L M N
Decimal.op_Explicit(System.Decimal) Method
O
[ILASM]
.method public hidebysig static specialname int64 op_Explicit(decimal value)
P
[C#]
public static explicit operator long(decimal value)
Q R
Summary
S
Performs an explicit conversion of a System.Decimal value to System.Int64.
T
Parameters
U V
Parameter
Description
value
The System.Decimal value to convert to System.Int64.
W X Y
Return Value
Z
A System.Int64 containing value rounded towards zero to the nearest integer.
1218
Contents | Index
System
Decimal Structure op_Explicit() Method
Exceptions Exception
Condition
System.OverflowException
The resulting integer value is greater than System.Int64.MaxValue or less than System.Int64.MinValue.
A B C D
Example
E
using System;
F namespace Samples { public class DecimalOp_Explicit { public static void Main() { try { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne; Console.WriteLine("{0} is {1}", one, (long) one); Console.WriteLine("{0} is {1}", zero, (long) zero); Console.WriteLine("{0} is {1}", minusOne, (long) minusOne); Console.WriteLine("{0} is {1}", max, (long) max); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
G H I J K L M N O P Q R S T U V W
The output is
X Y
1 is 1 0 is 0 -1 is -1 Exception: System.OverflowException: Value was either too large or too small for an Int64.
Z
1219
Contents | Index
Decimal Structure
System
op_Explicit() Method
at System.Decimal.ToInt64(Decimal d) at System.Decimal.op_Explicit(Decimal value) at Samples.DecimalOp_Explicit.Main() in C:\Books\BCL\Samples\System\Decimal\ Op_ExplicitInt64(System.Decimal)\Decimal.cs:line 21
A B C
Decimal.op_Explicit(System.Decimal) Method
D
[ILASM]
.method public hidebysig static specialname int8 op_Explicit(decimal value)
E
[C#]
public static explicit operator sbyte(decimal value)
F G
Summary
H
Performs an explicit conversion of a System.Decimal value to System.SByte.
I
Parameters
J K
Parameter
Description
value
The System.Decimal value to convert to System.SByte.
L M N O
Return Value
P
A System.SByte containing value rounded towards zero to the nearest integer.
Q
Description
R
This member is not CLS-compliant. For a CLS-compliant alternative to System.SByte, use System.Int16.
S T
Exceptions
U V W X
Exception
Condition
System.OverflowException
The resulting integer value is greater than System.SByte.MaxValue or less than System.SByte.MinValue.
Y Z
1220
Contents | Index
System
Decimal Structure op_Explicit() Method
Example using System; namespace Samples { public class DecimalOp_Explicit { public static void Main() { try { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne; Console.WriteLine("{0} is {1}", one, (sbyte) one); Console.WriteLine("{0} is {1}", zero, (sbyte) zero); Console.WriteLine("{0} is {1}", minusOne, (sbyte) minusOne); Console.WriteLine("{0} is {1}", max, (sbyte) max); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P Q R
The output is
S
1 is 1 0 is 0 -1 is -1 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Decimal.ToInt32(Decimal d) at System.Decimal.ToSByte(Decimal value) at System.Decimal.op_Explicit(Decimal value) at Samples.DecimalOp_Explicit.Main() in C:\Books\BCL\Samples\System\Decimal\ Op_ExplicitInt8(System.Decimal)\Decimal.cs:line 21
T U V W X Y Z
1221
Contents | Index
Decimal Structure
System
op_Explicit() Method
Decimal.op_Explicit(System.Decimal) Method [ILASM]
.method public hidebysig static specialname int16 op_Explicit(decimal value)
A
[C#]
B
public static explicit operator short(decimal value)
C
Summary
D
Performs an explicit conversion of a System.Decimal value to System.Int16.
E
Parameters
F G
Parameter
Description
H
value
The System.Decimal value to convert to System.Int16.
I J
Return Value
K
A System.Int16 containing value rounded towards zero to the nearest integer.
L
Exceptions
M N
Exception
Condition
O
System.OverflowException
The resulting integer value is greater than System.Int16.MaxValue or less than System.Int16.MinValue.
P Q
Example
R
using System;
S namespace Samples { public class DecimalOp_Explicit { public static void Main() { short max = short.MaxValue, min = short.MinValue; Console.WriteLine("{0} is {1}", max, (Decimal) max); Console.WriteLine("{0} is {1}", min, (Decimal) min); } } }
T U V W X Y Z
1222
Contents | Index
System
Decimal Structure op_Explicit() Method
The output is 32767 is 32767 -32768 is -32768
A B
Decimal.op_Explicit(System.Decimal) Method
C
[ILASM]
D
.method public hidebysig static specialname unsigned int32 op_Explicit(decimal value)
E
[C#]
F
public static explicit operator uint(decimal value)
G
Summary
H
Performs an explicit conversion of a System.Decimal value to System.UInt32.
I J
Parameters
K
Parameter
Description
value
The System.Decimal value to convert to System.UInt32.
L M N O
Return Value
P
A System.UInt32 containing value rounded towards zero to the nearest integer.
Q
Description
R
This member is not CLS-compliant. For a CLS-compliant alternative to System.UInt32, use System.Int64.
S
Exceptions
U
T
V
Exception
Condition
W
System.OverflowException
The resulting integer value is greater than System.UInt32.MaxValue or less than System.UInt32.MinValue.
X Y Z
1223
Contents | Index
Decimal Structure
System
op_Explicit() Method
Example using System; namespace Samples { public class DecimalOp_Explicit { public static void Main() { try { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero; Console.WriteLine("{0} is {1}", one, (uint) one); Console.WriteLine("{0} is {1}", zero, (uint) zero); Console.WriteLine("{0} is {1}", max, (uint) max); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P
The output is
Q R
1 is 1 0 is 0 Exception: System.OverflowException: Value was either too large or too small for a UInt32. at System.Decimal.ToUInt32(Decimal d) at System.Decimal.op_Explicit(Decimal value) at Samples.DecimalOp_Explicit.Main() in C:\Books\BCL\Samples\System\Decimal\ Op_ExplicitUInt32(System.Decimal)\Decimal.cs:line 18
S T U V W X
Decimal.op_Explicit(System.Decimal) Method
Y
[ILASM]
Z
.method public hidebysig static specialname unsigned int64 op_Explicit(decimal value) [C#]
public static explicit operator ulong(decimal value)
1224
Contents | Index
System
Decimal Structure op_Explicit() Method
Summary Performs an explicit conversion of a System.Decimal value to System.UInt64. A
Parameters
B
Parameter
Description
C
value
The System.Decimal value to convert to System.UInt64.
D E F
Return Value
G
A System.UInt64 containing value rounded towards zero to the nearest integer.
H
Description
I
This member is not CLS-compliant. For a CLS-compliant alternative to System.UInt64, use System.Int64.
J K
Exceptions
L M
Exception
Condition N
System.OverflowException
The resulting integer value is greater than System.UInt64.MaxValue or less than System.UInt64.MinValue.
O P Q
Example
R
using System;
S namespace Samples { public class DecimalOp_Explicit { public static void Main() { try { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero; Console.WriteLine("{0} is {1}", one, (ulong) one); Console.WriteLine("{0} is {1}",
T U V W X Y Z
1225
Contents | Index
Decimal Structure
System
op_Explicit() Method
zero, (ulong) zero); Console.WriteLine("{0} is {1}", max, (ulong) max); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); }
A B C }
D
} }
E F
The output is
G 1 is 1 0 is 0 Exception: System.OverflowException: Value was either too large or too small for a UInt64. at System.Decimal.ToUInt64(Decimal d) at System.Decimal.op_Explicit(Decimal value) at Samples.DecimalOp_Explicit.Main() in C:\Books\BCL\Samples\System\Decimal\ Op_ExplicitUInt64(System.Decimal)\Decimal.cs:line 18
H I J K L M N
Decimal.op_Explicit(System.Decimal) Method
O
[ILASM]
.method public hidebysig static specialname unsigned int16 op_Explicit(decimal value)
P
[C#]
public static explicit operator ushort(decimal value)
Q R
Summary
S
Performs an explicit conversion of a System.Decimal value to System.UInt16.
T
Parameters
U V
Parameter
Description
value
The System.Decimal value to convert to System.UInt16.
W X Y
Return Value
Z
A System.UInt16 containing value rounded towards zero to the nearest integer.
1226
Contents | Index
System
Decimal Structure op_GreaterThan() Method
Description This member is not CLS-compliant. For a CLS-compliant alternative to System.UInt16, use System.Int32. A
Exceptions
B C
Exception
Condition
System.OverflowException
The resulting integer value is greater than System.UInt16.MaxValue or less than System.UInt16.MinValue.
D E F G
Example
H
using System;
I namespace Samples { public class DecimalOp_Explicit { public static void Main() { ushort max = ushort.MaxValue, min = ushort.MinValue; Console.WriteLine("{0} is {1}", max, (Decimal) max); Console.WriteLine("{0} is {1}", min, (Decimal) min); } } }
J K L M N O P Q R S
The output is
T
65535 is 65535 0 is 0
U V W
Decimal.op_GreaterThan(System.Decimal, System.Decimal) Method
X
[ILASM]
Y
.method public hidebysig static specialname bool op_GreaterThan(decimal d1, decimal d2)
Z
[C#]
public static bool operator >(decimal d1, decimal d2)
1227
Contents | Index
Decimal Structure
System
op_GreaterThan() Method
Summary Determines whether one System.Decimal value is greater than another System.Decimal value. A
Parameters
B C
Parameter
Description
E
d1
The first System.Decimal to compare.
F
d2
The second System.Decimal to compare.
D
G H
Return Value
I
true if System.Decimal.Compare(d1, d2) returns a value that is greater than zero; otherwise, false.
J K
Example
L
using System;
M namespace Samples { public class DecimalOp_GreaterThan { public static void Main() { Decimal d1 = Decimal.MinValue; Decimal d2 = Decimal.MaxValue; Console.WriteLine("Is {0} greater than {1}: {2}", d1, d2, d1 > d2); Console.WriteLine("Is {0} greater than {1}: {2}", d2, d1, d2 > d1); Console.WriteLine("Is {0} greater than {1}: {2}", d1, d1, d1 > d1); } } }
N O P Q R S T U V W X
The output is
Y
Is -79228162514264337593543950335 greater than 79228162514264337593543950335: False Is 79228162514264337593543950335 greater than -79228162514264337593543950335: True Is -79228162514264337593543950335 greater than -79228162514264337593543950335: False
Z
1228
Contents | Index
System
Decimal Structure op_GreaterThanOrEqual() Method
Decimal.op_GreaterThanOrEqual(System.Decimal, System.Decimal) Method [ILASM]
.method public hidebysig static specialname bool op_GreaterThanOrEqual(decimal d1, decimal d2)
A
[C#]
B
public static bool operator >=(decimal d1, decimal d2)
C
Summary
D
Determines whether one System.Decimal value is greater than or equal to another System.Decimal value.
E F
Parameters
G H
Parameter
Description
d1
The first System.Decimal to compare.
J
d2
The second System.Decimal to compare.
K
I
L
Return Value
M
true if System.Decimal.Compare(d1, d2) returns a value that is greater than or equal to zero; otherwise, false.
N O P
Example
Q
using System;
R
namespace Samples { public class DecimalOp_GreaterThanOrEqual { public static void Main() { Decimal d1 = Decimal.MinValue; Decimal d2 = Decimal.MaxValue; Console.WriteLine("Is {0} greater than or equal to {1}: {2}", d1, d2, d1 >= d2); Console.WriteLine("Is {0} greater than or equal to {1}: {2}", d2, d1, d2 >= d1); Console.WriteLine("Is {0} greater than or equal to {1}: {2}", d1, d1, d1 >= d1); } } }
S T U V W X Y Z
1229
Contents | Index
Decimal Structure
System
op_Implicit() Method
The output is Is -79228162514264337593543950335 greater than or equal to 79228162514264337593543950335: False Is 79228162514264337593543950335 greater than or equal to -79228162514264337593543950335: True Is -79228162514264337593543950335 greater than or equal to -79228162514264337593543950335: True
A B C D E
Decimal.op_Implicit(System.Byte) Method
F [ILASM]
G
.method public hidebysig static specialname decimal op_Implicit(unsigned int8 value)
H
[C#]
public static implicit operator decimal(byte value)
I J
Summary
K
Performs an implicit conversion of a System.Byte value to System.Decimal.
L
Parameters
M N O
Parameter
Description
value
The System.Byte value to convert to System.Decimal.
P Q
Return Value
R
A System.Decimal with the specified value.
S
Example
T
using System;
U
namespace Samples { public class DecimalOp_GreaterThanOrEqual { public static void Main() { Decimal d1 = Decimal.MinValue; Decimal d2 = Decimal.MaxValue; Console.WriteLine("Is {0} greater than or equal to {1}: {2}", d1, d2, d1 >= d2);
V W X Y Z
1230
Contents | Index
System
Decimal Structure op_Implicit() Method
Console.WriteLine("Is d2, Console.WriteLine("Is d1,
{0} d1, {0} d1,
greater than or equal to {1}: {2}", d2 >= d1); greater than or equal to {1}: {2}", d1 >= d1);
A
} }
B
}
C
The output is
D E
Is -79228162514264337593543950335 greater than or equal to 79228162514264337593543950335: False Is 79228162514264337593543950335 greater than or equal to -79228162514264337593543950335: True Is -79228162514264337593543950335 greater than or equal to -79228162514264337593543950335: True
F G H I J
Decimal.op_Implicit(System.Char) Method
K [ILASM]
L
.method public hidebysig static specialname decimal op_Implicit(valuetype System.Char value) [C#]
M
public static implicit operator decimal(char value)
N O
Summary
P
Performs an implicit conversion of a System.Char value to System.Decimal.
Q
Parameters
R
Parameter
Description
value
The System.Char value to convert to System.Decimal.
S T U V
Return Value
W
A System.Decimal with the specified value.
X Y Z
1231
Contents | Index
Decimal Structure
System
op_Implicit() Method
Example using System; namespace Samples { public class DecimalOp_Implicit { public static void Main() { char max = char.MaxValue, min = char.MinValue; Decimal d; d = max; Console.WriteLine("{0} is {1}", max, d); d = min; Console.WriteLine("{0} is {1}", min, d); } } }
A B C D E F G H I J K
The output is
L
? is 65535 is 0
M N O
Decimal.op_Implicit(System.Int32) Method
P
[ILASM]
Q
.method public hidebysig static specialname decimal op_Implicit(int32 value)
R
public static implicit operator decimal(int value)
[C#]
S
Summary
T
Performs an implicit conversion of a System.Int32 value to System.Decimal.
U
Parameters
V W
Parameter
Description
value
The System.Int32 value to convert to System.Decimal.
X Y Z
Return Value A System.Decimal with the specified value. 1232
Contents | Index
System
Decimal Structure op_Implicit() Method
Example using System; namespace Samples { public class DecimalOp_Implicit { public static void Main() { int max = int.MaxValue, min = int.MinValue; Decimal d; d = max; Console.WriteLine("{0} is {1}", max, d); d = min; Console.WriteLine("{0} is {1}", min, d); } } }
A B C D E F G H I J K
The output is
L
2147483647 is 2147483647 -2147483648 is -2147483648
M N
Decimal.op_Implicit(System.Int64) Method
O
[ILASM]
P
.method public hidebysig static specialname decimal op_Implicit(int64 value)
Q
[C#]
R
public static implicit operator decimal(long value)
S
Summary
T
Performs an implicit conversion of a System.Int64 value to System.Decimal.
U
Parameters
V
Parameter
Description
value
The System.Int64 value to convert to System.Decimal.
W X Y Z
Return Value A System.Decimal with the specified value. 1233
Contents | Index
Decimal Structure
System
op_Implicit() Method
Example using System; namespace Samples { public class DecimalOp_Implicit { public static void Main() { long max = long.MaxValue, min = long.MinValue; Decimal d; d = max; Console.WriteLine("{0} is {1}", max, d); d = min; Console.WriteLine("{0} is {1}", min, d); } } }
A B C D E F G H I J K
The output is
L
9223372036854775807 is 9223372036854775807 -9223372036854775808 is -9223372036854775808
M N O
Decimal.op_Implicit(System.SByte) Method
P
[ILASM]
Q
.method public hidebysig static specialname decimal op_Implicit(int8 value)
R
public static implicit operator decimal(sbyte value)
[C#]
S
Summary
T
Performs an implicit conversion of a System.SByte value to System.Decimal. This member is not CLS-compliant.
U V
Parameters
W X Y
Parameter
Description
value
The System.SByte value to convert to System.Decimal.
Z
1234
Contents | Index
System
Decimal Structure op_Implicit() Method
Return Value A System.Decimal with the specified value. A
Example
B
using System;
C
namespace Samples { public class DecimalOp_Implicit { public static void Main() { sbyte max = sbyte.MaxValue, min = sbyte.MinValue; Decimal d; d = max; Console.WriteLine("{0} is {1}", max, d); d = min; Console.WriteLine("{0} is {1}", min, d); } } }
D E F G H I J K L M
The output is
N
127 is 127 -128 is -128
O P Q
Decimal.op_Implicit(System.Int16) Method
R
[ILASM]
.method public hidebysig static specialname decimal op_Implicit(int16 value)
S
[C#]
T
public static implicit operator decimal(short value)
U
Summary
V
Performs an implicit conversion of a System.Int16 value to System.Decimal.
W X
Parameters
Y
Parameter
Description
value
The System.Int16 value to convert to System.Decimal.
Z
1235
Contents | Index
Decimal Structure
System
op_Implicit() Method
Return Value A System.Decimal with the specified value. A
Example
B
using System;
C
namespace Samples { public class DecimalOp_Implicit { public static void Main() { short max = short.MaxValue, min = short.MinValue; Decimal d; d = max; Console.WriteLine("{0} is {1}", max, d); d = min; Console.WriteLine("{0} is {1}", min, d); } } }
D E F G H I J K L
The output is
M N
32767 is 32767 -32768 is -32768
O P Q
Decimal.op_Implicit(System.UInt32) Method
R
[ILASM]
.method public hidebysig static specialname decimal op_Implicit(unsigned int32 value)
S
[C#]
T
public static implicit operator decimal(uint value)
U
Summary
V
Performs an implicit conversion of a System.UInt32 value to System.Decimal. This member is not CLS-compliant.
W X
Parameters
Y Z
Parameter
Description
value
The System.UInt32 value to convert to System.Decimal.
1236
Contents | Index
System
Decimal Structure op_Implicit() Method
Return Value A System.Decimal with the specified value. A
Example
B
using System;
C
namespace Samples { public class DecimalOp_Implicit { public static void Main() { uint max = uint.MaxValue, min = uint.MinValue; Decimal d; d = max; Console.WriteLine("{0} is {1}", max, d); d = min; Console.WriteLine("{0} is {1}", min, d); } } }
D E F G H I J K L
The output is
M N
4294967295 is 4294967295 0 is 0
O P
Decimal.op_Implicit(System.UInt64) Method
Q
[ILASM]
R
.method public hidebysig static specialname decimal op_Implicit(unsigned int64 value)
S
[C#]
public static implicit operator decimal(ulong value)
T
Summary
U
Performs an implicit conversion of a System.UInt64 value to System.Decimal. This member is not CLS-compliant.
V W X
Parameters
Y
Parameter
Description
value
The System.UInt64 value to convert to System.Decimal.
Z
1237
Contents | Index
Decimal Structure
System
op_Implicit() Method
Return Value A System.Decimal with the specified value. A
Example
B
using System;
C
namespace Samples { public class DecimalOp_Implicit { public static void Main() { ulong max = ulong.MaxValue, min = ulong.MinValue; Decimal d; d = max; Console.WriteLine("{0} is {1}", max, d); d = min; Console.WriteLine("{0} is {1}", min, d); } } }
D E F G H I J K L M
The output is
N O
18446744073709551615 is 18446744073709551615 0 is 0
P Q R
Decimal.op_Implicit(System.UInt16) Method
S
[ILASM]
.method public hidebysig static specialname decimal op_Implicit(unsigned int16 value)
T
[C#]
public static implicit operator decimal(ushort value)
U V
Summary
W
Performs an implicit conversion of a System.UInt16 value to System.Decimal. This member is not CLS-compliant.
X Y Z
1238
Contents | Index
System
Decimal Structure op_Increment() Method
Parameters Parameter
Description
value
The System.UInt16 value to convert to System.Decimal.
A B C
Return Value
D
A System.Decimal with the specified value.
E F
Example
G
using System;
H
namespace Samples { public class DecimalOp_Implicit { public static void Main() { ushort max = ushort.MaxValue, min = ushort.MinValue; Decimal d; d = max; Console.WriteLine("{0} is {1}", max, d); d = min; Console.WriteLine("{0} is {1}", min, d); } } }
I J K L M N O P Q R
The output is
S T
65535 is 65535 0 is 0
U V
Decimal.op_Increment(System.Decimal) Method
W
[ILASM]
X
.method public hidebysig static specialname decimal op_Increment(decimal d)
Y
[C#]
public static decimal operator ++(decimal d)
Z
1239
Contents | Index
Decimal Structure
System
op_Increment() Method
Summary Returns the specified value incremented by one. A
Parameters
B C
Parameter
Description
D
d
A System.Decimal value.
E F
Return Value
G
The value returned by System.Decimal.Add(d, System.Decimal.One).
H
Exceptions
I J
Exception
Condition
System.OverflowException
The result is greater than System.Decimal.MaxValue or less than System.Decimal.MinValue.
K L M N
Example
O
using System;
P namespace Samples { public class DecimalOp_Increment { public static void Main() { try { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue; Console.WriteLine("Value: {0}, Incremented: {1}", one, ++one); Console.WriteLine("Value: {0}, Incremented: {1}", zero, ++zero); Console.WriteLine("Value: {0}, Incremented: {1}", minusOne, ++minusOne);
Q R S T U V W X Y Z
1240
Contents | Index
System
Decimal Structure op_Inequality() Method
Console.WriteLine("Value: {0}, Incremented: {1}", min, ++min); Console.WriteLine("Value: {0}, Incremented: {1}", max, ++max);
A
} catch(Exception e) { Console.WriteLine("Exception: {0}", e); }
B C D
} }
E
}
F
The output is
G H
Value: 1, Incremented: 2 Value: 0, Incremented: 1 Value: -1, Incremented: 0 Value: -79228162514264337593543950335, Incremented: -79228162514264337593543950334 Exception: System.OverflowException: Value was either too large or too small for a Decimal. at System.Decimal.Add(Decimal d1, Decimal d2) at System.Decimal.op_Increment(Decimal d) at Samples.DecimalOp_Increment.Main() in C:\Books\BCL\Samples\System\Decimal\ Op_Increment(System.Decimal)\Decimal.cs:line 24
I J K L M N O
Decimal.op_Inequality(System.Decimal, System.Decimal) Method
P
[ILASM]
Q
.method public hidebysig static specialname bool op_Inequality(decimal d1, decimal d2)
R
[C#]
S
public static bool operator !=(decimal d1, decimal d2)
T
Summary
U
Determines whether two decimals do not have the same value.
V W
Parameters
X
Parameter
Description
d1
The first System.Decimal to compare.
d2
The second System.Decimal to compare.
Y Z
1241
Contents | Index
Decimal Structure
System
op_LessThan() Method
Return Value true if System.Decimal.Compare(d1, d2) does not return zero; otherwise, false. A
Example
B
using System;
C
namespace Samples { public class DecimalOp_Inequality { public static void Main() { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue; Console.WriteLine("{0} != {1}: {2}", max, minusOne, max != minusOne); Console.WriteLine("{0} != {1}: {2}", max, zero, max != zero); Console.WriteLine("{0} != {1}: {2}", max, min, max != min); Console.WriteLine("{0} != {1}: {2}", max, one, max != one); Console.WriteLine("{0} != {1}: {2}", max, max, max != max); } } }
D E F G H I J K L M N O P Q
The output is
R
79228162514264337593543950335 79228162514264337593543950335 79228162514264337593543950335 79228162514264337593543950335 79228162514264337593543950335
S T U
!= != != != !=
-1: True 0: True -79228162514264337593543950335: True 1: True 79228162514264337593543950335: False
V W
Decimal.op_LessThan(System.Decimal, System.Decimal) Method
X
[ILASM]
Y
.method public hidebysig static specialname bool op_LessThan(decimal d1, decimal d2) [C#]
Z
public static bool operator <(decimal d1, decimal d2)
1242
Contents | Index
System
Decimal Structure op_LessThan() Method
Summary Determines whether one System.Decimal value is less than another System.Decimal value. A
Parameters
B C
Parameter
Description D
d1
The first System.Decimal to compare.
E
d2
The first System.Decimal to compare.
F G
Return Value
H
true if System.Decimal.Compare(d1, d2) returns a value that is less than zero; otherwise, false.
I J K
Example
L
using System; namespace Samples { public class DecimalOp_LessThan { public static void Main() { Decimal d1 = Decimal.MinValue; Decimal d2 = Decimal.MaxValue; Console.WriteLine("Is {0} less d1, d2, d1 < Console.WriteLine("Is {0} less d2, d1, d2 < Console.WriteLine("Is {0} less d1, d1, d1 < } } }
M N O P Q R
than {1}: {2}", d2); than {1}: {2}", d1); than {1}: {2}", d1);
S T U V W
The output is
X Y
Is -79228162514264337593543950335 less than 79228162514264337593543950335: True Is 79228162514264337593543950335 less than -79228162514264337593543950335: False Is -79228162514264337593543950335 less than -79228162514264337593543950335: False
Z
1243
Contents | Index
Decimal Structure
System
op_LessThanOrEqual() Method
Decimal.op_LessThanOrEqual(System.Decimal, System.Decimal) Method [ILASM]
A
.method public hidebysig static specialname bool op_LessThanOrEqual(decimal d1, decimal d2)
B
[C#]
public static bool operator <=(decimal d1, decimal d2)
C D
Summary
E
Determines whether one System.Decimal value is less than or equal to another System.Decimal value.
F
Parameters
G H
Parameter
Description
d1
The first System.Decimal to compare.
d2
The second System.Decimal to compare.
I J K L M
Return Value
N
true if System.Decimal.Compare(d1, d2) returns a value that is less than or equal to zero; otherwise, false.
O
Example
P
using System;
Q
namespace Samples { public class DecimalOp_LessThanOrEqual { public static void Main() { Decimal d1 = Decimal.MinValue; Decimal d2 = Decimal.MaxValue; Console.WriteLine("Is {0} less than or equal to {1}: {2}", d1, d2, d1 <= d2); Console.WriteLine("Is {0} less than or equal to {1}: {2}", d2, d1, d2 <= d1); Console.WriteLine("Is {0} less than or equal to {1}: {2}", d1, d1, d1 <= d1); } } }
R S T U V W X Y Z
1244
Contents | Index
System
Decimal Structure op_Modulus() Method
The output is Is -79228162514264337593543950335 less than or equal to 79228162514264337593543950335: True Is 79228162514264337593543950335 less than or equal to -79228162514264337593543950335: False Is -79228162514264337593543950335 less than or equal to -79228162514264337593543950335: True
A B C D E
Decimal.op_Modulus(System.Decimal, System.Decimal) Method
F
[ILASM]
G
.method public hidebysig static specialname decimal op_Modulus(decimal d1, decimal d2)
H
[C#]
public static decimal operator %(decimal d1, decimal d2)
I
Summary
J
Divides one System.Decimal value by another System.Decimal and returns the remainder.
K
Parameters
M
L
N
Parameter
Description
O
d1
The dividend.
P
d2
The divisor.
Q R S
Return Value
T
The value returned by System.Decimal.Remainder(d1, d2).
U
Exceptions Exception
V W
Condition
X System.DivideByZeroException
d2 is zero.
System.OverflowException
d1 divided by d2 is greater than System.Decimal.MaxValue or less than System.Decimal.MinValue.
Y Z
1245
Contents | Index
Decimal Structure
System
op_Modulus() Method
Example using System; namespace Samples { public class DecimalOp_Modulus { public static void Main() { try { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue, fortyTwo = 42; Console.WriteLine("{0} % {1}: {2}", max, minusOne, max % minusOne); Console.WriteLine("{0} % {1}: {2}", max, min, max % min); Console.WriteLine("{0} % {1}: {2}", max, one, max % one); Console.WriteLine("{0} % {1}: {2}", max, fortyTwo, max % fortyTwo); Console.WriteLine("{0} % {1}: {2}", one, zero, one % zero); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P Q R S T U
The output is
V
79228162514264337593543950335 % -1: 0 79228162514264337593543950335 % -79228162514264337593543950335: 0 79228162514264337593543950335 % 1: 0 79228162514264337593543950335 % 42: 21 Exception: System.DivideByZeroException: Attempted to divide by zero. at System.Decimal.Remainder(Decimal d1, Decimal d2) at System.Decimal.op_Modulus(Decimal d1, Decimal d2) at Samples.DecimalOp_Modulus.Main() in C:\Books\BCL\Samples\System\Decimal\ Op_Modulus(System.Decimal,System.Decimal)\Decimal.cs:line 25
W X Y Z
1246
Contents | Index
System
Decimal Structure op_Multiply() Method
Decimal.op_Multiply(System.Decimal, System.Decimal) Method [ILASM]
.method public hidebysig static specialname decimal op_Multiply(decimal d1, decimal d2)
A
[C#]
B
public static decimal operator *(decimal d1, decimal d2)
C
Summary
D
Returns the result of multiplying two System.Decimal values.
E F
Parameters
G
Parameter
Description
d1
The first operand.
d2
The second operand.
H I J K L
Return Value
M
The value returned by System.Decimal.Multiply(d1, d2).
N O
Exceptions
P
Exception
Condition
Q
The result is greater than System.Decimal.MaxValue or less than System.Decimal.MinValue.
R
System.OverflowException
S T
Example
U
using System;
V
namespace Samples { public class DecimalOp_Multiply { public static void Main() { try {
W X Y Z
1247
Contents | Index
Decimal Structure
System
op_Subtraction() Method
Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue, fortyTwo = 42; Console.WriteLine("{0} * {1}: {2}", max, minusOne, max * minusOne); Console.WriteLine("{0} * {1}: {2}", max, one, max * one); Console.WriteLine("{0} * {1}: {2}", one, fortyTwo, one * fortyTwo); Console.WriteLine("{0} * {1}: {2}", one, zero, one * zero); Console.WriteLine("{0} * {1}: {2}", max, min, max * min);
A B C D E F G H
} catch(Exception e) { Console.WriteLine("Exception: {0}", e); }
I J K }
L
} }
M
The output is
N O
79228162514264337593543950335 * -1: -79228162514264337593543950335 79228162514264337593543950335 * 1: 79228162514264337593543950335 1 * 42: 42 1 * 0: 0 Exception: System.OverflowException: Value was either too large or too small for a Decimal. at System.Decimal.Multiply(Decimal d1, Decimal d2) at System.Decimal.op_Multiply(Decimal d1, Decimal d2) at Samples.DecimalOp_Multiply.Main() in C:\Books\BCL\Samples\System\Decimal\ Op_Multiply(System.Decimal,System.Decimal)\Decimal.cs:line 25
P Q R S T U V W
Decimal.op_Subtraction(System.Decimal, System.Decimal) Method
X
[ILASM]
Y
.method public hidebysig static specialname decimal op_Subtraction(decimal d1, decimal d2)
Z
[C#]
public static decimal operator -(decimal d1, decimal d2)
1248
Contents | Index
System
Decimal Structure op_Subtraction() Method
Summary Subtracts one System.Decimal value from another. A
Parameters
B
Parameter
Description
C
d1
The left-side operand.
D
d2
The right-side operand.
E F G
Return Value
H
The value returned by System.Decimal.Subtract(d1, d2).
I
Exceptions
J K
Exception
Condition
System.OverflowException
The result is greater than System.Decimal.MaxValue or less than System.Decimal.MinValue.
L M N O
Example
P
using System;
Q namespace Samples { public class DecimalOp_Subtraction { public static void Main() { try { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue, fortyTwo = 42; Console.WriteLine("{0} - {1}: {2}", max, one, max - one); Console.WriteLine("{0} - {1}: {2}", one, fortyTwo, one - fortyTwo);
R S T U V W X Y Z
1249
Contents | Index
Decimal Structure
System
op_UnaryNegation() Method
Console.WriteLine("{0} - {1}: {2}", one, zero, one - zero); Console.WriteLine("{0} - {1}: {2}", minusOne, min, minusOne - min); Console.WriteLine("{0} - {1}: {2}", max, minusOne, max - minusOne);
A B
} catch(Exception e) { Console.WriteLine("Exception: {0}", e); }
C D E
} }
F }
G
The output is
H I
79228162514264337593543950335 - 1: 79228162514264337593543950334 1 - 42: -41 1 - 0: 1 -1 - -79228162514264337593543950335: 79228162514264337593543950334 Exception: System.OverflowException: Value was either too large or too small for a Decimal. at System.Decimal.Subtract(Decimal d1, Decimal d2) at System.Decimal.op_Subtraction(Decimal d1, Decimal d2) at Samples.DecimalOp_Subtraction.Main() in C:\Books\BCL\Samples\System\Decimal\ Op_Subtraction(System.Decimal,System.Decimal)\Decimal.cs:line 25
J K L M N O P
Decimal.op_UnaryNegation(System.Decimal) Method
Q
[ILASM]
R
.method public hidebysig static specialname decimal op_UnaryNegation(decimal d)
S
[C#]
public static decimal operator -(decimal d)
T U
Summary
V
Returns the specified value multiplied by negative one (–1).
W
Parameters
X Y
Parameter
Description
d
A System.Decimal value.
Z
1250
Contents | Index
System
Decimal Structure op_UnaryPlus() Method
Return Value The value returned by System.Decimal.Negate(d). A
Example
B
using System; namespace Samples { public class DecimalUnaryNegation { public static void Main() { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue; Console.WriteLine("Value: {0}, Negated: max, -max); Console.WriteLine("Value: {0}, Negated: one, -one); Console.WriteLine("Value: {0}, Negated: zero, -zero); Console.WriteLine("Value: {0}, Negated: minusOne, -minusOne); Console.WriteLine("Value: {0}, Negated: min, -min); } } }
C D E F G H I {1}",
J
{1}",
K L
{1}",
M {1}",
N
{1}",
O P Q R
The output is Value: Value: Value: Value: Value:
S
79228162514264337593543950335, Negated: -79228162514264337593543950335 1, Negated: -1 0, Negated: 0 -1, Negated: 1 -79228162514264337593543950335, Negated: 79228162514264337593543950335
T U V W X
Decimal.op_UnaryPlus(System.Decimal) Method
Y
[ILASM]
Z
.method public hidebysig static specialname decimal op_UnaryPlus(decimal d) [C#]
public static decimal operator +(decimal d)
1251
Contents | Index
Decimal Structure
System
op_UnaryPlus() Method
Summary Returns the specified value. A
Parameters
B C
Parameter
Description
D
d
A System.Decimal value.
E F
Return Value
G
Returns d.
H
Example
I
using System;
J
namespace Samples { public class DecimalUnaryPlus { public static void Main() { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue; Console.WriteLine("Value: {0}, after unary max, +max); Console.WriteLine("Value: {0}, after unary one, +one); Console.WriteLine("Value: {0}, after unary zero, +zero); Console.WriteLine("Value: {0}, after unary minusOne, +minusOne); Console.WriteLine("Value: {0}, after unary min, +min); } } }
K L M N O P Q R S T U V W X Y
plus: {1}", plus: {1}", plus: {1}", plus: {1}", plus: {1}",
Z
1252
Contents | Index
System
Decimal Structure Parse() Method
The output is Value: 79228162514264337593543950335, after unary plus: 79228162514264337593543950335 Value: 1, after unary plus: 1 Value: 0, after unary plus: 0 Value: -1, after unary plus: -1 Value: -79228162514264337593543950335, after unary plus: -79228162514264337593543950335
A B C D E
Decimal.Parse(System.String) Method
F
[ILASM]
G
.method public hidebysig static decimal Parse(string s)
H
[C#]
public static decimal Parse(string s)
I
Summary
J
Returns the specified System.String converted to a System.Decimal value.
K L
Parameters
M
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Number style, preserving scale.
N O P Q R
Return Value
S
The System.Decimal value obtained from s.
T
Description
U
This version of System.Decimal.Parse is equivalent to System.Decimal.Parse (s, System.Globalization.NumberStyles.Number, null). The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.] If necessary, the value of s is rounded using banker’s rounding. Any scale apparent in the string s is preserved unless the value is rounded or the value is zero (in which latter case the sign and scale will be 0). Hence the string “2.900” will be parsed to form the decimal with sign 0, coefficient 2900, and scale 3.
V W X Y Z
1253
Contents | Index
Decimal Structure
System
Parse() Method
Exceptions Exception
Condition
B
System.ArgumentNullException
s is a null reference.
C
System.FormatException
s is not in the correct format.
System.OverflowException
s represents a number greater than System.Decimal.MaxValue or less than System.Decimal.MinValue.
A
D E F G
Example
H
using System;
I namespace Samples { public class DecimalParse { public static void Main() { string s; try { s = Decimal.MaxValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Decimal.Parse(s)); s = "0"; Console.WriteLine("From String {0} yields {1}", s, Decimal.Parse(s)); s = Decimal.MinValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Decimal.Parse(s)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Decimal.Parse(s)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = String.Format("{0}1", Decimal.MaxValue.ToString()); Console.WriteLine("From String {0} yields {1}", s, Decimal.Parse(s));
J K L M N O P Q R S T U V W X Y Z
1254
Contents | Index
System
Decimal Structure Parse() Method
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A
}
B
}
C
}
D
The output is
E From String 79228162514264337593543950335 yields 79228162514264337593543950335 From String 0 yields 0 From String -79228162514264337593543950335 yields -79228162514264337593543950335 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseDecimal(String s, NumberStyles style, NumberFormatInfo info) at System.Decimal.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Decimal.Parse(String s) at Samples.DecimalParse.Main() in C:\Books\BCL\Samples\System\Decimal\ Parse(System.String)\Decimal.cs:line 22 Exception: System.OverflowException: Value was either too large or too small for a Decimal. at System.Number.ParseDecimal(String s, NumberStyles style, NumberFormatInfo info) at System.Decimal.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Decimal.Parse(String s) at Samples.DecimalParse.Main() in C:\Books\BCL\Samples\System\Decimal\ Parse(System.String)\Decimal.cs:line 32
F G H I J K L M N O P Q R
Decimal.Parse(System.String, System.Globalization.NumberStyles) Method
S
[ILASM]
T
.method public hidebysig static decimal Parse(string s, valuetype System.Globalization.NumberStyles style)
U
[C#]
public static decimal Parse(string s, NumberStyles style)
V W
Summary
X
Returns the specified System.String converted to a System.Decimal value.
Y Z
1255
Contents | Index
Decimal Structure
System
Parse() Method
Parameters Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style, preserving scale.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Number style.
A B C D E F G
Return Value
H
The System.Decimal value obtained from s.
I
Description
J
This version of System.Decimal.Parse is equivalent to System.Decimal.Parse(s, style, null). The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.] If necessary, the value of s is rounded using banker’s rounding.
K L M N O
Exceptions
P Q
Exception
Condition
S
System.ArgumentNullException
s is a null reference.
T
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.Decimal.MaxValue or less than System.Decimal.MinValue.
R
U V W X Y Z
1256
Contents | Index
System
Decimal Structure Parse() Method
Example using System; using System.Globalization;
A
namespace Samples { public class DecimalParse { public static void Main() { string s; try { s = "$0"; Console.WriteLine("From String {0} yields {1}", s, Decimal.Parse(s, NumberStyles.AllowCurrencySymbol)); s = String.Format("${0}", Decimal.MaxValue.ToString()); Console.WriteLine("From String {0} yields {1}", s, Decimal.Parse(s, NumberStyles.AllowCurrencySymbol)); s = String.Format("({0})", Decimal.MaxValue.ToString()); Console.WriteLine("From String {0} yields {1}", s, Decimal.Parse(s, NumberStyles.AllowParentheses)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Decimal.Parse(s, NumberStyles.Any)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = String.Format("{0}1", Decimal.MaxValue.ToString()); Console.WriteLine("From String {0} yields {1}", s, Decimal.Parse(s, NumberStyles.Any)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1257
Contents | Index
Decimal Structure
System
Parse() Method
The output is From String $0 yields 0 From String $79228162514264337593543950335 yields 79228162514264337593543950335 From String (79228162514264337593543950335) yields -79228162514264337593543950335 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseDecimal(String s, NumberStyles style, NumberFormatInfo info) at System.Decimal.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Decimal.Parse(String s, NumberStyles style) at Samples.DecimalParse.Main() in C:\Books\BCL\Samples\System\Decimal\ Parse(System.String,System.Globalization.NumberStyles)\Decimal.cs:line 29 Exception: System.OverflowException: Value was either too large or too small for a Decimal. at System.Number.ParseDecimal(String s, NumberStyles style, NumberFormatInfo info) at System.Decimal.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Decimal.Parse(String s, NumberStyles style) at Samples.DecimalParse.Main() in C:\Books\BCL\Samples\System\Decimal\ Parse(System.String,System.Globalization.NumberStyles)\Decimal.cs:line 41
A B C D E F G H I J K L
Decimal.Parse(System.String, System.Globalization.NumberStyles, System.IFormatProvider) Method
M N
[ILASM]
O
.method public hidebysig static decimal Parse(string s, valuetype System.Globalization.NumberStyles style, class System.IFormatProvider provider)
P
[C#]
Q
public static decimal Parse(string s, NumberStyles style, IFormatProvider provider)
R S
Summary
T
Returns the specified System.String converted to a System.Decimal value.
U V W X Y Z
1258
Contents | Index
System
Decimal Structure Parse() Method
Parameters Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style, preserving scale.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Number style.
A
provider
B C D E
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
F G H
Return Value
I
The System.Decimal value obtained from s.
J K
Description
L
The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. If necessary, the value of s is rounded using banker’s rounding.
M N O P
Exceptions
Q
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.Decimal.MaxValue or less than System.Decimal.MinValue.
R S T U V W X
Example
Y
using System; using System.Globalization;
Z
namespace Samples
1259
Contents | Index
Decimal Structure
System
Parse() Method
{ public class DecimalParse { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; string s = " ~0"; Console.WriteLine("From String {0} yields {1}", s, Decimal.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowLeadingSign, c)); s = "(1)"; Console.WriteLine("From String {0} yields {1}", s, Decimal.Parse(s, NumberStyles.AllowParentheses, c)); s = " !1 "; Console.WriteLine("From String {0} yields {1}", s, Decimal.Parse(s, NumberStyles.Any, c)); } }
A B C D E F G H I J K L M N O P
}
Q
The output is
R
From String ~0 yields 0 From String (1) yields -1 From String !1 yields -1
S T U V
Decimal.Parse(System.String, System.IFormatProvider) Method
W [ILASM]
X
.method public hidebysig static decimal Parse(string s, class System.IFormatProvider provider)
Y
[C#]
public static decimal Parse(string s, IFormatProvider provider)
Z
1260
Contents | Index
System
Decimal Structure Parse() Method
Summary Returns the specified System.String converted to a System.Decimal value. A
Parameters
B
Parameter
Description
C
A System.String containing the value to convert. The System.String is interpreted using the System.Globalization.NumberStyles.Number style, preserving scale.
D
s
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
E F G H I
Return Value
J
The System.Decimal value obtained from s.
K
Description
L
This version of System.Decimal.Parse is equivalent to System.Decimal.Parse(s, System.Globalization.NumberStyles.Number, provider). The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. If necessary, the value of s is rounded using banker’s rounding. Any scale apparent in the string s is preserved unless the value is rounded or the value is zero (in which latter case the sign and scale will be 0). Hence the string “2.900” will be parsed to form the decimal with sign 0, coefficient 2900, and scale 3.
M N O P Q R S T
Exceptions
U
Exception
Condition
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.Decimal.MaxValue or less than System.Decimal.MinValue.
V W X
System.ArgumentNullException
Y Z
s is a null reference.
1261
Contents | Index
Decimal Structure
System
Parse() Method
Example using System; using System.Globalization;
A namespace Samples { public class DecimalParse { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; try { s = "~0"; Console.WriteLine("From String {0} yields {1}", s, Decimal.Parse(s, c)); s = Decimal.MaxValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Decimal.Parse(s, c)); s = "!1"; Console.WriteLine("From String {0} yields {1}", s, Decimal.Parse(s, c)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Decimal.Parse(s, c)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = String.Format("{0}1", Decimal.MaxValue.ToString()); Console.WriteLine("From String {0} yields {1}", s, Decimal.Parse(s, c)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1262
Contents | Index
System
Decimal Structure Remainder() Method
The output is From String ~0 yields 0 From String 79228162514264337593543950335 yields 79228162514264337593543950335 From String !1 yields -1 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseDecimal(String s, NumberStyles style, NumberFormatInfo info) at System.Decimal.Parse(String s, IFormatProvider provider) at Samples.DecimalParse.Main() in C:\Books\BCL\Samples\System\Decimal\ Parse(System.String,System.IFormatProvider)\Decimal.cs:line 27 Exception: System.OverflowException: Value was either too large or too small for a Decimal. at System.Number.ParseDecimal(String s, NumberStyles style, NumberFormatInfo info) at System.Decimal.Parse(String s, IFormatProvider provider) at Samples.DecimalParse.Main() in C:\Books\BCL\Samples\System\Decimal\ Parse(System.String,System.IFormatProvider)\Decimal.cs:line 37
A B C D E F G H I J K
Decimal.Remainder(System.Decimal, System.Decimal) Method
L
[ILASM]
.method public hidebysig static decimal Remainder(decimal d1, decimal d2)
M
[C#]
N
public static decimal Remainder(decimal d1, decimal d2)
O
Summary
P
Computes the remainder after dividing two System.Decimal values.
Q R
Parameters
S
Parameter
Description
d1
The dividend.
d2
The divisor.
T U V W X
Return Value
Y
The remainder after dividing d1 by d2 to give an integer result. The sign of the result, if non-zero, is the same as the sign of d1, and the scale of the result is the larger of the scales of d1 and d2.
Z
1263
Contents | Index
Decimal Structure
System
Remainder() Method
For example, –10 % 3 gives –1, and 3.6 % 1.3 gives 1.0 (where % indicates the remainder operation). A
Exceptions
B C D
Exception
Condition
System.DivideByZeroException
d2 is zero.
System.OverflowException
d1 divided by d2 is greater than System.Decimal.MaxValue or less than System.Decimal.MinValue.
E F G H
Example
I
using System;
J namespace Samples { public class DecimalRemainder { public static void Main() { try { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue, fortyTwo = 42; Console.WriteLine("Decimal.Remainder({0}, {1}): {2}", max, one, Decimal.Remainder(max, minusOne)); Console.WriteLine("Decimal.Remainder({0}, {1}): {2}", max, minusOne, Decimal.Remainder(max, minusOne)); Console.WriteLine("Decimal.Remainder({0}, {1}): {2}", max, min, Decimal.Remainder(max, min)); Console.WriteLine("Decimal.Remainder({0}, {1}): {2}", max, fortyTwo, Decimal.Remainder(max, fortyTwo)); Console.WriteLine("Decimal.Remainder({0}, {1}): {2}", max, zero, Decimal.Remainder(max, zero));
K L M N O P Q R S T U V W X Y Z
1264
Contents | Index
System
Decimal Structure Round() Method
} catch(Exception e) { Console.WriteLine("Exception: {0}", e); }
A
}
B
}
C
}
D
The output is
E Decimal.Remainder(79228162514264337593543950335, 1): 0 Decimal.Remainder(79228162514264337593543950335, -1): 0 Decimal.Remainder(79228162514264337593543950335, -79228162514264337593543950335): 0 Decimal.Remainder(79228162514264337593543950335, 42): 21 Exception: System.DivideByZeroException: Attempted to divide by zero. at System.Decimal.Remainder(Decimal d1, Decimal d2) at Samples.DecimalRemainder.Main() in C:\Books\BCL\Samples\System\Decimal\ Remainder(System.Decimal,System.Decimal)\Decimal.cs:line 29
F G H I J K
Decimal.Round(System.Decimal, System.Int32) Method
L
[ILASM]
M
.method public hidebysig static decimal Round(decimal d, int32 decimals)
N
[C#]
O
public static decimal Round(decimal d, int decimals)
P
Summary
Q
Rounds a System.Decimal value to a specified number of decimal places.
R S
Parameters
T
Parameter
Description
d
The System.Decimal to round.
V
decimals
The number of decimal places to round to. 0 <= decimals <= 28.
W
U
X Y
Return Value
Z
The System.Decimal result of rounding d to decimals decimal places.
1265
Contents | Index
Decimal Structure
System
Round() Method
Description When d is exactly halfway between two rounded values, the result is the rounded value that has an even digit in the rightmost decimal position. For example, when rounded to two decimals, the value 2.345 becomes 2.34 and the value 2.355 becomes 2.36. [Note: This process is known as rounding half towards even, or banker’s rounding.] The scale of the result will be the smaller of decimals and the scale of d. [Note: The scale of d is never increased, so System.Decimal.Round cannot cause overflow.]
A B C D E
Exceptions
F G
Exception
Condition
H
System.ArgumentOutOfRangeException
decimals is not between 0 and 28, inclusive.
I J
Example
K
using System;
L
namespace Samples { public class DecimalRound { public static void Main() { Decimal d = 42.456456456456M; Console.WriteLine("Value is {0}", d); for(int i = 1; i < 10; i++) Console.WriteLine("Round to {0} places, {1}", d, Decimal.Round(d, i)); } } }
M N O P Q R S T U
The output is
V
Value Round Round Round Round Round Round Round Round Round
W X Y Z
is to to to to to to to to to
42.456456456456 42.456456456456 42.456456456456 42.456456456456 42.456456456456 42.456456456456 42.456456456456 42.456456456456 42.456456456456 42.456456456456
places, places, places, places, places, places, places, places, places,
42.5 42.46 42.456 42.4565 42.45646 42.456456 42.4564565 42.45645646 42.456456456
1266
Contents | Index
System
Decimal Structure Subtract() Method
Decimal.Subtract(System.Decimal, System.Decimal) Method [ILASM]
.method public hidebysig static decimal Subtract(decimal d1, decimal d2) [C#]
A
public static decimal Subtract(decimal d1, decimal d2)
B
Summary
C
Subtracts one System.Decimal value from another.
D E
Parameters
F
Parameter
Description
d1
The left-side operand.
d2
The right-side operand.
G H I J K
Return Value
L
A System.Decimal containing the result of subtracting d2 from d1. The scale of the result, before any rounding, is the larger of the scales of d1 and d2. For example, 1.1 – 2.22 gives –1.12, and 2.50 – 1 gives 1.50.
M N O
Exceptions
P
Exception
Condition
System.OverflowException
The result is greater than System.Decimal.MaxValue or less than System.Decimal.MinValue.
Q R S T
Example
U
using System;
V W
namespace Samples { public class DecimalSubtract { public static void Main() { try {
X Y Z
1267
Contents | Index
Decimal Structure
System
ToByte() Method
Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue; Console.WriteLine("{0} subtract {1}: {2}", max, one, Decimal.Subtract(max, one)); Console.WriteLine("{0} subtract {1}: {2}", one, max, Decimal.Subtract(one, max)); Console.WriteLine("{0} subtract {1}: {2}", zero, one, Decimal.Subtract(zero, one)); Console.WriteLine("{0} subtract {1}: {2}", minusOne, min, Decimal.Subtract(minusOne, min)); Console.WriteLine("{0} subtract {1}: {2}", max, minusOne, Decimal.Subtract(max, minusOne));
A B C D E F G H I
} catch(Exception e) { Console.WriteLine("Exception: {0}", e); }
J K L
} }
M }
N
The output is
O P
79228162514264337593543950335 subtract 1: 79228162514264337593543950334 1 subtract 79228162514264337593543950335: -79228162514264337593543950334 0 subtract 1: -1 -1 subtract -79228162514264337593543950335: 79228162514264337593543950334 Exception: System.OverflowException: Value was either too large or too small for a Decimal. at System.Decimal.Subtract(Decimal d1, Decimal d2) at Samples.DecimalSubtract.Main() in C:\Books\BCL\Samples\System\Decimal\ Subtract(System.Decimal,System.Decimal)\Decimal.cs:line 25
Q R S T U V W
Decimal.ToByte(System.Decimal) Method
X
[ILASM]
Y
.method public hidebysig static unsigned int8 ToByte(decimal value) [C#]
Z
public static byte ToByte(decimal value)
1268
Contents | Index
System
Decimal Structure ToDouble() Method
Summary Converts the value of the specified System.Decimal to the equivalent 8-bit unsigned integer. A
Parameters
B C
Parameter
Description
value
The System.Decimal value.
D E F
Return Value
G
An 8-bit unsigned integer equivalent to value.
H I
Description
J
Parameter value is rounded to the nearest integer value toward zero, and that result is returned.
K L
Exceptions
M
Exception
Condition
System.OverflowException
value is less than System.Byte.MinValue or greater than System.Byte.MaxValue.
N O P Q R
Decimal.ToDouble(System.Decimal) Method
S
[ILASM]
T
.method public hidebysig static float64 ToDouble(decimal d) [C#]
U
public static double ToDouble(decimal d)
V W
Summary
X
Converts the value of the specified System.Decimal to the equivalent double-precision floating-point number.
Y Z
1269
Contents | Index
Decimal Structure
System
ToInt16() Method
Parameters Parameter
Description
d
The System.Decimal value to convert.
A B C D
Return Value
E
A double-precision floating-point number equivalent to d.
F
Description
G
This operation can produce round-off errors because a double-precision floating-point number has fewer significant digits than a System.Decimal.
H I J
Decimal.ToInt16(System.Decimal) Method
K
[ILASM]
L
.method public hidebysig static int16 ToInt16(decimal value) [C#]
M
public static short ToInt16(decimal value)
N
Summary
O
Converts the value of the specified System.Decimal to the equivalent 16-bit signed integer.
P Q
Parameters
R S T
Parameter
Description
value
A System.Decimal value.
U V
Return Value
W
A 16-bit signed integer equivalent to value.
X Y Z
1270
Contents | Index
System
Decimal Structure ToInt32() Method
Exceptions Exception
Condition
System.OverflowException
value is less than System.Int16.MinValue or greater than System.Int16.MaxValue.
A B C D
Decimal.ToInt32(System.Decimal) Method
E
[ILASM]
F
.method public hidebysig static int32 ToInt32(decimal d)
G
[C#]
H
public static int ToInt32(decimal d)
I
Summary
J
Converts the value of the specified System.Decimal to the equivalent 32-bit signed integer.
K
Parameters
L M
Parameter
Description
d
The System.Decimal value to convert.
N O P
Return Value
Q
A 32-bit signed integer equivalent to the value of d.
R S
Description
T
The return value is the integral part of the decimal value; fractional digits are truncated.
U
Exceptions
V W
Exception
Condition X
System.OverflowException
d is less than System.Int32.MinValue or greater than System.Int32.MaxValue.
Y Z
1271
Contents | Index
Decimal Structure
System
ToInt64() Method
Decimal.ToInt64(System.Decimal) Method [ILASM]
.method public hidebysig static int64 ToInt64(decimal d)
A
[C#]
public static long ToInt64(decimal d)
B C
Summary
D
Converts the value of the specified System.Decimal to the equivalent 64-bit signed integer.
E
Parameters
F G
Parameter
Description
d
The System.Decimal value to convert.
H I J K
Return Value
L
A 64-bit signed integer equivalent to the value of d.
M
Description
N
The return value is the integral part of the decimal value; fractional digits are truncated.
O
Exceptions
P Q
Exception
Condition
System.OverflowException
d is less than System.Int64.MinValue or greater than System.Int64.MaxValue.
R S T U V
Decimal.ToOACurrency(System.Decimal) Method
W
[ILASM]
X
.method public hidebysig static int64 ToOACurrency(decimal value)
Y
public static long ToOACurrency(decimal value)
[C#]
Z
1272
Contents | Index
System
Decimal Structure ToSByte() Method
Summary Converts the specified System.Decimal value to the equivalent OLE Automation Currency value, which is contained in a 64-bit signed integer. A
Parameters Parameter
B C
Description
D
value
A System.Decimal value.
E F
Return Value
G
A 64-bit signed integer that contains the OLE Automation equivalent of value.
H I
Decimal.ToSByte(System.Decimal) Method
J
[ILASM]
K
.method public hidebysig static int8 ToSByte(decimal value)
L
[C#]
M
public static sbyte ToSByte(decimal value)
N
Summary
O
Converts the value of the specified System.Decimal to the equivalent 8-bit signed integer.
P
Parameters
Q
Parameter
Description
value
A System.Decimal value.
R S T U
Return Value
V
An 8-bit signed integer equivalent to value. This member is not CLS-compliant.
W
Exceptions
X
Exception
Condition
System.OverflowException
value is less than System.SByte.MinValue or greater than System.SByte.MaxValue.
Y Z
1273
Contents | Index
Decimal Structure
System
ToSingle() Method
Decimal.ToSingle(System.Decimal) Method [ILASM]
.method public hidebysig static float32 ToSingle(decimal d)
A
[C#]
B
public static float ToSingle(decimal d)
C
Summary
D
Converts the value of the specified System.Decimal to the equivalent single-precision floating-point number.
E F
Parameters
G H I
Parameter
Description
d
A System.Decimal value to convert.
J K
Return Value
L
A single-precision floating-point number equivalent to the value of d.
M
Description
N
This operation can produce round-off errors because a single-precision floating-point number has fewer significant digits than a System.Decimal.
O P Q
Decimal.ToString() Method
R
[ILASM]
S
.method public hidebysig virtual string ToString() [C#]
T
public override string ToString()
U
Summary
V
Returns a canonical System.String representation of the value of the current instance.
W X
Return Value
Y
A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the current system culture and preserves the scale of the number.
Z
1274
Contents | Index
System
Decimal Structure ToString() Method
Description This version of System.Decimal.ToString is equivalent to System.Decimal.ToString(null, null). [Note: The general format specifier formats the number in either fixed-point or exponential notation form, preserving the scale of the number. For a detailed description of the general format, see the System.IFormattable interface. This method overrides System.Object.ToString.]
A B C D
Example
E
using System;
F
namespace Samples { public class DecimalToString { public static void Main() { Decimal max = Decimal.MaxValue, min = Decimal.MinValue; Console.WriteLine("{0}.ToString() yields {1}", max, max.ToString()); Console.WriteLine("{0}.ToString() yields {1}", min, min.ToString()); } } }
G H I J K L M N O P
The output is
Q R
79228162514264337593543950335.ToString() yields 79228162514264337593543950335 -79228162514264337593543950335.ToString() yields -79228162514264337593543950335
S T
Decimal.ToString(System.String) Method
U
[ILASM]
V
.method public hidebysig instance string ToString(string format)
W
[C#]
public string ToString(string format)
X Y
Summary
Z
Returns a System.String representation of the value of the current instance.
1275
Contents | Index
Decimal Structure
System
ToString() Method
Parameters Parameter
Description
format
A System.String that specifies the format of the returned string. [Note: For a list of valid values, see System.Decimal.ToString(System.String, System.IFormatProvider).]
A B C D E
Return Value
F
A System.String representation of the current instance formatted as specified by format. The string takes into account the current system culture.
G H
Description
I
This version of System.Decimal.ToString is equivalent to System.Decimal.ToString(format, null). If format is a null reference, the general format specifier “G” is used.
J K L
Exceptions
M N O
Exception
Condition
System.FormatException
format is invalid.
P Q
Example
R
using System;
S
namespace Samples { public class DecimalToString { public static void Main() { Decimal max = Decimal.MaxValue, min = Decimal.MinValue; string[] formats = {"C","E","F","G","N","P"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\") yields {2}", max, f, max.ToString(f)); foreach(string f in formats)
T U V W X Y Z
1276
Contents | Index
System
Decimal Structure ToString() Method
Console.WriteLine("{0}.ToString(\"{1}\") yields {2}", min, f, min.ToString(f)); } }
A
}
B
The output is
C
79228162514264337593543950335.ToString("C") yields $79,228,162,514,264,337,593,543,950,335.00 79228162514264337593543950335.ToString("E") yields 7.922816E+028 79228162514264337593543950335.ToString("F") yields 79228162514264337593543950335.00 79228162514264337593543950335.ToString("G") yields 79228162514264337593543950335 79228162514264337593543950335.ToString("N") yields 79,228,162,514,264,337,593,543,950,335.00 79228162514264337593543950335.ToString("P") yields 7,922,816,251,426,433,759,354,395,033,500.00 % -79228162514264337593543950335.ToString("C") yields $79,228,162,514,264,337,593,543,950,335.00 -79228162514264337593543950335.ToString("E") yields -7.922816E+028 -79228162514264337593543950335.ToString("F") yields 79228162514264337593543950335.00 -79228162514264337593543950335.ToString("G") yields -79228162514264337593543950335 -79228162514264337593543950335.ToString("N") yields 79,228,162,514,264,337,593,543,950,335.00 -79228162514264337593543950335.ToString("P") yields 7,922,816,251,426,433,759,354,395,033,500.00 %
D E F G H I J K L M N O P Q
Decimal.ToString(System.String, System.IFormatProvider) Method
R
[ILASM]
S
.method public final hidebysig virtual string ToString(string format, class System.IFormatProvider provider)
T
[C#]
U
public string ToString(string format, IFormatProvider provider)
V
Summary
W
Returns a System.String representation of the value of the current instance.
X Y Z
1277
Contents | Index
Decimal Structure
System
ToString() Method
Parameters Parameter
Description
format
A System.String containing a character that specifies the format of the returned string, optionally followed by a non-negative integer that specifies the precision of the number in the returned System.String.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo instance containing culture-specific formatting information.
A B C D E F G
Return Value
H
A System.String representation of the current instance formatted as specified by format. The string takes into account the information in the System.Globalization.NumberFormatInfo instance supplied by provider.
I J K
Description
L
If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. The following table lists the characters that are valid for the format parameter.
M N O P
Format Characters
Description
Q
"C", "c"
Currency format.
"E", "e"
Exponential notation format.
"F", "f"
Fixed-point format.
U
"G", "g"
General format.
V
"N", "n"
Number format.
"P", "p"
Percent format.
R S T
W X Y
If format is a null reference, the general format specifier “G” is used. [Note: For a detailed description of formatting, see the System.IFormattable interface. This method is implemented to support the System.IFormattable interface.]
Z
1278
Contents | Index
System
Decimal Structure ToString() Method
Exceptions Exception
Condition
System.FormatException
format is invalid.
A B C
Example
D
using System; using System.Globalization;
E F
namespace Samples { public class DecimalToString { public static void Main() { Decimal max = Decimal.MaxValue, min = Decimal.MinValue; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; n.CurrencySymbol = "#"; string[] formats = {"C","E","F","G","N","P"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\",n) yields {2}", max, f, max.ToString(f, n)); foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\",n) yields {2}", min, f, min.ToString(f, n)); } } }
G H I J K L M N O P Q R S T U
The output is
V 79228162514264337593543950335.ToString("C",n) #79,228,162,514,264,337,593,543,950,335.00 79228162514264337593543950335.ToString("E",n) 79228162514264337593543950335.ToString("F",n) 79228162514264337593543950335.00 79228162514264337593543950335.ToString("G",n) 79228162514264337593543950335.ToString("N",n) 79,228,162,514,264,337,593,543,950,335.00
yields
W yields 7.922816E~028 yields
X Y
yields 79228162514264337593543950335 yields
Z
1279
Contents | Index
Decimal Structure
System
ToString() Method
79228162514264337593543950335.ToString("P",n) yields 7,922,816,251,426,433,759,354,395,033,500.00 % -79228162514264337593543950335.ToString("C",n) yields !#79,228,162,514,264,337,593,543,950,335.00 -79228162514264337593543950335.ToString("E",n) yields !7.922816E~028 -79228162514264337593543950335.ToString("F",n) yields !79228162514264337593543950335.00 -79228162514264337593543950335.ToString("G",n) yields !79228162514264337593543950335 -79228162514264337593543950335.ToString("N",n) yields !79,228,162,514,264,337,593,543,950,335.00 -79228162514264337593543950335.ToString("P",n) yields !7,922,816,251,426,433,759,354,395,033,500.00 %
A B C D E F G H
Decimal.ToString(System.IFormatProvider) Method
I [ILASM]
J
.method public final hidebysig virtual string ToString(class System.IFormatProvider provider)
K
[C#]
public string ToString(IFormatProvider provider)
L M
Summary
N
Returns a System.String representation of the value of the current instance.
O
Parameters
P Q
Parameter
Description
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
R S T U
Return Value
V
A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the formatting information in the System.Globalization.NumberFormatInfo instance supplied by provider.
W X Y
Description
Z
This version of System.Decimal.ToString is equivalent to System.Decimal.ToString(null, provider).
1280
Contents | Index
System
Decimal Structure ToUInt16() Method
If provider is null or if a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. [Note: The general format specifier formats the number in either fixed-point or exponential notation form. For a detailed description of the general format, see the System.IFormattable interface.]
A B
Example
C
using System; using System.Globalization;
D
namespace Samples { public class DecimalToString { public static void Main() { Decimal max = Decimal.MaxValue, min = Decimal.MinValue; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; Console.WriteLine("{0}.ToString yields {1}", max, max.ToString(c)); Console.WriteLine("{0}.ToString yields {1}", min, min.ToString(c)); } } }
F
E
G H I J K L M N O P Q
The output is
R
79228162514264337593543950335.ToString yields 79228162514264337593543950335 -79228162514264337593543950335.ToString yields !79228162514264337593543950335
S T U
Decimal.ToUInt16(System.Decimal) Method
V
[ILASM]
W
.method public hidebysig static unsigned int16 ToUInt16(decimal value) [C#]
X
public static ushort ToUInt16(decimal value)
Y
Summary
Z
Converts the value of the specified System.Decimal to the equivalent 16-bit unsigned integer. 1281
Contents | Index
Decimal Structure
System
ToUInt32() Method
Parameters Parameter
Description
value
A System.Decimal value to convert.
A B C D
Return Value
E
A 16-bit unsigned integer equivalent to the value of value.
F
Description
G
The return value is the integral part of the decimal value; fractional digits are truncated. This member is not CLS-compliant.
H I
Exceptions
J K
Exception
Condition
System.OverflowException
value is greater than System.UInt16.MaxValue or less than System.UInt16.MinValue.
L M N O P
Decimal.ToUInt32(System.Decimal) Method
Q
[ILASM]
.method public hidebysig static unsigned int32 ToUInt32(decimal d)
R
[C#]
public static uint ToUInt32(decimal d)
S T
Summary
U
Converts the value of the specified System.Decimal to the equivalent 32-bit unsigned integer.
V W
Parameters
X Y Z
Parameter
Description
d
A System.Decimal value to convert.
1282
Contents | Index
System
Decimal Structure ToUInt64() Method
Return Value A 32-bit unsigned integer equivalent to the value of d.
Description
A
The return value is the integral part of the decimal value; fractional digits are truncated. This member is not CLS-compliant.
B C D
Exceptions
E
Exception
Condition
System.OverflowException
d is negative or greater than System.UInt32.MaxValue.
F G H I
Decimal.ToUInt64(System.Decimal) Method
J
[ILASM]
K
.method public hidebysig static unsigned int64 ToUInt64(decimal d)
L
[C#]
M
public static ulong ToUInt64(decimal d)
N
Summary
O
Converts the value of the specified System.Decimal to the equivalent 64-bit unsigned integer.
P Q
Parameters
R
Parameter
Description
d
A System.Decimal value to convert.
S T U V
Return Value
W
A 64-bit unsigned integer equivalent to the value of d.
X
Description
Y
The return value is the integral part of the decimal value; fractional digits are truncated. This member is not CLS-compliant.
Z
1283
Contents | Index
Decimal Structure
System
Truncate() Method
Exceptions Exception
Condition
System.OverflowException
d is negative or greater than System.UInt64.MaxValue.
A B C D
Decimal.Truncate(System.Decimal) Method
E
[ILASM]
.method public hidebysig static decimal Truncate(decimal d)
F
[C#]
G
public static decimal Truncate(decimal d)
H
Summary
I
Rounds a System.Decimal value towards zero, to the closest integer value.
J
Parameters
K L M
Parameter
Description
d
The System.Decimal to truncate.
N O
Return Value
P
The System.Decimal result of truncating d. The scale of the result is 0.
Q
Example
R
using System;
S
namespace Samples { public class DecimalTruncate { public static void Main() { Decimal d1 = 42.4242m, d2 = -d1; Console.WriteLine("Value: {0}, Truncate: {1}", d1, Decimal.Truncate(d1)); Console.WriteLine("Value: {0}, Truncate: {1}", d2, Decimal.Truncate(d2)); } } }
T U V W X Y Z
1284
Contents | Index
System
Decimal Structure ToChar() Method
The output is Value: 42.4242, Truncate: 42 Value: -42.4242, Truncate: -42
A B
IConvertible.ToBoolean(System.IFormatProvider) Method
C
[ILASM]
D
.method private final hidebysig virtual bool System.IConvertible.ToBoolean(class System.IFormatProvider provider)
E
[C#]
F
bool IConvertible.ToBoolean(IFormatProvider provider)
G
Summary
H
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToBoolean.]
I J K
IConvertible.ToByte(System.IFormatProvider) Method
L
[ILASM]
M
.method private final hidebysig virtual unsigned int8 System.IConvertible.ToByte(class System.IFormatProvider provider)
N
[C#]
O
byte IConvertible.ToByte(IFormatProvider provider)
P
Summary
Q
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToByte.]
R S T
IConvertible.ToChar(System.IFormatProvider) Method
U
[ILASM]
V
.method private final hidebysig virtual valuetype System.Char System.IConvertible.ToChar(class System.IFormatProvider provider)
W
[C#]
X
char IConvertible.ToChar(IFormatProvider provider)
Y
Summary
Z
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToChar.] 1285
Contents | Index
Decimal Structure
System
ToDateTime() Method
IConvertible.ToDateTime(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual valuetype System.DateTime System.IConvertible.ToDateTime(class System.IFormatProvider provider)
B
[C#]
DateTime IConvertible.ToDateTime(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDateTime.]
F G H
IConvertible.ToDecimal(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual decimal System.IConvertible.ToDecimal(class System.IFormatProvider provider)
K
[C#]
decimal IConvertible.ToDecimal(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDecimal.]
O P Q
IConvertible.ToDouble(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual float64 System.IConvertible.ToDouble(class System.IFormatProvider provider)
T
[C#]
double IConvertible.ToDouble(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDouble.]
X Y Z
1286
Contents | Index
System
Decimal Structure ToInt64() Method
IConvertible.ToInt16(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual int16 System.IConvertible.ToInt16(class System.IFormatProvider provider)
A
[C#]
B
short IConvertible.ToInt16(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt16.]
E F G
IConvertible.ToInt32(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual int32 System.IConvertible.ToInt32(class System.IFormatProvider provider)
J
[C#]
K
int IConvertible.ToInt32(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt32.]
N O P
IConvertible.ToInt64(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual int64 System.IConvertible.ToInt64(class System.IFormatProvider provider)
S
[C#]
T
long IConvertible.ToInt64(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt64.]
W X Y Z
1287
Contents | Index
Decimal Structure
System
ToSByte() Method
IConvertible.ToSByte(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual int8 System.IConvertible.ToSByte(class System.IFormatProvider provider)
B
[C#]
sbyte IConvertible.ToSByte(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSByte.]
F G H
IConvertible.ToSingle(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual float32 System.IConvertible.ToSingle(class System.IFormatProvider provider)
K
[C#]
float IConvertible.ToSingle(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSingle.]
O P Q
IConvertible.ToType(System.Type, System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual object System.IConvertible.ToType(class System.Type type, class System.IFormatProvider provider)
T
[C#]
object IConvertible.ToType(Type type, IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToType.]
X Y Z
1288
Contents | Index
System
Decimal Structure ToUInt64() Method
IConvertible.ToUInt16(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual unsigned int16 System.IConvertible.ToUInt16(class System.IFormatProvider provider)
A
[C#]
B
ushort IConvertible.ToUInt16(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt16.] This member is not CLS-compliant.
E F G
IConvertible.ToUInt32(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual unsigned int32 System.IConvertible.ToUInt32(class System.IFormatProvider provider)
J
[C#]
K
uint IConvertible.ToUInt32(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt32.] This member is not CLS-compliant.
N O P
IConvertible.ToUInt64(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual unsigned int64 System.IConvertible.ToUInt64(class System.IFormatProvider provider)
S
[C#]
T
ulong IConvertible.ToUInt64(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt64.] This member is not CLS-compliant.
W X Y Z
1289
Contents | Index
System.Text Decoder
BCL
Object
A
Decoder
B
Summary
C
Converts blocks of bytes into blocks of characters, maintaining state across successive calls for reading from a System.IO.Stream.
D E
Type Summary
F
public abstract class Decoder { // Constructors protected Decoder ();
G H I
// Methods public abstract int GetCharCount (byte[] bytes, int index, int count); public abstract int GetChars (byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex);
J K L M N O
}
P
Description
Q
[Note: Following instantiation of a decoder, sequential blocks of bytes are converted into blocks of characters through calls to the System.Text.Decoder.GetChars method. The decoder maintains state between the conversions, allowing it to correctly decode a character whose bytes span multiple blocks. This greatly assists decoding streams of bytes into characters. An instance of a specific implementation of the System.Text.Decoder class is typically obtained through a call to the System.Text.Encoding.GetDecoder method of a System.Text.Encoding object.]
R S T U V W
Example
X
The following example demonstrates using the System.Text.UTF8Encoding implementation of the System.Text.Decoder class to convert two byte arrays to a character array, where one character’s bytes span multiple byte arrays. This demonstrates how to use a System.Text.Decoder in streaming-like situations.
Y Z
1290
Contents | Index
System.Text
Decoder GetCharCount() Method
using System; using System.Text; namespace Samples { public class DecoderSample { public static void Main() { byte[] b1 = { 0x41, 0x23, 0xe2 }; byte[] b2 = { 0x98, 0xa3 }; Decoder d = Encoding.UTF8.GetDecoder(); char[] chars = new char[3]; int i = d.GetChars(b1, 0, b1.Length, chars, 0); i += d.GetChars(b2, 0, b2.Length, chars, i); foreach(char c in chars) Console.Write("U+{0:x} ", (ushort)c); } } }
A B C D E F G H I J
The output is
K
U+41 U+23 U+2623
L M
Decoder() Constructor
N O
[ILASM] family rtspecialname specialname instance void .ctor() [C#] protected Decoder()
P Q R
Summary
S
Constructs a new instance of the System.Text.Decoder class.
T
Description
U
This constructor is called only by classes that inherit from the System.Text.Decoder class.
V W X
Decoder.GetCharCount(System.Byte[], System.Int32, System.Int32) Method
Y
[ILASM] .method public hidebysig virtual abstract int32 GetCharCount(class System.Byte[] bytes, int32 index, int32 count) [C#] public abstract int GetCharCount(byte[] bytes, int index, int count)
Z
1291
Contents | Index
Decoder
System.Text
GetCharCount() Method
Summary Determines the exact number of characters that will be produced by decoding the specified range of the specified array of bytes. A
Parameters
B C
Parameter
Description
bytes
A System.Byte array to decode.
F
index
A System.Int32 that specifies the first index in bytes to decode.
G
count
A System.Int32 that specifies the number elements in bytes to decode.
D E
H
Return Value
I
A System.Int32 containing the number of characters the next call to System.Text. Decoder.GetChars will produce if presented with the specified range of bytes. [Note: This value takes into account the state in which the current instance was left following the last call to System.Text.Decoder.GetChars. This contrasts with System.Text.Encoding.GetChars, which does not maintain state information across subsequent calls.]
J K L M N
How and When to Override
O
Override this method to return the appropriate value for a particular encoding.
P Q
Usage
R
Use this method to determine the appropriate size of a buffer to contain the decoded values.
S
Exceptions
T U
Exception
Condition
V
System.ArgumentNullException
bytes is null.
System.ArgumentOutOfRangeException
index < 0. -orcount < 0. -orindex and count do not specify a valid range in bytes (i.e., (index + count) > bytes.Length).
W X Y Z
1292
Contents | Index
System.Text
Decoder GetChars() Method
Decoder.GetChars(System.Byte[], System.Int32, System.Int32, System.Char[], System.Int32) Method [ILASM] .method public hidebysig virtual abstract int32 GetChars(class System.Byte[] bytes, int32 byteIndex, int32 byteCount, class System.Char[] chars, int32 charIndex) [C#] public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
A B C D E
Summary
F
Decodes the specified range of the specified array of bytes into the specified range of the specified array of characters for a particular encoding.
G H
Parameters
I J
Parameter
Description
bytes
A System.Byte array to decode.
byteIndex
A System.Int32 that specifies the first index of bytes from which to decode.
byteCount
A System.Int32 that specifies the number elements in bytes to decode.
N
chars
A System.Char array of characters to decode into.
O
charIndex
A System.Int32 that specifies the first index of chars to store the decoded bytes.
K L M
P Q R
Description
S
[Note: System.Text.Decoder.GetCharCount can be used to determine the exact number of characters that will be produced for a specified range of bytes. Alternatively, System.Text.Encoding.GetMaxCharCount of the System.Text.Encoding object that produced the current instance can be used to determine the maximum number of characters that may be produced for a specified number of bytes, regardless of the actual byte values.]
T U V W X
How and When to Override
Y
Override this method to decode the values of a System.Byte array for a particular encoding.
Z
1293
Contents | Index
Decoder
System.Text
GetChars() Method
Usage Use this method to decode the elements of a byte array for a particular encoding. A
Exceptions
B C
Exception
Condition
System.ArgumentException
chars does not contain sufficient space to store the decoded characters.
D E
bytes is null.
F System.ArgumentNullException
G
-orchars is null.
H
byteIndex < 0.
I
-or-
J
byteCount < 0.
K
-or-
L
System.ArgumentOutOfRangeException
M
charIndex < 0. -orbyteIndex and byteCount do not specify a valid range in bytes (i.e., (byteIndex + byteCount ) > bytes.Length).
N O
-orcharIndex > chars.Length.
P Q R S T U V W X Y Z
1294
Contents | Index
System Delegate
BCL
Object ICloneable
A
Delegate ISerializable MulticastDelegate
NotStandardized
NotStandardized
B
AsnyncCallback
C
EventHandler
D
ThreadStart
E
TimerCallback
F G
Summary
H
A class used to create types that invoke methods.
I
Type Summary
J
public abstract class Delegate : ICloneable, ISerializable { // Constructors MS CF protected Delegate (object target, string method); MS CF protected Delegate (Type target, string method);
K L M N
// Properties CF public MethodInfo Method { get; } CF public object Target { get; }
O P Q
// Methods CF public virtual object Clone (); CF public static Delegate Combine (Delegate[] delegates); public static Delegate Combine (Delegate a, Delegate b); MS protected virtual Delegate CombineImpl (Delegate d); CF public static Delegate CreateDelegate (Type type, object target, string method); MS CF public static Delegate CreateDelegate (Type type, object target, string method, bool ignoreCase); CF public static Delegate CreateDelegate (Type type, MethodInfo method); CF public static Delegate CreateDelegate (Type type, Type target, string method);
R S T U V W X Y Z
1295
Contents | Index
Delegate
System
Delegate Class
CF public object DynamicInvoke (object[] args); MS CF protected virtual object DynamicInvokeImpl (object[] args); public override bool Equals (object obj); public override int GetHashCode (); public virtual Delegate[] GetInvocationList (); MS CF protected virtual MethodInfo GetMethodImpl (); MS CF public virtual void GetObjectData (SerializationInfo info, StreamingContext context); public static bool operator ==(Delegate d1, Delegate d2); public static bool operator !=(Delegate d1, Delegate d2); public static Delegate Remove (Delegate source, Delegate value); CF 1.1 public static Delegate RemoveAll (Delegate source, Delegate value); MS protected virtual Delegate RemoveImpl (Delegate d); }
A B C D E F G H I J K
BA One important design point about delegates is that they are immutable. Notice that the Combine and Remove operations return a new instance. This immutability constraint is important to maintain the thread safety of delegates.
L M N
JR Programmers usually have a difficult time learning about delegates because
O
compilers typically offer abstractions over Delegate’s methods. For example, in C#, you can use the += and -= operators, which will call Delegate’s Combine and Remove methods, respectively.
P Q R
Description
S
Delegate types derive from the System.Delegate class. The declaration of a delegate type establishes a contract that specifies the signature of one or more methods. [Note: For an example of a delegate type declaration, see the examples at the end of this topic.] Delegate types are implicitly sealed: it is not permissible to derive a new type from a delegate type. [Note: The System.Delegate class is not considered a delegate type; it is a class used to derive delegate types.] [Note: For information on subclassing the Delegate class, see Partition II of the CLI Specification.] A delegate is an instance of a delegate type. A non-null delegate references an invocation list, which is made up of one or more entries. Each entry consists of a pair of values: a non-null method and a corresponding object, called the target. If the method is static, the corresponding target is null; otherwise the target is the instance on which the method is to be called.
T U V W X Y Z
1296
Contents | Index
System
Delegate Delegate Class
The signature of each method in the invocation list is required to exactly match the signature specified by the delegate’s type. When a delegate is invoked, the methods in the corresponding invocation list are invoked in the order in which they appear in that list. A delegate attempts to invoke every method in its invocation list, with duplicate methods being invoked once for each occurrence in that list. Delegates are immutable; once created, the invocation list of a delegate does not change. Combining operations, such as System.Delegate.Combine and System.Delegate.Remove, cannot alter existing delegates. Instead, such operations result in the return of either a new delegate that contains the results of the operation, an existing delegate, or the null value. [Note: A combining operation returns the null value when the result of the operation is an empty invocation list. A combining operation returns an existing delegate when the requested operation has no effect (for example, if an attempt is made to remove a nonexistent entry).] If an invoked method throws an exception, the method stops executing and the exception is passed back to the caller of the delegate. The delegate does not continue invoking methods from its invocation list. Catching the exception in the caller does not alter this behavior. It is possible that non-standard methods that implement combining operations allow the creation of delegates with different behavior. When this is the case, the non-standard methods are required to specify the behavior. When the signature of the methods invoked by a delegate includes a return value, the delegate returns the return value of the last element in the invocation list. When the signature includes a parameter that is passed by reference, the final value of the parameter is the result of every method in the invocation list executing sequentially and updating the parameter’s value.
A B C D E F G H I J K L M N O P
Example
Q
using System; namespace Samples { public delegate string MyDelegate(string s); public class MyClass { public static string StaticMethod(string s) { Console.WriteLine("StaticMethod(\"{0}\")", s); return(s.ToUpper()); } public string InstanceMethod(string s) { Console.WriteLine("InstanceMethod(\"{0}\")", s); return(s.ToLower()); } }
R S T U V W X Y Z
1297
Contents | Index
Delegate
System
Delegate() Constructor
public class DelegateSample { public static void Main() { MyClass m = new MyClass(); MyDelegate s = new MyDelegate(MyClass.StaticMethod); MyDelegate i = new MyDelegate(m.InstanceMethod); Console.WriteLine("Method is {0}", s.Method); Console.WriteLine("Method is {0}", i.Method); Console.WriteLine("Returns: {0}", s("Call 1")); Console.WriteLine("Returns: {0}", i("Call 2")); MyDelegate d = (MyDelegate) Delegate.Combine(s, i); Console.WriteLine("Returns: {0}", d("Call 3")); } }
A B C D E F G H I }
J K
The output is
L
Method is System.String StaticMethod(System.String) Method is System.String InstanceMethod(System.String) StaticMethod("Call 1") Returns: CALL 1 InstanceMethod("Call 2") Returns: call 2 StaticMethod("Call 3") InstanceMethod("Call 3") Returns: call 3
M N O P Q R S
Delegate(System.Object, System.String) Constructor
T [ILASM]
U
family rtspecialname specialname instance void .ctor(object target, string method)
V
[C#]
protected Delegate(object target, string method)
W X
Summary
Y
Initializes a delegate that invokes the specified instance method on the specified class instance.
Z
1298
Contents | Index
System
Delegate Delegate() Constructor
Parameters Parameter
Description
target
The class instance on which the delegate invokes method.
method
The name of the instance method that the delegate represents.
A B C D
Description
E
This constructor is called by a compiler-generated delegate type to create a delegate based on the name of an instance method and an instance of the class that defines that method. This constructor creates delegates for instance methods only. An instance method is a method that is associated with an instance of a class; a static method is a method that is associated with the class itself.
F G H I J
Exceptions
K
Exception
Condition
System.ArgumentNullException
target is null. -ormethod is null.
L M N O P
Permissions
Q
Permission
Description
System.Security.Permissions.ReflectionPermission
For enhancing security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions. ReflectionPermissionFlag.MemberAccess.
R S T U V W
Delegate(System.Type, System.String) Constructor
X
[ILASM]
Y
family rtspecialname specialname instance void .ctor(class System.Type target, string method)
Z
[C#]
protected Delegate(Type target, string method)
1299
Contents | Index
Delegate
System
Delegate() Constructor
Summary Initializes a delegate that invokes the specified static method from the specified class. A
Parameters
B C
Parameter
Description
D
target
The System.Type representing the class that defines method.
E
method
The name of the static method that the delegate represents.
F G
Description
H
This constructor is called by a compiler-generated delegate type to create a delegate based on the name of a static method and the System.Type representing the class that defines that method. This constructor creates delegates for static methods only. An instance method is a method that is associated with an instance of a class; a static method is a method that is associated with the class itself. To get the System.Type that represents a class, use the System.Type.GetType method with the fully qualified (including namespace) name of the class. For example, passing System.Threading.ThreadStart to System.Type.GetType returns a System.Type for the System.Threading.ThreadStart class.
I J K L M N O
Exceptions
P Q
Exception
Condition
System.ArgumentNullException
target is null. -ormethod is null.
R S T U
Permissions
V W
Permission
Description
System.Security.Permiss ions.ReflectionPermission
For enhancing security and performance when invoked latebound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
X Y Z
1300
Contents | Index
System
Delegate Method Property
Delegate.Method Property [ILASM] .property class System.Reflection.MethodInfo Method { public hidebysig specialname instance class System.Reflection.MethodInfo get_Method() } [C#] public MethodInfo Method { get; }
A B C
Summary
D
Gets the last method in a delegate’s invocation list.
E F
Description
G
This member must be implemented if the Reflection Library is present in the implementation.
H
Exceptions
I
Exception
Condition
System.MemberAccessException
The caller does not have the required permissions.
J K L M
Permissions
N
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to access type information. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
O P Q R S
Example
T
using System; namespace Samples { public delegate void MyDelegate(string s); public class MyClass { public static void StaticMethod(string s) { } public void InstanceMethod(string s) { }
U V W X Y Z
1301
Contents | Index
Delegate
System
Target Property
} public class DelegateMethod { public static void Main() { MyDelegate d1 = new MyDelegate(MyClass.StaticMethod); MyDelegate d2 = new MyDelegate(new MyClass().InstanceMethod); Console.WriteLine("Method is {0}", d1.Method); Console.WriteLine("Method is {0}", d2.Method); } }
A B C D E F }
G
The output is
H I
Method is Void StaticMethod(System.String) Method is Void InstanceMethod(System.String)
J K L
Delegate.Target Property
M
[ILASM] .property object Target { public hidebysig specialname instance object get_Target() } [C#] public object Target { get; }
N O P Q
Summary
R
Gets the last object upon which a delegate invokes an instance method.
S
Property Value
T
A System.Object instance, or null if the delegate invokes only static methods.
U V
Description
W
If the delegate invokes only static methods, this property returns null. If the delegate invokes one or more instance methods, this property returns the target of the last instance method/target pair in the invocation list.
X Y Z
1302
Contents | Index
System
Delegate Clone() Method
Example using System; namespace Samples { public delegate void MyDelegate(string s); public class MyClass { public static void StaticMethod(string s) { } public void InstanceMethod(string s) { } } public class DelegateTarget { public static void Main() { MyDelegate d1 = new MyDelegate(MyClass.StaticMethod); MyDelegate d2 = new MyDelegate(new MyClass().InstanceMethod); Console.WriteLine("Target is {0}", d1.Target); Console.WriteLine("Target is {0}", d2.Target); } } }
A B C D E F G H I J K L M N O
The output is
P
Target is Target is Samples.MyClass
Q R S
Delegate.Clone() Method
T
[ILASM] .method public hidebysig virtual object Clone() [C#] public virtual object Clone()
U V W
Summary
X
Creates a copy of the current instance.
Y Z
1303
Contents | Index
Delegate
System
Clone() Method
Description The System.Delegate.Clone method creates a new instance of the same type as the current instance and then copies the contents of each of the current instance’s non-static fields. [Note: This method is implemented to support the System.ICloneable interface.]
A B C
Behaviors
D
The returned object must have the exact same type and invocation list as the current instance.
E
Default
F
The default implementation of the System.Delegate.Clone method creates a new instance, which is the exact same type as the current instance, and then copies the contents of each of the current instance’s non-static fields. If the field is a value type, a bit-by-bit copy of the field is performed. If the field is a reference type, the object referenced by the field is not copied; instead, the returned object contains a copy of the reference. This behavior is identical to System.Object.MemberwiseClone.
G H I J K L
How and When to Override
M
Subclasses of System.Delegate should override System.Delegate.Clone to customize the way in which copies of the subclass are constructed.
N O
Example
P
using System; namespace Samples { public delegate string MyDelegate(string s); public class MyClass { public static string StaticMethod(string s) { Console.WriteLine("StaticMethod(\"{0}\")",s); return(s.ToUpper()); } public string InstanceMethod(string s) { Console.WriteLine("InstanceMethod(\"{0}\")",s); return(s.ToLower()); } } public class DelegateClone { public static void Main()
Q R S T U V W X Y Z
1304
Contents | Index
System
Delegate Combine() Method
{ MyDelegate d1 = new MyDelegate(MyClass.StaticMethod); MyDelegate d2 = (MyDelegate) d1.Clone(); Console.WriteLine("Returns: {0}", d2("Call 1")); MyDelegate d3 = new MyDelegate( new MyClass().InstanceMethod); d2 = (MyDelegate) d3.Clone(); Console.WriteLine("Returns: {0}", d2("Call 2"));
A B C D
}
E
}
F
}
G
The output is
H StaticMethod("Call 1") Returns: CALL 1 InstanceMethod("Call 2") Returns: call 2
I J K L
Delegate.Combine(System.Delegate[]) Method
M
[ILASM] .method public hidebysig static class System.Delegate Combine(class System.Delegate[] delegates) [C#] public static Delegate Combine(Delegate[] delegates)
N O P Q
Summary
R
Concatenates the invocation lists of the specified delegates.
S T
Parameters
U
Parameter
Description
V
delegates
An array of delegates of the exact same type.
W X Y
Return Value
Z
A new delegate, or null if delegates is null or has only null elements.
1305
Contents | Index
Delegate
System
Combine() Method
Description The invocation list of the returned delegate is constructed by concatenating the invocation lists of the delegates in delegates, in increasing subscript order. For example, consider the following situation, in which the elements of delegates have the following invocation lists (where En represents an entry in an invocation list, and null represents an empty invocation list): [0] = E1, [1] = null, [2] = E2 + E3, and [3] = E4 + E5 + E6. When these elements are combined, the resulting delegate contains the invocation list E1 + E2 + E3 + E4 + E5 + E6. Null elements in delegates are not included in the returned delegate. [Note: The invocation list of the returned delegate may contain duplicate methods.]
A B C D E F G
Exceptions
H I J
Exception
Condition
System.ArgumentException
The delegates in delegates are not of the same type.
K L
Example
M
using System; namespace Samples { public delegate string MyDelegate(string s); public class MyClass { public static string StaticMethod(string s) { Console.WriteLine("StaticMethod(\"{0}\")",s); return(s.ToUpper()); } public string InstanceMethod(string s) { Console.WriteLine("InstanceMethod(\"{0}\")",s); return(s.ToUpper()); } } public class DelegateCombine { public static void Main() { MyClass m = new MyClass(); Delegate[] a = new Delegate[2]; a[0] = new MyDelegate(MyClass.StaticMethod); a[1] = new MyDelegate(m.InstanceMethod);
N O P Q R S T U V W X Y Z
1306
Contents | Index
System
Delegate Combine() Method
MyDelegate d = (MyDelegate) Delegate.Combine(a); Console.WriteLine("Returns: {0}", d("After Combine()"));
A
} }
B
}
C
The output is
D E
StaticMethod("After Combine()") InstanceMethod("After Combine()") Returns: AFTER COMBINE()
F G H
Delegate.Combine(System.Delegate, System.Delegate) Method
I [ILASM] .method public hidebysig static class System.Delegate Combine(class System.Delegate a, class System.Delegate b) [C#] public static Delegate Combine(Delegate a, Delegate b)
J K L M
Summary
N
Concatenates the invocation lists of the specified delegates.
O
Parameters
P Q
Parameter
Description
a
The delegate whose invocation list will be first in the invocation list of the new delegate.
b
The delegate whose invocation list will be last in the invocation list of the new delegate.
R S T U V W
Return Value
X
A delegate, or null. The following table describes the value returned when a or b is null.
Y Z
1307
Contents | Index
Delegate
System
Combine() Method
a
b
Return Value
A
null
null
null
B
null
non-null
b
non-null
null
a
C D E
When a and b are non-null, this method returns a new delegate with the concatenated invocation lists of a and b.
F G
Description
H
Unless a or b is null, a and b are required to be the exact same type. Consider the following situation, in which D1, D2, D3, D4, and D5 are delegate instances of the same type, D1’s invocation list has one entry, E1, and D2’s invocation list has one entry, E2. Then, D3 = Combine(D1, D2) results in D3’s having an invocation list of E1 + E2. Then, D4 = Combine(D2, D1) results in D4’s having an invocation list of E2 + E1. Then, D5 = Combine(D3, D4) results in D5’s having an invocation list of E1 + E2 + E2 + E1. [Note: The invocation list of the returned delegate may contain duplicate methods. System.Delegate.Combine is useful for creating event handlers that call multiple methods each time an event occurs.]
I J K L M N O P
Exceptions
Q R
Exception
Condition
System.ArgumentException
a and b are not of the same type.
S T U
Example
V
using System; namespace Samples { public delegate string MyDelegate(string s); public class MyClass { public static string StaticMethod(string s) { Console.WriteLine("StaticMethod(\"{0}\")",s);
W X Y Z
1308
Contents | Index
System
Delegate CombineImpl() Method
return(s.ToUpper()); } public string InstanceMethod(string s) { Console.WriteLine("InstanceMethod(\"{0}\")",s); return(s.ToLower()); }
A B
} public class DelegateCombine { public static void Main() { MyClass m = new MyClass(); MyDelegate s = new MyDelegate(MyClass.StaticMethod); MyDelegate i = new MyDelegate(m.InstanceMethod); MyDelegate d = (MyDelegate) Delegate.Combine(s, i); Console.WriteLine("Returns: {0}", d("After Combine()")); } }
C D E F G H I J K L
}
M
The output is
N StaticMethod("After Combine()") InstanceMethod("After Combine()") Returns: after combine()
O P Q
Delegate.CombineImpl(System.Delegate) Method
R
[ILASM]
S
.method family hidebysig virtual class System.Delegate CombineImpl(class System.Delegate d)
T
[C#]
U
protected virtual Delegate CombineImpl(Delegate d)
V
Summary
W
Concatenates the invocation lists of the specified multicast (combinable) delegate and the current multicast (combinable) delegate.
X Y Z
1309
Contents | Index
Delegate
System
CombineImpl() Method
Parameters Parameter
Description
d
The multicast (combinable) delegate whose invocation list is to be appended to the end of the invocation list of the current multicast (combinable) delegate.
A B C D
Return Value
E
A new multicast (combinable) delegate with an invocation list that concatenates the invocation list of the current multicast (combinable) delegate and the invocation list of d or the current multicast (combinable) delegate, if d is null.
F G H
Description
I
This method applies only if the current delegate is multicast (combinable). The current implementation simply throws a System.MulticastNotSupportedException. The invocation list can contain duplicate entries; that is, entries that refer to the same method on the same object.
J K L
Exceptions
M N
Exception
Condition
System.MulticastNotSupportedException
Always thrown.
O P Q R
Permissions
S T
Permission
Description
System.Security.Permissions.ReflectionPermission
For enhancing security and performance when invoked latebound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
U V W X Y Z
1310
Contents | Index
System
Delegate CreateDelegate() Method
Delegate.CreateDelegate(System.Type, System.Object, System.String) Method [ILASM] .method public hidebysig static class System.Delegate CreateDelegate(class System.Type type, object target, string method) [C#] public static Delegate CreateDelegate(Type type, object target, string method)
A B C
Summary
D
Returns a new delegate with the specified target and instance method as its invocation list.
E F
Parameters
G
Parameter
Description
type
The System.Type of the delegate to return. This System.Type is required to derive from System.Delegate.
target
An instance of an object that implements method.
method
A System.String containing the name of the instance method to be invoked on target.
H I J K L M N
Return Value
O
A System.Delegate of type type that invokes method on target.
P Q
Description
R
[Note: This method is used to dynamically create delegates that invoke instance methods. To create a delegate that invokes static methods, see System.Delegate.CreateDelegate(System.Type, System.Type, System.String).] This member must be implemented if the Reflection Library is present in the implementation.
S T U V W X Y Z
1311
Contents | Index
Delegate
System
CreateDelegate() Method
Exceptions Exception
Condition
System.ArgumentNullException
type, target, or method is null.
A B C
type does not derive from System.Delegate.
D
-orSystem.ArgumentException
E
method is not an instance method. -or-
F
target does not implement method.
G System.MethodAccessException H
The caller does not have the required permission.
I
Permissions
J K
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to access type information. See System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
L M N O
Example
P
using System; namespace Samples { public delegate string MyDelegate(string s); public class MyClass { public string InstanceMethod(string s) { Console.WriteLine("InstanceMethod(\"{0}\")",s); return(s.ToUpper()); } } public class DelegateCreateDelegate { public static void Main() { MyClass m = new MyClass(); MyDelegate d = (MyDelegate) Delegate.CreateDelegate(
Q R S T U V W X Y Z
1312
Contents | Index
System
Delegate CreateDelegate() Method
typeof(MyDelegate), m, "InstanceMethod"); Console.WriteLine(d("Call 1"));
A
} }
B
}
C
The output is
D E
InstanceMethod("Call 1") CALL 1
F G
Delegate.CreateDelegate(System.Type, System.Object, System.String, System.Boolean) Method
H I
[ILASM] .method public hidebysig static class System.Delegate CreateDelegate(class System.Type type, object target, string method, bool ignoreCase) [C#] public static Delegate CreateDelegate(Type type, object target, string method, bool ignoreCase)
J K L M N
Summary
O
Creates a delegate of the specified type that represents the specified instance method to invoke on the specified class instance with the specified case sensitivity.
P Q
Parameters
R S
Parameter
Description
type
The System.Type of delegate to create.
target
The class instance on which method is invoked.
method
The name of the instance method that the delegate is to represent.
W
ignoreCase
A Boolean indicating whether to ignore the case when comparing the name of the method.
X
T U V
Y Z
1313
Contents | Index
Delegate
System
CreateDelegate() Method
Description This method creates delegates for instance methods only. An instance method is a method that is associated with an instance of a class; a static method is a method that is associated with the class itself. To get the System.Type that represents a class, use the System.Type.GetType method with the fully qualified (including namespace) name of the class. For example, passing System.Threading.ThreadStart to System.Type.GetType returns a System.Type for the System.Threading.ThreadStart class.
A B C D E
Exceptions
F G
Exception
Condition
H
type is null. I
-orSystem.ArgumentNullException
J
target is null.
K
-or-
L
method is null.
M
type does not inherit from either System.Delegate or System.MulticastDelegate.
System.ArgumentException
N O
-ormethod is not an instance method.
P Q R S
System.InvalidProgramException
The invoke method of type is not found.
System.MemberAccessException
The caller does not have access to the method represented by the delegate (for example, if the method is private).
System.MethodAccessException
method is outside the current assembly and the caller does not have System.Security.Permissions.ReflectionPermission for the assembly containing method.
T U V W X Y Z
1314
Contents | Index
System
Delegate CreateDelegate() Method
Permissions Permission
Description A
System.Security.Permissions.ReflectionPermissionFlag
For access to the method represented by the delegate, specifically MemberAccess.
B
D
System.Security.Permissions.ReflectionPermission
For enhancing security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions. ReflectionPermissionFlag.MemberAccess.
C
E F G H
Delegate.CreateDelegate(System.Type, System.Reflection.MethodInfo) Method
I
[ILASM] .method public hidebysig static class System.Delegate CreateDelegate(class System.Type type, class System.Reflection.MethodInfo method) [C#] public static Delegate CreateDelegate(Type type, MethodInfo method)
K
J
L M N
Summary
O
Returns a new delegate with the specified static method as its invocation list.
P Q
Parameters
R
Parameter
Description
type
The System.Type of System.Delegate to return. This System.Type is required to derive from System.Delegate.
U
method
A System.Reflection.MethodInfo that reflects a static method.
V
S T
W
Return Value
X
A System.Delegate of type type that invokes method.
Y Z
1315
Contents | Index
Delegate
System
CreateDelegate() Method
Description [Note: This method is used to dynamically create delegates that invoke static methods. To create a delegate that invokes instance methods, see System.Delegate.CreateDelegate(System.Type, System.Object, System.String).] This member must be implemented if the Reflection Library is present in the implementation.
A B C D
Exceptions
E F G
Exception
Condition
System.ArgumentNullException
type or method is null.
System.ArgumentException
type does not derive from System.Delegate. -ormethod does not reflect a static method.
System.ExecutionEngineException
The Invoke method of the type delegate was not found.
System.MethodAccessException
The caller does not have the required permission.
H I J K L M N
Permissions
O P
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to access type information. See System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
Q R S T
Example
U
using System; using System.Reflection; namespace Samples { public delegate string MyDelegate(string s); public class MyClass { public static string StaticMethod(string s) { Console.WriteLine("StaticMethod(\"{0}\")",s); return(s.ToUpper());
V W X Y Z
1316
Contents | Index
System
Delegate CreateDelegate() Method
} } public class DelegateCreateDelegate { public static void Main() { Type t = typeof(MyClass); Type[] args = new Type[]{typeof(string)}; MethodInfo m = t.GetMethod("StaticMethod", args); MyDelegate d = (MyDelegate) Delegate.CreateDelegate( typeof(MyDelegate), m); Console.WriteLine("Returns: {0}", d("Call 1")); } }
A B C D E F G H
}
I
The output is
J
StaticMethod("Call 1") Returns: CALL 1
K L M
Delegate.CreateDelegate(System.Type, System.Type, System.String) Method
N
[ILASM] .method public hidebysig static class System.Delegate CreateDelegate(class System.Type type, class System.Type target, string method) [C#] public static Delegate CreateDelegate(Type type, Type target, string method)
O P Q R
Summary
S
Returns a new delegate with the specified static method as its invocation list.
T
Parameters
U
Parameter
Description
type
The System.Type of delegate to return. This System.Type is required to derive from System.Delegate.
target
A System.Type representing the class that implements method.
method
A System.String containing the name of the static method implemented by target.
V W X Y Z
1317
Contents | Index
Delegate
System
CreateDelegate() Method
Return Value A System.Delegate of type type that invokes method. A
Description
B
[Note: This method is used to dynamically create delegates that invoke static methods. To create a delegate that invokes instance methods, see System.Delegate.CreateDelegate(System.Type, System.Object, System.String).] This member must be implemented if the Reflection Library is present in the implementation.
C D E F
Exceptions
G H
Exception
Condition
System.ArgumentNullException
type, target, or method is null.
I J
type does not derive from System.Delegate.
K
-or-
L System.ArgumentException M
method is not a static method. -or-
N
target does not implement method.
O
System.MethodAccessException
The caller does not have the required permission.
P Q
Permissions
R S
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to access type information. See System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
T U V W
Example
X
using System; namespace Samples { public delegate string MyDelegate(string s); public class MyClass {
Y Z
1318
Contents | Index
System
Delegate DynamicInvoke() Method
public static string StaticMethod(string s) { Console.WriteLine("StaticMethod(\"{0}\")",s); return(s.ToUpper()); }
A
} public class DelegateCreateDelegate { public static void Main() { MyDelegate d = (MyDelegate) Delegate.CreateDelegate( typeof(MyDelegate), typeof(MyClass), "StaticMethod"); Console.WriteLine(d("Call 1")); } }
B C D E F G H I
}
J K
The output is
L
StaticMethod("Call 1") CALL 1
M N O
Delegate.DynamicInvoke(System.Object[]) Method
P
[ILASM] .method public hidebysig instance object DynamicInvoke(class System.Object[] args) [C#] public object DynamicInvoke(object[] args)
Q R S
Summary
T
Causes a delegate to invoke the methods in its invocation list using the specified arguments.
U V
Parameters
W
Parameter
Description
args
An array of System.Object instances that are to be passed to the methods in the invocation list of the current instance. Specify null if the methods invoked by the current instance do not take arguments.
X Y Z
1319
Contents | Index
Delegate
System
DynamicInvoke() Method
Return Value The System.Object returned by the last method in the invocation list of the current instance. A B
Description
C
This member must be implemented if the Reflection Library is present in the implementation.
D
Exceptions
E F
Exception
Condition
System.ArgumentException
The type of one or more elements in args is invalid as a parameter to the methods implemented by the current instance.
G H I
The caller does not have the required permissions.
J System.MethodAccessException
K L M
-orThe number, order, or type of parameters listed in args is invalid. A method in the invocation list of the current instance is an instance method and its target object is null.
N System.Reflection.Target Exception
O P
-orA method in the invocation list of the current instance was invoked on a target object or a class that does not implement it.
Q R S T U
System.Reflection.Target ParameterCountException
The number of elements in args is not equal to the number of parameters required by the methods invoked by the current instance.
System.Reflection.Target InvocationException
A method in the invocation list of the current instance threw an exception.
V
Example
W
using System; namespace Samples { public delegate string MyDelegate(string s); public class MyClass { public static string StaticMethod(string s)
X Y Z
1320
Contents | Index
System
Delegate DynamicInvokeImpl() Method
{ Console.WriteLine("StaticMethod(\"{0}\")",s); return(s.ToUpper()); } } public class DelegateDynamicInvoke { public static void Main() { MyDelegate d = (MyDelegate) Delegate.CreateDelegate( typeof(MyDelegate), typeof(MyClass), "StaticMethod"); string[] args = {"Call 1"}; Console.WriteLine(d.DynamicInvoke(args)); } }
A B C D E F G H I
}
J K
The output is
L
StaticMethod("Call 1") CALL 1
M N
Delegate.DynamicInvokeImpl(System.Object[]) Method
O
[ILASM] .method family hidebysig virtual object DynamicInvokeImpl(class System.Object[] args) [C#] protected virtual object DynamicInvokeImpl(object[] args)
P Q R S
Summary
T
Dynamically invokes (late-bound) the method represented by the current delegate.
U V W X Y Z
1321
Contents | Index
Delegate
System
DynamicInvokeImpl() Method
Parameters Parameter
Description
A
An array of objects that are the arguments to pass to the method represented by the current delegate.
B C
args
-ornull, if the method represented by the current delegate does not require arguments.
D E F
Return Value
G
The object returned by the method represented by the delegate.
H I
Description
J
This method implements the System.Delegate.DynamicInvoke method.
K
Exceptions
L M
Exception
Condition
N
The caller does not have access to the method represented by the delegate (for example, if the method is private).
O P
System.MemberAccessException
Q
-orThe number, order, or type of parameters listed in args is invalid.
R S
The method represented by the delegate is an instance method and the target object is null.
T
System.Reflection.TargetException
U
-orThe method represented by the delegate is invoked on an object or a class that does not support it.
V W
System.Reflection.TargetInvocationException
X
One of the encapsulated methods throws an exception.
Y Z
1322
Contents | Index
System
Delegate Equals() Method
Permissions Permission
Description
System.Security.Permissions.ReflectionPermission
For enhancing security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions. ReflectionPermissionFlag.MemberAccess.
A B C D E F
Delegate.Equals(System.Object) Method
G
[ILASM] .method public hidebysig virtual bool Equals(object obj) [C#] public override bool Equals(object obj)
H
Summary
K
Determines whether the specified object is equal to the current instance.
L
I J
M
Parameters
N
Parameter
Description
obj
The System.Object to compare with the current instance.
O P Q R
Return Value
S
true if obj is equal to the current instance; otherwise false.
T
Description
U
Two delegates are equal if they are not null and are of the exact same type, their invocation lists contain the same number of elements, and every element in the invocation list of the first delegate is equal to the element in the corresponding position in the invocation list of the second delegate. Two invocation list elements are equal if they invoke the same instance method on the same target instance, or they invoke the same static method. [Note: This method overrides System.Object.Equals.]
V W X Y Z
1323
Contents | Index
Delegate
System
GetHashCode() Method
Example using System; namespace Samples { public delegate void MyDelegate(string s); public class MyClass { public static void StaticMethod(string s) { } public void InstanceMethod(string s) { } } public class DelegateEquals { public static void Main() { MyDelegate d1 = new MyDelegate(MyClass.StaticMethod); MyDelegate d2 = (MyDelegate) d1.Clone(); if(d1.Equals(d2)) Console.WriteLine("d1 is equal to d2"); else Console.WriteLine("d1 is not equal to d2"); MyDelegate d3 = new MyDelegate(new MyClass().InstanceMethod); if(d1.Equals(d3)) Console.WriteLine("d1 is equal to d3"); else Console.WriteLine("d1 is not equal to d3"); } } }
A B C D E F G H I J K L M N O P Q R S T
The output is
U d1 is equal to d2 d1 is not equal to d3
V W X
Delegate.GetHashCode() Method
Y
[ILASM] .method public hidebysig virtual int32 GetHashCode() [C#] public override int GetHashCode()
Z
1324
Contents | Index
System
Delegate GetHashCode() Method
Summary Generates a hash code for the current instance.
Description
A
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
B C D
Example
E
using System; namespace Samples { public delegate void MyDelegate(string s); class MyClass { public static void StaticMethod(string s) { } public void InstanceMethod(string s) { } } public class DelegateGetHashCode { public static void Main() { MyDelegate d1 = new MyDelegate(MyClass.StaticMethod); MyDelegate d2 = (MyDelegate) d1.Clone(); MyDelegate d3 = new MyDelegate( new MyClass().InstanceMethod); Console.WriteLine("{0} hash code is: {1}", d1, d1.GetHashCode()); Console.WriteLine("{0} hash code is: {1}", d2, d2.GetHashCode()); Console.WriteLine("{0} hash code is: {1}", d3, d3.GetHashCode()); } } }
F G H I J K L M N O P Q R S T U V W X Y
The output is
Z Samples.MyDelegate hash code is: 4083947 Samples.MyDelegate hash code is: 4083947 Samples.MyDelegate hash code is: 4083963
1325
Contents | Index
Delegate
System
GetInvocationList() Method
Delegate.GetInvocationList() Method [ILASM] .method public hidebysig virtual class System.Delegate[] GetInvocationList() [C#] public virtual Delegate[] GetInvocationList()
A B C
Summary
D
Returns the invocation list of the current delegate.
E F
Return Value
G
An ordered set of System.Delegate instances whose invocation lists collectively match those of the current delegate.
H I
Behaviors
J
The array contains a set of delegates, each having an invocation list of one entry. Invoking these delegates sequentially, in the order in which they appear in the array, produces the same results as invoking the current delegate.
K L M
How and When to Override
N
Override System.Delegate.GetInvocationList when subclassing Delegate.
O
Example
P
using System; namespace Samples { public delegate string MyDelegate(string s); public class MyClass { public static string StaticMethod(string s) { Console.WriteLine("StaticMethod(\"{0}\")",s); return(s.ToUpper()); } public string InstanceMethod(string s) { Console.WriteLine("InstanceMethod(\"{0}\")",s); return(s.ToLower()); } } public class DelegateGetInvocationList {
Q R S T U V W X Y Z
1326
Contents | Index
System
Delegate GetMethodImpl() Method
public static void Main() { MyClass m = new MyClass(); Delegate[] a = new Delegate[2]; a[0] = new MyDelegate(MyClass.StaticMethod); a[1] = new MyDelegate(m.InstanceMethod); MyDelegate c = (MyDelegate) Delegate.Combine(a); Delegate[] delegates = c.GetInvocationList(); foreach(MyDelegate d in delegates) Console.WriteLine("Returns: {0}", d("Call")); }
A B C D E F
} }
G
The output is
H I
StaticMethod("Call") Returns: CALL InstanceMethod("Call") Returns: call
J K L M
Delegate.GetMethodImpl() Method
N [ILASM] .method family hidebysig virtual class System.Reflection.MethodInfo GetMethodImpl() [C#] protected virtual MethodInfo GetMethodImpl()
O P Q R
Summary
S
Gets the static method represented by the current delegate.
T
Description
U
This method applies only if the current delegate represents a static method.
V W
Exceptions
X
Exception
Condition
System.MemberAccessException
The caller does not have access to the method represented by the delegate (for example, if the method is private).
Y Z
1327
Contents | Index
Delegate
System
GetObjectData() Method
Permissions Permission
Description
System.Security.Permissions.ReflectionPermission
For enhancing security and performance when invoked latebound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
A B C D E F
Delegate.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Method
G H
[ILASM] .method public hidebysig virtual void GetObjectData(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context) [C#] public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
I J K L M
Summary
N
Implements the System.Runtime.Serialization.ISerializable interface and returns the data needed to serialize the delegate.
O P
Parameters
Q R
Parameter
Description
info
A System.Runtime.Serialization.SerializationInfo containing information required to serialize the delegate.
context
A System.Runtime.Serialization.StreamingContext containing the source and destination of the serialized stream associated with the delegate.
S T U V W
Exceptions
X Y
Exception
Condition
System.ArgumentNullException
info is null.
Z
1328
Contents | Index
System
Delegate op_Equality() Method
Permissions Permission
Description
System.Security.Permissions.ReflectionPermission
For enhancing security and performance when invoked latebound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
A B C D E F
Delegate.op_Equality(System.Delegate, System.Delegate) Method
G
[ILASM] .method public hidebysig static specialname bool op_Equality(class System.Delegate d1, class System.Delegate d2) [C#] public static bool operator ==(Delegate d1, Delegate d2)
H I J K
Summary
L
Determines whether the specified delegates are equal.
M N
Parameters
O
Parameter
Description
P
d1
The first delegate to compare.
Q
d2
The second delegate to compare.
R S T
Return Value
U
true if d1.Equals(d2) returns true; otherwise, false.
V
Description
W
[Note: See System.Delegate.Equals.]
X Y Z
1329
Contents | Index
Delegate
System
op_Inequality() Method
Example using System; namespace Samples { public delegate void MyDelegate(string s); public class MyClass { public static void StaticMethod(string s) { } public void InstanceMethod(string s) { } } public class DelegateOperatorEquality { public static void Main() { MyDelegate d1 = new MyDelegate(MyClass.StaticMethod); MyDelegate d2 = (MyDelegate) d1.Clone(); if(d1 == d2) Console.WriteLine("d1 is equal to d2"); else Console.WriteLine("d1 is not equal to d2"); MyDelegate d3 = new MyDelegate(new MyClass().InstanceMethod); if(d1 == d3) Console.WriteLine("d1 is equal to d3"); else Console.WriteLine("d1 is not equal to d3"); } } }
A B C D E F G H I J K L M N O P Q R S
The output is
T U
d1 is equal to d2 d1 is not equal to d3
V W X
Delegate.op_Inequality(System.Delegate, System.Delegate) Method
Y
[ILASM] .method public hidebysig static specialname bool op_Inequality(class System.Delegate d1, class System.Delegate d2) [C#] public static bool operator !=(Delegate d1, Delegate d2)
Z
1330
Contents | Index
System
Delegate op_Inequality() Method
Summary Determines whether the specified delegates are not equal. A
Parameters
B
Parameter
Description
C
d1
The first delegate to compare.
D
d2
The second delegate to compare.
E F G
Return Value
H
true if d1.Equals(d2) returns false; otherwise, false.
I
Description
J
[Note: See System.Delegate.Equals.]
K L
Example
M
using System; namespace Samples { public delegate void MyDelegate(string s); public class MyClass { public static void StaticMethod(string s) { } public void InstanceMethod(string s) { } } public class DelegateOperatorInequality { public static void Main() { MyDelegate d1 = new MyDelegate(MyClass.StaticMethod); MyDelegate d2 = (MyDelegate) d1.Clone(); if(d1 != d2) Console.WriteLine("d1 is not equal to d2"); else Console.WriteLine("d1 is equal to d2");
N O P Q R S T U V W X Y Z
1331
Contents | Index
Delegate
System
Remove() Method
MyDelegate d3 = new MyDelegate( new MyClass().InstanceMethod); if(d1 != d3) Console.WriteLine("d1 is not equal to d3"); else Console.WriteLine("d1 is equal to d3");
A B }
C
} }
D
The output is
E F
d1 is equal to d2 d1 is not equal to d3
G H
Delegate.Remove(System.Delegate, System.Delegate) Method
I J
[ILASM] .method public hidebysig static class System.Delegate Remove(class System.Delegate source, class System.Delegate value) [C#] public static Delegate Remove(Delegate source, Delegate value)
K L M N
Summary
O
Removes the invocation list of a System.Delegate from the invocation list of another delegate.
P Q
Parameters
R S T
Parameter
Description
source
The delegate from which to remove the invocation list of value.
value
The delegate that supplies the invocation list to remove from source.
U V W
Return Value
X
Returns a new delegate, source, or null. If source and value are not null, are not equal, and the invocation list of value is contained in the invocation list of source, returns a new delegate with the invocation list of value removed from the invocation list of source. If the invocation lists of source and value
Y Z
1332
Contents | Index
System
Delegate Remove() Method
are equal, returns null. If the invocation list of value is not found in the invocation list of source, returns source. The following table describes the value returned when source or value is null. A B
source
value
Return Value
null
null
null
D
null
non-null
null
E
non-null
null
source
C
F G H
Description
I
The invocation list of value is required to be an exact match of a contiguous set of elements in the invocation list of source. If the invocation list of value occurs more than once in the invocation list of source, the last occurrence is removed.
J K L
Example
M
using System; namespace Samples { public delegate string MyDelegate(string s); public class MyClass { public static string StaticMethod(string s) { Console.WriteLine("StaticMethod(\"{0}\")",s); return(s.ToUpper()); } public string InstanceMethod(string s) { Console.WriteLine("InstanceMethod(\"{0}\")",s); return(s.ToLower()); } } public class DelegateRemove { public static void Main() { MyClass m = new MyClass(); MyDelegate s = new MyDelegate(MyClass.StaticMethod); MyDelegate i = new MyDelegate(m.InstanceMethod);
N O P Q R S T U V W X Y Z
1333
Contents | Index
Delegate
System
RemoveAll() Method
MyDelegate d1 = (MyDelegate) Delegate.Combine(s, i); Console.WriteLine("Returns: {0}", d1("After Combine()")); MyDelegate d2 = (MyDelegate) Delegate.Remove(d1, i); Console.WriteLine("Returns: {0}", d2("After Remove()"));
A B }
C
} }
D
The output is
E F
StaticMethod("After Combine()") InstanceMethod("After Combine()") Returns: after combine() StaticMethod("After Remove()") Returns: AFTER REMOVE()
G H I J K
Delegate.RemoveAll(System.Delegate, System.Delegate) Method
L
[ILASM] .method public hidebysig static class System.Delegate RemoveAll(class System.Delegate source, class System.Delegate value) [C#] public static Delegate RemoveAll(Delegate source, Delegate value)
M N O P
Summary
Q
Removes all matching occurrences of the invocation list of a System.Delegate from the invocation list of another delegate.
R S
Parameters
T U V
Parameter
Description
source
The delegate from which to remove all matching occurrences of the invocation list of value.
value
The delegate that supplies the invocation list to remove from source.
W X Y Z
Return Value Returns a new delegate, source, or null.
1334
Contents | Index
System
Delegate RemoveImpl() Method
If source and value are not null, are not equal, and the invocation list of value is contained in the invocation list of source, returns a new delegate with all matching occurrences of the invocation list of value removed from the invocation list of source. If the invocation lists of source and value are equal, or if source contains only a succession of invocation lists equal to value, returns null. If the invocation list of value is not found in the invocation list of source, returns source. The following table describes the value returned when source or value is null.
A B C D E
source
value
Return Value
null
null
null
G
null
non-null
null
H
non-null
null
source
I
F
J K
Description
L
The invocation list of value is required to be an exact match of a contiguous set of elements in the invocation list of source. If the invocation list of value occurs more than once in the invocation list of source, all occurrences are removed.
M N O
Delegate.RemoveImpl(System.Delegate) Method
P
[ILASM]
Q
.method family hidebysig virtual class System.Delegate RemoveImpl(class System.Delegate d)
R
[C#]
S
protected virtual Delegate RemoveImpl(Delegate d)
T
Summary
U
Removes the invocation list of a delegate from the invocation list of another delegate.
V W
Parameters
X
Parameter
Description
d
The delegate that supplies the invocation list to remove from the invocation list of the current delegate.
Y Z
1335
Contents | Index
Delegate
System
RemoveImpl() Method
Return Value A new delegate with an invocation list formed by taking the invocation list of the current delegate and removing the invocation list of d, if the invocation list of d is found within the current delegate’s invocation list. The current delegate, if d is null, or if the invocation list of d is not found within the current delegate’s invocation list. null, if the invocation list of d is equal to the current delegate’s invocation list.
A B C D
Description
E
If the invocation list of d matches a contiguous set of elements in the current delegate’s invocation list, then the invocation list of d is said to occur within the current delegate’s invocation list. If the invocation list of d occurs more than once in the current delegate’s invocation list, the last occurrence is removed.
F G H I
Exceptions
J K
Exception
Condition
System.MemberAccessException
The caller does not have access to the method represented by the delegate (for example, if the method is private).
L M N O
Permissions
P Q
Permission
Description
System.Security.Permissions.ReflectionPermission
For enhancing security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
R S T U V W X Y Z
1336
Contents | Index
System.Collections DictionaryEntry Structure
BCL
Object
A
ValueType
B
DictionaryEntry
C
Summary
D
Represents a dictionary entry consisting of a System.Collections.DictionaryEntry.Key and an associated System.Collections.DictionaryEntry.Value.
E F
Type Summary
G
public struct DictionaryEntry { // Constructors public DictionaryEntry (object key, object value);
H I J
// Properties public object Key { set; get; } public object Value { set; get; }
K L
}
M N
AH Note that we’ve used properties here when fields would have done. Using properties ensures that we can change the implementation later without breaking user code. In the design of the .NET Framework we preferred using properties over instance fields in almost every case.
O P Q R
JR When using the C# foreach statement with a Hashtable, each element through the loop is a DictionaryEntry. This is not obvious from the documentation and I know many programmers who have gotten stumped by this.
S T U
Description
V
[Note: Some types that manage or access collections of objects, such as System.Collections.Hashtable and System.Collections.IDictionaryEnumerator, rely on the use of one or more pairs of a key object and an associated value object. System.Collections.DictionaryEntry provides this functionality. This structure supports the C# foreach semantics for System.Collections.Hashtable.]
W X Y Z
1337
Contents | Index
DictionaryEntry Structure
System.Collections
DictionaryEntry() Constructor
Example using System; using System.Collections; namespace Samples { public class DictionaryEntrySample { public static void Main() { Hashtable t = new Hashtable(); t.Add("damien", "maire"); t.Add("mark", "sacha"); t.Add("brad", "tamara"); foreach(DictionaryEntry d in t) { Console.WriteLine("Key: {0} Value: {1}", d.Key, d.Value); } } } }
A B C D E F G H I J K
The output is
L Key: damien Value: maire Key: mark Value: sacha Key: brad Value: tamara
M N O
DictionaryEntry(System.Object, System.Object) Constructor
P
[ILASM] public rtspecialname specialname instance void .ctor(object key, object value) [C#] public DictionaryEntry(object key, object value)
Q R S T
Summary
U
Constructs and initializes a new instance of the System.Collections.DictionaryEntry class with the specified key and value objects.
V
Parameters
W X Y Z
Parameter
Description
key
The System.Object defined to reference a dictionary entry.
value
The System.Object that contains the content associated with key.
1338
Contents | Index
System.Collections
DictionaryEntry Structure Value Property
Exceptions Exception
Condition
System.ArgumentNullException
key is null.
A B C D
DictionaryEntry.Key Property
E
[ILASM] .property object Key { public hidebysig specialname instance object get_Key() public hidebysig specialname instance void set_Key(object value) } [C#] public object Key { get; set; }
F G H I
Summary
J
Gets or sets an object representing the key of the current System.Collections.DictionaryEntry.
K L
Exceptions
M
Exception
Condition
System.ArgumentNullException
Set value is null.
N O P Q R
DictionaryEntry.Value Property
S [ILASM] .property object Value { public hidebysig specialname instance object get_Value() public hidebysig specialname instance void set_Value(object value) } [C#] public object Value { get; set; }
T U V W
Summary
X
Gets or sets an object representing the content of the current System.Collections.DictionaryEntry.
Y Z
1339
Contents | Index
System.IO Directory
BCL
Object
A
Directory
B
Summary
C
Provides information and performs operations on directories.
D E
Type Summary
F
public sealed { // Methods MS public public public
G H I J
public public MS CF 1.1 public public public public
K L M N
public public public
O P
public public
Q R
public MS CF 1.1 public public MS CF 1.1 public MS CF public MS CF public public
S T U V W
CF public
X Y
MS CF 1.1 public
Z
public CF public
class Directory
static DirectoryInfo CreateDirectory (string path); static void Delete (string path); static void Delete (string path, bool recursive); static bool Exists (string path); static DateTime GetCreationTime (string path); static DateTime GetCreationTimeUtc (string path); static string GetCurrentDirectory (); static string[] GetDirectories (string path); static string[] GetDirectories (string path, string searchPattern); static string GetDirectoryRoot (string path); static string[] GetFiles (string path); static string[] GetFiles (string path, string searchPattern); static string[] GetFileSystemEntries (string path); static string[] GetFileSystemEntries (string path, string searchPattern); static DateTime GetLastAccessTime (string path); static DateTime GetLastAccessTimeUtc (string path); static DateTime GetLastWriteTime (string path); static DateTime GetLastWriteTimeUtc (string path); static string[] GetLogicalDrives (); static DirectoryInfo GetParent (string path); static void Move (string sourceDirName, string destDirName); static void SetCreationTime (string path, DateTime creationTime); static void SetCreationTimeUtc (string path, DateTime creationTimeUtc); static void SetCurrentDirectory (string path); static void SetLastAccessTime (string path, DateTime lastAccessTime);
1340
Contents | Index
System.IO
Directory Directory Class
MS CF 1.1 public static void SetLastAccessTimeUtc (string path, DateTime lastAccessTimeUtc); CF public static void SetLastWriteTime (string path, DateTime lastWriteTime); MS CF 1.1 public static void SetLastWriteTimeUtc (string path, DateTime lastWriteTimeUtc); }
A B C D
BA During the standardization process we had some debate about the format of the file path. The question was whether we should allow a path format such as “C:\\foo\bar” or “\\foo\\bar” or “foo::bar”or all of these? In the end we decided it was acceptable to leave the path format up to each implementer. This does not have as large an effect on portability as you might guess, because most applications read this kind of path information in at runtime from the user, or from a configuration file native to the host system.
E F G H I J
BG I came from a Unix background, and one of the first changes I made to our I/O
K
package was to add support for using ‘/’ as a directory separator. I believe implementers can vary Path::DirectorySeparatorChar and AltDirectorySeparatorChar as necessary for their platforms to support a common path separator character on all platforms, as well as handle their platform-specific characters. CLI implementations on Windows should use ‘\’ and ‘/’ respectively, whereas Unix implementations should use ‘/’ and ‘\’ and Mac implementations should probably use ‘:’ and ‘\’.
L M N O P Q
Description
R
Implementations are required to preserve the case of file and directory path strings, and to be case sensitive if and only if the current platform is case-sensitive. [Note: In most Directory methods that accept path arguments, the path can refer to a file or a directory. ]
S T U V
Example
W
using System; using System.IO; namespace Samples { public class DirectorySample { public static void Main() {
X Y Z
1341
Contents | Index
Directory
System.IO
CreateDirectory() Method
string s = Directory.GetCurrentDirectory() + @"\Test"; Directory.CreateDirectory(s); DateTime d = Directory.GetLastWriteTime(s); Console.WriteLine("Last write time: {0}", d); d = d.AddYears(1); Directory.SetLastWriteTime(s, d); d = Directory.GetLastWriteTime(s); Console.WriteLine("Last write time: {0}", d);
A B C D
} }
E }
F
The output is
G H
Last write time: 10/06/2003 2:29:42 PM Last write time: 10/06/2004 2:29:42 PM
I J
Directory.CreateDirectory(System.String) Method
K
[ILASM] .method public hidebysig static class System.IO.DirectoryInfo CreateDirectory(string path) [C#] public static DirectoryInfo CreateDirectory(string path)
L M N O
Summary
P
Creates all directories and subdirectories as specified by path.
Q R
Parameters
S T
Parameter
Description
U
path
The directory path to create.
V W
Description
X
Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. The path parameter specifies a directory path, not a file path. Creating a directory with only the colon (:) character is not supported, and will cause a NotSupportedException to be thrown. For an example of using this method, see the Example section below.
Y Z
1342
Contents | Index
System.IO
Directory CreateDirectory() Method
Exceptions Exception
Condition
System.IO.IOException
The directory specified by path is read-only or is not empty.
System.UnauthorizedAccessException
The caller does not have the required permission.
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by System.IO.Path.InvalidPathChars.
A B C D E F System.ArgumentNullException
path is null.
System.IO.PathTooLongException
The specified path, file name, or both exceed the systemdefined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
G H I J
System.IO.DirectoryNotFoundException
The specified path is invalid, such as being on an unmapped drive.
K
System.NotSupportedException
Creating a directory with only the colon (:) character was attempted.
M
L
N O
Example
P
The following example creates the specified directory. To create the directory C:\Users\User1\Public\Html when the current directory is C:\Users\User1, use any of the following calls to ensure that the backslash is interpreted properly.
Q R S
Directory.CreateDirectory("Public\\Html"); Directory.CreateDirectory("\\Users\\User1\\Public\\Html"); Directory.CreateDirectory("c:\\Users\\User1\\Public\\Html");
T U V
Permissions
W
Permission
Description
X
For reading from files or directories. Associated enumerations: System.Security.Permissions.FileIOPermissionAccess.Read, System.Security.Permissions.FileIOPermissionAccess.Write.
Y
System.Security.Permissions.FileIOPermission
Z
1343
Contents | Index
Directory
System.IO
Delete() Method
Directory.Delete(System.String) Method [ILASM] .method public hidebysig static void Delete(string path) [C#] public static void Delete(string path)
A B C
Summary
D
Deletes the empty directory specified in path.
E
Parameters
F G
Parameter
Description
path
A System.String containing the name of the directory to delete. This directory must be writable and empty.
H I J K
Description
L
This method behaves identically to System.IO.Directory.Delete(path, false). The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
M N O P
Exceptions
Q
Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.ArgumentNullException
path is null.
System.IO.DirectoryNotFoundException
The specified path was not found.
X
System.IO.IOException
The directory specified by path is read-only or is not empty.
Y
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
R S T U V W
Z
1344
Contents | Index
System.IO
Directory Delete() Method
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to write to the specified directory. See System.Security.Permissions.FileIOPermissionAccess.Write.
A B C D
Example
E
using System; using System.IO; namespace Samples { public class DirectoryDelete { public static void Main() { string s = Directory.GetCurrentDirectory() + @"\Test"; Directory.CreateDirectory(s); DateTime d = Directory.GetLastWriteTime(s); Console.WriteLine("Last write time: {0}", d); Directory.Delete(s); } } }
F G H I J K L M N O P
The output is
Q R
Last write time: 10/06/2003 2:32:12 PM
S T
Directory.Delete(System.String, System.Boolean) Method
U [ILASM] .method public hidebysig static void Delete(string path, bool recursive) [C#] public static void Delete(string path, bool recursive)
V W X
Summary
Y
Deletes the specified directory and, if indicated, any subdirectories in the directory.
Z
1345
Contents | Index
Directory
System.IO
Delete() Method
Parameters Parameter
Description
path
A System.String containing the name of the directory to delete. This directory must be writable and cannot contain files unless recursive is true.
recursive
Specify true to delete subdirectories and files in path; otherwise, specify false.
A B C D E F
Description
G
The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
H I J
Exceptions
K L
Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.ArgumentNullException
path is null.
System.IO.DirectoryNotFoundException
The specified path was not found.
System.IO.IOException
The directory specified by path is read-only, or recursive is false and path is not an empty directory.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
M N O P Q R S T U V W X Y Z
1346
Contents | Index
System.IO
Directory Exists() Method
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to write to the specified directory. See System.Security.Permissions.FileIOPermissionAccess.Write.
A B C D
Example
E
using System; using System.IO; namespace Samples { public class DirectoryDelete { public static void Main() { string s = Directory.GetCurrentDirectory() + @"\Test"; Directory.CreateDirectory(s); DateTime d = Directory.GetLastWriteTime(s); Console.WriteLine("Last write time: {0}", d); Directory.Delete(s, true); } } }
F G H I J K L M N O P
The output is
Q R
Last write time: 10/06/2003 2:31:21 PM
S T
Directory.Exists(System.String) Method
U [ILASM] .method public hidebysig static bool Exists(string path) [C#] public static bool Exists(string path)
V W X
Summary
Y
Returns a System.Boolean indicating whether the specified directory exists.
Z
1347
Contents | Index
Directory
System.IO
Exists() Method
Parameters Parameter
Description
path
A System.String containing the name of the directory to check.
A B C
Return Value
D
true if the caller has the required permissions and path contains the name of an existing directory; otherwise, false. If path is null, a zero-length string, or contains the name of a file, returns false.
E F G
Description
H
If the caller does not have sufficient permissions to read the files in the directory specified by path, no exception is thrown and the method returns false regardless of the existence of path. The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
I J K L M
Permissions
N O
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to read the specified directory. See System.Security.Permissions.FileIOPermissionAccess.Read.
P Q R S T
Example
U
using System; using System.IO; namespace Samples { public class DirectoryExists { public static void Main() { string d = Directory.GetCurrentDirectory() + @"\Test"; Directory.CreateDirectory(d); if(Directory.Exists(d))
V W X Y Z
1348
Contents | Index
System.IO
Directory GetCreationTime() Method
Console.WriteLine("Directory else Console.WriteLine( "Directory \"{0}\" Directory.Delete(d); if(Directory.Exists(d)) Console.WriteLine("Directory else Console.WriteLine( "Directory \"{0}\"
\"{0}\" exists", d);
does not exist", d);
A B
\"{0}\" exists", d);
C D
does not exist", d);
}
E
}
F
}
G
The output is
H Directory "C:\Books\BCL\Samples\System.IO\Directory\Exists(System.String)\Test" exists Directory "C:\Books\BCL\Samples\System.IO\Directory\Exists(System.String)\Test" does not exist
I J K L
Directory.GetCreationTime(System.String) Method
M
[ILASM] .method public hidebysig static valuetype System.DateTime GetCreationTime(string path) [C#] public static DateTime GetCreationTime(string path)
N O P Q
Summary
R
Returns the creation date and time of the specified file or directory.
S T
Parameters
U
Parameter
Description
V
A System.String containing the name of the file or directory for which to obtain creation date and time information.
W
path
X Y Z
1349
Contents | Index
Directory
System.IO
GetCreationTime() Method
Return Value A System.DateTime structure set to the creation date and time for the specified directory. This value is expressed in local time. Platforms that do not support this feature return System.DateTime.MinValue.
A B
Description
C
This method is equivalent to System.IO.File.GetCreationTime(path). The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
D E F G
Exceptions
H I
Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.ArgumentNullException
path is null.
System.IO.IOException
The directory specified by path was not found.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
J K L M N O P Q R S T
Permissions
U V W X
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to read the specified file or directory. See System.Security.Permissions.FileIOPermissionAccess.Read.
Y Z
1350
Contents | Index
System.IO
Directory GetCreationTimeUtc() Method
Example using System; using System.IO; namespace Samples { public class DirectoryGetCreationTime { public static void Main() { string d = Directory.GetCurrentDirectory() + @"\Test"; Directory.CreateDirectory(d); DateTime dt = Directory.GetCreationTime(d); Console.WriteLine("Creation time: {0}", dt); Directory.Delete(d); } } }
A B C D E F G H I J
The output is
K L
Creation time: 10/06/2003 2:34:14 PM
M N
Directory.GetCreationTimeUtc(System.String) Method
O
[ILASM] .method public hidebysig static valuetype System.DateTime GetCreationTimeUtc(string path) [C#] public static DateTime GetCreationTimeUtc(string path)
P Q R
Summary
S
Gets the creation date and time, in coordinated universal time (UTC) format, of a directory.
T U
Parameters
V
Parameter
Description
path
The path of the directory.
W X Y Z
1351
Contents | Index
Directory
System.IO
GetCurrentDirectory() Method
Exceptions Exception
Condition
B
System.IO.IOException
The specified path was not found.
C
System.UnauthorizedAccessException
The caller does not have the required permission.
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by System.IO.Path.InvalidPathChars.
System.ArgumentNullException
path is null.
System.IO.PathTooLongException
The specified path, file name, or both exceed the systemdefined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
A
D E F G H I J K L
Permissions
M N
Permission
Description
System.Security.Permissions.FileIOPermission
For reading the specified file or directory. Associated enumeration: System.Security.Permissions.FileIOPermissionAccess.Read.
O P Q R S
Directory.GetCurrentDirectory() Method
T
[ILASM] .method public hidebysig static string GetCurrentDirectory() [C#] public static string GetCurrentDirectory()
U V W X
Summary
Y
Returns the application’s current working directory.
Z
Return Value Platforms that do not support this feature return System.String.Empty.
1352
Contents | Index
System.IO
Directory GetDirectories() Method
Exceptions Exception
Condition A
System.UnauthorizedAccessException
B
The caller does not have the required permission.
C D
Permissions
E
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to access path information for the current directory. See System.Security.Permissions.FileIOPermissionAccess.PathDiscovery.
F G H I J
Example
K
using System; using System.IO; namespace Samples { public class DirectoryGetCurrentDirectory { public static void Main() { Console.WriteLine("Current directory: {0}", Directory.GetCurrentDirectory()); } } }
L M N O P Q R S T
The output is
U
Current directory: C:\Books\BCL\Samples\System.IO\Directory\GetCurrentDirectory()
V W X
Directory.GetDirectories(System.String) Method
Y
[ILASM] .method public hidebysig static class System.String[] GetDirectories(string path) [C#] public static string[] GetDirectories(string path)
Z
1353
Contents | Index
Directory
System.IO
GetDirectories() Method
Summary Returns the names of subdirectories in the specified directory. A
Parameters
B C
Parameter
Description
path
A System.String containing the name of the directory for which an array of subdirectory names is returned.
D E F
Description
G
This method is identical to System.IO.Directory.GetDirectories(path, “*”). The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.] The names returned by this method are prefixed with the directory information provided in path.
H I J K L
Exceptions
M N
Exception
Condition
System.ArgumentNullException
path is null.
System.ArgumentException
path is a zero-length string, contains only white space, or contains implementation-defined invalid characters.
System.IO.DirectoryNotFoundException
path was not found.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.IO.IOException
path is a file name.
System.UnauthorizedAccessException
The caller does not have the required permission.
O P Q R S T U V W X Y Z
1354
Contents | Index
System.IO
Directory GetDirectories() Method
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to access path information for the specified directory and its subdirectories. See System.Security.Permissions.FileIOPermissionAccess.PathDiscovery.
A B C D E
Example
F
using System; using System.IO; namespace Samples { public class DirectoryGetDirectories { public static void Main() { string d = Directory.GetCurrentDirectory(); int i = d.LastIndexOf('\\'); d = d.Remove(i, d.Length - i); Console.WriteLine("Directories below {0} are", d); string[] directories = Directory.GetDirectories(d); foreach(string s in directories) Console.WriteLine("Subdirectory: {0}", s); } } }
G H I J K L M N O P Q R
The output is
S
Directories below C:\Books\BCL\Samples\System.IO\Directory are Subdirectory: C:\Books\BCL\Samples\System.IO\Directory\Delete(System.String) ... Subdirectory: C:\Books\BCL\Samples\System.IO\Directory\Test
T U V W
Directory.GetDirectories(System.String, System.String) Method
X [ILASM]
Y
.method public hidebysig static class System.String[] GetDirectories(string path, string searchPattern)
Z
[C#]
public static string[] GetDirectories(string path, string searchPattern)
1355
Contents | Index
Directory
System.IO
GetDirectories() Method
Summary Returns the names of subdirectories in the specified directory that match the specified search pattern. A
Parameters
B C D E
Parameter
Description
path
A System.String containing the starting location for the search.
searchPattern
A System.String containing the text pattern to match against the names of subdirectories of path. searchPattern cannot contain System.IO.Path.DirectorySeparatorChar or System.IO.Path.AltDirectorySeparatorChar.
F G H I J
Return Value
K
A String array containing the names of subdirectories of path that match searchPattern.
L
Description
M
The following wild card specifiers are permitted in searchPattern:
N O P Q
Wild card
Description
*
Zero or more characters.
?
Exactly one character.
R S
The period (“.”) character, if immediately followed by a wild card specifier, indicates that the period or the empty string matches the pattern. For example, “foo.*” and “foo.?” match “foo”. Note that “foo.*” and “foo*” behave identically. If the period is not immediately followed by a wildcard, it has no special meaning (it represents a period). Characters other than the wild card specifiers represent themselves, for example, the searchPattern string “*t” searches for all names in path ending with the letter “t”. The searchPattern string “s*” searches for all names in path beginning with the letter “s”. The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
T U V W X Y Z
1356
Contents | Index
System.IO
Directory GetDirectories() Method
Exceptions Exception
Condition
System.ArgumentNullException
path or searchPattern is null.
System.ArgumentException
path is a zero-length string, contains only white space, or contains implementation-defined invalid characters.
D
searchPattern does not contain a valid pattern.
E
A
System.IO.DirectoryNotFoundException
path was not found.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
B C
F G
System.IO.IOException
path is a file name.
System.UnauthorizedAccessException
The caller does not have permission to access the requested information.
H I J K L M N
Permissions
O
Permission
Description
P
Requires permission to access path information for the specified directory and its subdirectories. See System.Security.Permissions.FileIOPermissionAccess.PathDiscovery.
Q
System.Security.Permissions.FileIOPermission
R S T
Example
U
using System; using System.IO; namespace Samples { public class DirectoryGetDirectories { public static void Main() { string d = Directory.GetCurrentDirectory(); int i = d.LastIndexOf('\\');
V W X Y Z
1357
Contents | Index
Directory
System.IO
GetDirectoryRoot() Method
d = d.Remove(i, d.Length - i); string p = "S*"; Console.WriteLine( "Directories below {0} " + "matching this pattern \"{1}\" are: ", d, p); string[] directories = Directory.GetDirectories(d, p); foreach(string s in directories) Console.WriteLine("Subdirectory: {0} ", s);
A B C }
D
} }
E F
The output is
G Directories below C:\Books\BCL\Samples\System.IO\Directory matching this pattern "S*" are: Subdirectory: C:\Books\BCL\Samples\System.IO\Directory\ SetCurrentDirectory(System.String) Subdirectory: C:\Books\BCL\Samples\System.IO\Directory\ SetLastAccessTime(System.String,System.Date) Subdirectory: C:\Books\BCL\Samples\System.IO\Directory\ SetLastWriteTime(System.String,System.Date)
H I J K L M N
Directory.GetDirectoryRoot(System.String) Method
O
[ILASM] .method public hidebysig static string GetDirectoryRoot(string path) [C#] public static string GetDirectoryRoot(string path)
P Q R
Summary
S
Returns the path root component of the specified path.
T
Parameters
U V
Parameter
Description
path
A System.String containing the name of a file or directory.
W X Y
Return Value
Z
Platforms that do not support this feature return System.String.Empty.
1358
Contents | Index
System.IO
Directory GetDirectoryRoot() Method
Description This method obtains the full path information for path, as returned by System.IO.Path. GetFullPath(path) and returns the path root component. The specified path is not required to exist. The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
A B C D
Exceptions
E
Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
F G
System.ArgumentNullException
path is null.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
H I J K L M
System.UnauthorizedAccessException
N
The caller does not have the required permission.
O P
Permissions
Q
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to access path information for the specified file or directory. See System.Security.Permissions.FileIOPermissionAccess.PathDiscovery.
R S T U V
Example
W
using System; using System.IO; namespace Samples { public class DirectoryGetDirectoryRoot { public static void Main() {
X Y Z
1359
Contents | Index
Directory
System.IO
GetFiles() Method
string s = Directory.GetCurrentDirectory(); Console.WriteLine("The root for {0} is: {1}", s, Directory.GetDirectoryRoot(s)); }
A
} }
B C
The output is
D The root for C:\Books\BCL\Samples\System.IO\Directory\ GetDirectoryRoot(System.String) is: C:\
E F G
Directory.GetFiles(System.String) Method
H
[ILASM]
I
.method public hidebysig static class System.String[] GetFiles(string path) [C#]
J
public static string[] GetFiles(string path)
K
Summary
L
Returns the names of all files in the specified directory.
M N
Parameters
O P Q
Parameter
Description
path
A System.String containing the name of the directory for which file names are returned.
R S
Return Value
T
Platforms that do not support this feature return null.
U V
Description
W
This method is identical to System.IO.Directory.GetFiles(path, “*”). The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
X Y Z
1360
Contents | Index
System.IO
Directory GetFiles() Method
Exceptions Exception
Condition
System.ArgumentNullException
path is null.
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementationdefined invalid characters.
A B C D E
System.IO.DirectoryNotFoundException
path was not found.
System.IO.IOException
path is a file name.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
F G H I J
System.UnauthorizedAccessException
The caller does not have the required permission.
K L M
Permissions
N
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to access path information for the specified directory and the files in that directory. See System.Security.Permissions.FileIOPermissionAccess.PathDiscovery.
O P Q R S T
Example
U
using System; using System.IO; namespace Samples { public class DirectoryGetFiles { public static void Main() { string d = Directory.GetCurrentDirectory(); Console.WriteLine("Files in {0} are", d); string[] files = Directory.GetFiles(d);
V W X Y Z
1361
Contents | Index
Directory
System.IO
GetFiles() Method
foreach(string s in files) Console.WriteLine("File: {0}", s); } }
A
}
B
The output is
C
Files in C:\Books\BCL\Samples\System.IO\Directory\GetFiles(System.String) are File: C:\Books\BCL\Samples\System.IO\Directory\GetFiles(System.String)\book.output File: C:\Books\BCL\Samples\System.IO\Directory\GetFiles(System.String)\ Directory.cs File: C:\Books\BCL\Samples\System.IO\Directory\GetFiles(System.String)\ Directory.exe File: C:\Books\BCL\Samples\System.IO\Directory\GetFiles(System.String)\ Directory.pdb File: C:\Books\BCL\Samples\System.IO\Directory\GetFiles(System.String)\makefile
D E F G H I J K
Directory.GetFiles(System.String, System.String) Method
L
[ILASM] .method public hidebysig static class System.String[] GetFiles(string path, string searchPattern) [C#] public static string[] GetFiles(string path, string searchPattern)
M N O P
Summary
Q
Returns the names of files in the specified directory that match the specified search pattern.
R
Parameters
S T U
Parameter
Description
path
A System.String containing the name of the directory to search.
searchPattern
A System.String containing the text pattern to match against the names of files in path. searchPattern cannot contain System.IO.Path.DirectorySeparatorChar or System.IO.Path.AltDirectorySeparatorChar.
V W X Y Z
1362
Contents | Index
System.IO
Directory GetFiles() Method
Description The following wild card specifiers are permitted in searchPattern: Wild card
Description
*
Zero or more characters.
?
Exactly one character.
A B C D E F
The period (“.”) character, if immediately followed by a wild card specifier, indicates that the period or the empty string matches the pattern. For example, “foo.*” and “foo.?” match “foo”. Note that “foo.*” and “foo*” behave identically. If the period is not immediately followed by a wild card, it has no special meaning (it represents a period). Characters other than the wild card specifiers and the period always represent themselves, for example, the searchPattern string “*t” searches for all names in path ending with the letter “t”. The searchPattern string “s*” searches for all names in path beginning with the letter “s”. The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
G H I J K L M N
Exceptions Exception
O P
Condition
Q System.ArgumentNullException
searchPattern or path is null.
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
T
System.IO.IOException
path is a file name.
U
System.IO.DirectoryNotFoundException
path was not found.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
R S
V W X Y Z
1363
Contents | Index
Directory
System.IO
GetFileSystemEntries() Method
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to access path information for the specified directory and the files in that directory. See System.Security.Permissions.FileIOPermissionAccess.PathDiscovery.
A B C D E
Example
F
using System; using System.IO; namespace Samples { public class DirectoryGetFiles { public static void Main() { string d = Directory.GetCurrentDirectory(); string f = "*.cs"; Console.WriteLine("Files in {0} are", d); string[] files = Directory.GetFiles(d, f); foreach(string s in files) Console.WriteLine("File: {0}", s); } } }
G H I J K L M N O P Q
The output is
R Files in C:\Books\BCL\Samples\System.IO\Directory\ GetFiles(System.String,System.String) are File: C:\Books\BCL\Samples\System.IO\Directory\ GetFiles(System.String,System.String)\Directory.cs
S T U V
Directory.GetFileSystemEntries(System.String) Method
W
[ILASM] .method public hidebysig static class System.String[] GetFileSystemEntries(string path) [C#] public static string[] GetFileSystemEntries(string path)
X Y Z
1364
Contents | Index
System.IO
Directory GetFileSystemEntries() Method
Summary Returns the names of all files and subdirectories in the specified directory. A
Parameters
B
Parameter
Description
path
A System.String containing the name of the directory for which file and subdirectory names are returned.
C D E F
Description
G
This method is identical to System.IO.Directory.GetFileSystemEntries(path, “*”). The names returned by this method are prefixed with the directory information provided in path. The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
H I J K
Exceptions
L M
Exception
Condition
System.ArgumentNullException
path is null.
O
path is a zero-length string, contains only white space, or contains one or more implementationdefined invalid characters.
P
System.ArgumentException
N
Q R
System.IO.DirectoryNotFoundException
path was not found.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.IO.IOException
path is a file name.
System.UnauthorizedAccessException
The caller does not have the required permission.
S T U V W X Y Z
1365
Contents | Index
Directory
System.IO
GetFileSystemEntries() Method
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to access path information for the specified directory. See System.Security.Permissions.FileIOPermissionAccess.PathDiscovery.
A B C D E
Example
F
using System; using System.IO; namespace Samples { public class DirectoryGetFileSystemEntries { public static void Main() { string d = Directory.GetCurrentDirectory(); Console.WriteLine("Subdirectories/Files in {0} are:", d); string[] contents = Directory.GetFileSystemEntries(d); foreach(string s in contents) Console.WriteLine("Subdirectories/Files: {0}", s); } } }
G H I J K L M N O P
The output is
Q Subdirectories/Files in C:\Books\BCL\Samples\System.IO\Directory\ GetFileSystemEntries(System.String) are: Subdirectories/Files: C:\Books\BCL\Samples\System.IO\Directory\ GetFileSystemEntries(System.String)\book.output Subdirectories/Files: C:\Books\BCL\Samples\System.IO\Directory\ GetFileSystemEntries(System.String)\Directory.cs Subdirectories/Files: C:\Books\BCL\Samples\System.IO\Directory\ GetFileSystemEntries(System.String)\Directory.exe Subdirectories/Files: C:\Books\BCL\Samples\System.IO\Directory\ GetFileSystemEntries(System.String)\Directory.pdb Subdirectories/Files: C:\Books\BCL\Samples\System.IO\Directory\ GetFileSystemEntries(System.String)\makefile
R S T U V W X Y Z
1366
Contents | Index
System.IO
Directory GetFileSystemEntries() Method
Directory.GetFileSystemEntries(System.String, System.String) Method [ILASM] .method public hidebysig static class System.String[] GetFileSystemEntries(string path, string searchPattern) [C#] public static string[] GetFileSystemEntries(string path, string searchPattern)
A B C
Summary
D
Returns an array of file and directory names matching the specified search criteria.
E F
Parameters
G
Parameter
Description
path
A System.String containing the name of the directory to search.
searchPattern
A System.String containing the text pattern for which to search. searchPattern cannot contain System.IO.Path.DirectorySeparatorChar or System.IO.Path.AltDirectorySeparatorChar.
H I J K L M
Description
N
The following wild card specifiers are permitted in searchPattern:
O
Wild card
Description
*
Zero or more characters.
?
Exactly one character.
P Q R S T U
The period (“.”) character, if immediately followed by a wild card specifier, indicates that the period or the empty string matches the pattern. For example, “foo.*” and “foo.?” match “foo”. Note that “foo.*” and “foo*” behave identically. If the period is not immediately followed by a wild card, it has no special meaning (it represents a period). Characters other than the wild card specifiers represent themselves, for example, the searchPattern string “*t” searches for all names in path ending with the letter “t”. The searchPattern string “s*” searches for all names in path beginning with the letter “s”. The names returned by this method are prefixed with the directory information provided in path. The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory.
V W X Y Z
1367
Contents | Index
Directory
System.IO
GetFileSystemEntries() Method
[Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.] A
Exceptions
B
Exception
Condition
System.ArgumentNullException
searchPattern or path is null.
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementationdefined invalid characters.
System.IO.DirectoryNotFoundException
path was not found.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
L
System.IO.IOException
path is a file name.
M
System.UnauthorizedAccessException
The caller does not have the required permission.
C D E F G H I J K
N O
Permissions
P Q
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to access path information for the specified directory. See System.Security.Permissions.FileIOPermissionAccess.PathDiscovery.
R S T U V W X Y Z
1368
Contents | Index
System.IO
Directory GetLastAccessTime() Method
Example using System; using System.IO; namespace Samples { public class DirectoryGetFileSystemEntries { public static void Main() { string d = Directory.GetCurrentDirectory(); string f = "*.cs"; Console.WriteLine("Subdirectories/Files in {0} are:", d); string[] contents = Directory.GetFileSystemEntries(d, f); foreach(string s in contents) Console.WriteLine("Subdirectories/Files: {0}", s); } } }
A B C D E F G H I J
The output is
K L
Subdirectories/Files in C:\Books\BCL\Samples\System.IO\Directory\ GetFileSystemEntries(System.String,System.String) are: Subdirectories/Files: C:\Books\BCL\Samples\System.IO\Directory\ GetFileSystemEntries(System.String,System.String)\Directory.cs
M N O
Directory.GetLastAccessTime(System.String) Method
P Q
[ILASM] .method public hidebysig static valuetype System.DateTime GetLastAccessTime(string path) [C#] public static DateTime GetLastAccessTime(string path)
R S T
Summary
U
Returns the date and time the specified file or directory was last accessed.
V W
Parameters
X
Parameter
Description
path
A System.String containing the name of the file or directory for which to obtain access date and time information.
Y Z
1369
Contents | Index
Directory
System.IO
GetLastAccessTime() Method
Return Value A System.DateTime structure set to the date and time the specified file or directory was last accessed. This value is expressed in local time. Platforms that do not support this feature return System.DateTime.MinValue.
A B
Description
C
This method is equivalent to System.IO.File.GetLastAccessTime(path). The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
D E F G
Exceptions
H
Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.ArgumentNullException
path is null.
N
System.IO.IOException
The specified path was not found.
O
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
I J K L M
P Q R S
Permissions
T U
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to read the specified file or directory. See System.Security.Permissions.FileIOPermissionAccess.Read.
V W X Y Z
1370
Contents | Index
System.IO
Directory GetLastAccessTimeUtc() Method
Example using System; using System.IO; namespace Samples { public class DirectoryGetLastAccessTime { public static void Main() { string d = Directory.GetCurrentDirectory(); Console.WriteLine( "Directory {0} accessed at: {1}", d, Directory.GetLastAccessTime(d)); } } }
A B C D E F G H I
The output is
J Directory C:\Books\BCL\Samples\System.IO\Directory\ GetLastAccessTime(System.String,System.String) accessed at: 10/06/2003 2:45:30 PM
K L M
Directory.GetLastAccessTimeUtc(System.String) Method
N
[ILASM]
O
.method public hidebysig static valuetype System.DateTime GetLastAccessTimeUtc(string path)
P
[C#]
Q
public static DateTime GetLastAccessTimeUtc(string path)
R
Summary
S
Returns the date and time, in universal coordinated time (UTC) format, that the specified file or directory was last accessed.
T U
Parameters
V
Parameter
Description
path
The file or directory for which to obtain access date and time information.
W X Y Z
1371
Contents | Index
Directory
System.IO
GetLastWriteTime() Method
Return Value A System.DateTime structure set to the date and time the specified file or directory was last accessed. This value is expressed in UTC time. A
Exceptions
B C
Exception
Condition
E
System.IO.IOException
The specified path was not found.
F
System.UnauthorizedAccessException
The caller does not have the required permission.
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by System.IO.Path.InvalidPathChars.
System.ArgumentNullException
path is null.
System.IO.PathTooLongException
The specified path, file name, or both exceed the systemdefined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
System.NotSupportedException
The path parameter is in an invalid format.
D
G H I J K L M N O P
Permissions
Q R
Permission
Description
System.Security.Permissions.FileIOPermission
For reading the specified file or directory. Associated enumeration: System.Security.Permissions.FileIOPermissionAccess.Read.
S T U V W
Directory.GetLastWriteTime(System.String) Method
X
[ILASM] .method public hidebysig static valuetype System.DateTime GetLastWriteTime(string path) [C#] public static DateTime GetLastWriteTime(string path)
Y Z
1372
Contents | Index
System.IO
Directory GetLastWriteTime() Method
Summary Returns the date and time the specified file or directory was last written to. A
Parameters
B
Parameter
Description
C
A System.String containing the name of the file or directory for which to obtain modification date and time information.
D
path
E F
Return Value
G
A System.DateTime structure set to the date and time the specified file or directory was last written to. This value is expressed in local time. Platforms that do not support this feature return System.DateTime.MinValue.
H I J
Description
K
This method is equivalent to System.IO.File.GetLastWriteTime(path). The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
L M N O
Exceptions
P
Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementationdefined invalid characters.
System.ArgumentNullException
path is null.
System.IO.IOException
The specified path was not found.
V
The length of path or the absolute path information for path exceeds the system-defined maximum length.
W
System.IO.PathTooLongException
System.UnauthorizedAccessException
The caller does not have the required permission.
Q R S T U
X Y Z
1373
Contents | Index
Directory
System.IO
GetLastWriteTimeUtc() Method
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to read the specified file or directory. See System.Security.Permissions.FileIOPermissionAccess.Read.
A B C D E
Example
F
using System; using System.IO; namespace Samples { public class DirectoryGetLastWriteTime { public static void Main() { string d = Directory.GetCurrentDirectory(); Console.WriteLine( "Directory {0} last written to at: {1}", d, Directory.GetLastWriteTime(d)); } } }
G H I J K L M N O
The output is
P
Directory C:\Books\BCL\Samples\System.IO\Directory\GetLastWriteTime(System.String) last written to at: 10/06/2003 2:47:38 PM
Q R S
Directory.GetLastWriteTimeUtc(System.String) Method
T
[ILASM] .method public hidebysig static valuetype System.DateTime GetLastWriteTimeUtc(string path) [C#] public static DateTime GetLastWriteTimeUtc(string path)
U V W X Y
Summary
Z
Returns the date and time, in universal coordinated time (UTC) format, that the specified file or directory was last written to.
1374
Contents | Index
System.IO
Directory GetLogicalDrives() Method
Parameters Parameter
Description
path
The file or directory for which to obtain modification date and time information.
A B C
Exceptions
D E
Exception
Condition
System.IO.IOException
The specified path was not found.
System.UnauthorizedAccessException
The caller does not have the required permission.
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by System.IO.Path.InvalidPathChars.
K
System.ArgumentNullException
path is null.
L
System.IO.PathTooLongException
The specified path, file name, or both exceed the systemdefined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
F G H I J
M N O P Q
Permissions
R
Permission
Description
System.Security.Permissions.FileIOPermission
For reading the specified file or directory. Associated enumeration: System.Security.Permissions.FileIOPermissionAccess.Read.
S T U V W X
Directory.GetLogicalDrives() Method
Y [ILASM] .method public hidebysig static class System.String[] GetLogicalDrives() [C#] public static string[] GetLogicalDrives()
Z
1375
Contents | Index
Directory
System.IO
GetParent() Method
Summary Retrieves the names of the logical drives on this computer in the form “:\”. A
Exceptions
B C
Exception
Condition
D
System.IO.IOException
An I/O error occurs (for example, a disk error).
System.UnauthorizedAccessException
The caller does not have the required permission.
E F G H
Permissions
I J
Permission
Description
System.Security.Permissions.SecurityPermission
To call unmanaged code, such as calling native code with PInvoke or COM interop. Associated enumeration: System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode.
K L M N O
Directory.GetParent(System.String) Method
P
[ILASM] .method public hidebysig static class System.IO.DirectoryInfo GetParent(string path) [C#] public static DirectoryInfo GetParent(string path)
Q R S T
Summary
U
Retrieves the parent directory of the specified path, including both absolute and relative paths.
V
Parameters
W X Y Z
Parameter
Description
path
The path from which to retrieve the parent directory.
1376
Contents | Index
System.IO
Directory GetParent() Method
Return Value The parent directory, or null if path is the root directory, including the root of a UNC server or share name. A
Description
B
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory. The path parameter is not case-sensitive.
C D E F
Exceptions
G
Exception
Condition
System.IO.IOException
The directory specified by path is read-only.
H I J
System.UnauthorizedAccessException
The caller does not have the required permission.
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by System.IO.Path.InvalidPathChars.
M
System.ArgumentNullException
path is null.
O
System.IO.PathTooLongException
The specified path, file name, or both exceed the systemdefined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
K L
N
P Q R S System.IO.DirectoryNotFoundException
The specified path was not found.
T U V
Permissions
W
Permission
Description
System.Security.Permissions.FileIOPermission
For reading from files or directories. Associated enumeration: System.Security.Permissions.FileIOPermissionAccess.Read.
X Y Z
1377
Contents | Index
Directory
System.IO
Move() Method
Directory.Move(System.String, System.String) Method [ILASM] .method public hidebysig static void Move(string sourceDirName, string destDirName) [C#] public static void Move(string sourceDirName, string destDirName)
A B C D
Summary
E
Moves a file or a directory and its contents to a new location.
F
Parameters
G H I
Parameter
Description
sourceDirName
A System.String containing the name of the file or directory to move.
destDirName
A System.String containing the new location for sourceDirName. This string cannot identify an existing file or directory.
J K L M
Description
N
The destDirName argument cannot specify a location on a different disk or volume than sourceDirName. The sourceDirName and destDirName arguments cannot identify the same file or directory. [Note: This method throws a System.IO.IOException if, for example, you try to move “\mydir” to “\public”, and “\public” already exists. You must specify “\public\mydir” as the destDirName.] The sourceDirName and destDirName arguments are permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
O P Q R S T U V W X Y Z
1378
Contents | Index
System.IO
Directory Move() Method
Exceptions Exception
Condition
System.ArgumentException
sourceDirName or destDirName is a zero-length string, contains only white space, or contains implementation-defined invalid characters.
System.ArgumentNullException
sourceDirName or destDirName is null.
System.UnauthorizedAccessException
The caller does not have the required permission.
System.IO.IOException
An attempt was made to move a directory to a different volume, or destDirName already exists.
System.IO.DirectoryNotFoundException
sourceDirName was not found.
System.IO.PathTooLongException
The length or absolute path information for sourceDirName or destDirName exceeds the system-defined maximum length.
A B C D E F G H I J K L M
Permissions
N O
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to read from sourceDirName, and write to sourceDirName and destDirName. See System.Security.Permissions.FileIOPermissionAccess.Read, System.Security.Permissions.FileIOPermissionAccess.Write.
P Q R S T U
Example
V
using System; using System.IO; namespace Samples { public class DirectoryMove { public static void Main() { string d = Directory.GetCurrentDirectory(); string original = d + @"\original.cs",
W X Y Z
1379
Contents | Index
Directory
System.IO
SetCreationTime() Method
target = d + @"\target.cs"; Console.WriteLine("Files in {0} are:", d); string[] files = Directory.GetFiles(d, "*.cs"); foreach(string s in files) Console.WriteLine("File: {0}", s); Directory.Move(original, target); Console.WriteLine("Files in {0} are:", d); files = Directory.GetFiles(d, "*.cs"); foreach(string s in files) Console.WriteLine("File: {0}", s); Directory.Move(target, original);
A B C D E }
F
} }
G
The output is
H I
Files in C:\Books\BCL\Samples\System.IO\Directory\ Move(System.String,System.String) are: File: C:\Books\BCL\Samples\System.IO\Directory\ Move(System.String,System.String)\Directory.cs File: C:\Books\BCL\Samples\System.IO\Directory\ Move(System.String,System.String)\original.cs Files in C:\Books\BCL\Samples\System.IO\Directory\ Move(System.String,System.String) are: File: C:\Books\BCL\Samples\System.IO\Directory\ Move(System.String,System.String)\Directory.cs File: C:\Books\BCL\Samples\System.IO\Directory\ Move(System.String,System.String)\target.cs
J K L M N O P Q R
Directory.SetCreationTime(System.String, System.DateTime) Method
S
[ILASM] .method public hidebysig static void SetCreationTime(string path, valuetype System.DateTime creationTime) [C#] public static void SetCreationTime(string path, DateTime creationTime)
T U V W
Summary
X
Sets the creation date and time for the specified file or directory.
Y Z
1380
Contents | Index
System.IO
Directory SetCreationTime() Method
Parameters Parameter
Description
path
A System.String containing the name of the file or directory for which to set the creation date and time information.
creationTime
A System.DateTime containing the value to set for the creation date and time of path. This value is expressed in local time.
A B C D E
Description
F
The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.] On platforms that do not support this feature, this method has no effect. If this feature is supported, the range of dates that is valid for this operation is implementation-specific.
G H I J K
Exceptions
L
Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.ArgumentOutOfRangeException
creationTime specifies a value outside the range of date/ times permitted for this operation.
System.ArgumentNullException
path is null.
System.IO.FileNotFoundException
path was not found.
System.IO.IOException
An I/O error occurred while performing the operation.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
M N O P Q R S T U V W X Y Z
1381
Contents | Index
Directory
System.IO
SetCreationTimeUtc() Method
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to write to the specified file or directory. See System.Security.Permissions.FileIOPermissionAccess.Write.
A B C D E
Example
F
using System; using System.IO; namespace Samples { public class DirectorySetCreationTime { public static void Main() { string n = Directory.GetCurrentDirectory() + @"\Test"; Directory.CreateDirectory(n); DateTime d = Directory.GetCreationTime(n); Console.WriteLine("Creation time: {0}", d); d = d.AddYears(1); Directory.SetCreationTime(n, d); d = Directory.GetCreationTime(n); Console.WriteLine("Creation time: {0}", d); Directory.Delete(n); } } }
G H I J K L M N O P Q R S
The output is
T Creation time: 10/06/2003 2:57:00 PM Creation time: 10/06/2004 2:57:00 PM
U V W
Directory.SetCreationTimeUtc(System.String, System.DateTime) Method
X [ILASM] .method public hidebysig static void SetCreationTimeUtc(string path, valuetype System.DateTime creationTimeUtc) [C#] public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc)
Y Z
1382
Contents | Index
System.IO
Directory SetCreationTimeUtc() Method
Summary Sets the creation date and time, in universal coordinated time (UTC) format, for the specified file or directory. A
Parameters Parameter
B C
Description
D
path
The file or directory for which to set the creation date and time information.
E
creationTimeUtc
A System.DateTime containing the value to set for the creation date and time of path. This value is expressed in UTC time.
F G H
Description
I
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory. The path parameter is not case-sensitive.
J K L M
Exceptions
N
Exception
Condition
System.IO.FileNotFoundException
The specified path was not found.
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by System.IO.Path.InvalidPathChars.
System.ArgumentNullException
path is null.
System.IO.PathTooLongException
The specified path, file name, or both exceed the systemdefined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
O P Q R S T U V W X
System.UnauthorizedAccessException
The caller does not have the required permission.
System.ArgumentOutOfRangeException
creationTimeUtc specifies a value outside the range of dates or times permitted for this operation.
Y Z
1383
Contents | Index
Directory
System.IO
SetCurrentDirectory() Method
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
For writing to the specified file or directory. Associated enumeration: System.Security.Permissions.FileIOPermissionAccess.Write.
A B C D E
Directory.SetCurrentDirectory(System.String) Method
F
[ILASM] .method public hidebysig static void SetCurrentDirectory(string path) [C#] public static void SetCurrentDirectory(string path)
G H I J
Summary
K
Sets the application’s current working directory to the specified directory.
L
Parameters
M N
Parameter
Description
path
A System.String containing the path to which the current working directory is set.
O P Q R
Description
S
When the application terminates, the working directory is restored to its original location (the directory where the process was started). The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.] On platforms that do not support this feature, this method has no effect.
T U V W X Y Z
1384
Contents | Index
System.IO
Directory SetCurrentDirectory() Method
Exceptions Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
A
System.ArgumentNullException
path is null.
System.IO.FileNotFoundException
path was not found.
System.IO.IOException
An I/O error occurred while performing the operation.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
B C D E F G H I J K
Example
L
using System; using System.IO; namespace Samples { public class DirectorySetCurrentDirectory { public static void Main() { Console.WriteLine("Current directory: {0}", Directory.GetCurrentDirectory()); string d = Directory.GetCurrentDirectory(); int i = d.LastIndexOf('\\'); d = d.Remove(i, d.Length - i); Directory.SetCurrentDirectory(d); Console.WriteLine("Current directory: {0}", Directory.GetCurrentDirectory()); } } }
M N O P Q R S T U V W X
The output is
Y Z
Current directory: C:\Books\BCL\Samples\System.IO\Directory\ SetCurrentDirectory(System.String) Current directory: C:\Books\BCL\Samples\System.IO\Directory
1385
Contents | Index
Directory
System.IO
SetLastAccessTime() Method
Directory.SetLastAccessTime(System.String, System.DateTime) Method [ILASM] .method public hidebysig static void SetLastAccessTime(string path, valuetype System.DateTime lastAccessTime) [C#] public static void SetLastAccessTime(string path, DateTime lastAccessTime)
A B C D
Summary
E
Sets the date and time the specified file or directory was last accessed.
F
Parameters
G H
Parameter
Description
path
A System.String containing the name of the file or directory for which to set the access date and time information.
lastAccessTime
A System.DateTime containing the value to set for the access date and time of path. This value is expressed in local time.
I J K L M
Description
N
The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.] On platforms that do not support this feature, this method has no effect. If this feature is supported, the range of dates that is valid for this operation is implementation-specific.
O P Q R S T U V W X Y Z
1386
Contents | Index
System.IO
Directory SetLastAccessTime() Method
Exceptions Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
A B C D
System.ArgumentNullException
path is null.
System.IO.IOException
path was not found.
F
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
G
System.UnauthorizedAccessException
The caller does not have the required permission.
E
H I J K
Permissions
L
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to write to the specified file or directory. See System.Security.Permissions.FileIOPermissionAccess.Write.
M N O P Q
Example
R
using System; using System.IO; namespace Samples { public class DirectorySetLastAccessTime { public static void Main() { string n = Directory.GetCurrentDirectory() + @"\Test"; Directory.CreateDirectory(n); DateTime d = Directory.GetLastAccessTime(n); Console.WriteLine("Last access time: {0}", d); d = d.AddYears(1); Directory.SetLastAccessTime(n, d);
S T U V W X Y Z
1387
Contents | Index
Directory
System.IO
SetLastAccessTimeUtc() Method
d = Directory.GetLastAccessTime(n); Console.WriteLine("Last access time: {0}", d); Directory.Delete(n); }
A
} }
B C
The output is
D Last access time: 10/06/2003 2:59:33 PM Last access time: 10/06/2004 2:59:33 PM
E F G
Directory.SetLastAccessTimeUtc(System.String, System.DateTime) Method
H
[ILASM] .method public hidebysig static void SetLastAccessTimeUtc(string path, valuetype System.DateTime lastAccessTimeUtc) [C#] public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc)
I J K L
Summary
M
Sets the date and time, in universal coordinated time (UTC) format, that the specified file or directory was last accessed.
N O
Parameters
P Q R
Parameter
Description
path
The file or directory for which to set the access date and time information.
lastAccessTimeUtc
A System.DateTime containing the value to set for the access date and time of path. This value is expressed in UTC time.
S T U V
Description
W
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory. The path parameter is not case-sensitive.
X Y Z
1388
Contents | Index
System.IO
Directory SetLastWriteTime() Method
Exceptions Exception
Condition A
System.IO.FileNotFoundException
The specified path was not found.
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by System.IO.Path.InvalidPathChars.
D
System.ArgumentNullException
path is null.
F
System.IO.PathTooLongException
The specified path, file name, or both exceed the systemdefined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
B C
E
G H I J System.UnauthorizedAccessException
The caller does not have the required permission.
K L M
Permissions
N
Permission
Description
System.Security.Permissions.FileIOPermission
For writing to the specified file or directory. Associated enumeration: System.Security.Permissions.FileIOPermissionAccess.Write.
O P Q R S T
Directory.SetLastWriteTime(System.String, System.DateTime) Method
U
[ILASM] .method public hidebysig static void SetLastWriteTime(string path, valuetype System.DateTime lastWriteTime) [C#] public static void SetLastWriteTime(string path, DateTime lastWriteTime)
V W X
Summary
Y
Sets the date and time a directory was last written to.
Z
1389
Contents | Index
Directory
System.IO
SetLastWriteTime() Method
Parameters Parameter
Description
path
A System.String containing the name of the directory for which to set the date and time information.
lastWriteTime
A System.DateTime containing the value to set for the last write date and time of path. This value is expressed in local time.
A B C D E F
Description
G
Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.] On platforms that do not support this feature, this method has no effect. If this feature is supported, the range of dates that is valid for this operation is implementation-specific.
H I J K
Exceptions
L M N O P Q R S T U V
Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.ArgumentNullException
path is null.
System.IO.IOException
path was not found.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
W X Y Z
1390
Contents | Index
System.IO
Directory SetLastWriteTimeUtc() Method
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to write to the specified file. See System.Security.Permissions.FileIOPermissionAccess.Write.
A B C D
Example
E
using System; using System.IO; namespace Samples { public class DirectorySetLastWriteTime { public static void Main() { string n = Directory.GetCurrentDirectory() + @"\Test"; Directory.CreateDirectory(n); DateTime d = Directory.GetLastWriteTime(n); Console.WriteLine("Last write time: {0}", d); d = d.AddYears(1); Directory.SetLastWriteTime(n, d); d = Directory.GetLastWriteTime(n); Console.WriteLine("Last write time: {0}", d); Directory.Delete(n); } } }
F G H I J K L M N O P Q R S
The output is
T Last write time: 10/06/2003 3:00:57 PM Last write time: 10/06/2004 3:00:57 PM
U V W
Directory.SetLastWriteTimeUtc(System.String, System.DateTime) Method
X [ILASM] .method public hidebysig static void SetLastWriteTimeUtc(string path, valuetype System.DateTime lastWriteTimeUtc) [C#] public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc)
Y Z
1391
Contents | Index
Directory
System.IO
SetLastWriteTimeUtc() Method
Summary Sets the date and time, in universal coordinated time (UTC) format, that a directory was last written to. A
Parameters
B C D E F
Parameter
Description
path
The path of the directory.
lastWriteTimeUtc
The date and time the directory was last written to. This value is expressed in UTC time.
G H
Description
I
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory. The path parameter is not case-sensitive.
J K L M
Exceptions
N O P Q
Exception
Condition
System.IO.FileNotFoundException
The specified path was not found.
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by System.IO.Path.InvalidPathChars.
System.ArgumentNullException
path is null.
System.IO.PathTooLongException
The specified path, file name, or both exceed the systemdefined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
System.UnauthorizedAccessException
The caller does not have the required permission.
R S T U V W X Y Z
1392
Contents | Index
System.IO
Directory SetLastWriteTimeUtc() Method
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
For writing to the specified file or directory. Associated enumeration: System.Security.Permissions.FileIOPermissionAccess.Write.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1393
Contents | Index
System.IO DirectoryNotFoundException
BCL
Object
A
Exception
B
ISerializable
NotStandardized
SystemException IOException
C
DirectoryNotFoundException
D E
Summary
F
Represents the error that occurs when part of a file or directory argument cannot be found.
G
Type Summary
H
public class DirectoryNotFoundException : IOException { // Constructors public DirectoryNotFoundException(); public DirectoryNotFoundException(string message); CF public DirectoryNotFoundException(string message,Exception innerException); MS CF protected DirectoryNotFoundException (SerializationInfo info, StreamingContext context); }
I J K L M N O
Example
P
using System; using System.IO; namespace Samples { public class DirectoryNotFoundExceptionSample { public static void Main() { try { string n = @"C:\foo\bar"; string[] s = Directory.GetFiles(n); } catch(DirectoryNotFoundException e) { Console.WriteLine("Exception: {0}", e); } } } }
Q R S T U V W X Y Z
1394
Contents | Index
System.IO
DirectoryNotFoundException DirectoryNotFoundException() Constructor
The output is Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path "C:\foo\bar". at System.IO.__Error.WinIOError(Int32 errorCode, String str) at System.IO.Directory.InternalGetFileDirectoryNames(String fullPath, Boolean file) at System.IO.Directory.InternalGetFiles(String path, String searchPattern) at System.IO.Directory.GetFiles(String path, String searchPattern) at System.IO.Directory.GetFiles(String path) at Samples.DirectoryNotFoundExceptionSample.Main() in C:\Books\BCL\Samples\ System.IO\DirectoryNotFoundException\DirectoryNotFoundException.cs:line 13
A B C D E F G
DirectoryNotFoundException() Constructor
H I
[ILASM] public rtspecialname specialname instance void .ctor() [C#] public DirectoryNotFoundException()
J K L
Summary
M
Constructs and initializes a new instance of the System.IO.DirectoryNotFoundException class.
N O
Description
P
This constructor initializes the System.IO.DirectoryNotFoundException.Message property of the new instance to a system-supplied message that describes the error, such as “Could not find the specified directory.” This message takes into account the current system culture. The System.IO.DirectoryNotFoundException.InnerException property of the new instance is initialized to null.
Q R S T U V
DirectoryNotFoundException(System.String) Constructor
W
[ILASM] public rtspecialname specialname instance void .ctor(string message) [C#] public DirectoryNotFoundException(string message)
X Y Z
1395
Contents | Index
DirectoryNotFoundException
System.IO
DirectoryNotFoundException() Constructor
Summary Constructs and initializes a new instance of the System.IO.DirectoryNotFoundException class. A
Parameters
B C D
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
E F G H
Description
I
This constructor initializes the System.IO.DirectoryNotFoundException.Message property of the new instance using message. If message is null, the System.IO.DirectoryNotFoundException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.IO.DirectoryNotFoundException.InnerException property is initialized to null.
J K L M N O
DirectoryNotFoundException(System.String, System.Exception) Constructor
P
[ILASM] public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException) [C#] public DirectoryNotFoundException(string message, Exception innerException)
Q R S T
Summary
U
Constructs and initializes a new instance of the System.IO.DirectoryNotFoundException class.
V W X Y Z
1396
Contents | Index
System.IO
DirectoryNotFoundException DirectoryNotFoundException() Constructor
Parameters Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
A
innerException
B C D
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
E F G
Description
H
This constructor initializes the System.IO.DirectoryNotFoundException.Message property of the new instance using message and the System.IO.DirectoryNotFoundException.InnerException property using innerException. If message is null, the System.IO.DirectoryNotFoundException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For more information on inner exceptions, see System.Exception.InnerException.]
I J K L M N
DirectoryNotFoundException(System.Runtime.Serialization. SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
O P Q
[ILASM] family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context) [C#] protected DirectoryNotFoundException(SerializationInfo info, StreamingContext context)
R S T U V
Summary
W
Initializes a new instance of the System.IO.DirectoryNotFoundException class with the specified serialization and context information.
X Y Z
1397
Contents | Index
DirectoryNotFoundException
System.IO
DirectoryNotFoundException() Constructor
Parameters Parameter
Description
info
The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown.
context
The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1398
Contents | Index
System DivideByZeroException
BCL
Object Exception
ISerializable
NotStandardized
A B
SystemException ArithmeticException
C
DivideByZeroException
D
Summary
E
Represents the error that is caused by an attempt to divide a number by zero.
F G
Type Summary
H
public class DivideByZeroException : ArithmeticException { // Constructors public DivideByZeroException (); public DivideByZeroException (string message); public DivideByZeroException (string message, Exception innerException); MS CF protected DivideByZeroException (SerializationInfo info, StreamingContext context); }
I J K L M N
Example
O
using System;
P Q
namespace Samples { public class DivideByZeroExceptionSample { public static void Main() { try { int i = 0; Console.WriteLine(42 / i); } catch(DivideByZeroException e) { Console.WriteLine("Exception: {0}", e); } } } }
R S T U V W X Y Z
1399
Contents | Index
DivideByZeroException
System
DivideByZeroException() Constructor
The output is Exception: System.DivideByZeroException: Attempted to divide by zero. at Samples.DivideByZeroExceptionSample.Main() in C:\Books\BCL\Samples\System\ DivideByZeroException\DivideByZeroException.cs:line 12
A B C
DivideByZeroException() Constructor
D [ILASM]
E
public rtspecialname specialname instance void .ctor()
F
[C#]
public DivideByZeroException()
G H
Summary
I
Constructs and initializes a new instance of the System.DivideByZeroException class.
J
Description
K
This constructor initializes the System.DivideByZeroException.Message property of the new instance to a system-supplied message that describes the error, such as “Attempted to divide by zero.” This message takes into account the current system culture. The System.DivideByZeroException.InnerException property is initialized to null.
L M N O P
DivideByZeroException(System.String) Constructor
Q
[ILASM]
public rtspecialname specialname instance void .ctor(string message)
R
[C#]
S
public DivideByZeroException(string message)
T
Summary
U
Constructs and initializes a new instance of the System.DivideByZeroException class.
V W
Parameters
X Y
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
Z
1400
Contents | Index
System
DivideByZeroException DivideByZeroException() Constructor
Description This constructor initializes the System.DivideByZeroException.Message property of the new instance using message. If message is null, the System.DivideByZeroException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.DivideByZeroException.InnerException property is initialized to null.
A B C D
DivideByZeroException(System.String, System.Exception) Constructor
E
[ILASM]
F
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
G
[C#]
H
public DivideByZeroException(string message, Exception innerException)
I
Summary
J
Constructs and initializes a new instance of the System.DivideByZeroException class.
K
Parameters
M
L
N
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
O P Q R
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
S T U
Description
V
This constructor initializes the System.DivideByZeroException.Message property of the new instance using message, and the System.DivideByZeroException.InnerException property using innerException. If message is null, the System.DivideByZeroException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
W X Y Z
1401
Contents | Index
DivideByZeroException
System
DivideByZeroException() Constructor
DivideByZeroException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor A
[ILASM]
B
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
C
[C#]
protected DivideByZeroException(SerializationInfo info, StreamingContext context)
D E
Summary
F
Initializes a new instance of the System.DivideByZeroException class with serialized data.
G H
Parameters
I J
Parameter
Description
info
The object that holds the serialized object data.
context
The contextual information about the source or destination.
K L M N O
Description
P
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
Q R S T U V W X Y Z
1402
Contents | Index
System Double Structure
Extended Numerics
Object
Double
A
IComparable
ValueType ExtendedNumerics
B
IFormattable IConvertible
NotStandardized
C D
Summary
E
Represents a 64-bit double-precision floating-point number.
F G
Type Summary public struct Double : IComparable, IFormattable, IConvertible { // Fields public const double Epsilon = 4.9406564584124654E-324; public const double MaxValue = 1.7976931348623157E+308; public const double MinValue = -1.7976931348623157E+308; public const double NaN = (double)0.0 / (double)0.0; public const double NegativeInfinity = (double)-1.0 / (double)0.0; public const double PositiveInfinity = (double)1.0 / (double)0.0;
H I J K L M N
// Methods public int CompareTo (object value); public override bool Equals (object obj); public override int GetHashCode (); MS public TypeCode GetTypeCode (); public static bool IsInfinity (double d); public static bool IsNaN (double d); public static bool IsNegativeInfinity (double d); public static bool IsPositiveInfinity (double d); public static double Parse (string s); public static double Parse (string s, NumberStyles style); public static double Parse (string s, NumberStyles style, IFormatProvider provider); public static double Parse (string s, IFormatProvider provider); public override string ToString (); public string ToString (string format); public string ToString (string format, IFormatProvider provider); public string ToString (IFormatProvider provider); MS CF public static bool TryParse (string s, NumberStyles style, IFormatProvider provider, out double result);
O P Q R S T U V W X Y Z
1403
Contents | Index
Double Structure
System
Double Structure
// MS MS MS MS MS MS MS MS MS MS MS MS MS MS MS
A B C D E F G H
Explicit Interface Members bool IConvertible.ToBoolean(IFormatProvider provider); byte IConvertible.ToByte(IFormatProvider provider); char IConvertible.ToChar(IFormatProvider provider); DateTime IConvertible.ToDateTime(IFormatProvider provider); decimal IConvertible.ToDecimal(IFormatProvider provider); double IConvertible.ToDouble(IFormatProvider provider); short IConvertible.ToInt16(IFormatProvider provider); int IConvertible.ToInt32(IFormatProvider provider); long IConvertible.ToInt64(IFormatProvider provider); sbyte IConvertible.ToSByte(IFormatProvider provider); float IConvertible.ToSingle(IFormatProvider provider); object IConvertible.ToType(Type type,IFormatProvider provider); ushort IConvertible.ToUInt16(IFormatProvider provider); uint IConvertible.ToUInt32(IFormatProvider provider); ulong IConvertible.ToUInt64(IFormatProvider provider);
}
I J
M
BA Notice that we use the common casing of NaN for Not-A-Number. Strictly following the design guideline rules would have led us to Double.Nan. This is a case where we did the right thing in violating the guidelines. It reminds me of the line, “foolish consistency is the hobgoblin of little minds...” by Ralph Waldo Emerson.
N
BG You might wonder why this simple code would throw an OverflowException:
K L
O
string s = Double.MaxValue.ToString(); double d = Convert.ToDouble(s);
P
The Convert.ToDouble() method throws an exception due to rounding errors. Note that the IEEE spec for doubles says that a double has about 15.7 decimal digits worth of precision, but to accurately represent that number you need to print out 17 digits to avoid rounding errors.
Q R S T
It is actually difficult to correctly generate those 17 digits on all hardware (at least in an efficient way). In the implementation of this class we happen to support it just fine on x86 due to some special case x86 assembly code. So on x86, you can use the “R” format (for round-trippable), but keep in mind that the “R” format may not work efficiently on all platforms. Here is an example of using the “R” format:
U V W X
CultureInfo ci = CultureInfo.InvariantCulture; Double d = Double.Parse(Double.MaxValue.ToString("R", ci), ci);
Y Z
continued
1404
Contents | Index
System
Double Structure Double Structure
As you may know, number formatting is culture sensitive. If you are writing code that needs to work identically on all machines, you should use the invariant culture. If you are writing a client application you can use the thread’s current culture to get the appropriate decimal formatting for that culture.
A B
KG The default formatting behavior for Double has caused some confusion. Simply stated, formatting a double by default selects the shortest available representation. For example:
C D E
Double d1 = 0.0004; Double d2 = 0.00004;
F G
Console.WriteLine(d1); //Prints 0.0004 Console.WriteLine(d2); //Prints 4E-05
H I
Description
J
System.Double is a 64-bit double precision floating-point type that represents values ranging from approximately 5.0E–324 to 1.7E+308 and from approximately –5.0E–324 to –1.7E+308 with a precision of 15–16 decimal digits. The System.Double type conforms to standard IEC 60559:1989, Binary Floating-point Arithmetic for Microprocessor Systems. A System.Double can represent the following values: • •
• •
K L M N
The finite set of non-zero values of the form s * m * 2e, where s is 1 or –1, and 0 < m < 253
O
and –1075 <= e <= 970. Positive infinity and negative infinity. Infinities are produced by operations that produce results with a magnitude greater than that which can be represented by a System.Double, such as dividing a non-zero number by zero. For example, using System.Double operands, 1.0 / 0.0 yields positive infinity, and -1.0 / 0.0 yields negative infinity. Operations include passing parameters and returning values. The Not-a-Number value (NaN). NaN values are produced by invalid floating-point operations, such as dividing zero by zero. When performing binary operations, if one of the operands is a System.Double, then the other operand is required to be an integral type or a floating-point type (System.Double or System.Single). Prior to performing the operation, if the other operand is not a System.Double, it is converted to System.Double, and the operation is performed using at least System.Double range and precision. If the operation produces a numeric result, the type of the result is System.Double.
P Q R S T U V W X Y Z
1405
Contents | Index
Double Structure
System
Double Structure
The floating-point operators, including the assignment operators, do not throw exceptions. Instead, in exceptional situations, the result of a floating-point operation is zero, infinity, or NaN, as described below: A
•
B C
•
D E
• •
F G
•
H I J K L
If the result of a floating-point operation is too small for the destination format, the result of the operation is zero. If the magnitude of the result of a floating-point operation is too large for the destination format, the result of the operation is positive infinity or negative infinity, as appropriate for the sign of the result. If a floating-point operation is invalid, the result of the operation is NaN. If one or both operands of a floating-point operation are NaN, the result of the operation is NaN. Conforming implementations of the CLI are permitted to perform floating-point operations using a precision that is higher than that required by the System.Double type. For example, hardware architectures that support an “extended” or “long double” floating-point type with greater range and precision than the System.Double type could implicitly perform all floating-point operations using this higher precision type. Expressions evaluated using a higher precision may cause a finite result to be produced instead of an infinity.
M
Example
N
using System;
O namespace Samples { public class DoubleMaxValue { public static void Main() { Double max = Double.MaxValue, epsilon = Double.Epsilon, nan = Double.NaN, negativeInfinity = Double.NegativeInfinity, positiveInfinity = Double.PositiveInfinity, min = Double.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("Epsilon: {0}", epsilon); Console.WriteLine("Nan: {0}", nan); Console.WriteLine("NegativeInfinity: {0}", negativeInfinity); Console.WriteLine("PositiveInfinity: {0}", positiveInfinity); Console.WriteLine("MinValue: {0}", min); string s = Double.MaxValue.ToString("R");
P Q R S T U V W X Y Z
1406
Contents | Index
System
Double Structure Epsilon Field
Console.WriteLine("From String {0} yields {1}", s, Double.Parse(s)); string[] formats = {"C","E","e4","F","G","N","P","R"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\") yields {2}", epsilon, f, epsilon.ToString(f));
A B
} }
C
}
D
The output is
E F
MaxValue: 1.79769313486232E+308 Epsilon: 4.94065645841247E-324 Nan: NaN NegativeInfinity: -Infinity PositiveInfinity: Infinity MinValue: -1.79769313486232E+308 From String 1.7976931348623157E+308 yields 1.79769313486232E+308 4.94065645841247E-324.ToString("C") yields $0.00 4.94065645841247E-324.ToString("E") yields 4.940656E-324 4.94065645841247E-324.ToString("e4") yields 4.9407e-324 4.94065645841247E-324.ToString("F") yields 0.00 4.94065645841247E-324.ToString("G") yields 4.94065645841247E-324 4.94065645841247E-324.ToString("N") yields 0.00 4.94065645841247E-324.ToString("P") yields 0.00 % 4.94065645841247E-324.ToString("R") yields 4.94065645841247E-324
G H I J K L M N O P
Double.Epsilon Field
Q
[ILASM]
R
.field public static literal float64 Epsilon [C#]
S
public const double Epsilon = 4.9406564584124654e-324
T
Summary
U
Represents the smallest positive System.Double value greater than zero.
V
Description
W
The value of this constant is 4.9406564584124654E–324.
X Y Z
1407
Contents | Index
Double Structure
System
MaxValue Field
Example using System; namespace Samples { public class DoubleEpsilon { public static void Main() { Double max = Double.MaxValue, epsilon = Double.Epsilon, nan = Double.NaN, negativeInfinity = Double.NegativeInfinity, positiveInfinity = Double.PositiveInfinity, min = Double.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("Epsilon: {0}", epsilon); Console.WriteLine("Nan: {0}", nan); Console.WriteLine("NegativeInfinity: {0}", negativeInfinity); Console.WriteLine("PositiveInfinity: {0}", positiveInfinity); Console.WriteLine("MinValue: {0}", min); } } }
A B C D E F G H I J K L M N
The output is
O MaxValue: 1.79769313486232E+308 Epsilon: 4.94065645841247E-324 Nan: NaN NegativeInfinity: -Infinity PositiveInfinity: Infinity MinValue: -1.79769313486232E+308
P Q R S T
Double.MaxValue Field
U
[ILASM]
V
.field public static literal float64 MaxValue
W
[C#]
public const double MaxValue = 1.7976931348623157e+308
X Y
Summary
Z
Contains the maximum positive value for the System.Double type.
1408
Contents | Index
System
Double Structure MinValue Field
Description The value of this constant is 1.7976931348623157E+308.
Example
A
using System;
B C
namespace Samples { public class DoubleSample { public static void Main() { Double max = Double.MaxValue, epsilon = Double.Epsilon, nan = Double.NaN, negativeInfinity = Double.NegativeInfinity, positiveInfinity = Double.PositiveInfinity, min = Double.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("Epsilon: {0}", epsilon); Console.WriteLine("Nan: {0}", nan); Console.WriteLine("NegativeInfinity: {0}", negativeInfinity); Console.WriteLine("PositiveInfinity: {0}", positiveInfinity); Console.WriteLine("MinValue: {0}", min); } } }
D E F G H I J K L M N O P
The output is
Q
MaxValue: 1.79769313486232E+308 Epsilon: 4.94065645841247E-324 Nan: NaN NegativeInfinity: -Infinity PositiveInfinity: Infinity MinValue: -1.79769313486232E+308
R S T U V
Double.MinValue Field
W
[ILASM]
X
.field public static literal float64 MinValue
Y
[C#]
Z
public const double MinValue = -1.7976931348623157e+308
1409
Contents | Index
Double Structure
System
NaN Field
Summary Contains the minimum (most negative) value for the System.Double type. A
Description
B
The value of this constant is –1.7976931348623157E+308.
C
Example
D
using System;
E namespace Samples { public class DoubleMinValue { public static void Main() { Double max = Double.MaxValue, epsilon = Double.Epsilon, nan = Double.NaN, negativeInfinity = Double.NegativeInfinity, positiveInfinity = Double.PositiveInfinity, min = Double.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("Epsilon: {0}", epsilon); Console.WriteLine("Nan: {0}", nan); Console.WriteLine("NegativeInfinity: {0}", negativeInfinity); Console.WriteLine("PositiveInfinity: {0}", positiveInfinity); Console.WriteLine("MinValue: {0}", min); } } }
F G H I J K L M N O P Q R
The output is
S MaxValue: 1.79769313486232E+308 Epsilon: 4.94065645841247E-324 Nan: NaN NegativeInfinity: -Infinity PositiveInfinity: Infinity MinValue: -1.79769313486232E+308
T U V W X
Double.NaN Field
Y
[ILASM]
Z
.field public static literal float64 NaN [C#]
public const double NaN = (double)0.0 / (double)0.0
1410
Contents | Index
System
Double Structure NaN Field
Summary Represents an undefined result of operations involving System.Double.
Description
A
Not-a-Number (NaN) values are returned when the result of a System.Double operation is undefined. A NaN value is not equal to any other value, including another NaN value. The value of this field is obtained by dividing System.Double zero by zero. [Note: System.Double.NaN represents one of many possible NaN values. To test whether a System.Double value is a NaN, use the System.Double.IsNaN method.]
B C D E F G
Example
H
using System;
I
namespace Samples { public class DoubleNaN { public static void Main() { Double max = Double.MaxValue, epsilon = Double.Epsilon, nan = Double.NaN, negativeInfinity = Double.NegativeInfinity, positiveInfinity = Double.PositiveInfinity, min = Double.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("Epsilon: {0}", epsilon); Console.WriteLine("Nan: {0}", nan); Console.WriteLine("NegativeInfinity: {0}", negativeInfinity); Console.WriteLine("PositiveInfinity: {0}", positiveInfinity); Console.WriteLine("MinValue: {0}", min); } } }
J K L M N O P Q R S T U V
The output is
W X
MaxValue: 1.79769313486232E+308 Epsilon: 4.94065645841247E-324 Nan: NaN NegativeInfinity: -Infinity PositiveInfinity: Infinity MinValue: -1.79769313486232E+308
Y Z
1411
Contents | Index
Double Structure
System
NegativeInfinity Field
Double.NegativeInfinity Field [ILASM]
.field public static literal float64 NegativeInfinity
A
[C#]
B
public const double NegativeInfinity = (double)-1.0 / (double)(0.0)
C
Summary
D
Represents a negative infinity of type System.Double.
E
Description
F
The value of this constant is obtained by dividing a negative System.Double by zero. [Note: To test whether a System.Double value is a negative infinity value, use the System.Double.IsNegativeInfinity method.]
G H I
Example
J
using System;
K
namespace Samples { public class DoubleNegativeInfinity { public static void Main() { Double max = Double.MaxValue, epsilon = Double.Epsilon, nan = Double.NaN, negativeInfinity = Double.NegativeInfinity, positiveInfinity = Double.PositiveInfinity, min = Double.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("Epsilon: {0}", epsilon); Console.WriteLine("Nan: {0}", nan); Console.WriteLine("NegativeInfinity: {0}", negativeInfinity); Console.WriteLine("PositiveInfinity: {0}", positiveInfinity); Console.WriteLine("MinValue: {0}", min); } } }
L M N O P Q R S T U V W
The output is
X
MaxValue: 1.79769313486232E+308 Epsilon: 4.94065645841247E-324 Nan: NaN NegativeInfinity: -Infinity PositiveInfinity: Infinity MinValue: -1.79769313486232E+308
Y Z
1412
Contents | Index
System
Double Structure PositiveInfinity Field
Double.PositiveInfinity Field [ILASM]
.field public static literal float64 PositiveInfinity [C#]
A
public const double PositiveInfinity = (double)1.0 / (double)(0.0)
B
Summary
C
Represents a positive infinity of type System.Double.
D E
Description
F
The value of this constant is obtained by dividing a positive System.Double by zero. [Note: To test whether a System.Double value is a positive infinity value, use the System.Double.IsPositiveInfinity method.]
G H
Example
I
using System;
J K
namespace Samples { public class DoublePositiveInfinity { public static void Main() { Double max = Double.MaxValue, epsilon = Double.Epsilon, nan = Double.NaN, negativeInfinity = Double.NegativeInfinity, positiveInfinity = Double.PositiveInfinity, min = Double.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("Epsilon: {0}", epsilon); Console.WriteLine("Nan: {0}", nan); Console.WriteLine("NegativeInfinity: {0}", negativeInfinity); Console.WriteLine("PositiveInfinity: {0}", positiveInfinity); Console.WriteLine("MinValue: {0}", min); } } }
L M N O P Q R S T U V W
The output is
X
MaxValue: 1.79769313486232E+308 Epsilon: 4.94065645841247E-324 Nan: NaN NegativeInfinity: -Infinity PositiveInfinity: Infinity MinValue: -1.79769313486232E+308
Y Z
1413
Contents | Index
Double Structure
System
CompareTo() Method
Double.CompareTo(System.Object) Method [ILASM]
.method public final hidebysig virtual int32 CompareTo(object value)
A
[C#]
public int CompareTo(object value)
B C
Summary
D
Returns the sort order of the current instance compared to the specified System.Object.
E
Parameters
F G
Parameter
Description
value
The System.Object to compare to the current instance.
H I J
Return Value
K
A System.Int32 containing a value that reflects the sort order of the current instance as compared to value. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number.
L M N O
Value
P Q
any negative number
R S
zero
T
Description Current instance < value. Current instance is a NaN and value is not a NaN and is not a null reference. Current instance == value. Current instance and value are both NaN, positive infinity, or negative infinity. Current instance > value.
U
any positive number
V
value is a null reference. Current instance is not a NaN and value is a NaN.
W X
Description
Y
[Note: This method is implemented to support the System.IComparable interface. Note that, although a NaN is not considered to be equal to another NaN (even itself), the System.IComparable interface requires that A.CompareTo(A) return zero.]
Z
1414
Contents | Index
System
Double Structure CompareTo() Method
Exceptions Exception
Condition
System.ArgumentException
value is not a null reference and is not of type System.Double.
A B C D
Example
E
using System;
F namespace Samples { public class DoubleCompareTo { private static string CompareDoubles(Double d1, Double d2) { int i = d1.CompareTo(d2); if(0 == i) return String.Format("{0} is equal to {1}", d1, d2); if(i > 0) return String.Format("{0} is greater than {1}", d1, d2); else return String.Format("{0} is less than {1}", d1, d2); } public static void Main() { Double max = Double.MaxValue, min = Double.MinValue; Console.WriteLine(CompareDoubles(min, min)); Console.WriteLine(CompareDoubles(max, min)); Console.WriteLine(CompareDoubles(min, max)); } } }
G H I J K L M N O P Q R S T U
The output is
V W
-1.79769313486232E+308 is equal to -1.79769313486232E+308 1.79769313486232E+308 is greater than -1.79769313486232E+308 -1.79769313486232E+308 is less than 1.79769313486232E+308
X Y Z
1415
Contents | Index
Double Structure
System
Equals() Method
Double.Equals(System.Object) Method [ILASM]
.method public hidebysig virtual bool Equals(object obj)
A
[C#]
public override bool Equals(object obj)
B C
Summary
D
Determines whether the current instance and the specified System.Object represent the same type and value.
E F
Parameters
G H
Parameter
Description
obj
The System.Object to compare to the current instance.
I J K
Return Value
L
true if obj is a System.Double with the same value as the current instance; otherwise, false. If obj is a null reference or is not an instance of System.Double, returns false. If either obj or the current instance is NaN and the other is not, returns false. If obj and the current instance are both NaN, positive infinity, or negative infinity, returns true.
M N O P
Description
Q
[Note: This method overrides System.Object.Equals.]
R
Example
S
using System;
T namespace Samples { public class DoubleEquals { public static void Main() { Double max = Double.MaxValue, min = Double.MinValue; Console.WriteLine("Is {0} equal to {1}: {2}", max, max, max.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", max, min, max.Equals(min));
U V W X Y Z
1416
Contents | Index
System
Double Structure GetHashCode() Method
Console.WriteLine("Is {0} equal to {1}: {2}", min, max, min.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", min, min, min.Equals(min));
A
} }
B
}
C
The output is Is Is Is Is
D
1.79769313486232E+308 equal to 1.79769313486232E+308: True 1.79769313486232E+308 equal to -1.79769313486232E+308: False -1.79769313486232E+308 equal to 1.79769313486232E+308: False -1.79769313486232E+308 equal to -1.79769313486232E+308: True
E F G H
Double.GetHashCode() Method
I
[ILASM]
J
.method public hidebysig virtual int32 GetHashCode()
K
[C#]
public override int GetHashCode()
L
Summary
M
Generates a hash code for the current instance.
N O
Return Value
P
A System.Int32 containing the hash code for this instance.
Q
Description
R
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
S T
Example
U
using System;
V
namespace Samples { public class DoubleGetHashCode { public static void Main() { Double max = Double.MaxValue, zero = 0, min = Double.MinValue;
W X Y Z
1417
Contents | Index
Double Structure
System
GetTypeCode() Method
Console.WriteLine("{0} has hashcode of: {1}", max, max.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", zero, zero.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", min, min.GetHashCode());
A B }
C
} }
D
The output is
E F
1.79769313486232E+308 has hashcode of: -2146435072 0 has hashcode of: 0 -1.79769313486232E+308 has hashcode of: 1048576
G H I
Double.GetTypeCode() Method
J [ILASM]
K
.method public final hidebysig virtual valuetype System.TypeCode GetTypeCode() [C#]
L
public TypeCode GetTypeCode()
M
Summary
N
Returns the System.TypeCode for value type System.Double.
O P
Double.IsInfinity(System.Double) Method
Q R
[ILASM]
S
[C#]
.method public hidebysig static bool IsInfinity(float64 d) public static bool IsInfinity(double d)
T U
Summary
V
Determines whether the specified System.Double represents an infinity, which can be either positive or negative.
W X
Parameters
Y Z
Parameter
Description
d
The System.Double to be checked.
1418
Contents | Index
System
Double Structure IsInfinity() Method
Return Value true if d represents a positive or negative infinity value; otherwise, false.
Description
A
[Note: Floating-point operations return positive or negative infinity values to signal an overflow condition.]
B C D
Example
E
using System;
F namespace Samples { public class DoubleIsInfinity { public static void Main() { Double nan = Double.NaN, negativeInfinity = Double.NegativeInfinity, positiveInfinity = Double.PositiveInfinity; Console.WriteLine("{0} IsInfinity: {1}", nan, Double.IsInfinity(nan)); Console.WriteLine("{0} IsInfinity: {1}", negativeInfinity, Double.IsInfinity(negativeInfinity)); Console.WriteLine("{0} IsInfinity: {1}", positiveInfinity, Double.IsInfinity(positiveInfinity)); Console.WriteLine("{0} IsNaN: {1}", nan, Double.IsNaN(nan)); Console.WriteLine("{0} IsNaN: {1}", positiveInfinity, Double.IsNaN(positiveInfinity)); } } }
G H I J K L M N O P Q R S T
The output is
U
NaN IsInfinity: False -Infinity IsInfinity: True Infinity IsInfinity: True NaN IsNaN: True Infinity IsNaN: False
V W X Y Z
1419
Contents | Index
Double Structure
System
IsNaN() Method
Double.IsNaN(System.Double) Method [ILASM]
.method public hidebysig static bool IsNaN(float64 d)
A
[C#]
public static bool IsNaN(double d)
B C
Summary
D
Determines whether the value of the specified System.Double is undefined (Not-aNumber).
E F
Parameters
G H
Parameter
Description
d
The System.Double to be checked.
I J K
Return Value
L
true if d represents a NaN value; otherwise, false.
M N
Description
O
[Note: Floating-point operations return NaN values to signal that the result of the operation is undefined. For example, dividing (double) 0.0 by 0.0 results in a NaN value.]
P Q
Example
R
using System;
S
namespace Samples { public class DoubleIsNan { public static void Main() { Double nan = Double.NaN, negativeInfinity = Double.NegativeInfinity, positiveInfinity = Double.PositiveInfinity; Console.WriteLine("{0} IsInfinity: {1}", nan, Double.IsInfinity(nan)); Console.WriteLine("{0} IsInfinity: {1}", negativeInfinity, Double.IsInfinity(negativeInfinity)); Console.WriteLine("{0} IsInfinity: {1}", positiveInfinity, Double.IsInfinity(positiveInfinity));
T U V W X Y Z
1420
Contents | Index
System
Double Structure IsNegativeInfinity() Method
Console.WriteLine("{0} IsNaN: {1}", nan, Double.IsNaN(nan)); Console.WriteLine("{0} IsNaN: {1}", positiveInfinity, Double.IsNaN(positiveInfinity));
A
} }
B
}
C
The output is
D E
NaN IsInfinity: False -Infinity IsInfinity: True Infinity IsInfinity: True NaN IsNaN: True Infinity IsNaN: False
F G H I
Double.IsNegativeInfinity(System.Double) Method
J
[ILASM]
K
.method public hidebysig static bool IsNegativeInfinity(float64 d)
L
[C#]
public static bool IsNegativeInfinity(double d)
M
Summary
N
Determines whether the specified System.Double represents a negative infinity value.
O P
Parameters
Q
Parameter
Description
d
The System.Double to be checked.
R S T U
Return Value
V
true if d represents a negative infinity value; otherwise, false.
W
Description
X
[Note: Floating-point operations return negative infinity values to signal an overflow condition.]
Y Z
1421
Contents | Index
Double Structure
System
IsPositiveInfinity() Method
Example using System; namespace Samples { public class DoubleIsNegativeInfinity { public static void Main() { Double nan = Double.NaN, negativeInfinity = Double.NegativeInfinity, positiveInfinity = Double.PositiveInfinity; Console.WriteLine("{0} IsInfinity: {1}", nan, Double.IsInfinity(nan)); Console.WriteLine("{0} IsInfinity: {1}", negativeInfinity, Double.IsInfinity(negativeInfinity)); Console.WriteLine("{0} IsInfinity: {1}", positiveInfinity, Double.IsInfinity(positiveInfinity)); Console.WriteLine("{0} IsNegativeInfinity: {1}", negativeInfinity, Double.IsNegativeInfinity(negativeInfinity)); Console.WriteLine("{0} IsNegativeInfinity: {1}", positiveInfinity, Double.IsNegativeInfinity(positiveInfinity)); } } }
A B C D E F G H I J K L M N O
The output is
P
NaN IsInfinity: False -Infinity IsInfinity: True Infinity IsInfinity: True -Infinity IsNegativeInfinity: True Infinity IsNegativeInfinity: False
Q R S T U
Double.IsPositiveInfinity(System.Double) Method
V
[ILASM]
W
.method public hidebysig static bool IsPositiveInfinity(float64 d) [C#]
X
public static bool IsPositiveInfinity(double d)
Y
Summary
Z
Determines whether the specified System.Double represents a positive infinity value.
1422
Contents | Index
System
Double Structure IsPositiveInfinity() Method
Parameters Parameter
Description
d
The System.Double to be checked.
A B C
Return Value
D
true if d represents a positive infinity value; otherwise, false.
E F
Description
G
[Note: Floating-point operations return positive infinity values to signal an overflow condition.]
H I
Example
J
using System;
K namespace Samples { public class DoubleIsPositiveInfinity { public static void Main() { Double nan = Double.NaN, negativeInfinity = Double.NegativeInfinity, positiveInfinity = Double.PositiveInfinity; Console.WriteLine("{0} IsInfinity: {1}", nan, Double.IsInfinity(nan)); Console.WriteLine("{0} IsInfinity: {1}", negativeInfinity, Double.IsInfinity(negativeInfinity)); Console.WriteLine("{0} IsInfinity: {1}", positiveInfinity, Double.IsInfinity(positiveInfinity)); Console.WriteLine("{0} IsPositiveInfinity: {1}", negativeInfinity, Double.IsPositiveInfinity(negativeInfinity)); Console.WriteLine("{0} IsPositiveInfinity: {1}", positiveInfinity, Double.IsPositiveInfinity(positiveInfinity)); } } }
L M N O P Q R S T U V W X Y Z
1423
Contents | Index
Double Structure
System
Parse() Method
The output is NaN IsInfinity: False -Infinity IsInfinity: True Infinity IsInfinity: True -Infinity IsPositiveInfinity: False Infinity IsPositiveInfinity: True
A B C D E
Double.Parse(System.String) Method
F
[ILASM]
.method public hidebysig static float64 Parse(string s)
G
[C#]
public static double Parse(string s)
H I
Summary
J
Returns the specified System.String converted to a System.Double value.
K
Parameters
L M
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Float and/or System.Globalization.NumberStyles.AllowThousands style.
N O P Q
Return Value
R
The System.Double value obtained from s. If the parsed value is less than System.Double.MinValue, this method returns System.Double.NegativeInfinity. If the parsed value is greater than System.Double.MaxValue, this method returns System.Double.PositiveInfinity. If s equals System.Globalization.NumberFormatInfo.NaNSymbol, this method returns System.Double.NaN.
S T U V W
Description
X
This version of System.Double.Parse is equivalent to System.Double.Parse (s, System.Globalization.NumberStyles.Float| System.Globalization.NumberStyles.AllowThousands, null). The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.]
Y Z
1424
Contents | Index
System
Double Structure Parse() Method
Exceptions Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
A B C D
Example
E
using System;
F
namespace Samples { public class DoubleParse { public static void Main() { string s; try { s = Double.MaxValue.ToString("R"); Console.WriteLine("From String {0} yields s, Double.Parse(s)); s = "0"; Console.WriteLine("From String {0} yields s, Double.Parse(s)); s = Double.MinValue.ToString("R"); Console.WriteLine("From String {0} yields s, Double.Parse(s)); s = String.Empty; Console.WriteLine("From String {0} yields s, Double.Parse(s)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = Double.MaxValue.ToString(); Console.WriteLine("From String {0} yields s, Double.Parse(s)); } catch(OverflowException e)
G H I J K L M
{1}",
N O
{1}",
P Q
{1}",
R {1}",
S T U V W X
{1}",
Y Z
1425
Contents | Index
Double Structure
System
Parse() Method
{ Console.WriteLine("Exception: {0}", e); } }
A
} }
B C
The output is
D From String 1.7976931348623157E+308 yields 1.79769313486232E+308 From String 0 yields 0 From String -1.7976931348623157E+308 yields -1.79769313486232E+308 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseDouble(String s, NumberStyles style, NumberFormatInfo info) at System.Double.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Double.Parse(String s) at Samples.DoubleParse.Main() in C:\Books\BCL\Samples\System\Double\ Parse(System.String)\Double.cs:line 22 Exception: System.OverflowException: Value was either too large or too small for a Double. at System.Number.ParseDouble(String s, NumberStyles style, NumberFormatInfo info) at System.Double.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Double.Parse(String s) at Samples.DoubleParse.Main() in C:\Books\BCL\Samples\System\Double\ Parse(System.String)\Double.cs:line 32
E F G H I J K L M N O P Q
Double.Parse(System.String, System.Globalization.NumberStyles) Method
R
[ILASM]
S
.method public hidebysig static float64 Parse(string s, valuetype System.Globalization.NumberStyles style)
T
[C#]
public static double Parse(string s, NumberStyles style)
U V
Summary
W
Returns the specified System.String converted to a System.Double value.
X Y Z
1426
Contents | Index
System
Double Structure Parse() Method
Parameters Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Float and System.Globalization.NumberStyles.AllowThousands styles.
A B C D E F G
Return Value
H
The System.Double value obtained from s. If the parsed value is less than System.Double.MinValue, this method returns System.Double.NegativeInfinity. If the parsed value is greater than System.Double.MaxValue, this method returns System.Double.PositiveInfinity. If s equals System.Globalization.NumberFormatInfo.NaNSymbol, this method returns System.Double.NaN.
I J K L
Description
M
This version of System.Double.Parse is equivalent to System.Double.Parse(s, style, null). The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.]
N O P Q R
Exceptions
S
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
T U V W X Y Z
1427
Contents | Index
Double Structure
System
Parse() Method
Example using System; using System.Globalization;
A namespace Samples { public class DoubleParse { public static void Main() { string s; try { s = "$0"; Console.WriteLine("From String {0} yields {1}", s, Double.Parse(s, NumberStyles.AllowCurrencySymbol)); s = "$42"; Console.WriteLine("From String {0} yields {1}", s, Double.Parse(s, NumberStyles.AllowCurrencySymbol)); s = "(42)"; Console.WriteLine("From String {0} yields {1}", s, Double.Parse(s, NumberStyles.AllowParentheses)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Double.Parse(s, NumberStyles.Any)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = Double.MaxValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Double.Parse(s, NumberStyles.Any)); } catch(OverflowException e)
B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1428
Contents | Index
System
Double Structure Parse() Method
{ Console.WriteLine("Exception: {0}", e); } }
A
} }
B C
The output is
D
From String $0 yields 0 From String $42 yields 42 From String (42) yields -42 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseDouble(String s, NumberStyles style, NumberFormatInfo info) at System.Double.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Double.Parse(String s, NumberStyles style) at Samples.DoubleParse.Main() in C:\Books\BCL\Samples\System\Double\ Parse(System.String,System.Globalization.NumberStyles)\Double.cs:line 29 Exception: System.OverflowException: Value was either too large or too small for a Double. at System.Number.ParseDouble(String s, NumberStyles style, NumberFormatInfo info) at System.Double.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Double.Parse(String s, NumberStyles style) at Samples.DoubleParse.Main() in C:\Books\BCL\Samples\System\Double\ Parse(System.String,System.Globalization.NumberStyles)\Double.cs:line 41
E F G H I J K L M N O P
Double.Parse(System.String, System.Globalization.NumberStyles, System.IFormatProvider) Method
Q
[ILASM]
S
.method public hidebysig static float64 Parse(string s, valuetype System.Globalization.NumberStyles style, class System.IFormatProvider provider)
T
R
[C#]
U
public static double Parse(string s, NumberStyles style, IFormatProvider provider)
V
Summary
W
Returns the specified System.String converted to a System.Double value.
X Y Z
1429
Contents | Index
Double Structure
System
Parse() Method
Parameters Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Float and System.Globalization.NumberStyles.AllowThousands styles.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
A B C D E F G H I J
Return Value
K
The System.Double value obtained from s. If the parsed value is less than System.Double.MinValue, this method returns System.Double.NegativeInfinity. If the parsed value is greater than System.Double.MaxValue, this method returns System.Double.PositiveInfinity. If s equals System.Globalization.NumberFormatInfo.NaNSymbol, this method returns System.Double.NaN.
L M N O
Description
P
The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used.
Q R S T
Exceptions
U V
Exception
Condition
W
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
X Y Z
1430
Contents | Index
System
Double Structure Parse() Method
Example using System; using System.Globalization;
A namespace Samples { public class DoubleParse { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; string s = " ~0"; Console.WriteLine("From String {0} yields {1}", s, Double.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowLeadingSign, c)); s = "(1)"; Console.WriteLine("From String {0} yields {1}", s, Double.Parse(s, NumberStyles.AllowParentheses, c)); s = " !1 "; Console.WriteLine("From String {0} yields {1}", s, Double.Parse(s, NumberStyles.Any, c)); } } }
B C D E F G H I J K L M N O P Q R S T U
The output is
V W
From String ~0 yields 0 From String (1) yields -1 From String !1 yields -1
X Y Z
1431
Contents | Index
Double Structure
System
Parse() Method
Double.Parse(System.String, System.IFormatProvider) Method [ILASM]
A
.method public hidebysig static float64 Parse(string s, class System.IFormatProvider provider)
B
[C#]
public static double Parse(string s, IFormatProvider provider)
C D
Summary
E
Returns the specified System.String converted to a System.Double value.
F
Parameters
G H
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Float and/or System.Globalization.NumberStyles.AllowThousands style.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
I J K L M N O
Return Value
P
The System.Double value obtained from s. If the parsed value is less than System.Double.MinValue, this method returns System.Double.NegativeInfinity. If the parsed value is greater than System.Double.MaxValue, this method returns System.Double.PositiveInfinity. If s equals System.Globalization.NumberFormatInfo.NaNSymbol, this method returns System.Double.NaN.
Q R S T
Description
U
This version of System.Double.Parse is equivalent to System.Double.Parse(s, System.Globalization.NumberStyles.Float| System.Globalization.NumberStyles.AllowThousands, provider). The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used.
V W X Y Z
1432
Contents | Index
System
Double Structure Parse() Method
Exceptions Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
A B C D
Example
E
using System; using System.Globalization;
F G
namespace Samples { public class DoubleParse { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; try { s = "~0"; Console.WriteLine("From String {0} yields s, Double.Parse(s, c)); s = Double.MaxValue.ToString("R", c); Console.WriteLine("From String {0} yields s, Double.Parse(s, c)); s = "!1"; Console.WriteLine("From String {0} yields s, Double.Parse(s, c)); s = String.Empty; Console.WriteLine("From String {0} yields s, Double.Parse(s, c)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = Double.MaxValue.ToString(c);
H I J K L M N O P
{1}",
Q R
{1}",
S T
{1}",
U {1}",
V W X Y Z
1433
Contents | Index
Double Structure
System
ToString() Method
Console.WriteLine("From String {0} yields {1}", s, Double.Parse(s, c)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C
} }
D
}
E
The output is
F
From String ~0 yields 0 From String 1.7976931348623157E~308 yields 1.79769313486232E+308 From String !1 yields -1 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseDouble(String s, NumberStyles style, NumberFormatInfo info) at System.Double.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Double.Parse(String s, IFormatProvider provider) at Samples.DoubleParse.Main() in C:\Books\BCL\Samples\System\Double\ Parse(System.String,System.IFormatProvider)\Double.cs:line 27 Exception: System.OverflowException: Value was either too large or too small for a Double. at System.Number.ParseDouble(String s, NumberStyles style, NumberFormatInfo info) at System.Double.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Double.Parse(String s, IFormatProvider provider) at Samples.DoubleParse.Main() in C:\Books\BCL\Samples\System\Double\ Parse(System.String,System.IFormatProvider)\Double.cs:line 37
G H I J K L M N O P Q R
Double.ToString() Method
S
[ILASM]
T
.method public hidebysig virtual string ToString() [C#]
U
public override string ToString()
V
Summary
W
Returns a System.String representation of the value of the current instance.
X Y
Return Value
Z
A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the current system culture.
1434
Contents | Index
System
Double Structure ToString() Method
Description This version of System.Double.ToString is equivalent to System.Double.ToString(null, null). [Note: The general format specifier formats the number in either fixed-point or exponential notation form. For a detailed description of the general format, see the System.IFormattable interface. This method overrides System.Object.ToString.]
A B C
Example
D
using System;
E F
namespace Samples { public class DoubleToString { public static void Main() { Double max = Double.MaxValue, min = Double.MinValue; Console.WriteLine("{0}.ToString() yields {1}", max, max.ToString()); Console.WriteLine("{0}.ToString() yields {1}", min, min.ToString()); } } }
G H I J K L M N O
The output is
P Q
1.79769313486232E+308.ToString() yields 1.79769313486232E+308 -1.79769313486232E+308.ToString() yields -1.79769313486232E+308
R S
Double.ToString(System.String) Method
T
[ILASM]
U
.method public hidebysig instance string ToString(string format)
V
[C#]
W
public string ToString(string format)
X
Summary
Y
Returns a System.String representation of the value of the current instance.
Z
1435
Contents | Index
Double Structure
System
ToString() Method
Parameters Parameter
Description
format
A System.String that specifies the format of the returned string. [Note: For a list of valid values, see System.Double.ToString(System.String, System.IFormatProvider).]
A B C D E
Return Value
F
A System.String representation of the current instance formatted as specified by format. The string takes into account the current system culture.
G H
Description
I
This version of System.Double.ToString is equivalent to System.Double.ToString(format, null). If format is a null reference, the general format specifier “G” is used.
J K L
Exceptions
M N O
Exception
Condition
System.FormatException
format is invalid.
P Q
Example
R
using System;
S
namespace Samples { public class DoubleToString { public static void Main() { Double d = 42.42; string[] formats = {"C","E","e4","F","G","N","P","R"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\") yields {2}", d, f, d.ToString(f)); } } }
T U V W X Y Z
1436
Contents | Index
System
Double Structure ToString() Method
The output is 42.42.ToString("C") yields $42.42 42.42.ToString("E") yields 4.242000E+001 42.42.ToString("e4") yields 4.2420e+001 42.42.ToString("F") yields 42.42 42.42.ToString("G") yields 42.42 42.42.ToString("N") yields 42.42 42.42.ToString("P") yields 4,242.00 % 42.42.ToString("R") yields 42.42
A B C D E F
Double.ToString(System.String, System.IFormatProvider) Method
G
[ILASM]
H
.method public final hidebysig virtual string ToString(string format, class System.IFormatProvider provider)
I
[C#]
J
public string ToString(string format, IFormatProvider provider)
K
Summary
L
Returns a System.String representation of the value of the current instance.
M N
Parameters
O
Parameter
Description
format
A System.String containing a character that specifies the format of the returned string, optionally followed by a non-negative integer that specifies the precision of the number in the returned System.String.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo instance containing culture-specific formatting information.
P Q R S T U V
Return Value
W
A System.String representation of the current instance formatted as specified by format. The string takes into account the information in the System.Globalization.NumberFormatInfo instance supplied by provider.
X Y Z
1437
Contents | Index
Double Structure
System
ToString() Method
Description If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. If format is a null reference, the general format specifier “G” is used. The following table lists the format characters that are valid for the System.Double type.
A B C D E
Format Characters
Description
F
"C", "c"
Currency format.
"E", "e"
Exponential notation format.
"F", "f"
Fixed-point format.
J
"G", "g"
General format.
K
"N", "n"
Number format.
"P", "p"
Percent format.
"R", "r"
Round-trip format.
G H I
L M N O
[Note: For a detailed description of formatting, see the System.IFormattable interface. This method is implemented to support the System.IFormattable interface.]
P Q R
Exceptions
S T
Exception
Condition
U
System.FormatException
format is invalid.
V W
Example
X
using System; using System.Globalization;
Y
namespace Samples { public class DoubleToString
Z
1438
Contents | Index
System
Double Structure ToString() Method
{ public static void Main() { Double d = 42.42; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; n.CurrencySymbol = "#"; string[] formats = {"C", "E", "F", "G", "N", "P", "R"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\",n) yields {2}", d, f, d.ToString(f, c)); }
A B C D E F G
}
H
}
I
The output is 42.42.ToString("C",n) 42.42.ToString("E",n) 42.42.ToString("F",n) 42.42.ToString("G",n) 42.42.ToString("N",n) 42.42.ToString("P",n) 42.42.ToString("R",n)
yields yields yields yields yields yields yields
J
#42.42 4.242000E~001 42.42 42.42 42.42 4,242.00 % 42.42
K L M N O
Double.ToString(System.IFormatProvider) Method
P
[ILASM]
Q
.method public final hidebysig virtual string ToString(class System.IFormatProvider provider)
R
[C#]
S
public string ToString(IFormatProvider provider)
T
Summary
U
Returns a System.String representation of the value of the current instance.
V W
Parameters
X
Parameter
Description
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
Y Z
1439
Contents | Index
Double Structure
System
ToString() Method
Return Value A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the formatting information in the System.Globalization.NumberFormatInfo instance supplied by provider.
A B
Description
C
This version of System.Double.ToString is equivalent to System.Double.ToString(null, provider). If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. [Note: The general format specifier formats the number in either fixed-point or exponential notation form. For a detailed description of the general format, see the System.IFormattable interface.]
D E F G H I
Example
J
using System; using System.Globalization;
K L
namespace Samples { public class DoubleToString { public static void Main() { Double max = Double.MaxValue, min = Double.MinValue; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; Console.WriteLine("{0}.ToString yields {1}", max, max.ToString(c)); Console.WriteLine("{0}.ToString yields {1}", min, min.ToString(c)); } } }
M N O P Q R S T U V W X
The output is
Y 1.79769313486232E+308.ToString yields 1.79769313486232E~308 -1.79769313486232E+308.ToString yields !1.79769313486232E~308
Z
1440
Contents | Index
System
Double Structure TryParse() Method
Double.TryParse(System.String, System.Globalization.NumberStyles, System.IFormatProvider, System.Double&) Method [ILASM]
A
.method public hidebysig static bool TryParse(string s, valuetype System.Globalization.NumberStyles style, class System.IFormatProvider provider, class System.Double& result)
B C
[C#]
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out double result)
D E
Summary
F
Converts the string representation of a number in a specified style and culture-specific format to its double-precision floating-point number equivalent.
G H I
Parameters
J
Parameter
Description
s
A string containing a number to convert.
style
The combination of one or more System.Globalization.NumberStyles constants that indicate the permitted format of s.
provider
A System.IFormatProvider that supplies culture-specific formatting information about s.
O
A double-precision floating-point number equivalent to the numeric value or symbol specified in s. If the return value is false, result is set to zero.
Q
result
K L M N
P
R S
Return Value
T
true if s is converted successfully; otherwise, false.
U
Description
V
The System.Double.TryParse method is like the System.Double.Parse method, except this method does not throw an exception if the conversion fails. If the conversion succeeds, the return value is true and the result parameter is set to the outcome of the conversion. If the conversion fails, the return value is false and the result parameter is set to zero. The conversion fails if the s parameter is null or not a numeric value, the provider parameter does not yield a System.Globalization.NumberFormatInfo object, or
W X Y Z
1441
Contents | Index
Double Structure
System
ToBoolean() Method
the style parameter is not a combination of bit flags from the System.Globalization.NumberStyles enumeration. The s parameter can contain System.Globalization.NumberFormatInfo.PositiveInfinitySymbol, System.Globalization.NumberFormatInfo.NegativeInfinitySymbol, System.Globalization.NumberFormatInfo.NaNSymbol, or a string of the form:
A B C D
[ws][sign]integral-digits[.[fractional-digits]][e[sign]exponential-digits][ws]
E
Optional items are framed in square brackets ([ and]). Items containing the term “digits” consist of a series of numeric characters ranging from 0 to 9. Some examples of s are “100”, “–123,456,789”, “123.45+e6”, “+500”, “5e2”, “3.1416”, “600.”, “–.123”, and “–Infinity”.
F G H I
IConvertible.ToBoolean(System.IFormatProvider) Method
J [ILASM]
K
.method private final hidebysig virtual bool System.IConvertible.ToBoolean(class System.IFormatProvider provider)
L
[C#]
M
bool IConvertible.ToBoolean(IFormatProvider provider)
N
Summary
O
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToBoolean.]
P Q R
IConvertible.ToByte(System.IFormatProvider) Method
S [ILASM]
T
.method private final hidebysig virtual unsigned int8 System.IConvertible.ToByte(class System.IFormatProvider provider)
U
[C#]
V
byte IConvertible.ToByte(IFormatProvider provider)
W
Summary
X
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToByte.]
Y Z
1442
Contents | Index
System
Double Structure ToDecimal() Method
IConvertible.ToChar(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual valuetype System.Char System.IConvertible.ToChar(class System.IFormatProvider provider)
A
[C#]
B
char IConvertible.ToChar(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToChar.]
E F G
IConvertible.ToDateTime(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual valuetype System.DateTime System.IConvertible.ToDateTime(class System.IFormatProvider provider)
J
[C#]
K
DateTime IConvertible.ToDateTime(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDateTime.]
N O P
IConvertible.ToDecimal(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual decimal System.IConvertible.ToDecimal(class System.IFormatProvider provider)
S
[C#]
T
decimal IConvertible.ToDecimal(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDecimal.]
W X Y Z
1443
Contents | Index
Double Structure
System
ToDouble() Method
IConvertible.ToDouble(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual float64 System.IConvertible.ToDouble(class System.IFormatProvider provider)
B
[C#]
double IConvertible.ToDouble(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDouble.]
F G H
IConvertible.ToInt16(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual int16 System.IConvertible.ToInt16(class System.IFormatProvider provider)
K
[C#]
short IConvertible.ToInt16(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt16.]
O P Q
IConvertible.ToInt32(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual int32 System.IConvertible.ToInt32(class System.IFormatProvider provider)
T
[C#]
int IConvertible.ToInt32(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt32.]
X Y Z
1444
Contents | Index
System
Double Structure ToSingle() Method
IConvertible.ToInt64(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual int64 System.IConvertible.ToInt64(class System.IFormatProvider provider)
A
[C#]
B
long IConvertible.ToInt64(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt64.]
E F G
IConvertible.ToSByte(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual int8 System.IConvertible.ToSByte(class System.IFormatProvider provider)
J
[C#]
K
sbyte IConvertible.ToSByte(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSByte.]
N O P
IConvertible.ToSingle(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual float32 System.IConvertible.ToSingle(class System.IFormatProvider provider)
S
[C#]
T
float IConvertible.ToSingle(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSingle.]
W X Y Z
1445
Contents | Index
Double Structure
System
ToType() Method
IConvertible.ToType(System.Type, System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual object System.IConvertible.ToType(class System.Type type, class System.IFormatProvider provider)
B
[C#]
object IConvertible.ToType(Type type, IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToType.]
F G H
IConvertible.ToUInt16(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual unsigned int16 System.IConvertible.ToUInt16(class System.IFormatProvider provider)
K
[C#]
ushort IConvertible.ToUInt16(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt16.] This member is not CLS-compliant.
O P Q
IConvertible.ToUInt32(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual unsigned int32 System.IConvertible.ToUInt32(class System.IFormatProvider provider)
T
[C#]
uint IConvertible.ToUInt32(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt32.] This member is not CLS-compliant.
X Y Z
1446
Contents | Index
System
Double Structure ToUInt64() Method
IConvertible.ToUInt64(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual unsigned int64 System.IConvertible.ToUInt64(class System.IFormatProvider provider)
A
[C#]
B
ulong IConvertible.ToUInt64(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt64.] This member is not CLS-compliant.
E F G H I J K L M N O P Q R S T U V W X Y Z
1447
Contents | Index
System DuplicateWaitObjectException
BCL
Object
A
Exception
B
ISerializable
NotStandardized
SystemException ArgumentException
C
DuplicateWaitObjectException
D E
Summary
F
Represents the error that occurs when an object appears more than once in an array of System.Threading.WaitHandle instances.
G H
Type Summary
I
CF public class DuplicateWaitObjectException : ArgumentException { // Constructors CF public DuplicateWaitObjectException (); CF public DuplicateWaitObjectException (string parameterName); CF public DuplicateWaitObjectException (string parameterName, string message); MS CF protected DuplicateWaitObjectException (SerializationInfo info, StreamingContext context); }
J K L M N O P Q
BA See my comments on ArgumentNullException.
R S
Description
T
[Note: It is generally unnecessary for applications to throw System.DuplicateWaitObjectException. This exception is thrown by thread synchronization methods, such as System.Threading.WaitHandle.WaitAll and System.Threading.WaitHandle.WaitAny.]
U V W X
Example
Y
using System; using System.Threading;
Z
namespace Samples {
1448
Contents | Index
System
DuplicateWaitObjectException DuplicateWaitObjectException() Constructor
public class DuplicateWaitObjectExceptionSample { public static AutoResetEvent[] autoResetEvents = new AutoResetEvent[2]; public static void Main() { try { autoResetEvents[0] = new AutoResetEvent(false); autoResetEvents[1] = autoResetEvents[0]; WaitHandle.WaitAll(autoResetEvents); } catch(DuplicateWaitObjectException e) { Console.WriteLine("Exception: {0}", e); } } }
A B C D E F G H I
}
J K
The output is
L
Exception: System.DuplicateWaitObjectException: Duplicate objects in argument. at System.Threading.WaitHandle.WaitMultiple(WaitHandle[] waitHandles, Int32 millisecondsTimeout, Boolean exitContext, Boolean WaitAll) at System.Threading.WaitHandle.WaitAll(WaitHandle[] waitHandles, Int32 millisecondsTimeout, Boolean exitContext) at System.Threading.WaitHandle.WaitAll(WaitHandle[] waitHandles) at Samples.DuplicateWaitObjectExceptionSample.Main() in C:\Books\BCL\Samples\ System\DuplicateWaitObjectException\DuplicateWaitObjectException.cs:line 16
M N O P Q R
DuplicateWaitObjectException() Constructor
S
[ILASM]
T
public rtspecialname specialname instance void .ctor()
U
[C#]
public DuplicateWaitObjectException()
V W
Summary
X
Constructs and initializes a new instance of the System.DuplicateWaitObjectException class.
Y Z
1449
Contents | Index
DuplicateWaitObjectException
System
DuplicateWaitObjectException() Constructor
Description This constructor initializes the System.DuplicateWaitObjectException.Message property of the new instance to a system-supplied message that describes the error, such as “Duplicate objects in argument.” This message takes into account the current system culture. The System.DuplicateWaitObjectException.InnerException and System.DuplicateWaitObjectException.ParamName properties are initialized to null.
A B C D E
DuplicateWaitObjectException(System.String) Constructor
F
[ILASM]
G
public rtspecialname specialname instance void .ctor(string parameterName)
H
[C#]
public DuplicateWaitObjectException(string parameterName)
I J
Summary
K
Constructs and initializes a new instance of the System.DuplicateWaitObjectException class.
L M
Parameters
N O
Parameter
Description
parameterName
A System.String that contains the name of the parameter that caused the exception. The content of parameterName is intended to be understood by humans.
P Q R S
Description
T
This constructor initializes the System.DuplicateWaitObjectException.Message property of the new instance to a system-supplied message that describes the error. This message takes into account the current system culture. The System.DuplicateWaitObjectException.InnerException property is initialized to null. This constructor initializes the System.DuplicateWaitObjectException.ParamName property of the new instance using parameterName.
U V W X Y Z
1450
Contents | Index
System
DuplicateWaitObjectException DuplicateWaitObjectException() Constructor
DuplicateWaitObjectException(System.String, System.String) Constructor [ILASM]
public rtspecialname specialname instance void .ctor(string parameterName, string message)
A
[C#]
B
public DuplicateWaitObjectException(string parameterName, string message)
C
Summary
D
Constructs and initializes a new instance of the System.DuplicateWaitObjectException class.
E
Parameters
G
F
H
Parameter
Description
parameterName
A System.String that contains the name of the parameter that caused the exception. The content of parameterName is intended to be understood by humans.
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
I J K L M N O
Description
P
This constructor initializes the System.DuplicateWaitObjectException.ParamName property of the new instance using parameterName, and the System.DuplicateWaitObjectException.Message property using message. If message is null, the System.DuplicateWaitObjectException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.DuplicateWaitObjectException.InnerException property is initialized to null.
Q R S T U V W X Y Z
1451
Contents | Index
DuplicateWaitObjectException
System
DuplicateWaitObjectException() Constructor
DuplicateWaitObjectException(System.Runtime.Serialization.Serialization Info, System.Runtime.Serialization.StreamingContext) Constructor A
[ILASM]
B
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
C
[C#]
protected DuplicateWaitObjectException(SerializationInfo info, StreamingContext context)
D E F
Summary
G
Initializes a new instance of the System.DuplicateWaitObjectException class with serialized data.
H I
Parameters
J K L M
Parameter
Description
info
The object that holds the serialized object data.
context
The contextual information about the source or destination.
N O
Description
P
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
Q R S T U V W X Y Z
1452
Contents | Index
System.Text Encoder
BCL
Object
A
Encoder
B
Summary
C
Converts blocks of characters into blocks of bytes.
D E
Type Summary public abstract class Encoder { // Constructors protected Encoder ();
F G H
// Methods public abstract int GetByteCount (char[] chars, int index, int count, bool flush); public abstract int GetBytes (char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush);
I J K L M N O
}
P
Description
Q
[Note: Following instantiation of a System.Text.Encoder, sequential blocks of characters are converted into blocks of bytes through calls to the System.Text.Encoder.GetBytes method. The encoder maintains state between the conversions, allowing it to correctly encode character sequences that span adjacent blocks. An instance of a specific implementation of the System.Text.Encoder class is typically obtained through a call to the System.Text.Encoding.GetEncoder.]
R S T U V W
Encoder() Constructor
X
[ILASM] family rtspecialname specialname instance void .ctor() [C#] protected Encoder()
Y Z
1453
Contents | Index
Encoder
System.Text
GetByteCount() Method
Summary Constructs a new instance of the System.Text.Encoder class. A
Description
B
This constructor is called only by classes that inherit from the System.Text.Encoder class.
C D E
Encoder.GetByteCount(System.Char[], System.Int32, System.Int32, System.Boolean) Method
F G
[ILASM] .method public hidebysig virtual abstract int32 GetByteCount(class System.Char[] chars, int32 index, int32 count, bool flush) [C#] public abstract int GetByteCount(char[] chars, int index, int count, bool flush)
H I J K
Summary
L
Determines the exact number of bytes required to encode the specified range in the specified array of characters.
M N
Parameters
O P Q R
Parameter
Description
chars
A System.Char array of characters to encode.
index
A System.Int32 that specifies the first index of chars to encode.
count
A System.Int32 that specifies the number of elements in chars to encode.
flush
A System.Boolean value that determines whether the current instance flushes its internal state following a conversion. Specify true to flush the internal state of the current instance following a conversion; otherwise, specify false.
S T U V W X
Return Value
Y
A System.Int32 containing the number of bytes required to encode the range in chars from index to index + count – 1 for a particular encoding. [Note: This value takes into account the state in which the current instance was left following the last call to System.Text.Encoder.GetBytes.]
Z
1454
Contents | Index
System.Text
Encoder GetBytes() Method
Description The state of the current instance is not affected by a call to this method.
Usage
A
Use this method to determine the exact number of bytes required to encode the specified range of an array of System.Char objects for a particular encoding.
B
Exceptions
D
C
E
Exception
Condition
F
System.ArgumentNullException
chars is null.
G H
Return value is greater than System.Int32.MaxValue.
I
-or-
J
index < 0. System.ArgumentOutOfRangeException
K
-orcount < 0.
L
-or-
M
index and count do not specify a valid range in chars (i.e., (index + count) > chars.Length).
N O P
Encoder.GetBytes(System.Char[], System.Int32, System.Int32, System.Byte[], System.Int32, System.Boolean) Method
Q
[ILASM] .method public hidebysig virtual abstract int32 GetBytes(class System.Char[] chars, int32 charIndex, int32 charCount, class System.Byte[] bytes, int32 byteIndex, bool flush) [C#] public abstract int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush)
S
R
T U V W
Summary
X
Encodes the specified range of the specified array of characters into the specified range of the specified array of bytes.
Y Z
1455
Contents | Index
Encoder
System.Text
GetBytes() Method
Parameters Parameter
Description
chars
A System.Char array of characters to encode.
C
charIndex
A System.Int32 that specifies the first index of chars to encode.
D
charCount
A System.Int32 that specifies the number of elements in chars to encode.
bytes
A System.Byte array to encode into.
byteIndex
A System.Int32 that specifies the first index of bytes to encode into.
flush
A System.Boolean value. Specify true to flush the internal state of the current instance following a conversion; otherwise, specify false. [Note: To ensure correct termination of a sequence of blocks of encoded bytes, it is recommended that the last call to System.Text.Encoder.GetBytes specify true.]
A B
E F G H I J K L
Return Value
M
A System.Int32 containing the number of bytes encoded into bytes for a particular encoding.
N O
Description
P
The encoding takes into account the state in which the current instance was left following the last call to this method if flush was specified as true for that call.
Q R
Usage
S
Use this method to encode the values of an array of System.Char objects as an array of System.Byte objects for a particular encoding.
T U V W X Y Z
1456
Contents | Index
System.Text
Encoder GetBytes() Method
Exceptions Exception
Condition
System.ArgumentException
bytes does not contain sufficient space to store the encoded characters.
A B C
chars is null. System.ArgumentNullException
D
-or-
E
bytes is null.
F
charIndex < 0.
G
-or-
System.ArgumentOutOfRangeException
charCount < 0.
H
-or-
I
byteIndex < 0.
J
-or-
K
(chars.Length – charIndex) < charCount.
L
-or-
M
byteIndex > bytes.Length.
N O P Q R S T U V W X Y Z
1457
Contents | Index
System.Text Encoding
BCL
Object
A
Encoding
B
ASCIIEncoding
C
UnicodeEncoding
D
UTF8Encoding
E
Summary
F
Represents a character encoding.
G
Type Summary
H
public abstract class Encoding { // Constructors protected Encoding (); MS protected Encoding (int codePage);
I J K L M N
MS
O P
MS MS MS MS MS MS
Q R S T U V
MS
W
// Properties public static Encoding ASCII { get; } public static Encoding BigEndianUnicode { get; } CF public virtual string BodyName { get; } MS public virtual int CodePage { get; } public static Encoding Default { get; } CF public virtual string EncodingName { get; } CF public virtual string HeaderName { get; } CF public virtual bool IsBrowserDisplay { get; } CF public virtual bool IsBrowserSave { get; } CF public virtual bool IsMailNewsDisplay { get; } CF public virtual bool IsMailNewsSave { get; } public static Encoding Unicode { get; } MS public static Encoding UTF7 { get; } public static Encoding UTF8 { get; } MS public virtual string WebName { get; } CF public virtual int WindowsCodePage { get; } // Methods public static byte[] Convert (Encoding srcEncoding, Encoding dstEncoding, byte[] bytes); public static byte[] Convert (Encoding srcEncoding, Encoding dstEncoding, byte[] bytes, int index,
X Y Z
1458
Contents | Index
System.Text
Encoding Encoding Class
int count); public override bool Equals (object value); public virtual int GetByteCount (char[] chars); public abstract int GetByteCount (char[] chars, int index, int count); public virtual int GetByteCount (string s); public virtual byte[] GetBytes (char[] chars); public virtual byte[] GetBytes (char[] chars, int index, int count); public abstract int GetBytes (char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex); public virtual byte[] GetBytes (string s); public virtual int GetBytes (string s, int charIndex, int charCount, byte[] bytes, int byteIndex); public virtual int GetCharCount (byte[] bytes); public abstract int GetCharCount (byte[] bytes, int index, int count); public virtual char[] GetChars (byte[] bytes); public virtual char[] GetChars (byte[] bytes, int index, int count); public abstract int GetChars (byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex); public virtual Decoder GetDecoder (); public virtual Encoder GetEncoder (); MS public static Encoding GetEncoding (int codepage); MS public static Encoding GetEncoding (string name); public override int GetHashCode (); public abstract int GetMaxByteCount (int charCount); public abstract int GetMaxCharCount (int byteCount); public virtual byte[] GetPreamble (); CF public virtual string GetString (byte[] bytes); public virtual string GetString (byte[] bytes, int index, int count);
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
}
1459
Contents | Index
Encoding
System.Text
Encoding Class
YL The CLR is totally based on the Unicode standard, and it uses UTF-16 internally as the encoding for the Unicode characters. When the CLR needs to interoperate with other encodings, Encoding class is used to handle the conversion from UTF-16 to other encodings. Traditionally, Win32 API provides WideCharToMultiByte() to convert UTF-16 characters to other codepages, and MultiByteToWideChar() to convert bytes in codepages to UTF-16 characters. The Encoding.GetChars() and Encoding.GetBytes() are designed to provide the same functionalities.
A B C D E
When Encoding was designed, one of the goals was to provide the encoding ability from both the Windows operating system and the MLang. MLang is a COM-based interfaced introduced in IE to provide more Internet-oriented globalization functionality. One of the important features that MLang provides is to support “buffered” operation in encoding. Because of the nature of the Internet, data is sent in packets. When codepage bytes are sent in packets, chances are that MBCS (Multi-Byte Character Set) bytes can be split in the middle. For example, a 3-byte UTF8 sequence can be split into one byte in the first packet and another two bytes in the second packet. MLang provides a function call to remember the state between two conversion calls, so that the final Unicode character can be assembled correctly. The Encoding class provides the same functionality by using the Encoder and Decoder class. Encoder supports the buffered operation for converting Unicode to bytes in other encodings. That is, if there is a surrogate split in two buffers, it will generate the bytes correctly by remembering the high-surrogate in the first buffer. Similarly, Decoder supports the buffered operation for convert bytes in other encoding back into Unicode characters. If a sequence of MBCS bytes is split, it will generate the Unicode characters by remembering the leading bytes in the first buffer.
F G H I J K L M N O P Q R
The name of Encoder and Decoder can be confusing sometimes. The way to think about it is that Encoder encodes Unicode characters to bytes in other encodings, and Decoder decodes bytes in other encoding back into Unicode characters.
S T
BA I really like what we did here by providing the common encodings right in the
U
class. I find that takes it care of greater than 80% of the cases. And notice that, because we used properties, the encodings’ creation can be delayed until they are first requested.
V W X
The ASCII and UTF8 properties are not cased correctly. They should be Utf8 and Ascii, respectively. We finalized the rules for casing properties too late to fix these issues.
Y Z
continued
1460
Contents | Index
System.Text
Encoding Encoding Class
BG In retrospect I would have named the Default property more precisely. In the Microsoft CLI implementation, it returns an encoding representing the machine’s current ANSI code page. ANSI code pages may have been a good idea in the early 90’s before Unicode, and we still need to support reading text in various code pages; however they are no longer valuable in mainstream usage. So Default should either be a Unicode transformation format to represent all Unicode code points (such as UTF-8), or it should be named something like DefaultCodePage. In practice, any application that will run in more than one locale should probably never use this property.
A B C D E
JR Normally, there is no need for your application code to construct an Encoding-
F
derived object (such as ASCIIEncoding). Instead, you normally obtain an Encoding-derived object by calling one of Encoding class’s static, read-only properties. Here is an example:
G H I
ASCIIEncoding asciiEncoding = Encoding.ASCII;
J
This is more efficient because it returns a reference to a single ASCIIEncoding object rather than creating new ASCIIEncoding objects.
K L
Description
M
Characters are abstract entities that can be represented using many different character schemes or codepages. For example, Unicode UTF-16 encoding represents, or encodes, characters as sequences of 16-bit integers while Unicode UTF-8 represents the same characters as sequences of 8-bit bytes. The BCL includes the following types derived from System.Text.Encoding:
N
• • •
O P Q R
System.Text.ASCIIEncoding—encodes Unicode characters as 7-bit ASCII characters. This encoding only supports code points between U+0000 and U+007F inclusive. System.Text.UnicodeEncoding—encodes each Unicode character as two consecutive bytes. Both little-endian and big-endian byte orders are supported. System.Text.UTF8Encoding—encodes Unicode characters using the UTF-8 (UCS Transformation Format, 8-bit form) encoding. This encoding supports all Unicode character values.
S T U V W
An application can use the properties of this class such as System.Text.Encoding.ASCII, System.Text.Encoding.Default, System.Text.Encoding.Unicode, and System.Text.Encoding.UTF8 to obtain encodings. Applications can initialize new instances of System.Text.Encoding objects through the System.Text.ASCIIEncoding, System.Text.UnicodeEncoding, and System.Text.UTF8Encoding classes.
X Y Z
1461
Contents | Index
Encoding
System.Text
Encoding Class
Through an encoding, the System.Text.Encoding.GetBytes method is used to convert arrays of Unicode characters to arrays of bytes, and the System.Text.Encoding.GetChars method is used to convert arrays of bytes to arrays of Unicode characters. The System.Text.Encoding.GetBytes and System.Text.Encoding.GetChars methods maintain no state between conversions. When the data to be converted is only available in sequential blocks (such as data read from a stream) or when the amount of data is so large that it needs to be divided into smaller blocks, an application can choose to use a System.Text.Decoder or a System.Text.Encoder to perform the conversion. Decoders and encoders allow sequential blocks of data to be converted and they maintain the state required to support conversions of data that spans adjacent blocks. Decoders and encoders are obtained using the System.Text.Encoding.GetDecoder and System.Text.Encoding.GetEncoder methods. The core System.Text.Encoding.GetBytes and System.Text.Encoding.GetChars methods require the caller to provide the destination buffer and ensure that the buffer is large enough to hold the entire result of the conversion. When using these methods, either directly on a System.Text.Encoding object or on an associated System.Text.Decoder or System.Text.Encoder, an application can use one of two methods to allocate destination buffers. The System.Text.Encoding.GetByteCount and System.Text.Encoding.GetCharCount methods can be used to compute the exact size of the result of a particular conversion, and an appropriately sized buffer for that conversion can then be allocated. The System.Text.Encoding.GetMaxByteCount and System.Text.Encoding.GetMaxCharCount methods can be used to compute the maximum possible size of a conversion of a given number of characters or bytes, regardless of the actual character or byte values, and a buffer of that size can then be reused for multiple conversions. The first method generally uses less memory, whereas the second method generally executes faster.
A B C D E F G H I J K L M N O P Q R S T
Example
U
using System; using System.Text; namespace Samples { public class EncoderSample { public static void Main() { UTF8Encoding u = (UTF8Encoding) Encoding.UTF8; string s = "Pi is (\u03a0)"; Byte[] bytes = u.GetBytes(s); foreach(Int16 i in bytes)
V W X Y Z
1462
Contents | Index
System.Text
Encoding Encoding() Constructor
Console.Write("{0}, ", i); Console.WriteLine(); int count = u.GetCharCount(bytes, 0, bytes.Length); char[] chars = new char[count]; u.GetChars(bytes, 0, bytes.Length, chars, 0); foreach(Int16 i in chars) Console.Write("{0}, ", i); Console.WriteLine();
A B C D
} }
E
}
F
The output is
G H
80, 105, 32, 105, 115, 32, 40, 206, 160, 41, 80, 105, 32, 105, 115, 32, 40, 928, 41,
I J
Encoding() Constructor
K
[ILASM] family rtspecialname specialname instance void .ctor() [C#] protected Encoding()
L M N O
Summary
P
Constructs a new instance of the System.Text.Encoding class.
Q R
Encoding(System.Int32) Constructor
S
[ILASM] family rtspecialname specialname instance void .ctor(int32 codePage) [C#] protected Encoding(int codePage)
T U V
Summary
W
Initializes a new instance of the System.Text.Encoding class.
X Y Z
1463
Contents | Index
Encoding
System.Text
ASCII Property
Parameters Parameter
Description
codePage
A code page value that corresponds to the preferred encoding.
A B C
Exceptions
D E
Exception
Condition
System.ArgumentOutOfRangeException
codePage is less than zero.
F G H I
Encoding.ASCII Property
J
[ILASM] .property class System.Text.Encoding ASCII { public hidebysig static specialname class System.Text.Encoding get_ASCII() } [C#] public static Encoding ASCII { get; }
K L M N
Summary
O
Gets an encoding for the ASCII (7-bit) character set.
P Q
Description
R
[Note: ASCII characters can represent Unicode characters from U+0000 to U+007f, inclusive.]
S T
Encoding.BigEndianUnicode Property
U
[ILASM] .property class System.Text.Encoding BigEndianUnicode { public hidebysig static specialname class System.Text.Encoding get_BigEndianUnicode() } [C#] public static Encoding BigEndianUnicode { get; }
V W X Y
Summary
Z
Gets an encoding for the Unicode format in big-endian byte order.
1464
Contents | Index
System.Text
Encoding CodePage Property
Description [Note: Unicode characters can be stored in two different byte orders, big-endian and littleendian. On little-endian platforms such as those implemented on Intel processors, it is generally more efficient to store Unicode characters in little-endian byte order. However, many other platforms can store Unicode characters in big-endian byte order. Unicode files can be distinguished by the presence of the byte order mark (U+FEFF), which will be written as either 0xfe 0xff or 0xff 0xfe. This encoding automatically detects a byte order mark and, if necessary, switches byte orders.]
A B C D E F
Encoding.BodyName Property
G [ILASM] .property string BodyName { public hidebysig virtual specialname string get_BodyName() } [C#] public virtual string BodyName { get; }
H I J K
Summary
L
Gets the name for this encoding that can be used with mail agent body tags.
M
Description
N
For example, if this encoding is equivalent to System.Text.UTF8Encoding, this property returns “utf-8”. If the encoding cannot be used, the property value is the empty string (“ “).
O P Q R
Encoding.CodePage Property
S [ILASM] .property int32 CodePage { public hidebysig virtual specialname int32 get_CodePage() } [C#] public virtual int CodePage { get; }
T U V W
Summary
X
When overridden in a derived class, gets the code page identifier of this encoding.
Y
Description
Z
This property must be implemented or overridden.
1465
Contents | Index
Encoding
System.Text
Default Property
Encoding.Default Property [ILASM] .property class System.Text.Encoding Default { public hidebysig static specialname class System.Text.Encoding get_Default() } [C#] public static Encoding Default { get; }
A B C D
Summary
E
Gets an encoding for the ANSI code page of the current system.
F G
Encoding.EncodingName Property
H
[ILASM] .property string EncodingName { public hidebysig virtual specialname string get_EncodingName() } [C#] public virtual string EncodingName { get; }
I J K L
Summary
M
Gets the human-readable description of the encoding.
N
Description
O
An example of a System.Text.Encoding.EncodingName is Hebrew (DOS) for code page 862.
P Q R
Encoding.HeaderName Property
S
[ILASM] .property string HeaderName { public hidebysig virtual specialname string get_HeaderName() } [C#] public virtual string HeaderName { get; }
T U V W
Summary
X
Gets the name for this encoding that can be used with mail agent header tags.
Y
Description
Z
For example, if this encoding is equivalent to System.Text.UTF8Encoding, this property returns “utf-8”. If the encoding cannot be used, the string is empty. 1466
Contents | Index
System.Text
Encoding IsBrowserSave Property
Encoding.IsBrowserDisplay Property [ILASM] .property bool IsBrowserDisplay { public hidebysig virtual specialname bool get_IsBrowserDisplay() } [C#] public virtual bool IsBrowserDisplay { get; }
A B C
Summary
D
Gets an indication whether this encoding can be used for display by browser clients.
E F
Property Value
G
true if this encoding can be used for display; otherwise, false.
H
Description
I
For example, this property returns true for code page 1252 (Windows-1252), but false for code page 437 (IBM-437).
J K L
Encoding.IsBrowserSave Property
M
[ILASM] .property bool IsBrowserSave { public hidebysig virtual specialname bool get_IsBrowserSave() } [C#] public virtual bool IsBrowserSave { get; }
N O P Q
Summary
R
Gets an indication whether this encoding can be used for saving by browser clients.
S T
Property Value
U
true if this encoding can be used for saving by browser clients; otherwise, false.
V
Description
W
For example, this property returns true for code page 1252 (Windows-1252), but false for code page 437 (IBM-437).
X Y Z
1467
Contents | Index
Encoding
System.Text
IsMailNewsDisplay Property
Encoding.IsMailNewsDisplay Property [ILASM] .property bool IsMailNewsDisplay { public hidebysig virtual specialname bool get_IsMailNewsDisplay() } [C#] public virtual bool IsMailNewsDisplay { get; }
A B C D
Summary
E
Gets an indication whether this encoding can be used for display by mail and news clients.
F
Property Value
G
true if this encoding can be used for displaying by mail and news clients; otherwise, false.
H I
Description
J
For example, this property returns true for code page 1252 (Windows-1252), but false for code page 437 (IBM-437).
K L
Encoding.IsMailNewsSave Property
M
[ILASM] .property bool IsMailNewsSave { public hidebysig virtual specialname bool get_IsMailNewsSave() } [C#] public virtual bool IsMailNewsSave { get; }
N O P Q R
Summary
S
Gets an indication whether this encoding can be used for saving by mail and news clients.
T
Property Value
U
true if this encoding can be used for saving by mail and news clients; otherwise, false.
V W
Description
X
For example, this property returns true for code page 1252 (Windows-1252), but false for code page 437 (IBM-437).
Y Z
1468
Contents | Index
System.Text
Encoding UTF8 Property
Encoding.Unicode Property [ILASM] .property class System.Text.Encoding Unicode { public hidebysig static specialname class System.Text.Encoding get_Unicode() } [C#] public static Encoding Unicode { get; }
A B C
Summary
D
Gets an encoding for the Unicode format in little-endian byte order.
E F
Description
G
[Note: Unicode characters can be stored in two different byte orders, big-endian and littleendian. On little-endian platforms such as those implemented on Intel processors, it is generally more efficient to store Unicode characters in little-endian byte order. However, many other platforms can store Unicode characters in big-endian byte order. Unicode files can be distinguished by the presence of the byte order mark (U+FEFF), which will be written as either 0xfe 0xff or 0xff 0xfe. This encoding automatically detects a byte order mark and, if necessary, switches byte orders.]
H I J K L M
Encoding.UTF7 Property
N
[ILASM] .property class System.Text.Encoding UTF7 { public hidebysig static specialname class System.Text.Encoding get_UTF7() } [C#] public static Encoding UTF7 { get; }
O P Q R
Summary
S
Gets an encoding for the UTF-7 format.
T U V
Encoding.UTF8 Property
W
[ILASM] .property class System.Text.Encoding UTF8 { public hidebysig static specialname class System.Text.Encoding get_UTF8() } [C#] public static Encoding UTF8 { get; }
X Y Z
1469
Contents | Index
Encoding
System.Text
WebName Property
Summary Gets an encoding for the UTF-8 format. A
Property Value
B
A System.Text.Encoding for the UTF-8 format.
C D
Description
E
[Note: For detailed information regarding UTF-8 encoding, see System.Text.UTF8Encoding.]
F G
Encoding.WebName Property
H
[ILASM] .property string WebName { public hidebysig virtual specialname string get_WebName() } [C#] public virtual string WebName { get; }
I J K L
Summary
M
Gets the name registered with the Internet Assigned Numbers Authority (IANA) for this encoding.
N O P
Encoding.WindowsCodePage Property
Q
[ILASM] .property int32 WindowsCodePage { public hidebysig virtual specialname int32 get_WindowsCodePage() } [C#] public virtual int WindowsCodePage { get; }
R S T U
Summary
V
Gets the Windows operating system code page that most closely corresponds to this encoding.
W X Y Z
1470
Contents | Index
System.Text
Encoding Convert() Method
Encoding.Convert(System.Text.Encoding, System.Text.Encoding, System.Byte[]) Method [ILASM] .method public hidebysig static class System.Byte[] Convert(class System.Text.Encoding srcEncoding, class System.Text.Encoding dstEncoding, class System.Byte[] bytes) [C#] public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes)
A B C D E
Summary
F
Converts the specified System.Byte array from one specified encoding to another specified encoding.
G H I
Parameters
J
Parameter
Description
srcEncoding
The System.Text.Encoding that bytes is in.
dstEncoding
The System.Text.Encoding desired for the returned System.Byte array.
bytes
The System.Byte array containing the values to convert.
K L M N O P
Exceptions
Q
Exception
Condition
System.ArgumentNullException
srcEncoding, dstEncoding, or bytes is null.
R S T U V
Encoding.Convert(System.Text.Encoding, System.Text.Encoding, System.Byte[], System.Int32, System.Int32) Method
W X
[ILASM] .method public hidebysig static class System.Byte[] Convert(class System.Text.Encoding srcEncoding, class System.Text.Encoding dstEncoding, class System.Byte[] bytes, int32 index, int32 count)
Y Z
1471
Contents | Index
Encoding
System.Text
Equals() Method
[C#] public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes, int index, int count)
A
Summary
B
Converts the specified range of the specified System.Byte array from one specified encoding to another specified encoding.
C D
Parameters
E F
Parameter
Description
srcEncoding
The System.Text.Encoding that bytes is in.
I
dstEncoding
The System.Text.Encoding desired for the returned System.Byte array.
J
bytes
The System.Byte array containing the values to convert.
index
A System.Int32 containing the first index of bytes from which to convert.
count
A System.Int32 containing the number of bytes to convert.
G H
K L M N
Exceptions
O P
Exception
Condition
System.ArgumentNullException
srcEncoding, dstEncoding, or bytes is null.
System.ArgumentOutOfRangeException
index and count do not denote a valid range in bytes.
Q R S T U V
Encoding.Equals(System.Object) Method
W
[ILASM] .method public hidebysig virtual bool Equals(object value) [C#] public override bool Equals(object value)
X Y Z
1472
Contents | Index
System.Text
Encoding GetByteCount() Method
Summary Determines whether the current instance and the specified System.Object represent the same type and value. A
Parameters
B C
Parameter
Description
value
The System.Object to compare to the current instance.
D E F
Return Value
G
true if value represents the same type and value as the current instance. If value is a null reference or is not an instance of System.Text.Encoding, returns false.
H
Description
J
[Note: This method overrides System.Object.Equals.]
K
I
L M
Encoding.GetByteCount(System.Char[]) Method
N [ILASM] .method public hidebysig virtual int32 GetByteCount(class System.Char[] chars) [C#] public virtual int GetByteCount(char[] chars)
O P Q
Summary
R
Returns the number of bytes required to encode the specified System.Char array.
S T
Parameters
U
Parameter
Description
V
chars
The System.Char array to encode.
W X Y
How and When to Override
Z
This method is overridden by types derived from System.Text.Encoding to return the appropriate number of bytes for the particular encoding.
1473
Contents | Index
Encoding
System.Text
GetByteCount() Method
Usage System.Text.Encoding.GetByteCount can be used to determine the exact number of bytes that will be produced from encoding the given array of characters. An appropriately sized buffer for that conversion can then be allocated. Alternatively, System.Text.Encoding.GetMaxByteCount can be used to determine the maximum number of bytes that will be produced from converting a given number of characters, regardless of the actual character values. A buffer of that size can then be reused for multiple conversions. System.Text.Encoding.GetByteCount generally uses less memory and System.Text.Encoding.GetMaxByteCount generally executes faster.
A B C D E F G
Exceptions
H I J
Exception
Condition
System.ArgumentNullException
chars is null.
K L
Encoding.GetByteCount(System.Char[], System.Int32, System.Int32) Method
M
[ILASM] .method public hidebysig virtual abstract int32 GetByteCount(class System.Char[] chars, int32 index, int32 count) [C#] public abstract int GetByteCount(char[] chars, int index, int count)
N O P Q R
Summary
S
Returns the number of bytes required to encode the specified range of characters in the specified Unicode character array.
T
Parameters
U V
Parameter
Description
X
chars
The System.Char array to encode.
Y
index
A System.Int32 containing the first index of chars to encode.
count
A System.Int32 containing the number of characters to encode.
W
Z
1474
Contents | Index
System.Text
Encoding GetByteCount() Method
Return Value A System.Int32 containing the number of bytes required to encode the range in chars from index to index + count – 1. A
How and When to Override
B
This method is overridden by types derived from System.Text.Encoding to return the appropriate number of bytes for the particular encoding.
C D
Usage
E
System.Text.Encoding.GetByteCount can be used to determine the exact the number of bytes that will be produced from encoding a given range of characters. An appropriately sized buffer for that conversion can then be allocated. Alternatively, System.Text.Encoding.GetMaxByteCount can be used to determine the maximum number of bytes that will be produced from converting a given number of characters, regardless of the actual character values. A buffer of that size can then be reused for multiple conversions. System.Text.Encoding.GetByteCount generally uses less memory and System.Text.Encoding.GetMaxByteCount generally executes faster.
F G H I J K L M
Exceptions
N
Exception
Condition
System.ArgumentNullException
chars is null.
System.ArgumentOutOfRangeException
The number of bytes required to encode the specified elements in chars is greater than System.Int32.MaxValue. -orindex or count is less than zero. -orindex and count do not specify a valid range in chars (i.e., (index + count) > chars.Length).
O P Q R S T U V W X
Encoding.GetByteCount(System.String) Method
Y
[ILASM] .method public hidebysig virtual int32 GetByteCount(string s) [C#] public virtual int GetByteCount(string s)
Z
1475
Contents | Index
Encoding
System.Text
GetBytes() Method
Summary Returns the number of bytes required to encode the specified System.String. A
Parameters
B C
Parameter
Description
D
s
The System.String to decode.
E F
How and When to Override
G
This method is overridden by types derived from System.Text.Encoding to return the appropriate number of bytes for the particular encoding.
H I
Usage
J
System.Text.Encoding.GetByteCount can be used to determine the exact number of bytes that will be produced from encoding the given System.String. An appropriately sized buffer for that conversion can then be allocated. Alternatively, System.Text.Encoding.GetMaxByteCount can be used to determine the maximum number of bytes that will be produced from converting a given number of characters, regardless of the actual character values. A buffer of that size can then be reused for multiple conversions. System.Text.Encoding.GetByteCount generally uses less memory and System.Text.Encoding.GetMaxByteCount generally executes faster.
K L M N O P Q
Exceptions
R S
Exception
Condition
System.ArgumentNullException
s is null.
T U V W
Encoding.GetBytes(System.Char[]) Method
X [ILASM] .method public hidebysig virtual class System.Byte[] GetBytes(class System.Char[] chars) [C#] public virtual byte[] GetBytes(char[] chars)
Y Z
1476
Contents | Index
System.Text
Encoding GetBytes() Method
Summary Encodes the specified System.Char array. A
Parameters
B
Parameter
Description
chars
The System.Char array to encode.
C D E
How and When to Override
F
This method is overridden by types derived from System.Text.Encoding to perform the encoding.
G H I
Exceptions
J
Exception
Condition
System.ArgumentNullException
chars is null.
K L M N
Encoding.GetBytes(System.Char[], System.Int32, System.Int32) Method
O
[ILASM] .method public hidebysig virtual class System.Byte[] GetBytes(class System.Char[] chars, int32 index, int32 count) [C#] public virtual byte[] GetBytes(char[] chars, int index, int count)
P Q R S
Summary
T
Encodes the specified range of the specified System.Char array.
U
Parameters
V
Parameter
Description
chars
The System.Char array to encode.
index
A System.Int32 containing the first index of chars to encode.
count
A System.Int32 containing the number of characters to encode.
W X Y Z
1477
Contents | Index
Encoding
System.Text
GetBytes() Method
Return Value A System.Byte array containing the encoded representation of the range in chars from index to index + count – 1. A B
How and When to Override
C
This method is overridden by types derived from System.Text.Encoding to perform the encoding.
D E
Exceptions
F G H
Exception
Condition
System.ArgumentNullException
chars is null.
System.ArgumentOutOfRangeException
index and count do not denote a valid range in chars.
I J K L
Encoding.GetBytes(System.Char[], System.Int32, System.Int32, System.Byte[], System.Int32) Method
M N
[ILASM] .method public hidebysig virtual abstract int32 GetBytes(class System.Char[] chars, int32 charIndex, int32 charCount, class System.Byte[] bytes, int32 byteIndex) [C#] public abstract int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
O P Q R S
Summary
T
Encodes the specified range of the specified System.Char array into the specified range of the specified System.Byte array.
U V W X Y Z
1478
Contents | Index
System.Text
Encoding GetBytes() Method
Parameters Parameter
Description
chars
A System.Char array to encode.
charIndex
A System.Int32 containing the first index of chars to encode.
C
charCount
A System.Int32 containing the number of characters to encode.
D
bytes
A System.Byte array to encode into.
byteIndex
A System.Int32 containing the first index of bytes to encode into.
A B
E F G H
Return Value
I
The number of bytes encoded into bytes.
J K
How and When to Override
L
This method is overridden by types derived from System.Text.Encoding to perform the encoding.
M N
Usage
O
System.Text.Encoding.GetByteCount can be used to determine the exact number of bytes that will be produced for a given range of characters. Alternatively, System.Text.Encoding.GetMaxByteCount can be used to determine the maximum number of bytes that will be produced for a given number of characters, regardless of the actual character values.
P Q R S T U V W X Y Z
1479
Contents | Index
Encoding
System.Text
GetBytes() Method
Exceptions Exception
Condition
System.ArgumentException
bytes does not contain sufficient space to store the encoded characters.
System.ArgumentNullException
chars is null. -orbytes is null.
System.ArgumentOutOfRangeException
charIndex < 0. -orcharCount < 0. -orbyteIndex < 0. -or(chars.Length – charIndex) < charCount. -orbyteIndex > bytes.Length.
A B C D E F G H I J K L M N
Encoding.GetBytes(System.String) Method
O
[ILASM] .method public hidebysig virtual class System.Byte[] GetBytes(string s) [C#] public virtual byte[] GetBytes(string s)
P Q R S
Summary
T
Encodes the specified System.String.
U
Parameters
V W
Parameter
Description
s
The System.String to encode.
X Y Z
1480
Contents | Index
System.Text
Encoding GetBytes() Method
How and When to Override This method is overridden by types derived from System.Text.Encoding to perform the encoding. A
Exceptions
B
Exception
C
Condition
D System.ArgumentNullException
s is null.
E F G
Encoding.GetBytes(System.String, System.Int32, System.Int32, System.Byte[], System.Int32) Method
H I
[ILASM] .method public hidebysig virtual int32 GetBytes(string s, int32 charIndex, int32 charCount, class System.Byte[] bytes, int32 byteIndex) [C#] public virtual int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex)
J K L M
Summary
N
Encodes the specified range of the specified System.String into the specified range of the specified System.Byte array.
O
Parameters
Q
P
R
Parameter
Description
s
A System.String to encode.
T
charIndex
A System.Int32 containing the first index of s from which to encode.
U
charCount
A System.Int32 containing the number of characters of s to encode.
bytes
The System.Byte array to encode into.
byteIndex
A System.Int32 containing the first index of bytes to encode into.
S
V W X Y Z
1481
Contents | Index
Encoding
System.Text
GetCharCount() Method
Return Value A System.Int32 containing the number of bytes encoded into bytes. A
How and When to Override
B
This method is overridden by types derived from System.Text.Encoding to perform the encoding.
C D
Exceptions
E F
Exception
Condition
System.ArgumentException
bytes does not contain sufficient space to store the encoded characters.
G H I
s is null.
J
System.ArgumentNullException
-or-
K
bytes is null.
L
charIndex < 0.
M
-orcharCount < 0.
N
-or-
O
System.ArgumentOutOfRangeException
P
byteIndex < 0. -or-
Q
(s.Length – charIndex) < charCount.
R
-or-
S
byteIndex >= bytes.Length.
T U
Encoding.GetCharCount(System.Byte[]) Method
V [ILASM] .method public hidebysig virtual int32 GetCharCount(class System.Byte[] bytes) [C#] public virtual int GetCharCount(byte[] bytes)
W X Y
Summary
Z
Determines the exact number of characters that will be produced by decoding the specified System.Byte array. 1482
Contents | Index
System.Text
Encoding GetCharCount() Method
Parameters Parameter
Description
bytes
The System.Byte array to decode.
A B C
How and When to Override
D
This method is overridden by types derived from System.Text.Encoding to return the appropriate number of bytes for the particular encoding.
E
Usage
G
Use System.Text.Encoding.GetCharCount to determine the exact number of characters that will be produced from converting a given byte array. An appropriately sized buffer for that conversion can then be allocated. Alternatively, use System.Text.Encoding.GetMaxCharCount to determine the maximum number of characters that will be produced for a given number of bytes, regardless of the actual byte values. A buffer of that size can then be reused for multiple conversions. System.Text.Encoding.GetCharCount generally uses less memory and System.Text.Encoding.GetMaxCharCount generally executes faster.
H
F
I J K L M N
Exceptions
O
Exception
Condition
System.ArgumentNullException
bytes is null.
P Q R S T
Encoding.GetCharCount(System.Byte[], System.Int32, System.Int32) Method
U
[ILASM] .method public hidebysig virtual abstract int32 GetCharCount(class System.Byte[] bytes, int32 index, int32 count) [C#] public abstract int GetCharCount(byte[] bytes, int index, int count)
V W X
Summary
Y
Determines the exact number of characters that will be produced by decoding the specified range of the specified System.Byte array.
Z
1483
Contents | Index
Encoding
System.Text
GetCharCount() Method
Parameters Parameter
Description
bytes
The System.Byte array to decode.
index
The first index in bytes to decode.
count
The number of bytes to decode.
A B C D E F
Return Value
G
A System.Int32 containing the number of characters the next call to System.Text.Decoder.GetChars will produce if presented with the specified range of bytes.
H I
How and When to Override
J
This method is overridden by types derived from System.Text.Encoding to return the appropriate number of bytes for the particular encoding.
K L
Usage
M
Use System.Text.Encoding.GetCharCount to determine the exact number of characters that will be produced from converting a given range of bytes. An appropriately sized buffer for that conversion can then be allocated. Alternatively, use System.Text.Encoding.GetMaxCharCount to determine the maximum number of characters that will be produced for a given number of bytes, regardless of the actual byte values. A buffer of that size can then be reused for multiple conversions. System.Text.Encoding.GetCharCount generally uses less memory and System.Text.Encoding.GetMaxCharCount generally executes faster.
N O P Q R S
Exceptions
T U V
Exception
Condition
System.ArgumentNullException
bytes is null.
System.ArgumentOutOfRangeException
index and count do not specify a valid range in bytes (i.e., (index + count) > bytes.Length).
W X Y Z
1484
Contents | Index
System.Text
Encoding GetChars() Method
Encoding.GetChars(System.Byte[]) Method [ILASM] .method public hidebysig virtual class System.Char[] GetChars(class System.Byte[] bytes) [C#] public virtual char[] GetChars(byte[] bytes)
A B C
Summary
D
Decodes a System.Byte array.
E F
Parameters
G
Parameter
Description
bytes
The System.Byte array to decode.
H I J K
Exceptions
L
Exception
Condition
System.ArgumentNullException
bytes is null.
M N O P Q
Encoding.GetChars(System.Byte[], System.Int32, System.Int32) Method
R
[ILASM] .method public hidebysig virtual class System.Char[] GetChars(class System.Byte[] bytes, int32 index, int32 count) [C#] public virtual char[] GetChars(byte[] bytes, int index, int count)
S T U
Summary
V
Decodes the specified range of the specified System.Byte array.
W X Y Z
1485
Contents | Index
Encoding
System.Text
GetChars() Method
Parameters Parameter
Description
bytes
The System.Byte array to decode.
C
index
A System.Int32 containing the first index of bytes to decode.
D
count
A System.Int32 containing the number of bytes to decode.
A B
E F
Return Value
G
A System.Char array containing the decoded representation of the range in bytes between index to index + count.
H
Exceptions
I J
Exception
Condition
System.ArgumentNullException
bytes is null.
System.ArgumentOutOfRangeException
index and count do not denote a valid range in the byte array.
K L M N O
Encoding.GetChars(System.Byte[], System.Int32, System.Int32, System.Char[], System.Int32) Method
P Q
[ILASM] .method public hidebysig virtual abstract int32 GetChars(class System.Byte[] bytes, int32 byteIndex, int32 byteCount, class System.Char[] chars, int32 charIndex) [C#] public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
R S T U V
Summary
W
Decodes the specified range of the specified System.Byte array into the specified range of the specified System.Char array.
X Y Z
1486
Contents | Index
System.Text
Encoding GetChars() Method
Parameters Parameter
Description
bytes
The System.Byte array to decode.
byteIndex
A System.Int32 containing the first index of bytes to decode.
C
byteCount
A System.Int32 containing the number of bytes to decode.
D
chars
The System.Char array to decode into.
charIndex
A System.Int32 containing the first index of chars to decode into.
A B
E F G H
Return Value
I
The number of characters stored in chars.
J K
Behaviors
L
This method requires the caller to provide the destination buffer and ensure that the buffer is large enough to hold the entire result of the conversion.
M N
How and When to Override
O
This method is overridden by types derived from System.Text.Encoding to perform the particular decoding.
P Q
Usage
R
When using this method directly on a System.Text.Encoding object or on an associated System.Text.Decoder or System.Text.Encoder, use System.Text.Encoding.GetCharCount or System.Text.Encoding.GetMaxCharCount to allocate destination buffers.
S T U V W X Y Z
1487
Contents | Index
Encoding
System.Text
GetDecoder() Method
Exceptions Exception
Condition
System.ArgumentException
chars does not contain sufficient space to store the decoded characters.
A B C
bytes is null. D
System.ArgumentNullException
E
-orchars is null.
F
byteIndex < 0.
G
-or-
H
byteCount < 0.
I
-orSystem.ArgumentOutOfRangeException
J K
charIndex < 0. -or-
L
byteIndex and byteCount do not specify a valid range in bytes (i.e., (byteIndex + byteCount ) > bytes.Length).
M
-orcharIndex > chars.Length.
N O P
Encoding.GetDecoder() Method
Q [ILASM] .method public hidebysig virtual class System.Text.Decoder GetDecoder() [C#] public virtual Decoder GetDecoder()
R S T U
Summary
V
Returns a System.Text.Decoder for the current instance.
W
Default
X
The default implementation returns a System.Text.Decoder that forwards calls made to the System.Text.Encoding.GetCharCount and System.Text.Encoding.GetChars methods to the corresponding methods of the current instance.
Y Z
1488
Contents | Index
System.Text
Encoding GetEncoder() Method
How and When to Override Encoding that requires state to be maintained between successive conversions should override this method and return an instance of an appropriate System.Text.Decoder implementation.
A B
Usage
C
Unlike the System.Text.Encoding.GetChars methods, a System.Text.Decoder can convert partial sequences of bytes into partial sequences of characters by maintaining the appropriate state between the conversions.
D E F G
Encoding.GetEncoder() Method
H [ILASM] .method public hidebysig virtual class System.Text.Encoder GetEncoder() [C#] public virtual Encoder GetEncoder()
I J K
Summary
L
Returns a System.Text.Encoder for the current instance.
M
Default
N
The default implementation returns a System.Text.Encoder that forwards calls made to the System.Text.Encoding.GetByteCount and System.Text.Encoding.GetBytes methods to the corresponding methods of the current instance.
O
How and When to Override
R
Types derived from System.Text.Encoding override this method to return an instance of an appropriate System.Text.Encoder.
S
Usage
U
Unlike the System.Text.Encoding.GetBytes method, a System.Text.Encoder can convert partial sequences of characters into partial sequences of bytes by maintaining the appropriate state between the conversions.
V
P Q
T
W X Y Z
1489
Contents | Index
Encoding
System.Text
GetEncoding() Method
Encoding.GetEncoding(System.Int32) Method [ILASM] .method public hidebysig static class System.Text.Encoding GetEncoding(int32 codepage) [C#] public static Encoding GetEncoding(int codepage)
A B C D
Summary
E
Returns a System.Text.Encoding that corresponds to the specified code page value.
F
Parameters
G H I
Parameter
Description
codepage
A code page value that corresponds to the preferred encoding.
J K
Description
L
The System.Text.Encoding.GetEncoding method relies on the underlying platform to support most code pages. However, system support is supplied for the following cases: Specify code page 0 for the default encoding, that is, the encoding specified in the regional settings for the computer executing this method; 1200 for little-endian Unicode (UTF-16LE); 1201 for big-endian Unicode (UTF-16BE); 1252 for Windows operating system (Windows-1252); 65000 for UTF-7; 65001 for UTF-8; 20127 for ASCII; and 54936 for GB18030 (Chinese Simplified). For example, the encoding for the Windows-1252 code page (code page value 1252) can be created by the following C# code:
M N O P Q R S
Encoding enc = Encoding.GetEncoding(1252);
T
W
A specific code page might not be supported by certain platforms. For example, the Japanese shift-jis code page (code page 932) might not be supported in the United States version of Windows 98. In that case, the System.Text.Encoding.GetEncoding method throws System.NotSupportedException when the following C# code is executed:
X
Encoding enc = Encoding.GetEncoding(932);
U V
Y Z
1490
Contents | Index
System.Text
Encoding GetEncoding() Method
Exceptions Exception
Condition A
System.ArgumentOutOfRangeException
codepage is less than zero or greater than 65535.
System.NotSupportedException
codepage is not supported by the current regional options of the computer executing this method.
B C D E F
Encoding.GetEncoding(System.String) Method
G H
[ILASM] .method public hidebysig static class System.Text.Encoding GetEncoding(string name) [C#] public static Encoding GetEncoding(string name)
I J K
Summary
L
Returns a System.Text.Encoding for the specified name.
M N
Parameters
O
Parameter
Description
name
The name of a System.Text.Encoding.
P Q R S
Description
T
The System.Text.Encoding.GetEncoding method relies on the underlying platform to support most code pages. However, system support is supplied for the following cases: The default encoding, that is, the encoding specified in the regional settings for the computer executing this method; little-endian Unicode (UTF-16LE); big-endian Unicode (UTF-16BE); Windows operating system (Windows-1252); UTF-7; UTF-8; ASCII; and GB18030 (Chinese Simplified). Specify one of the names listed in the following table to obtain the system-supported encoding with the corresponding code page.
U V W X Y Z
1491
Contents | Index
Encoding
System.Text
GetHashCode() Method
code page
name
A
1200
“UTF-16LE”, “utf-16”, “ucs-2”, “unicode”, or “ISO-10646-UCS-2”
B
1201
“UTF-16BE” or “unicodeFFFE”
C
1252
“windows-1252”
65000
“utf-7”, “csUnicode11UTF7”, “unicode-1-1-utf-7”, “unicode-2-0-utf-7”, “x-unicode-1-1-utf-7”, or “x-unicode-2-0-utf-7”
65001
“utf-8”, “unicode-1-1-utf-8”, “unicode-2-0-utf-8”, “x-unicode-1-1-utf-8”, or “xunicode-2-0-utf-8”
20127
“us-ascii”, “us”, “ascii”, “ANSI_X3.4-1968”, “ANSI_X3.4-1986”, “cp367”, “csASCII”, “IBM367”, “iso-ir-6”, “ISO646-US”, or “ISO_646.irv:1991”
54936
“GB18030”
D E F G H I J K
A specific code page might not be supported by certain platforms. For example, the Japanese shift-jis code page (code page 932) might not be supported in the United States version of Windows 98. In that case, the System.Text.Encoding.GetEncoding method throws System.NotSupportedException when the following C# code is executed:
L M N O
Encoding enc = Encoding.GetEncoding("shift-jis");
P
Exceptions
Q R S T
Exception
Condition
System.NotSupportedException
The name encoding is not supported by the current regional options of the computer executing this method.
U V W
Encoding.GetHashCode() Method
X
[ILASM] .method public hidebysig virtual int32 GetHashCode() [C#] public override int GetHashCode()
Y Z
1492
Contents | Index
System.Text
Encoding GetMaxByteCount() Method
Summary Generates a hash code for the current instance.
Description
A
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
B C D E
Encoding.GetMaxByteCount(System.Int32) Method
F
[ILASM] .method public hidebysig virtual abstract int32 GetMaxByteCount(int32 charCount) [C#] public abstract int GetMaxByteCount(int charCount)
G H I
Summary
J
Returns the maximum number of bytes required to encode the specified number of characters, regardless of the actual character values.
K L
Parameters
M
Parameter
Description
charCount
A System.Int32 containing the number of characters to encode.
N O P Q
How and When to Override
R
This method is overridden by types derived from System.Text.Encoding to return the appropriate number of bytes for the particular encoding.
S T
Usage
U
System.Text.Encoding.GetMaxByteCount can be used to determine the minimum buffer size for byte arrays passed to the System.Text.Encoding.GetBytes of the current encoding. Using this minimum buffer size ensures that no buffer overflow exceptions occur.
V W X Y Z
1493
Contents | Index
Encoding
System.Text
GetMaxCharCount() Method
Encoding.GetMaxCharCount(System.Int32) Method [ILASM] .method public hidebysig virtual abstract int32 GetMaxCharCount(int32 byteCount) [C#] public abstract int GetMaxCharCount(int byteCount)
A B C
Summary
D
Returns the maximum number of characters produced by decoding the specified number of bytes, regardless of the actual byte values.
E F
Parameters
G H
Parameter
Description
byteCount
A System.Int32 containing the number of bytes to decode.
I J K
How and When to Override
L
This method is overridden by types derived from System.Text.Encoding to return the appropriate number of bytes for the particular encoding.
M N
Usage
O
System.Text.Encoding.GetMaxCharCount can be used to determine the minimum buffer size for byte arrays passed to the System.Text.Encoding.GetChars of the current encoding. Using this minimum buffer size ensures that no buffer overflow exceptions will occur.
P Q R S T
Encoding.GetPreamble() Method
U
[ILASM] .method public hidebysig virtual class System.Byte[] GetPreamble() [C#] public virtual byte[] GetPreamble()
V W X
Summary
Y
Returns the bytes used at the beginning of a System.IO.Stream to determine which System.Text.Encoding the stream was created with.
Z
1494
Contents | Index
System.Text
Encoding GetString() Method
Description [Note: The preamble can be the Unicode byte order mark (U+FEFF written in the appropriate encoding) or any other type of identifying marks. This method can return an empty array.]
A B
Default
C
The default implementation returns an empty System.Byte array.
D
How and When to Override
E
Override this method to return a System.Byte array containing the preamble appropriate for the type derived from System.Text.Encoding.
F G H
Encoding.GetString(System.Byte[]) Method
I
[ILASM] .method public hidebysig virtual string GetString(class System.Byte[] bytes) [C#] public virtual string GetString(byte[] bytes)
J K L M
Summary
N
Decodes the specified System.Byte array.
O
Parameters
P Q
Parameter
Description R
bytes
The System.Byte array to decode.
S T
How and When to Override
U
This method is overridden by particular character encodings.
V W
Exceptions
X
Exception
Condition
System.ArgumentNullException
bytes is null.
Y Z
1495
Contents | Index
Encoding
System.Text
GetString() Method
Encoding.GetString(System.Byte[], System.Int32, System.Int32) Method [ILASM] .method public hidebysig virtual string GetString(class System.Byte[] bytes, int32 index, int32 count) [C#] public virtual string GetString(byte[] bytes, int index, int count)
A B C D
Summary
E
Decodes the specified range of the specified System.Byte array.
F
Parameters
G H I
Parameter
Description
bytes
The System.Byte array to decode.
index
A System.Int32 containing the starting index of bytes to decode.
count
A System.Int32 containing the number of bytes to decode.
J K L M N
Return Value
O
A System.String containing the decoded representation of the range of bytes from index to index + count.
P Q
How and When to Override
R
This method is overridden by particular character encodings.
S
Exceptions
T U
Exception
Condition
System.ArgumentNullException
bytes is null.
System.ArgumentOutOfRangeException
index and count do not denote a valid range in bytes.
V W X Y Z
1496
Contents | Index
System.IO EndOfStreamException
BCL
Object Exception
ISerializable
A
NotStandardized
B
SystemException IOException
C
EndOfStreamException
D E
Summary
F
Represents the error that occurs when an attempt is made to read past the end of a stream.
G
Type Summary
H
public class EndOfStreamException : IOException { // Constructors public EndOfStreamException (); public EndOfStreamException (string message); public EndOfStreamException (string message, Exception innerException); MS CF protected EndOfStreamException (SerializationInfo info, StreamingContext context); }
I J K L M N O P
BA Our general rule on the use of Exceptions is that they are to be used in excep-
Q
tional situations only. By exceptional we mean situations that the client will very likely have to write special case error handling code. So, is reading to the end of a stream an exceptional situation? Not if you are reading byte-by-byte through the stream; in such a case you always read the end of the stream, so that is not an exceptional situation. However, if you are reading 32 bit values out of the stream and you find the end of the stream when you have read only 16 bits out then that is exceptional, and clearly an error case. The file format you are reading is likely corrupted. This latter case is where this exception should be used.
R S T U V W X Y Z
1497
Contents | Index
EndOfStreamException
System.IO
EndOfStreamException() Constructor
Example using System; using System.IO; using System.Text; namespace Samples { public class EndOfStreamExceptionSample { public static void Main() { string s = "filestream.txt"; FileStream fs = new FileStream(s, FileMode.Open); BinaryReader br = new BinaryReader(fs, Encoding.ASCII ); try { while(true) { char c = br.ReadChar(); } } catch(EndOfStreamException e ) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P
The output is
Q R
Exception: System.IO.EndOfStreamException: Unable to read beyond the end of the stream. at System.IO.__Error.EndOfFile() at System.IO.BinaryReader.ReadChar() at Samples.EndOfStreamExceptionSample.Main() in C:\Books\BCL\Samples\System.IO\ EndOfStreamException\EndOfStreamException.cs:line 19
S T U V W
EndOfStreamException() Constructor
X [ILASM] public rtspecialname specialname instance void .ctor() [C#] public EndOfStreamException()
Y Z
1498
Contents | Index
System.IO
EndOfStreamException EndOfStreamException() Constructor
Summary Constructs and initializes a new instance of the System.IO.EndOfStreamException class. A
Description
B
This constructor initializes the System.IO.EndOfStreamException.Message property of the new instance to a system-supplied message that describes the error, such as “Attempted to read past the end of the stream.” This message takes into account the current system culture. The System.IO.EndOfStreamException.InnerException property of the new instance is initialized to null.
C D E F G H
EndOfStreamException(System.String) Constructor
I
[ILASM] public rtspecialname specialname instance void .ctor(string message) [C#] public EndOfStreamException(string message)
J K L
Summary
M
Constructs and initializes a new instance of the System.IO.EndOfStreamException class.
N O P
Parameters
Q
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
R S T U V
Description
W
This constructor initializes the System.IO.EndOfStreamException.Message property of the new instance using message. If message is null, the System.IO.EndOfStreamException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.IO.EndOfStreamException.InnerException property of the new instance is initialized to null.
X Y Z
1499
Contents | Index
EndOfStreamException
System.IO
EndOfStreamException() Constructor
EndOfStreamException(System.String, System.Exception) Constructor [ILASM] public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException) [C#] public EndOfStreamException(string message, Exception innerException)
A B C D
Summary
E
Constructs and initializes a new instance of the System.IO.EndOfStreamException class.
F
Parameters
G H
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
I J K L M N O
Description
P
This constructor initializes the System.IO.EndOfStreamException.Message property of the new instance using message and the System.IO.EndOfStreamException.InnerException property using innerException. If message is null, the System.IO.EndOfStreamException.Message property is initialized to the systemsupplied message provided by the constructor that takes no arguments. [Note: For more information on inner exceptions, see System.Exception.InnerException.]
Q R S T U V
EndOfStreamException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
W X
[ILASM] family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context) [C#] protected EndOfStreamException(SerializationInfo info, StreamingContext context)
Y Z
1500
Contents | Index
System.IO
EndOfStreamException EndOfStreamException() Constructor
Summary Initializes a new instance of the System.IO.EndOfStreamException class with the specified serialization and context information. A
Parameters
B C
Parameter
Description
info
The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown.
context
The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination.
D E F G H I J K L M N O P Q R S T U V W X Y Z
1501
Contents | Index
System Enum
BCL
Object
A
IComparable
ValueType
B
Enum
IFormattable
C
AttributeTargets
D
DateTimeStyles
E
NumberStyles
IConvertible
NotStandardized
UnicodeCategory
F
FileAccess
G
FileMode
H FileShare
I SeekOrigin
J EnvironmentPermissionAccess
K
FileIOPermissionAccess
L
PermissionState
M
SecurityAction
N
SecurityPermissionFlag
O
ThreadPriority
P
ThreadState
Q R
Summary
S
Provides support for all enumeration types. Serves as the base class for all enumeration types.
T
Type Summary
U
public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible { // Methods CF public int CompareTo (object target); CF public override bool Equals (object obj); CF public static string Format (Type enumType, object value, string format); CF public override int GetHashCode ();
V W X Y Z
1502
Contents | Index
System
Enum Enum Class
CF public static string GetName (Type enumType, object value); CF public static string[] GetNames (Type enumType); MS public TypeCode GetTypeCode (); public static Type GetUnderlyingType (Type enumType); CF public static Array GetValues (Type enumType); public static bool IsDefined (Type enumType, object value); CF public static object Parse (Type enumType, string value); CF public static object Parse (Type enumType, string value, bool ignoreCase); CF public static object ToObject (Type enumType, byte value); CF public static object ToObject (Type enumType, int value); CF public static object ToObject (Type enumType, long value); public static object ToObject (Type enumType, object value); CF public static object ToObject (Type enumType, sbyte value); CF public static object ToObject (Type enumType, short value); CF public static object ToObject (Type enumType, uint value); CF public static object ToObject (Type enumType, ulong value); CF public static object ToObject (Type enumType, ushort value); public override string ToString (); CF public string ToString (string format); CF public string ToString (string format, IFormatProvider provider); CF public string ToString (IFormatProvider provider);
A B C D E F G H I J K L M N O P Q R S T
// MS MS MS MS MS MS MS MS MS MS MS
Explicit Interface Members bool IConvertible.ToBoolean(IFormatProvider provider); byte IConvertible.ToByte(IFormatProvider provider); char IConvertible.ToChar(IFormatProvider provider); DateTime IConvertible.ToDateTime(IFormatProvider provider); decimal IConvertible.ToDecimal(IFormatProvider provider); double IConvertible.ToDouble(IFormatProvider provider); short IConvertible.ToInt16(IFormatProvider provider); int IConvertible.ToInt32(IFormatProvider provider); long IConvertible.ToInt64(IFormatProvider provider); sbyte IConvertible.ToSByte(IFormatProvider provider); float IConvertible.ToSingle(IFormatProvider provider);
U V W X Y Z
1503
Contents | Index
Enum
System
Enum Class
MS MS MS MS
A
object IConvertible.ToType(Type type,IFormatProvider provider); ushort IConvertible.ToUInt16(IFormatProvider provider); uint IConvertible.ToUInt32(IFormatProvider provider); ulong IConvertible.ToUInt64(IFormatProvider provider);
}
B C
BA Notice that System.Enum is the only reference type that extends Sys-
D
tem.ValueType. In general I discourage designs where there is one special class that does not follow the rules. In this case the rule is that all subclasses of ValueType are stack allocated values. However, in this case I believe it was warranted to be able to have all Enums to have a common base.
E F G
Notice that enums can have any integral underlying type. By default in C# it is int, but it could be long or byte etc. That is why we have all the overloads of ToObject().
H I J
public enum FamilyMember : byte { Tamara = 0, Brad = 1, Boston = 2, }
K L M
In practice, this feature is rarely used. Unless you need the additional space it is best to use the default type of int.
N O
Notice that enum values in the CLR are not forced to be defined in the class at compile time. You can cast any value (of the same underlying type) to the enum type. That is why it is always a good idea to do a check to be sure your enum value is expected. This line of code is perfectly legal and verifiable.
P Q R S
FamilyMember fm = (FamilyMember) 42;
T
BG We really have two different concepts of enums. One is the straight, simple enu-
U
merated type containing distinct values such as the days of the week. The other is what we’ve called “bitfields,” where we expect users to bitwise OR multiple fields together. While the CLR stores both of these as enums, I’ve always fancied that some language would distinguish between these cases, making bitwise operations on simple enums illegal. To make this distinction though, you must use the FlagsAttribute to indicate that an enum is a bitfield.
V W X Y Z
continued
1504
Contents | Index
System
Enum Enum Class
JR Since enums have an integral underlying type, enums are considered primitive values by most compilers (including C#). Compiler primitive values are compiled directly into code. This causes an interesting problem: If an assembly defines a public enum type with a symbol, say MaxEntriesInList, set to 50 and then another assembly is built referring to MaxEntriesInList, the value 50 is extracted at compile time and embedded into the referencing assembly. At runtime, the assembly that defines the enum type may not be required at all. This sounds good at first; but, if the value of MaxEntriesInList is later changed from 50 to 100, the referencing assembly will not be aware of this change—it must be recompiled to pick up the new value, 100. If you want to have a runtime association of a value between assemblies, do not use enumerated types, use read-only fields instead.
A B C D E F G H
Description
I
A System.Enum is a distinct type with named constant members. Each enumeration type has a corresponding integral type called the underlying type of the enumeration type. This underlying type is required to be a system-supplied integer type that is large enough to represent all values defined in the enumeration; the field that holds the underlying type must be called value__. A System.Enum declaration is allowed to explicitly declare any integral type other than System.Char as an underlying type. This includes System.Byte, System.SByte, System.Int16, System.Int32, System.Int64, System.UInt16, System.UInt32, and System.UInt64. A System.Enum declaration that does not explicitly declare an underlying type has an underlying type of System.Int32. System.Enum derives from System.ValueType but is not a value type. Programming languages typically provide syntax to declare sets of a specified enumeration type consisting of named constants and their values. It is possible to treat instances of a System.Enum as bit fields containing multiple values. For more information, see System.FlagsAttribute. [Note: System.Enum provides methods to compare instances of enumeration types, convert the value of an instance to its System.String representation, convert the System.String representation of a number to an instance of the enumeration type, and create an instance of a specified enumeration and value.]
J K L M N O P Q R S T U V W
Example
X
The following example demonstrates the use of two types of enumerations, one with the Flags attribute applied and one without. It is fair to say, however, that use of the attribute is a little contrived in this sample.
Y Z
1505
Contents | Index
Enum
System
Enum Class
using System; namespace Samples { public class EnumToString { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; [Flags] enum MonthOfYear {January = 0x1, February = 0x2, March = 0x4, April = 0x8, May = 0x10, June = 0x20, July = 0x40, August = 0x80, September = 0x100, Ocotber = 0x200, November = 0x400, December = 0x800}; public static void Main() { string[] f = {"D", "F", "X", "G"}; DayOfWeek d = DayOfWeek.Saturday; foreach(string s in f) Console.WriteLine( "Value {0} formatted with {1}: {2}", d, s, d.ToString(s)); ++d; foreach(string s in f) Console.WriteLine( "Value {0} formatted with {1}: {2}", d, s, d.ToString(s)); MonthOfYear ThirtyDayMonths = MonthOfYear.September | MonthOfYear.April | MonthOfYear.June | MonthOfYear.November; Console.WriteLine("30 day months: {0}", ThirtyDayMonths); } } }
A B C D E F G H I J K L M N O P Q R S T
The output is
U Value Saturday formatted with D: 6 Value Saturday formatted with F: Saturday Value Saturday formatted with X: 00000006 Value Saturday formatted with G: Saturday Value 7 formatted with D: 7 Value 7 formatted with F: Monday, Saturday Value 7 formatted with X: 00000007 Value 7 formatted with G: 7 30 day months: April, June, September, November
V W X Y Z
1506
Contents | Index
System
Enum CompareTo() Method
Enum.CompareTo(System.Object) Method [ILASM] .method public final hidebysig virtual int32 CompareTo(object target) [C#] public int CompareTo(object target)
A B C
Summary
D
Returns the sort order of the current instance compared to the specified System.Object.
E
Parameters
F
Parameter
Description
target
An object to compare the current instance to.
G H I J
Return Value
K
A System.Int32 containing a value that reflects the sort order of the current instance as compared to target. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number.
L M N O
Return Value
Description
Any negative integer
The value of the current instance is less than the value of target.
Q
Zero
The value of the current instance is equal to the value of target.
R
Any positive integer
The value of the current instance is greater than the value of target, or target is null.
P
S T U
Description
V
[Note: This method is implemented to support the System.IComparable interface.]
W X Y Z
1507
Contents | Index
Enum
System
CompareTo() Method
Exceptions Exception
Condition
System.ArgumentException
target and the current instance are not of the same enumeration type.
A B C D
Example
E
using System; namespace Samples { public class EnumCompareTo { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; private static string CompareEnums(Enum e1, Enum e2) { int i = e1.CompareTo(e2); if(0 == i) return String.Format("{0} is equal to {1}", e1, e2); if(i > 0) return String.Format("{0} is greater than {1}", e1, e2); else return String.Format("{0} is less than {1}", e1, e2); } public static void Main() { Console.WriteLine(CompareEnums(DayOfWeek.Monday, DayOfWeek.Monday)); Console.WriteLine(CompareEnums(DayOfWeek.Sunday, DayOfWeek.Monday)); Console.WriteLine(CompareEnums(DayOfWeek.Tuesday, DayOfWeek.Monday)); } } }
F G H I J K L M N O P Q R S T U V W
The output is
X
Monday is equal to Monday Sunday is less than Monday Tuesday is greater than Monday
Y Z
1508
Contents | Index
System
Enum Equals() Method
Enum.Equals(System.Object) Method [ILASM] .method public hidebysig virtual bool Equals(object obj) [C#] public override bool Equals(object obj)
A B C
Summary
D
Determines whether the current instance and the specified System.Object represent the same type and value.
E F
Parameters
G
Parameter
Description
obj
An object to compare the current instance to.
H I J K
Return Value
L
true if obj is of the same enumeration type and represents the same value as the current instance; otherwise, false.
M N
Description
O
[Note: This method overrides System.Object.Equals.]
P
Example
Q
using System; namespace Samples { public class EnumCompareTo { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; private static string CompareEnums(Enum e1, Enum e2) { int i = e1.CompareTo(e2); if(0 == i) return String.Format("{0} is equal to {1}", e1, e2); if(i > 0) return String.Format("{0} is greater than {1}", e1, e2); else return String.Format("{0} is less than {1}", e1, e2);
R S T U V W X Y Z
1509
Contents | Index
Enum
System
Format() Method
} public static void Main() { Console.WriteLine(CompareEnums(DayOfWeek.Monday, DayOfWeek.Monday)); Console.WriteLine(CompareEnums(DayOfWeek.Sunday, DayOfWeek.Monday)); Console.WriteLine(CompareEnums(DayOfWeek.Tuesday, DayOfWeek.Monday)); }
A B C D }
E
}
F
The output is
G
Is Monday equal to Monday: True Is Monday equal to Tuesday: False
H I J
Enum.Format(System.Type, System.Object, System.String) Method
K
[ILASM] .method public hidebysig static string Format(class System.Type enumType, object value, string format) [C#] public static string Format(Type enumType, object value, string format)
L M N O
Summary
P
Converts the specified element of the specified enumeration type to its System.String representation using the specified format.
Q R
Parameters
S T
Parameter
Description
enumType
A System.Type that specifies the type of the enumeration of which value is a member.
value
The enumeration element to be converted.
format
A System.String that specifies the output format to use.
U V W X Y Z
1510
Contents | Index
System
Enum Format() Method
Description For cross-platform portability, the only valid values for format are: A
Format
Description
“G” or “g”
If value is equal to a defined value of enumType, returns the element name defined for value. If the System.FlagsAttribute attribute is set on the System.Enum declaration and value is a built-in integer type and is equal to a summation of enumeration elements, the return value contains the element names in an unspecified order, separated by commas (e.g., “Red, Yellow”). Otherwise, value is returned in decimal format.
B C D E F G
“X” or “x”
Returns value in hexadecimal format, without a leading 0x. The value is padded with leading zeroes to ensure the returned value is at least eight digits in length.
“F” or “f ”
Behaves identically to “G”, except the FlagsAttribute is not required to be present on the System.Enum declaration.
I
Returns value in decimal format with no leading zeroes.
K
“D” or “d”
H
J
L M
Exceptions
N
Exception
Condition
System.ArgumentNullException
enumType, value, or format is a null reference.
P
enumType is not a System.Enum.
Q
-or-
R
value is neither of type enumType nor does it have the same underlying type as enumType.
S
System.ArgumentException
O
T System.FormatException
format contains an invalid value.
U V W X Y Z
1511
Contents | Index
Enum
System
GetHashCode() Method
Example using System; namespace Samples { public class EnumFormat { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main() { DayOfWeek d = DayOfWeek.Monday; string[] f = {"G", "X", "D"}; foreach(string s in f) Console.WriteLine("{0} formatted with {1}: {2}", d, s, Enum.Format(typeof(DayOfWeek), d, s)); } } }
A B C D E F G H I J K
The output is
L
Monday formatted with G: Monday Monday formatted with X: 00000001 Monday formatted with D: 1
M N O
Enum.GetHashCode() Method
P [ILASM] .method public hidebysig virtual int32 GetHashCode() [C#] public override int GetHashCode()
Q R S T
Summary
U
Generates a hash code for the current instance.
V
Description
W
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
X Y Z
1512
Contents | Index
System
Enum GetName() Method
Example using System; namespace Samples { public class EnumGetHashCode { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main() { for(DayOfWeek d = DayOfWeek.Sunday; d <= DayOfWeek.Saturday; d++) Console.WriteLine("{0}.GetHashCode(): {1}", d, d.GetHashCode()); } } }
A B C D E F G H I
The output is
J
Sunday.GetHashCode(): 0 Monday.GetHashCode(): 1 Tuesday.GetHashCode(): 2 Wednesday.GetHashCode(): 3 Thursday.GetHashCode(): 4 Friday.GetHashCode(): 5 Saturday.GetHashCode(): 6
K L M N O P
Enum.GetName(System.Type, System.Object) Method
Q
[ILASM] .method public hidebysig static string GetName(class System.Type enumType, object value) [C#] public static string GetName(Type enumType, object value)
R S T
Summary
U
Retrieves the name of the constant of the specified enumeration type that has the specified value.
V W X Y Z
1513
Contents | Index
Enum
System
GetName() Method
Parameters Parameter
Description
enumType
A System.Type that specifies the type of the enumeration.
value
A System.Object that contains the integral value or the name of an enumeration constant.
A B C D E
Return Value
F
A System.String containing the name of the enumerated constant in enumType whose value is value, or a null reference if no such constant is found.
G H
Exceptions
I J K
Exception
Condition
System.ArgumentNullException
enumType or value is a null reference.
L
enumType is not a System.Type that describes a System.Enum.
M System.ArgumentException
N
-orvalue is neither of type enumType nor does it have the same underlying type as enumType.
O P Q
Example
R
using System; namespace Samples { public class EnumGetName { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main() { Type t = typeof(DayOfWeek); for(int i = 0; i <= 7; i++) Console.WriteLine("GetName({0}, {1}): {2}", t, i, Enum.GetName(t, i)); } } }
S T U V W X Y Z
1514
Contents | Index
System
Enum GetNames() Method
The output is GetName(Samples.EnumGetName+DayOfWeek, GetName(Samples.EnumGetName+DayOfWeek, GetName(Samples.EnumGetName+DayOfWeek, GetName(Samples.EnumGetName+DayOfWeek, GetName(Samples.EnumGetName+DayOfWeek, GetName(Samples.EnumGetName+DayOfWeek, GetName(Samples.EnumGetName+DayOfWeek, GetName(Samples.EnumGetName+DayOfWeek,
0): 1): 2): 3): 4): 5): 6): 7):
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
A B C D E F
Enum.GetNames(System.Type) Method
G
[ILASM] .method public hidebysig static class System.String[] GetNames(class System.Type enumType) [C#] public static string[] GetNames(Type enumType)
H I J K
Summary
L
Returns a zero-based, one-dimensional System.String array that contains the names of the constants of the specified enumeration type.
M N
Parameters
O
Parameter
Description
enumType
A System.Type that specifies the type of an enumeration.
P Q R S
Return Value
T
A System.String vector of the names of the constants in enumType. The elements of the vector are sorted by the values of the enumerated constants.
U V W X Y Z
1515
Contents | Index
Enum
System
GetTypeCode() Method
Exceptions Exception
Condition
System.ArgumentNullException
enumType is a null reference.
System.ArgumentException
enumType is not a System.Type that describes a System.Enum.
A B C D E
Example
F
using System; namespace Samples { public class EnumGetNames { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main() { string[] strings = Enum.GetNames(typeof(DayOfWeek)); foreach(string s in strings) Console.WriteLine(s); } } }
G H I J K L M N O P
The output is
Q Sunday Monday Tuesday Wednesday Thursday Friday Saturday
R S T U V W
Enum.GetTypeCode() Method
X
[ILASM] .method public final hidebysig virtual valuetype System.TypeCode GetTypeCode() [C#] public TypeCode GetTypeCode()
Y Z
1516
Contents | Index
System
Enum GetUnderlyingType() Method
Summary Returns the underlying System.TypeCode for this instance. A
Enum.GetUnderlyingType(System.Type) Method
B
[ILASM] .method public hidebysig static class System.Type GetUnderlyingType(class System.Type enumType) [C#] public static Type GetUnderlyingType(Type enumType)
C D E F
Summary
G
Returns the underlying type of the specified enumeration type.
H I
Parameters
J K
Parameter
Description
enumType
The System.Type of an enumeration.
L M N
Exceptions
O
Exception
Condition
System.ArgumentNullException
enumType is a null reference.
System.ArgumentException
enumType is not an enumeration type.
P Q R S T
Example
U
using System; namespace Samples { public class EnumGetUnderlyingType { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; enum Color : long {Red, Green, Blue} ; public static void Main() {
V W X Y Z
1517
Contents | Index
Enum
System
GetValues() Method
Type t = typeof(DayOfWeek); Console.WriteLine("Underlying type for {0} is {1}", t, Enum.GetUnderlyingType(t)); t = typeof(Color); Console.WriteLine("Underlying type for {0} is {1}", t, Enum.GetUnderlyingType(t));
A B }
C
} }
D
The output is
E F
Underlying type for Samples.EnumGetUnderlyingType+DayOfWeek is System.Int32 Underlying type for Samples.EnumGetUnderlyingType+Color is System.Int64
G H
Enum.GetValues(System.Type) Method
I J
[ILASM] .method public hidebysig static class System.Array GetValues(class System.Type enumType) [C#] public static Array GetValues(Type enumType)
K L M N
Summary
O
Returns a zero-based, one-dimensional array of the values of the constants of the specified enumeration type.
P Q
Parameters
R S T
Parameter
Description
enumType
The System.Type of an enumeration.
U V
Return Value
W
A vector of the enumeration type specified by enumType containing the values of the constants in enumType. The elements of the array are sorted by the values of the enumeration constants.
X Y Z
1518
Contents | Index
System
Enum IsDefined() Method
Exceptions Exception
Condition
System.ArgumentNullException
enumType is a null reference.
System.ArgumentException
enumType is not an enumeration type.
A B C D
Example
E
using System; namespace Samples { public class EnumGetValues { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main() { Array a = Enum.GetValues(typeof(DayOfWeek)); foreach(int i in a) Console.WriteLine("The value of {0} is {1}", Enum.Format(typeof(DayOfWeek), i, "G"), i); } } }
F G H I J K L M N O P
The output is The The The The The The The
value value value value value value value
of of of of of of of
Q R
Sunday is 0 Monday is 1 Tuesday is 2 Wednesday is 3 Thursday is 4 Friday is 5 Saturday is 6
S T U V W X
Enum.IsDefined(System.Type, System.Object) Method
Y
[ILASM] .method public hidebysig static bool IsDefined(class System.Type enumType, object value) [C#] public static bool IsDefined(Type enumType, object value)
Z
1519
Contents | Index
Enum
System
IsDefined() Method
Summary Returns a System.Boolean indicating whether a constant with the specified value exists in the specified enumeration type. A
Parameters
B C
Parameter
Description
E
enumType
A System.Type that describes an enumeration.
F
value
The constant or value being searched for in enumType.
D
G H
Return Value
I
true if a constant in the enumeration described by enumType has a value equal to value; otherwise, false.
J K
Exceptions
L M N
Exception
Condition
System.ArgumentNullException
enumType or value is a null reference.
O
enumType is not an enumeration type.
P System.ArgumentException
Q
-orThe type of value is not an enumType or an underlying type of enumType.
R S T
Example
U
using System; namespace Samples { public class EnumIsDefined { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main() { Type t = typeof(DayOfWeek); for(int i = 0; i < 10; i++) Console.WriteLine(
V W X Y Z
1520
Contents | Index
System
Enum Parse() Method
"Is the value {0} defined in {1}: {2}", i, t, Enum.IsDefined(t, i)); } }
A
}
B
The output is Is Is Is Is Is Is Is Is Is Is
the the the the the the the the the the
value value value value value value value value value value
0 1 2 3 4 5 6 7 8 9
C
defined defined defined defined defined defined defined defined defined defined
in in in in in in in in in in
Samples.EnumIsDefined+DayOfWeek: Samples.EnumIsDefined+DayOfWeek: Samples.EnumIsDefined+DayOfWeek: Samples.EnumIsDefined+DayOfWeek: Samples.EnumIsDefined+DayOfWeek: Samples.EnumIsDefined+DayOfWeek: Samples.EnumIsDefined+DayOfWeek: Samples.EnumIsDefined+DayOfWeek: Samples.EnumIsDefined+DayOfWeek: Samples.EnumIsDefined+DayOfWeek:
True True True True True True True False False False
D E F G H I J K
Enum.Parse(System.Type, System.String) Method
L
[ILASM] .method public hidebysig static object Parse(class System.Type enumType, string value) [C#] public static object Parse(Type enumType, string value)
M N O P
Summary
Q
Converts the specified System.String representation of one or more enumerated constants of a specified enumeration type to an equivalent enumerated object.
R S
Parameters
T
Parameter
Description
enumType
The System.Type of an enumeration.
value
A System.String containing one or more names or a single numeric value to convert. If the string contains more than one name, each name is required to be separated by a comma (‘,’). The names are parsed in a case-sensitive manner. The names or number can be surrounded by any amount of white space.
U V W X Y Z
1521
Contents | Index
Enum
System
Parse() Method
Description This version of System.Enum.Parse is equivalent to System.Enum.Parse(enumType, value, false). A
Exceptions
B C
Exception
Condition
System.ArgumentNullException
enumType or value is a null reference.
D E F
enumType is not a System.Type that describes a System.Enum.
G
-or-
H System.ArgumentException I
value is either equal to System.String.Empty or contains only white space. -or-
J
value represents one or more names, and at least one name represented by value is not of type enumType.
K L M
Example
N
using System; namespace Samples { public class EnumParse { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main() { Object o = Enum.Parse(typeof(DayOfWeek), "Wednesday"); Console.WriteLine("Returned object of type {0}", o.GetType()); Console.WriteLine("with a value of {0:D} or {1}", o, o); } } }
O P Q R S T U V W X Y
The output is
Z
Returned object of type Samples.EnumParse+DayOfWeek with a value of 3 or Wednesday
1522
Contents | Index
System
Enum Parse() Method
Enum.Parse(System.Type, System.String, System.Boolean) Method [ILASM] .method public hidebysig static object Parse(class System.Type enumType, string value, bool ignoreCase) [C#] public static object Parse(Type enumType, string value, bool ignoreCase)
A B C
Summary
D
Converts the specified System.String representation of one or more enumerated constants of a specified enumeration type to an equivalent enumerated object. This method behaves in a case-sensitive or -insensitive manner according to the specified System.Boolean.
E F G
Parameters
H I
Parameter
Description
enumType
The System.Type of an enumeration.
value
A System.String containing one or more names or a single numeric value to convert. If the string contains more than one name, each name is required to be separated by a comma (‘,’). The names or number can be surrounded by any amount of white space.
ignoreCase
A System.Boolean value. Specify true to have names in value parsed in a case-insensitive manner. Specify false to have names parsed in a case-sensitive manner.
J K L M N O P Q
Exceptions
R
Exception
Condition
System.ArgumentNullException
enumType or value is a null reference.
S T
System.ArgumentException
U
enumType is not a System.Type that describes a System.Enum.
V
-or-
W
value is either equal to System.String.Empty or contains only white space.
X Y
-or-
Z
value represents one or more names, and at least one name represented by value is not of type enumType.
1523
Contents | Index
Enum
System
Parse() Method
Example using System; namespace Samples { public class EnumParse { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main() { try { Object o = Enum.Parse(typeof(DayOfWeek), "wednesday", true); Console.WriteLine("Returned object of type {0}", o.GetType()); Console.WriteLine("with a value of {0:D} or {1}", o, o); o = Enum.Parse(typeof(DayOfWeek), "wednesday", false); Console.WriteLine("Returned object of type {0}", o.GetType()); Console.WriteLine("with a value of {0:D} or {1}", o, o); } catch(ArgumentException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P Q R S
The output is
T Returned object of type Samples.EnumParse+DayOfWeek with a value of 3 or Wednesday Exception: System.ArgumentException: Requested value wednesday was not found. at System.Enum.Parse(Type enumType, String value, Boolean ignoreCase) at Samples.EnumParse.Main() in C:\Books\BCL\Samples\System\Enum\ Parse(System.Type,System.String,System.Boolean)\Enum.cs:line 19
U V W X Y Z
1524
Contents | Index
System
Enum ToObject() Method
Enum.ToObject(System.Type, System.Byte) Method [ILASM] .method public hidebysig static object ToObject(class System.Type enumType, unsigned int8 value) [C#] public static object ToObject(Type enumType, byte value)
A B C
Summary
D
Returns an instance of the specified enumeration type set to the specified System.Byte value.
E
Parameters
G
F
H
Parameter
Description
enumType
The System.Type of an enumeration.
value
The System.Byte value to set.
I J K L M
Exceptions
N
Exception
Condition
System.ArgumentNullException
enumType is a null reference.
System.ArgumentException
enumType is not a System.Type that describes a System.Enum.
O P Q R S T
Example
U
using System; namespace Samples { public class EnumToObject { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main() { Type t = typeof(DayOfWeek); for(Byte i = (Byte) DayOfWeek.Sunday,
V W X Y Z
1525
Contents | Index
Enum
System
ToObject() Method
until = (Byte) DayOfWeek.Saturday + 1; i <= until; i++) Console.WriteLine( "The value {0} defined in {1} is: {2}", i, t, Enum.ToObject(t, i));
A }
B }
C
}
D
The output is
E The The The The The The The The
F G H I J
value value value value value value value value
0 1 2 3 4 5 6 7
defined defined defined defined defined defined defined defined
in in in in in in in in
Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek
is: is: is: is: is: is: is: is:
Sunday Monday Tuesday Wednesday Thursday Friday Saturday 7
K L
Enum.ToObject(System.Type, System.Int32) Method
M
[ILASM]
N
.method public hidebysig static object ToObject(class System.Type enumType, int32 value)
O
[C#]
public static object ToObject(Type enumType, int value)
P Q
Summary
R
Returns an instance of the specified enumeration type set to the specified System.Int32 value.
S T
Parameters
U V
Parameter
Description
W
enumType
The System.Type of an enumeration.
value
The System.Int32 value to set.
X Y Z
1526
Contents | Index
System
Enum ToObject() Method
Exceptions Exception
Condition
System.ArgumentNullException
enumType is a null reference.
System.ArgumentException
enumType is not a System.Type that describes a System.Enum.
A B C D E
Example
F
using System; namespace Samples { public class EnumToObject { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main() { Type t = typeof(DayOfWeek); for(Int32 i = (Int32) DayOfWeek.Sunday - 1, until = (Int32) DayOfWeek.Saturday + 1; i <= until; i++) Console.WriteLine( "The value {0} defined in {1} is: {2}", i, t, Enum.ToObject(t, i)); } } }
G H I J K L M N O P Q R
The output is The The The The The The The The The
value value value value value value value value value
S T
-1 defined in Samples.EnumToObject+DayOfWeek is: -1 0 defined in Samples.EnumToObject+DayOfWeek is: Sunday 1 defined in Samples.EnumToObject+DayOfWeek is: Monday 2 defined in Samples.EnumToObject+DayOfWeek is: Tuesday 3 defined in Samples.EnumToObject+DayOfWeek is: Wednesday 4 defined in Samples.EnumToObject+DayOfWeek is: Thursday 5 defined in Samples.EnumToObject+DayOfWeek is: Friday 6 defined in Samples.EnumToObject+DayOfWeek is: Saturday 7 defined in Samples.EnumToObject+DayOfWeek is: 7
U V W X Y Z
1527
Contents | Index
Enum
System
ToObject() Method
Enum.ToObject(System.Type, System.Int64) Method [ILASM] .method public hidebysig static object ToObject(class System.Type enumType, int64 value) [C#] public static object ToObject(Type enumType, long value)
A B C D
Summary
E
Returns an instance of the specified enumeration type set to the specified System.Int64 value.
F G
Parameters
H I J
Parameter
Description
enumType
The System.Type of an enumeration.
value
The System.Int64 value to set.
K L M
Exceptions
N O
Exception
Condition
System.ArgumentNullException
enumType is a null reference.
System.ArgumentException
enumType is not a System.Type that describes a System.Enum.
P Q R S T
Example
U
using System; namespace Samples { public class EnumToObject { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main() { Type t = typeof(DayOfWeek); for(Int64 i = (Int64) DayOfWeek.Sunday - 1,
V W X Y Z
1528
Contents | Index
System
Enum ToObject() Method
until = (Int64) DayOfWeek.Saturday + 1; i <= until; i++) Console.WriteLine( "The value {0} defined in {1} is: {2}", i, t, Enum.ToObject(t, i));
A
}
B
}
C
}
D
The output is
E The The The The The The The The The
value value value value value value value value value
-1 defined in Samples.EnumToObject+DayOfWeek is: -1 0 defined in Samples.EnumToObject+DayOfWeek is: Sunday 1 defined in Samples.EnumToObject+DayOfWeek is: Monday 2 defined in Samples.EnumToObject+DayOfWeek is: Tuesday 3 defined in Samples.EnumToObject+DayOfWeek is: Wednesday 4 defined in Samples.EnumToObject+DayOfWeek is: Thursday 5 defined in Samples.EnumToObject+DayOfWeek is: Friday 6 defined in Samples.EnumToObject+DayOfWeek is: Saturday 7 defined in Samples.EnumToObject+DayOfWeek is: 7
F G H I J K L
Enum.ToObject(System.Type, System.Object) Method
M
[ILASM] .method public hidebysig static object ToObject(class System.Type enumType, object value) [C#] public static object ToObject(Type enumType, object value)
N O P Q
Summary
R
Returns an instance of the specified enumeration type set to the specified value.
S T
Parameters
U
Parameter
Description
V
enumType
The System.Type of the enumeration.
W
value
The value to set.
X Y Z
1529
Contents | Index
Enum
System
ToObject() Method
Exceptions Exception
Condition
System.ArgumentNullException
enumType is a null reference.
System.ArgumentException
enumType is not a System.Type that describes a System.Enum.
A B C D E
Example
F
using System; namespace Samples { public class EnumToObject { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main() { Type t = typeof(DayOfWeek); for(int i = (int) DayOfWeek.Sunday - 1, until = (int) DayOfWeek.Saturday + 1; i <= until; i++) Console.WriteLine( "The value {0} defined in {1} is: {2}", i, t, Enum.ToObject(t, (Object)i)); } } }
G H I J K L M N O P Q R
The output is
S T
The The The The The The The The The
U V W X Y
value value value value value value value value value
-1 defined in Samples.EnumToObject+DayOfWeek is: -1 0 defined in Samples.EnumToObject+DayOfWeek is: Sunday 1 defined in Samples.EnumToObject+DayOfWeek is: Monday 2 defined in Samples.EnumToObject+DayOfWeek is: Tuesday 3 defined in Samples.EnumToObject+DayOfWeek is: Wednesday 4 defined in Samples.EnumToObject+DayOfWeek is: Thursday 5 defined in Samples.EnumToObject+DayOfWeek is: Friday 6 defined in Samples.EnumToObject+DayOfWeek is: Saturday 7 defined in Samples.EnumToObject+DayOfWeek is: 7
Z
1530
Contents | Index
System
Enum ToObject() Method
Enum.ToObject(System.Type, System.SByte) Method [ILASM] .method public hidebysig static object ToObject(class System.Type enumType, int8 value) [C#] public static object ToObject(Type enumType, sbyte value)
A B C
Summary
D
Returns an instance of the specified enumeration type set to the specified System.SByte value.
E
Parameters
G
F
H
Parameter
Description
enumType
The System.Type of an enumeration.
J
value
The System.SByte value to set.
K
I
L
Description
M
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Enum. ToObject(System.Type, System.Int16).
N O
Exceptions
P Q
Exception
Condition
System.ArgumentNullException
enumType is a null reference.
S
System.ArgumentException
enumType is not a System.Type that describes a System.Enum.
T
R
U V
Example
W
using System; namespace Samples { public class EnumToObject { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main()
X Y Z
1531
Contents | Index
Enum
System
ToObject() Method
{ Type t = typeof(DayOfWeek); for(SByte i = (SByte) DayOfWeek.Sunday - 1, until = (SByte) DayOfWeek.Saturday + 1; i <= until; i++) Console.WriteLine( "The value {0} defined in {1} is: {2}", i, t, Enum.ToObject(t, i));
A B C }
D
} }
E
The output is
F G
The The The The The The The The The
H I J K L
value value value value value value value value value
-1 defined in Samples.EnumToObject+DayOfWeek is: -1 0 defined in Samples.EnumToObject+DayOfWeek is: Sunday 1 defined in Samples.EnumToObject+DayOfWeek is: Monday 2 defined in Samples.EnumToObject+DayOfWeek is: Tuesday 3 defined in Samples.EnumToObject+DayOfWeek is: Wednesday 4 defined in Samples.EnumToObject+DayOfWeek is: Thursday 5 defined in Samples.EnumToObject+DayOfWeek is: Friday 6 defined in Samples.EnumToObject+DayOfWeek is: Saturday 7 defined in Samples.EnumToObject+DayOfWeek is: 7
M N
Enum.ToObject(System.Type, System.Int16) Method
O
[ILASM] .method public hidebysig static object ToObject(class System.Type enumType, int16 value) [C#] public static object ToObject(Type enumType, short value)
P Q R S
Summary
T
Returns an instance of the specified enumeration type set to the specified System.Int16 value.
U V
Parameters
W X Y
Parameter
Description
enumType
The System.Type of an enumeration.
value
The System.Int16 value to set.
Z
1532
Contents | Index
System
Enum ToObject() Method
Exceptions Exception
Condition
System.ArgumentNullException
enumType is a null reference.
System.ArgumentException
enumType is not a System.Type that describes a System.Enum.
A B C D E
Example
F
using System; namespace Samples { public class EnumToObject { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main() { Type t = typeof(DayOfWeek); for(Int16 i = (Int16) DayOfWeek.Sunday - 1, until = (Int16) DayOfWeek.Saturday + 1; i <= until; i++) Console.WriteLine( "The value {0} defined in {1} is: {2}", i, t, Enum.ToObject(t, i)); } } }
G H I J K L M N O P Q R
The output is The The The The The The The The The
value value value value value value value value value
S T
-1 defined in Samples.EnumToObject+DayOfWeek is: -1 0 defined in Samples.EnumToObject+DayOfWeek is: Sunday 1 defined in Samples.EnumToObject+DayOfWeek is: Monday 2 defined in Samples.EnumToObject+DayOfWeek is: Tuesday 3 defined in Samples.EnumToObject+DayOfWeek is: Wednesday 4 defined in Samples.EnumToObject+DayOfWeek is: Thursday 5 defined in Samples.EnumToObject+DayOfWeek is: Friday 6 defined in Samples.EnumToObject+DayOfWeek is: Saturday 7 defined in Samples.EnumToObject+DayOfWeek is: 7
U V W X Y Z
1533
Contents | Index
Enum
System
ToObject() Method
Enum.ToObject(System.Type, System.UInt32) Method [ILASM] .method public hidebysig static object ToObject(class System.Type enumType, unsigned int32 value) [C#] public static object ToObject(Type enumType, uint value)
A B C D
Summary
E
Returns an instance of the specified enumeration type set to the specified System.UInt32 value.
F G
Parameters
H I J K
Parameter
Description
enumType
The System.Type of an enumeration.
value
The System.UInt32 value to set.
L M
Description
N
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Enum.ToObject(System.Type, System.Int64).
O P
Exceptions
Q R
Exception
Condition
System.ArgumentNullException
enumType is a null reference.
System.ArgumentException
enumType is not a System.Type that describes a System.Enum.
S T U V W X Y Z
1534
Contents | Index
System
Enum ToObject() Method
Example using System; namespace Samples { public class EnumToObject { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main() { Type t = typeof(DayOfWeek); for(UInt32 i = (UInt32) DayOfWeek.Sunday, until = (UInt32) DayOfWeek.Saturday + 1; i <= until; i++) Console.WriteLine( "The value {0} defined in {1} is: {2}", i, t, Enum.ToObject(t, i)); } } }
A B C D E F G H I J K
The output is
L The The The The The The The The
value value value value value value value value
0 1 2 3 4 5 6 7
defined defined defined defined defined defined defined defined
in in in in in in in in
Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek
is: is: is: is: is: is: is: is:
Sunday Monday Tuesday Wednesday Thursday Friday Saturday 7
M N O P Q R
Enum.ToObject(System.Type, System.UInt64) Method
S
[ILASM] .method public hidebysig static object ToObject(class System.Type enumType, unsigned int64 value) [C#] public static object ToObject(Type enumType, ulong value)
T U V W
Summary
X
Returns an instance of the specified enumeration type set to the specified System.UInt64 value.
Y Z
1535
Contents | Index
Enum
System
ToObject() Method
Parameters Parameter
Description
enumType
The System.Type of an enumeration.
value
The System.UInt64 value to set.
A B C D E
Description
F
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Enum.ToObject(System.Type, System.Int64).
G H
Exceptions
I J
Exception
Condition
K
System.ArgumentNullException
enumType is a null reference.
System.ArgumentException
enumType is not a System.Type that describes a System.Enum.
L M N O
Example
P
using System; namespace Samples { public class EnumToObject { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main() { Type t = typeof(DayOfWeek); for(UInt64 i = (UInt64) DayOfWeek.Sunday, until = (UInt64) DayOfWeek.Saturday + 1; i <= until; i++) Console.WriteLine( "The value {0} defined in {1} is: {2}", i, t, Enum.ToObject(t, i)); } } }
Q R S T U V W X Y Z
1536
Contents | Index
System
Enum ToObject() Method
The output is The The The The The The The The
value value value value value value value value
0 1 2 3 4 5 6 7
defined defined defined defined defined defined defined defined
in in in in in in in in
Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek
is: is: is: is: is: is: is: is:
Sunday Monday Tuesday Wednesday Thursday Friday Saturday 7
A B C D E F
Enum.ToObject(System.Type, System.UInt16) Method
G
[ILASM] .method public hidebysig static object ToObject(class System.Type enumType, unsigned int16 value) [C#] public static object ToObject(Type enumType, ushort value)
H I J K
Summary
L
Returns an instance of the specified enumeration type set to the specified System.UInt16 value.
M N
Parameters
O P
Parameter
Description
enumType
The System.Type of an enumeration.
R
value
The System.UInt16 value to set.
S
Q
T
Description
U
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Enum.ToObject(System.Type, System.Int32).
V W X Y Z
1537
Contents | Index
Enum
System
ToObject() Method
Exceptions Exception
Condition
System.ArgumentNullException
enumType is a null reference.
System.ArgumentException
enumType is not a System.Type that describes a System.Enum.
A B C D E
Example
F
using System; namespace Samples { public class EnumToObject { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main() { Type t = typeof(DayOfWeek); for(UInt16 i = (UInt16) DayOfWeek.Sunday, until = (UInt16) DayOfWeek.Saturday + 1; i <= until; i++) Console.WriteLine( "The value {0} defined in {1} is: {2}", i, t, Enum.ToObject(t, i)); } } }
G H I J K L M N O P Q R
The output is
S T
The The The The The The The The
U V W X
value value value value value value value value
0 1 2 3 4 5 6 7
defined defined defined defined defined defined defined defined
in in in in in in in in
Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek Samples.EnumToObject+DayOfWeek
is: is: is: is: is: is: is: is:
Sunday Monday Tuesday Wednesday Thursday Friday Saturday 7
Y Z
1538
Contents | Index
System
Enum ToString() Method
Enum.ToString() Method [ILASM] .method public hidebysig virtual string ToString() [C#] public override string ToString()
A B C
Summary
D
Converts the name of the value of the current instance to its equivalent System.String representation.
E F
Description
G
This version of System.Enum.ToString is equivalent to System.Enum.ToString ("G", null). This method returns the same value as System.Enum.Format with the “g” or “G” format option. An instance of an enumeration is set to a named constant value. This method returns the name of the constant an instance is set to, not the value itself.
H I J K L
Example
M
using System; namespace Samples { public class EnumToString { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main() { for(DayOfWeek d = DayOfWeek.Sunday - 1, until = DayOfWeek.Saturday + 1; d <= until; d++) Console.WriteLine( "Value {0}.ToString(): {1}", d, d.ToString()); } } }
N O P Q R S T U V W X Y
The output is
Z
Value -1.ToString(): -1 Value Sunday.ToString(): Sunday Value Monday.ToString(): Monday
1539
Contents | Index
Enum
System
ToString() Method
Value Value Value Value Value Value
A B
Tuesday.ToString(): Tuesday Wednesday.ToString(): Wednesday Thursday.ToString(): Thursday Friday.ToString(): Friday Saturday.ToString(): Saturday 7.ToString(): 7
C
Enum.ToString(System.String) Method
D E
[ILASM] .method public hidebysig instance string ToString(string format) [C#] public string ToString(string format)
F G H
Summary
I
Converts the value of the current instance to its equivalent System.String representation using the specified format.
J K
Parameters
L M
Parameter
Description
format
A System.String that specifies the format to use when converting the current instance to a System.String. Specify one of the following values in upper- or lowercase: “G”, “D”, “X”, or “F”.
N O P Q
Description
R
If format is a null reference or an empty string, the return value is formatted using the general format specifier (“G”). [Note: For details on the format specifiers used with an enumeration object, see System.Enum.Format.]
S T U V
Exceptions
W X
Exception
Condition
System.FormatException
format contains an invalid value.
Y Z
1540
Contents | Index
System
Enum ToString() Method
Example using System; namespace Samples { public class EnumToString { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main() { string[] f = {"D", "F", "X", "G"}; DayOfWeek d = DayOfWeek.Saturday; foreach(string s in f) Console.WriteLine( "Value {0} formatted with {1}: {2}", d, s, d.ToString(s)); ++d; foreach(string s in f) Console.WriteLine( "Value {0} formatted with {1}: {2}", d, s, d.ToString(s)); } } }
A B C D E F G H I J K L M N
The output is
O Value Value Value Value Value Value Value Value
Saturday formatted with D: 6 Saturday formatted with F: Saturday Saturday formatted with X: 00000006 Saturday formatted with G: Saturday 7 formatted with D: 7 7 formatted with F: Monday, Saturday 7 formatted with X: 00000007 7 formatted with G: 7
P Q R S T U V
Enum.ToString(System.String, System.IFormatProvider) Method
W
[ILASM] .method public final hidebysig virtual string ToString(string format, class System.IFormatProvider provider) [C#] public string ToString(string format, IFormatProvider provider)
X Y Z
1541
Contents | Index
Enum
System
ToString() Method
Summary Converts the numeric value of the current instance to its equivalent System.String representation using the specified format. A
Parameters
B C
Parameter
Description
format
A System.String that specifies the format to use when converting the current instance to a System.String. Specify one of the following values in upper- or lowercase: “G”, “D”, “X”, or “F”.
provider
An object that implements the System.IFormatProvider interface or a null reference. The System.IFormatProvider is not used in the implementation of this method. [Note: There is no System.IFormatProvider that corresponds to a System.Enum object; therefore, provider is not utilized by this method, and any System.IFormatProvider may be passed as a parameter.]
D E F G H I J K
Description
L
If format is a null reference or an empty string, the return value is formatted using the general format specifier (“G”). [Note: For details on the format specifiers used with an enumeration object, see System.Enum.Format. This method is implemented to support the System.IFormattable interface.]
M N O P
Exceptions
Q R
Exception
Condition
System.FormatException
format does not contain a valid format specifier.
S T U
Example
V
using System; using System.Globalization; namespace Samples { public class EnumToString { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main()
W X Y Z
1542
Contents | Index
System
Enum ToString() Method
{ CultureInfo ci = new CultureInfo("en-AU"); string[] f = {"D", "F", "X", "G"}; DayOfWeek d = DayOfWeek.Saturday; foreach(string s in f) Console.WriteLine( "Value {0} formatted with {1}: {2}", d, s, d.ToString(s, ci)); d++; foreach(string s in f) Console.WriteLine( "Value {0} formatted with {1}: {2}", d, s, d.ToString(s, ci));
A B C D E F
}
G
}
H
}
I
The output is
J Value Value Value Value Value Value Value Value
Saturday formatted with D: 6 Saturday formatted with F: Saturday Saturday formatted with X: 00000006 Saturday formatted with G: Saturday 7 formatted with D: 7 7 formatted with F: Monday, Saturday 7 formatted with X: 00000007 7 formatted with G: 7
K L M N O P
Enum.ToString(System.IFormatProvider) Method
Q
[ILASM] .method public final hidebysig virtual string ToString(class System.IFormatProvider provider) [C#] public string ToString(IFormatProvider provider)
R S T U
Summary
V
Converts the name of the value of the current instance to its equivalent System.String representation.
W X Y Z
1543
Contents | Index
Enum
System
ToBoolean() Method
Parameters Parameter
Description
provider
An object that implements the System.IFormatProvider interface or a null reference. The System.IFormatProvider is not used in the implementation of this method. [Note: There is no System.IFormatProvider that corresponds to a System.Enum object; therefore, provider is not utilized by this method, and any System.IFormatProvider may be passed as a parameter.]
A B C D E F
Description
G
This method is equivalent to the version of System.Enum.ToString that takes no arguments.
H I
Example
J
using System; using System.Globalization; namespace Samples { public class EnumToString { enum DayOfWeek {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; public static void Main() { CultureInfo ci = new CultureInfo("en-AU"); DayOfWeek d = DayOfWeek.Saturday; Console.WriteLine("Value {0}.ToString(\"en-AU\"): {1}", d, d.ToString(ci)); } } }
K L M N O P Q R S T
The output is
U
Value Saturday.ToString("en-AU"): Saturday
V W X
IConvertible.ToBoolean(System.IFormatProvider) Method
Y
[ILASM]
.method private final hidebysig virtual bool System.IConvertible.ToBoolean(class System.IFormatProvider provider)
Z
[C#]
bool IConvertible.ToBoolean(IFormatProvider provider)
1544
Contents | Index
System
Enum ToDateTime() Method
Summary Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToBoolean.] A B
IConvertible.ToByte(System.IFormatProvider) Method
C
[ILASM]
D
.method private final hidebysig virtual unsigned int8 System.IConvertible.ToByte(class System.IFormatProvider provider)
E
[C#]
F
byte IConvertible.ToByte(IFormatProvider provider)
G
Summary
H
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToByte.]
I J K
IConvertible.ToChar(System.IFormatProvider) Method
L
[ILASM]
M
.method private final hidebysig virtual valuetype System.Char System.IConvertible.ToChar(class System.IFormatProvider provider)
N
[C#]
O
char IConvertible.ToChar(IFormatProvider provider)
P
Summary
Q
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToChar.]
R S T
IConvertible.ToDateTime(System.IFormatProvider) Method
U
[ILASM]
V
.method private final hidebysig virtual valuetype System.DateTime System.IConvertible.ToDateTime(class System.IFormatProvider provider)
W
[C#]
X
DateTime IConvertible.ToDateTime(IFormatProvider provider)
Y
Summary
Z
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDateTime.]
1545
Contents | Index
Enum
System
ToDecimal() Method
IConvertible.ToDecimal(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual decimal System.IConvertible.ToDecimal(class System.IFormatProvider provider)
B
[C#]
decimal IConvertible.ToDecimal(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDecimal.]
F G H
IConvertible.ToDouble(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual float64 System.IConvertible.ToDouble(class System.IFormatProvider provider)
K
[C#]
double IConvertible.ToDouble(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDouble.]
O P Q
IConvertible.ToInt16(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual int16 System.IConvertible.ToInt16(class System.IFormatProvider provider)
T
[C#]
short IConvertible.ToInt16(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt16.]
X Y Z
1546
Contents | Index
System
Enum ToSByte() Method
IConvertible.ToInt32(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual int32 System.IConvertible.ToInt32(class System.IFormatProvider provider)
A
[C#]
B
int IConvertible.ToInt32(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt32.]
E F G
IConvertible.ToInt64(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual int64 System.IConvertible.ToInt64(class System.IFormatProvider provider)
J
[C#]
K
long IConvertible.ToInt64(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt64.]
N O P
IConvertible.ToSByte(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual int8 System.IConvertible.ToSByte(class System.IFormatProvider provider)
S
[C#]
T
sbyte IConvertible.ToSByte(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSByte.]
W X Y Z
1547
Contents | Index
Enum
System
ToSingle() Method
IConvertible.ToSingle(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual float32 System.IConvertible.ToSingle(class System.IFormatProvider provider)
B
[C#]
float IConvertible.ToSingle(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSingle.]
F G H
IConvertible.ToType(System.Type, System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual object System.IConvertible.ToType(class System.Type type, class System.IFormatProvider provider)
K
[C#]
object IConvertible.ToType(Type type, IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToType.]
O P Q
IConvertible.ToUInt16(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual unsigned int16 System.IConvertible.ToUInt16(class System.IFormatProvider provider)
T
[C#]
ushort IConvertible.ToUInt16(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt16.] This member is not CLS-compliant.
X Y Z
1548
Contents | Index
System
Enum ToUInt64() Method
IConvertible.ToUInt32(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual unsigned int32 System.IConvertible.ToUInt32(class System.IFormatProvider provider)
A
[C#]
B
uint IConvertible.ToUInt32(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt32.] This member is not CLS-compliant.
E F G
IConvertible.ToUInt64(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual unsigned int64 System.IConvertible.ToUInt64(class System.IFormatProvider provider)
J
[C#]
K
ulong IConvertible.ToUInt64(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt64.] This member is not CLS-compliant.
N O P Q R S T U V W X Y Z
1549
Contents | Index
System Environment
BCL
Object
A
Environment
B
Summary
C
Provides the current settings for, and information about, the execution environment.
D E
Type Summary public sealed class Environment { // Properties CF public static string CommandLine { get; } MS CF public static string CurrentDirectory { set; get; } CF public static int ExitCode { set; get; } CF 1.1 public static bool HasShutdownStarted { get; } MS CF public static string MachineName { get; } CF public static string NewLine { get; } MS public static OperatingSystem OSVersion { get; } CF public static string StackTrace { get; } MS CF public static string SystemDirectory { get; } public static int TickCount { get; } MS CF public static string UserDomainName { get; } MS CF public static bool UserInteractive { get; } MS CF public static string UserName { get; } public static Version Version { get; } MS CF public static long WorkingSet { get; }
F G H I J K L M N O P Q
// CF MS CF CF CF CF MS CF MS CF }
R S T U V
Methods public static public static public static public static public static public static public static
void Exit (int exitCode); string ExpandEnvironmentVariables (string name); string[] GetCommandLineArgs (); string GetEnvironmentVariable (string variable); IDictionary GetEnvironmentVariables (); string GetFolderPath (Environment.SpecialFolder folder); string[] GetLogicalDrives ();
W X Y Z
1550
Contents | Index
System
Environment Environment Class
BA One could argue that the NewLine member should have been a literal field rather than a property. The reason we did not use a literal field is because the value of NewLine changes from platform to platform. Literal values are burned into the call site so an application built for one platform would end up with the wrong value for NewLine when run on a different platform.
A B C
BG This class is a great example of what I would call a “static class,” referring to a
D
design pattern more than any language keyword. The class isn’t instantiable (i.e., it has a private default constructor), is sealed, and all the members have to be static. Console is another example of a static class. However in the V1 implementation of the Microsoft CLI, I messed up and accidentally added a property to this class that wasn’t static (HasShutdownStarted). Since it was an instance method on a class that could never be instantiated, no one could call it. We didn’t discover the problem early enough in the product cycle to fix it before releasing V1.0.
E F G H I J
If I were inventing a new language, I would explicitly add the concept of a static class into the language to help people avoid falling into this trap.
K L
Example
M
using System; using System.Collections; namespace Samples { public class EnvironmentSample { public static void Main() { Console.WriteLine("Command line: {0}", Environment.CommandLine); Console.WriteLine("CLR Version: {0}", Environment.Version); string[] a = Environment.GetCommandLineArgs(); foreach(string s in a) Console.WriteLine("Command Line Argument: {0}", s); IDictionary d = Environment.GetEnvironmentVariables(); IDictionaryEnumerator e = d.GetEnumerator(); while(e.MoveNext()) Console.WriteLine("Key: {0} Value: {1}", e.Key, e.Value); } } }
N O P Q R S T U V W X Y Z
1551
Contents | Index
Environment
System
CommandLine Property
The output is Command line: Environment CLR Version: 1.0.3705.288 Command Line Argument: Environment Key: SystemDrive Value: C: Key: USERPROFILE Value: C:\Documents and Settings\damien Key: INCLUDE Value: C:\Program Files\Microsoft Visual Studio .NET\VC7\ATLMFC\INCLUDE;C:\Program Files\Microsoft Visual Studio .NET\VC7\INCLUDE;C:\Program Files\Microsoft Visual Studio .NET\VC7\PlatformSDK\include\prerelease;C:\Program Files\Microsoft Visual Studio .NET\VC7\PlatformSDK\include;C:\Program Files\Microsoft Visual Studio .NET\FrameworkSDK\include;C:\Program Files\Microsoft Visual Studio .NET\FrameworkSDK\include\ ... Key: HOMEPATH Value: \Documents and Settings\damien Key: PROMPT Value: $P$G Key: TEMP Value: C:\DOCUME~1\damien\LOCALS~1\Temp Key: LIB Value: C:\Program Files\Microsoft Visual Studio .NET\VC7\ATLMFC\LIB;C:\Program Files\Microsoft Visual Studio .NET\VC7\LIB;C:\Program Files\Microsoft Visual Studio .NET\VC7\PlatformSDK\lib\prerelease;C:\Program Files\Microsoft Visual Studio .NET\VC7\PlatformSDK\lib;C:\Program Files\Microsoft Visual Studio .NET\FrameworkSDK\lib;C:\Program Files\Microsoft Visual Studio .NET\FrameworkSDK\Lib\ Key: PROCESSOR_REVISION Value: 080a Key: SESSIONNAME Value: Console
A B C D E F G H I J K L M N O P Q
Environment.CommandLine Property
R
[ILASM] .property string CommandLine { public hidebysig static specialname string get_CommandLine() } [C#] public static string CommandLine { get; }
S T U V
Summary
W
Gets the information entered on the command line when the current process was started.
X
Description
Y
This property provides access to the program name and any arguments specified on the command line when the current process was started. If the environment does not support a program name, as may be the case with compact devices, then the program name is equal to System.String.Empty.
Z
1552
Contents | Index
System
Environment CurrentDirectory Property
The format of the information returned by this property is implementation-defined. [Note: The program name may, but is not required to, include path information. Use the System.Environment.GetCommandLineArgs method to retrieve the command line information parsed and stored in an array of strings.]
A B
Example
C
using System; namespace Samples { public class EnvironmentCommandLine { public static void Main() { string s = Environment.CommandLine; if(s.IndexOf("/u") != -1) s = s.ToUpper(); Console.WriteLine(s); } } }
D E F G H I J K L
The output is
M
Environment
N O P
Environment.CurrentDirectory Property
Q
[ILASM] .property string CurrentDirectory { public hidebysig static specialname string get_CurrentDirectory() public hidebysig static specialname void set_CurrentDirectory(string value) } [C#] public static string CurrentDirectory { get; set; }
R S T U
Summary
V
Gets and sets the fully qualified path of the current directory, that is, the directory from which this process starts.
W X
Description
Y
By definition, if this process starts in the root directory of a local or network drive, the value of this property is the drive name followed by a trailing slash (for example, “C:\”). If
Z
1553
Contents | Index
Environment
System
ExitCode Property
this process starts in a subdirectory, the value of this property is the drive and subdirectory path, without a trailing slash (for example, “C:\mySubDirectory”). A
Exceptions
B C D E
Exception
Condition
System.ArgumentException
Attempted to set to an empty string (“ ”).
System.ArgumentNullException
Attempted to set to null.
System.IO.IOException
An I/O error occurred.
System.IO.FileNotFoundException
Attempted to set a local path that cannot be found.
System.IO.DirectoryNotFoundException
Attempted to set a universal naming convention (UNC) path that cannot be found.
System.Security.SecurityException
The caller does not have the appropriate permission.
F G H I J K L M N
Permissions
O P Q R
Permission
Description
System.Security.Permissions.FileIOPermission
For writing to files or directories. Associated enumeration: System.Security.Permissions.FileIOPermissionAccess.Write.
System.Security.Permissions.FileIOPermission
For access to path information for the current directory. Associated enumeration: System.Security.Permissions.FileIOPermissionAccess.PathDiscovery.
S T U V W
Environment.ExitCode Property
X
[ILASM] .property int32 ExitCode { public hidebysig static specialname int32 get_ExitCode() public hidebysig static specialname void set_ExitCode(int32 value) } [C#] public static int ExitCode { get; set; }
Y Z
1554
Contents | Index
System
Environment HasShutdownStarted Property
Summary Gets or sets the exit code of a process.
Property Value
A
A System.Int32 value returned by a process. The default value is zero.
B C
Description
D
When a process exits, if the process does not return a value, the value of System.Environment.ExitCode is returned. If the value of this property is not set by an application, zero is returned. On operating systems that do not support process exit codes, CLI implementations are required to fully support getting and setting values for this property.
E F G H
Example
I
using System; namespace Samples { public class EnvironmentExitCode { public static void Main() { Console.WriteLine("Default exit code value: {0}", Environment.ExitCode); Environment.ExitCode = 42; return; } } }
J K L M N O P Q R S
The output is
T
Default exit code value: 0
U V
Environment.HasShutdownStarted Property
W
[ILASM] .property bool HasShutdownStarted { public hidebysig static specialname instance bool get_HasShutdownStarted() } [C#] public static bool HasShutdownStarted { get; }
X Y Z
1555
Contents | Index
Environment
System
MachineName Property
Summary Gets a value indicating whether an application has started to shut down. A
Property Value
B
A System.Boolean where true indicates the shutdown process has started; otherwise false.
C D
Description
E
[Note: This property is for use inside the finalizer of an application. If the shutdown process has started, static members should not be accessed; they may have been cleaned up by the garbage collector. If the member has been cleaned up, any access attempt will cause an exception to be thrown. System.Console.Out is a special case that is always available after the shutdown process has started.]
F G H I J
Environment.MachineName Property
K [ILASM] .property string MachineName { public hidebysig static specialname string get_MachineName() } [C#] public static string MachineName { get; }
L M N O
Summary
P
Gets the NetBIOS name of this local computer.
Q R
Description
S
The name of this computer is established at system startup when the name is read from the registry. If this computer is a node in a cluster, the name of the node is returned.
T U
Exceptions
V W X
Exception
Condition
System.InvalidOperationException
The name of this computer cannot be obtained.
Y Z
1556
Contents | Index
System
Environment NewLine Property
Permissions Permission
Description
System.Security.Permissions.EnvironmentPermission
For full access to the resource protected by this permission. Associated enumeration: System.Security.Permissions.PermissionState.Unrestricted.
A B C D E
Environment.NewLine Property
F [ILASM] .property string NewLine { public hidebysig static specialname string get_NewLine() } [C#] public static string NewLine { get; }
G H I J
Summary
K
Gets the newline string for the current platform.
L
Description
M
[Note: This property is intended for platform-independent formatting of multi-line strings. This value is automatically appended to text when using WriteLine methods, such as System.Console.WriteLine.]
N O P
Example
Q
using System; namespace Samples { public class EnvironmentNewLine { public static void Main() { Console.Write("Hello "); Console.Write(Environment.NewLine); Console.Write("world!"); } } }
R S T U V W X Y
The output is
Z
Hello world!
1557
Contents | Index
Environment
System
OSVersion Property
Environment.OSVersion Property [ILASM]
A
.property class System.OperatingSystem OSVersion { public hidebysig static specialname class System.OperatingSystem get_OSVersion() }
B
[C#]
public static OperatingSystem OSVersion { get; }
C D
Summary
E
Gets a System.OperatingSystem object that contains the current platform identifier and version number.
F
Exceptions
G H
Exception
Condition
I
This property was unable to obtain the system version.
J System.ExecutionEngineException
K
-orThe platform identifier is not a member of System.PlatformID.
L M N
Environment.StackTrace Property
O [ILASM] .property string StackTrace { public hidebysig static specialname string get_StackTrace() } [C#] public static string StackTrace { get; }
P Q R S
Summary
T
Returns a string representation of the state of the call stack.
U V
Property Value
W
A System.String containing a description of the methods currently in the call stack. This value can be System.String.Empty.
X Y
Description
Z
[Note: An example of how the System.String returned by this property might be formatted follows, where one line of information is provided for each method on the call stack: at FullClassName.MethodName(MethodParms) in FileName:line
1558
Contents | Index
System
Environment SystemDirectory Property
LineNumberFullClassName, MethodName, MethodParms, FileName, and LineNumber are defined as follows: The literal “at” is preceded by a single space. The literals “in” and “:line” are omitted if debug symbols are not available. The method calls are described in reverse chronological order (the most recent method call is described first). System.Environment.StackTrace may not report as many method calls as expected, due to code transformations that occur during optimization.]
A B C
Example
D
using System; namespace Samples { public class EnvironmentStackTrace { public static void Main() { Console.Write(Environment.StackTrace); } } }
E F G H I J K L
The output is
M
at System.Environment.GetStackTrace(Exception e) at System.Environment.GetStackTrace(Exception e) at System.Environment.get_StackTrace() at Samples.EnvironmentStackTrace.Main() in C:\Books\BCL\Samples\System\ Environment\StackTrace\Environment.cs:line 9
N O P Q
Environment.SystemDirectory Property
R
[ILASM] .property string SystemDirectory { public hidebysig static specialname string get_SystemDirectory() } [C#] public static string SystemDirectory { get; }
S T U V
Summary
W
Gets the fully qualified path of the system directory.
X Y
Description
Z
An example of the value returned is the string “C:\WinNT\System32”.
1559
Contents | Index
Environment
System
TickCount Property
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
For permission to read from a file or directory. Associated enumeration: System.Security.Permissions.FileIOPermissionAccess.Read.
A B C D E
Environment.TickCount Property
F
[ILASM] .property int32 TickCount { public hidebysig static specialname int32 get_TickCount() } [C#] public static int TickCount { get; }
G H I J
Summary
K
Gets the number of milliseconds elapsed since the system was started.
L M
Description
N
The resolution of the System.Environment.TickCount property cannot be less than 500 milliseconds. The value of this property is derived from the system timer. The System.Environment.TickCount property handles an overflow condition by resetting its value to 0. The minimum value returned by System.Environment.TickCount is 0. [Note: System.Environment.TickCount is measured in milliseconds, not in “ticks”. The System.Environment.TickCount reaches its maximum value after approximately 24.8 days of continuous up time. For applications that require a finer granularity or a larger maximum time than System.Environment.TickCount supports, see System.DateTime.Now.]
O P Q R S T U V W X Y Z
1560
Contents | Index
System
Environment UserDomainName Property
Example using System; using System.Threading; namespace Samples { public class EnvironmentTickCount { public static void Main() { Console.WriteLine("Start: {0}", Environment.TickCount); Thread.Sleep(1000); Console.WriteLine("Finish: {0}", Environment.TickCount); } } }
A B C D E F G H
The output is
I
Start: 16285837 Finish: 16286839
J K L
Environment.UserDomainName Property
M
[ILASM] .property string UserDomainName { public hidebysig static specialname string get_UserDomainName() } [C#] public static string UserDomainName { get; }
N O P Q
Summary
R
Gets the network domain name associated with the current user.
S T
Description
U
The value of this property is typically the host computer name, but can depend upon the application solution being deployed. The current user is the name specified in System.Environment.UserName.
V W X Y Z
1561
Contents | Index
Environment
System
UserInteractive Property
Exceptions Exception
Condition
System.PlatformNotSupportedException
The current operating system does not support retrieving the network domain name.
System.InvalidOperationException
The network domain name cannot be retrieved.
A B C D E
Permissions
F G
Permission
Description
System.Security.Permissions.EnvironmentPermission
For reading an environment variable. Associated enumeration: System.Security.Permissions.EnvironmentPermissionAccess.Read.
H I J K L
Environment.UserInteractive Property
M
[ILASM] .property bool UserInteractive { public hidebysig static specialname bool get_UserInteractive() } [C#] public static bool UserInteractive { get; }
N O P Q
Summary
R
Gets a value indicating whether the current process is running in user interactive mode.
S T
Property Value
U
true if the current process is running in user interactive mode; otherwise, false.
V
Description
W
This will be false only when running as a service process or from inside a Web application. When this property is false, you should not display any modal dialogs or message boxes, because there is no graphical user interface for the user to interact with.
X Y Z
1562
Contents | Index
System
Environment Version Property
Environment.UserName Property [ILASM] .property string UserName { public hidebysig static specialname string get_UserName() } [C#] public static string UserName { get; }
A B C
Summary
D
Gets the user name of the person who started the current thread.
E F
Description
G
This property can be used to identify the current user to the system and application for security or access purposes. It can also be used to customize a particular application for each user.
H I J
Permissions
K
Permission
Description
System.Security.Permissions.EnvironmentPermission
For the ability to obtain the user name. Associated enumeration: System.Security.Permissions.EnvironmentPermissionAccess.Read.
L M N O P Q
Environment.Version Property
R
[ILASM] .property class System.Version Version { public hidebysig static specialname class System.Version get_Version() } [C#] public static Version Version { get; }
S T U
Summary
V
Gets the current version of the execution engine.
W X
Property Value
Y
A System.Version object that contains the major, minor, build, and revision numbers of the execution engine.
Z
1563
Contents | Index
Environment
System
WorkingSet Property
Example using System; namespace Samples { public class EnvironmentVersion { public static void Main() { Console.WriteLine("You are running Version: {0} of the CLR", Environment.Version); } } }
A B C D E F G
The output is
H
You are running Version: 1.0.3705.288 of the CLR
I J
Environment.WorkingSet Property
K [ILASM] .property int64 WorkingSet { public hidebysig static specialname int64 get_WorkingSet() } [C#] public static long WorkingSet { get; }
L M N O
Summary
P
Gets the amount of physical memory mapped to the process context.
Q
Permissions
R S T U V
Permission
Description
System.Security.Permissions.EnvironmentPermission
For full access to the resource protected by this permission. Associated enumeration: System.Security.Permissions.PermissionState.Unrestricted.
W X
Environment.Exit(System.Int32) Method
Y
[ILASM] .method public hidebysig static void Exit(int32 exitCode) [C#] public static void Exit(int exitCode)
Z
1564
Contents | Index
System
Environment Exit() Method
Summary Terminates the current process and sets the process exit code to the specified value. A
Parameters
B
Parameter
Description
exitCode
A System.Int32 value that is provided to the operating system.
C D E
Description
F
This method causes an executing program to halt.
G H
Exceptions
I
Exception
Condition
System.Security.SecurityException
The immediate caller does not have the required permission.
J K L M
Permissions
N
Permission
Description
System.Security.Permissions.EnvironmentPermission
Requires permission to read environment variables. See System.Security.Permissions.EnvironmentPermissionAccess.Read.
O P Q R S
Example
T
using System; namespace Samples { public class EnvironmentExit { public static void Main() { Console.WriteLine("Do we print this?"); Environment.Exit(0); Console.WriteLine("And this?"); } } }
U V W X Y Z
1565
Contents | Index
Environment
System
ExpandEnvironmentVariables() Method
The output is Do we print this?
A B
Environment.ExpandEnvironmentVariables(System.String) Method
C [ILASM] .method public hidebysig static string ExpandEnvironmentVariables(string name) [C#] public static string ExpandEnvironmentVariables(string name)
D E F G
Summary
H
Replaces the name of each environment variable embedded in the specified string with the string equivalent of the value of the variable, then returns the resulting string.
I
Parameters
J K L M
Parameter
Description
name
A string containing the names of zero or more environment variables. Each environment variable is quoted with the percent sign character (%).
N O
Description
P
COM interop is used to retrieve the environment variables from the operating system. If the environment variables cannot be retrieved due to a COM error, the HRESULT that explains the cause of the failure is used to generate one of several possible exceptions; that is, the exception depends on the HRESULT. For more information about how the HRESULT is processed, see the Remarks section of the System.Runtime.InteropServices.Marshal.ThrowExceptionForHR method. Replacement only occurs for environment variables that are set. For example, suppose name is “MyENV = %MyENV%”. If the environment variable, MyENV, is set to 42, this method returns “MyENV = 42”. If MyENV is not set, no change occurs; this method returns “MyENV = %MyENV%”. The size of the return value is limited to 32K on Windows NT 4.0 and earlier, and Windows 2000 and later. There is no size restriction on Windows 98 and Windows Me.
Q R S T U V W X Y Z
1566
Contents | Index
System
Environment GetCommandLineArgs() Method
Exceptions Exception
Condition
System.ArgumentNullException
name is null.
A B C
Permissions
D E
Permission
Description F
System.Security.Permissions.EnvironmentPermission
For the ability to access the environment variables in name. Associated enumeration: System.Security.Permissions.PermissionState.Unrestricted.
G H I J
Environment.GetCommandLineArgs() Method
K
[ILASM] .method public hidebysig static class System.String[] GetCommandLineArgs() [C#] public static string[] GetCommandLineArgs()
L M N
Summary
O
Returns the arguments specified on the command line.
P Q
Return Value
R
Returns a System.String array. Each System.String in the array contains a single command line argument.
S T
Description
U
The first element in the array contains the filename of the executing program. If the filename is not available, the first element is equal to System.String.Empty. The remaining elements contain any additional tokens entered on the command line. [Note: The program filename may, but is not required to, include path information. To obtain the command line as a single System.String, use the System.Environment.CommandLine property.]
V W X Y Z
1567
Contents | Index
Environment
System
GetEnvironmentVariable() Method
Example using System; namespace Samples { public class EnvironmentGetCommandLineArgs { public static void Main() { string[] strings = Environment.GetCommandLineArgs(); foreach(string s in strings) Console.WriteLine(s); } } }
A B C D E F G H
The output is
I Environment
J K
Environment.GetEnvironmentVariable(System.String) Method
L
[ILASM] .method public hidebysig static string GetEnvironmentVariable(string variable) [C#] public static string GetEnvironmentVariable(string variable)
M N O P
Summary
Q
Returns the value of the specified environment variable.
R
Parameters
S T
Parameter
Description
variable
A System.String containing the name of an environment variable.
U V W
Return Value
X
A System.String containing the current setting of variable, or null.
Y Z
1568
Contents | Index
System
Environment GetEnvironmentVariable() Method
Description If variable contains a valid name for an environment variable, and if the caller has sufficient permissions, this method returns the current setting for variable. Environment variable names are case-insensitive. If variable specifies an invalid name or the system does not support environment variables, this method returns null. [Note: To obtain names and settings for all environment variables, use the System.Environment.GetEnvironmentVariables method.]
A B C D E
Exceptions Exception
F G
Condition
H System.ArgumentNullException
variable is a null reference.
System.Security.SecurityException
The caller does not have the required permission.
I J K L
Permissions
M N
Permission
Description
System.Security.Permissions.EnvironmentPermission
Requires permission to read environment variables. See System.Security.Permissions.EnvironmentPermissionAccess.Read.
O P Q R
Example
S
using System; namespace Samples { public class EnvironmentGetEnvironmentVariable { public static void Main() { string[] strings = {"COMPUTERNAME", "LOGONSERVER", "SystemDrive", "SystemRoot", "TEMP", "USERDOMAIN", "USERNAME", "USERPROFILE"}; foreach(string s in strings) {
T U V W X Y Z
1569
Contents | Index
Environment
System
GetEnvironmentVariables() Method
Console.WriteLine("Variable: {0} Value: {1}", s, Environment.GetEnvironmentVariable(s)); } }
A
} }
B C
The output is
D Variable: Variable: Variable: Variable: Variable: Variable: Variable: Variable:
E F G H I
COMPUTERNAME Value: PROJECT42 LOGONSERVER Value: \\PROJECT42 SystemDrive Value: C: SystemRoot Value: C:\WINDOWS TEMP Value: C:\DOCUME~1\damien\LOCALS~1\Temp USERDOMAIN Value: PROJECT42 USERNAME Value: damien USERPROFILE Value: C:\Documents and Settings\damien
J K
Environment.GetEnvironmentVariables() Method
L
[ILASM] .method public hidebysig static class System.Collections.IDictionary GetEnvironmentVariables() [C#] public static IDictionary GetEnvironmentVariables()
M N O P
Summary
Q
Returns all environment variables and their current settings.
R
Return Value
S
A System.Collections.IDictionary object containing environment variable names and settings, or null if the system does not support environment variables.
T U
Description
V
The names and settings for the environment variables are stored in the returned System.Collections.IDictionary object as keys and values, respectively. [Note: To obtain the setting of a single environment variable, use the System.Environment.GetEnvironmentVariable method.]
W X Y Z
1570
Contents | Index
System
Environment GetEnvironmentVariables() Method
Exceptions Exception
Condition A
System.Security.SecurityException
B
The caller does not have the required permission.
C D
Permissions
E
Permission
Description
System.Security.Permissions.EnvironmentPermission
Requires permission to read environment variables. See System.Security.Permissions.EnvironmentPermissionAccess.Read.
F G H I J
Example
K
using System; using System.Collections; namespace Samples { public class EnvironmentGetEnvironmentVariables { public static void Main() { IDictionary d = Environment.GetEnvironmentVariables(); IDictionaryEnumerator e = d.GetEnumerator(); foreach(DictionaryEntry de in d) Console.WriteLine("Key: {0} Value: {1}", de.Key, de.Value); } } }
L M N O P Q R S T U
The output is Key: Key: ... Key: Key: Key: Key: Key: Key:
V
SystemDrive Value: C: USERPROFILE Value: C:\Documents and Settings\damien
W X
HOMEDRIVE Value: C: COMPUTERNAME Value: PROJECT42 USERDOMAIN Value: PROJECT42 VSINSTALLDIR Value: C:\Program Files\Microsoft Visual Studio .NET\Common7\IDE PROCESSOR_LEVEL Value: 6 OS Value: Windows_NT
Y Z
1571
Contents | Index
Environment
System
GetFolderPath() Method
Key: VSCOMNTOOLS Value: "C:\Program Files\Microsoft Visual Studio .NET\Common7\Tools\" Key: PROCESSOR_IDENTIFIER Value: x86 Family 6 Model 8 Stepping 10, GenuineIntel Key: windir Value: C:\WINDOWS Key: FrameworkVersion Value: v1.0.3705 Key: ALLUSERSPROFILE Value: C:\Documents and Settings\All Users Key: USERNAME Value: damien Key: ProgramFiles Value: C:\Program Files ... Key: SESSIONNAME Value: Console
A B C D E F
Environment.GetFolderPath(System.Environment+SpecialFolder) Method
G [ILASM] .method public hidebysig static string GetFolderPath(valuetype System.Environment+SpecialFolder folder) [C#] public static string GetFolderPath(SpecialFolder folder)
H I J K
Summary
L
Gets the path to the system special folder identified by the specified enumeration.
M
Parameters
N O
Parameter
Description
folder
An enumerated constant that identifies a system special folder.
P Q R
Return Value
S
The path to the specified system special folder, if that folder physically exists on your computer; otherwise, the empty string (“ “). A folder will not physically exist if the operating system did not create it, the existing folder was deleted, or the folder is a virtual directory, such as My Computer, which does not correspond to a physical path.
T U V W
Description
X
This method retrieves the path to a system special folder, such as Program Files, Programs, System, or Startup, which can be used to access common information. Special folders are set by default by the system, or explicitly by the user, when installing a version of Windows. The folder parameter designates the special folder to retrieve and must be one of the values in the Environment.SpecialFolder enumeration; any other value throws an exception.
Y Z
1572
Contents | Index
System
Environment GetLogicalDrives() Method
Exceptions Exception
Condition
System.ArgumentException
folder is not a member of System.Environment.SpecialFolder.
A B C D
Environment.GetLogicalDrives() Method
E F
[ILASM] .method public hidebysig static class System.String[] GetLogicalDrives() [C#] public static string[] GetLogicalDrives()
G H I
Summary
J
Returns an array of string containing the names of the logical drives on the current computer.
K
Return Value
L
An array of string where each element contains the name of a logical drive. For example, if the computer’s hard drive is the first logical drive, the first element returned is “C:\”.
M
Exceptions
O
N
P
Exception
Condition
System.IO.IOException
An I/O error occurs.
System.Security.SecurityException
The caller does not have the required permissions.
Q R S T U
Permissions
V W
Permission
Description
System.Security.Permissions.EnvironmentPermission
For full access to the resource protected by this permission. Associated enumeration: System.Security.Permissions.PermissionState.Unrestricted.
X Y Z
1573
Contents | Index
System.Security.Permissions EnvironmentPermission
BCL
ISecurityEncodable
A
IStackWalk
Object
B
CodeAccessPermission
C
EnvironmentPermission
NotStandardized
NotStandardized
IPermission IUnrestrictedPermission
NotStandardized
D
Summary
E
Controls access to environment variables.
F
Type Summary
G
CF public sealed class EnvironmentPermission : CodeAccessPermission, IUnrestrictedPermission { // Constructors CF public EnvironmentPermission(PermissionState state) CF public EnvironmentPermission(EnvironmentPermissionAccess flag, string pathList)
H I J K L
// Methods MS CF public void AddPathList (EnvironmentPermissionAccess flag, string pathList); CF public override IPermission Copy (); CF public override void FromXml (SecurityElement esd); MS CF public string GetPathList (EnvironmentPermissionAccess flag); CF public override IPermission Intersect (IPermission target); CF public override bool IsSubsetOf (IPermission target); MS CF public bool IsUnrestricted (); MS CF public void SetPathList (EnvironmentPermissionAccess flag, string pathList); CF public override SecurityElement ToXml (); CF public override IPermission Union (IPermission other); }
M N O P Q R S T U
Description
V
[Note: System.Security.Permissions.EnvironmentPermission objects describe protected operations on environment variables. This permission distinguishes between the following types of access provided by System.Security.Permissions.EnvironmentPermissionAccess: These access levels are independent, meaning that rights to one do not imply rights to another. For example, Write permission does not imply permission to Read. System.Security.Permissions. EnvironmentPermissionAccess values can be combined using a bitwise OR operator. The System.Environment class is used to access environment variables, subject to the permissions defined by
W X Y Z
1574
Contents | Index
System.Security.Permissions
EnvironmentPermission EnvironmentPermission Class
System.Security.Permissions.EnvironmentPermission. Environment variables are case-insensitive.] The XML encoding of a System.Security.Permissions.EnvironmentPermission instance is defined below in EBNF format. The following conventions are used: • • •
• • •
A B
All non-literals in the grammar below are shown in normal type. All literals are in bold font. The following meta-language symbols are used: – ’*’ represents a meta-language symbol suffixing an expression that can appear zero or more times. – ’?’ represents a meta-language symbol suffixing an expression that can appear zero or one time. – ’+’ represents a meta-language symbol suffixing an expression that can appear one or more times. – ’(’,’)’ is used to group literals, non-literals, or a mixture of literals and non-literals. – ’|’ denotes an exclusive disjunction between two expressions. – ’::=’ denotes a production rule where a left-hand non-literal is replaced by a righthand expression containing literals, non-literals, or both. BuildVersion refers to the build version of the shipping CLI. This is specified as a dotted build number such as ’2412.0’. ECMAPubKeyToken ::= b77a5c561934e089 EnvironmentVariable refers to the name of a single environment variable, such as ’PROMPT’.
C D E F G H I J K L M N O P
The XML encoding of an EnvironmentPermission instance is as follows:
Q
EnvironmentPermissionXML ::=
R S T U V W X Y Z
1575
Contents | Index
EnvironmentPermission
System.Security.Permissions
EnvironmentPermission Class
Example using System; using System.Security; using System.Security.Permissions; namespace Samples { public class EnvironmentPermissionSample { public static void Main() { string ev = "USERNAME"; EnvironmentPermission p = new EnvironmentPermission( EnvironmentPermissionAccess.Read, ev); p.Assert(); TestAccess(ev); CodeAccessPermission.RevertAssert(); p.Deny(); TestAccess(ev); CodeAccessPermission.RevertDeny(); p.PermitOnly(); TestAccess(ev); TestAccess("TEMP"); CodeAccessPermission.RevertPermitOnly(); } public static void TestAccess(string s) { try { Console.WriteLine("Variable {0} Value: {1}", s, Environment.GetEnvironmentVariable(s)); } catch(Exception) { Console.WriteLine("Variable {0} cannot be read", s); } } } }
A B C D E F G H I J K L M N O P Q R S T U V W X
The output is
Y Z
Variable Variable Variable Variable
USERNAME Value: damien USERNAME cannot be read USERNAME Value: damien TEMP cannot be read
1576
Contents | Index
System.Security.Permissions
EnvironmentPermission EnvironmentPermission() Constructor
EnvironmentPermission(System.Security.Permissions.PermissionState) Constructor [ILASM] public rtspecialname specialname instance void .ctor(valuetype System.Security.Permissions.PermissionState state) [C#] public EnvironmentPermission(PermissionState state)
A B C D
Summary
E
Constructs and initializes a new instance of the System.Security.Permissions.EnvironmentPermission class with the specified System.Security.Permissions.PermissionState value.
F G H
Parameters
I J
Parameter
Description
state
A System.Security.Permissions.PermissionState value.
K L M
Description
N
[Note: The instance returned by this constructor has either fully restricted (System.Security.Permissions.PermissionState.None) or unrestricted (System.Security.Permissions.PermissionState.Unrestricted) access to all environment variables.]
O P Q R
Exceptions
S
Exception
Condition
System.ArgumentException
state is not a valid System.Security.Permissions.PermissionState value.
T U V W X Y Z
1577
Contents | Index
EnvironmentPermission
System.Security.Permissions
EnvironmentPermission() Constructor
Example using System; using System.Security; using System.Security.Permissions; namespace Samples { public class EnvironmentPermissionConstructor { public static void Main() { string ev = "COMPUTERNAME"; EnvironmentPermission p = new EnvironmentPermission( PermissionState.Unrestricted); p.SetPathList(EnvironmentPermissionAccess.AllAccess, ev); p.Assert(); TestAccess(ev); CodeAccessPermission.RevertAssert(); p.Deny(); TestAccess(ev); CodeAccessPermission.RevertDeny(); p.PermitOnly(); TestAccess(ev); TestAccess("TEMP"); CodeAccessPermission.RevertPermitOnly(); } public static void TestAccess(string s) { try { Console.WriteLine( "Environment Variable {0} Value: {1}", s, Environment.GetEnvironmentVariable(s)); } catch(Exception) { Console.WriteLine( "Environment Variable {0} cannnot be read", s); } } } }
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1578
Contents | Index
System.Security.Permissions
EnvironmentPermission EnvironmentPermission() Constructor
The output is Environment Environment Environment Environment
Variable Variable Variable Variable
COMPUTERNAME COMPUTERNAME COMPUTERNAME TEMP cannnot
Value: PROJECT42 cannnot be read Value: PROJECT42 be read
A B C
EnvironmentPermission(System.Security.Permissions. EnvironmentPermissionAccess, System.String) Constructor
D
[ILASM] public rtspecialname specialname instance void .ctor(valuetype System.Security.Permissions.EnvironmentPermissionAccess flag, string pathList) [C#] public EnvironmentPermission(EnvironmentPermissionAccess flag, string pathList)
F
E
G H I
Summary
J
Constructs a new instance of the System.Security.Permissions.EnvironmentPermission class with the specified access to the specified environment variables.
K
Parameters
M
L
N
Parameter
Description
O
flag
One of values defined by System.Security.Permissions.EnvironmentPermissionAccess.
P
pathList
Q
A System.String containing one or more case-insensitive environment variable names separated by System.IO.Path.PathSeparator.
R S T
Exceptions
U
Exception
Condition
System.ArgumentNullException
pathList is null.
System.ArgumentException
flag specifies a value not defined in System.Security.Permissions.EnvironmentPermissionAccess.
V W X Y Z
1579
Contents | Index
EnvironmentPermission
System.Security.Permissions
EnvironmentPermission() Constructor
Example using System; using System.Security; using System.Security.Permissions; namespace Samples { public class EnvironmentPermissionConstructor { public static void Main() { string ev = "USERNAME"; EnvironmentPermission p = new EnvironmentPermission( EnvironmentPermissionAccess.Read, ev); p.Assert(); TestAccess(ev); CodeAccessPermission.RevertAssert(); p.Deny(); TestAccess(ev); CodeAccessPermission.RevertDeny(); p.PermitOnly(); TestAccess(ev); TestAccess("TEMP"); CodeAccessPermission.RevertPermitOnly(); } public static void TestAccess(string s) { try { Console.WriteLine( "Environment Variable {0} Value: {1}", s, Environment.GetEnvironmentVariable(s)); } catch(Exception) { Console.WriteLine( "Environment Variable {0} cannnot be read", s); } } } }
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1580
Contents | Index
System.Security.Permissions
EnvironmentPermission AddPathList() Method
The output is Environment Environment Environment Environment
Variable Variable Variable Variable
USERNAME Value: damien USERNAME cannnot be read USERNAME Value: damien TEMP cannnot be read
A B C
EnvironmentPermission.AddPathList(System.Security.Permissions. EnvironmentPermissionAccess, System.String) Method
D
[ILASM] .method public hidebysig instance void AddPathList(valuetype System.Security.Permissions.EnvironmentPermissionAccess flag, string pathList) [C#] public void AddPathList(EnvironmentPermissionAccess flag, string pathList)
F
E
G H I
Summary
J
Adds access for the specified environment variables to the existing state of the permission.
K L
Parameters
M
Parameter
Description
flag
One of the System.Security.Permissions.EnvironmentPermissionAccess values.
pathList
A list of environment variables (semicolon-separated).
N O P Q R
Description
S
Use this method to modify environment variable access by adding to the state of the current permission.
T U
Exceptions
V
Exception
Condition
System.ArgumentNullException
The pathList parameter is null.
System.ArgumentException
The flag parameter is not a valid value of System.Security.Permissions.EnvironmentPermissionAccess.
W X Y Z
1581
Contents | Index
EnvironmentPermission
System.Security.Permissions
Copy() Method
EnvironmentPermission.Copy() Method [ILASM] .method public hidebysig virtual class System.Security.IPermission Copy() [C#] public override IPermission Copy()
A B C
Summary
D
Returns a new System.Security.Permissions.EnvironmentPermission object containing the same values as the current instance.
E F
Description
G
[Note: The object returned by this method represents the same level of access to the same environment variables as the current instance.] This method overrides System.Security.CodeAccessPermission.Copy and is implemented to support the System.Security.IPermission interface.
H I J K
Example
L
using System; using System.Security; using System.Security.Permissions; namespace Samples { public class EnvironmentPermissionCopy { public static void Main() { EnvironmentPermission p1 = new EnvironmentPermission( EnvironmentPermissionAccess.Read, "COMPUTERNAME"); EnvironmentPermission p2 = (EnvironmentPermission) p1.Copy(); p1.SetPathList(EnvironmentPermissionAccess.Read, "USERNAME"); Console.WriteLine( "p1.GetPathList() yields: {0}", p1.GetPathList(EnvironmentPermissionAccess.Read)); Console.WriteLine( "p2.GetPathList() yields: {0}", p2.GetPathList(EnvironmentPermissionAccess.Read)); } } }
M N O P Q R S T U V W X Y Z
1582
Contents | Index
System.Security.Permissions
EnvironmentPermission FromXml() Method
The output is p1.GetPathList() yields: USERNAME p2.GetPathList() yields: COMPUTERNAME
A B
EnvironmentPermission.FromXml(System.Security.SecurityElement) Method
C
[ILASM] .method public hidebysig virtual void FromXml(class System.Security.SecurityElement esd) [C#] public override void FromXml(SecurityElement esd)
D E F G
Summary
H
Reconstructs the state of a System.Security.Permissions.EnvironmentPermission object using the specified XML encoding.
I J
Parameters
K L
Parameter
Description
esd
A System.Security.SecurityElement instance containing the XML encoding to use to reconstruct the state of a System.Security.Permissions.EnvironmentPermission object.
M N O P
Description
Q
The state of the current instance is changed to the state encoded in esd. [Note: For the XML encoding for this class, see the System.Security.Permissions.EnvironmentPermission class page. This method overrides System.Security.CodeAccessPermission.FromXml.]
R S T
Exceptions
U V
Exception
Condition
System.ArgumentNullException
esd is null.
X Y
System.ArgumentException
esd does not contain the encoding for a System.Security.Permissions.EnvironmentPermission instance.
W
Z
The version number of esd is not valid.
1583
Contents | Index
EnvironmentPermission
System.Security.Permissions
GetPathList() Method
Example using System; using System.Security; using System.Security.Permissions; namespace Samples { public class EnvironmentPermissionFromXml { public static void Main() { EnvironmentPermission p1 = new EnvironmentPermission( EnvironmentPermissionAccess.Read, "COMPUTERNAME"); SecurityElement s = p1.ToXml(); EnvironmentPermission p2 = new EnvironmentPermission( PermissionState.Unrestricted); p2.FromXml(s); Console.WriteLine(p2); } } }
A B C D E F G H I J K L M
The output is
N O
P Q R
EnvironmentPermission.GetPathList(System.Security.Permissions. EnvironmentPermissionAccess) Method
S T U
[ILASM] .method public hidebysig instance string GetPathList(valuetype System.Security.Permissions.EnvironmentPermissionAccess flag) [C#] public string GetPathList(EnvironmentPermissionAccess flag)
V W X Y
Summary
Z
Gets all environment variables with the specified System.Security.Permissions.EnvironmentPermissionAccess.
1584
Contents | Index
System.Security.Permissions
EnvironmentPermission GetPathList() Method
Parameters Parameter
Description
flag
One of the System.Security.Permissions.EnvironmentPermissionAccess values that represent a single type of environment variable access.
A B C D
Return Value
E
A list of environment variables (semicolon-separated) for the selected flag.
F G
Description
H
Use this method to get the state of the current permission. To get both Read and Write access states requires two calls to this method. The flag parameter is limited to the values of System.Security.Permissions.EnvironmentPermissionAccess, which represent single types of environment variable access. Those values are System.Security.Permissions.EnvironmentPermissionAccess.Read and System.Security.Permissions.EnvironmentPermissionAccess.Write. The values acceptable to flag do not include System.Security.Permissions.EnvironmentPermissionAccess.NoAccess and System.Security.Permissions.EnvironmentPermissionAccess.AllAccess, which do not represent single types of environment variable access.
I J K L M N O P
Exceptions
Q
Exception
Condition
R S
flag is not a valid value of System.Security.Permissions.EnvironmentPermissionAccess.
T
-orSystem.ArgumentException
U
flag is System.Security.Permissions.EnvironmentPermissionAccess.AllAccess, which represents more than one type of environment variable access, or System.Security.Permissions.EnvironmentPermissionAccess.NoAccess, which does not represent any type of environment variable access.
V W X Y Z
1585
Contents | Index
EnvironmentPermission
System.Security.Permissions
Intersect() Method
EnvironmentPermission.Intersect(System.Security.IPermission) Method [ILASM] .method public hidebysig virtual class System.Security.IPermission Intersect(class System.Security.IPermission target) [C#] public override IPermission Intersect(IPermission target)
A B C D
Summary
E
Returns a new System.Security.Permissions.EnvironmentPermission object that is the intersection of the current instance and the specified object.
F G
Parameters
H I J
Parameter
Description
target
A System.Security.Permissions.EnvironmentPermission instance to intersect with the current instance.
K L
Return Value
M
A new System.Security.Permissions.EnvironmentPermission instance that represents the intersection of the current instance and target. If the intersection is empty or target is null, returns null. If the current instance is unrestricted, returns a copy of target. If target is unrestricted, returns a copy of the current instance.
N O P Q
Description
R
[Note: The intersection of two permissions is a permission that secures the resources and operations secured by both permissions. Specifically, it represents the minimum permission such that any demand that passes both permissions will also pass their intersection. This method overrides System.Security.CodeAccessPermission.Intersect and is implemented to support the System.Security.IPermission interface.]
S T U V
Exceptions
W X
Exception
Condition
System.ArgumentException
target is not null and is not of type System.Security.Permissions.EnvironmentPermission.
Y Z
1586
Contents | Index
System.Security.Permissions
EnvironmentPermission IsSubsetOf() Method
Example using System; using System.Security; using System.Security.Permissions; namespace Samples { public class EnvironmentPermissionIntersect { public static void Main() { EnvironmentPermission p1 = new EnvironmentPermission( EnvironmentPermissionAccess.Read, "USERNAME"); EnvironmentPermission p2 = new EnvironmentPermission( EnvironmentPermissionAccess.Read, "USERNAME"); Console.WriteLine(p1.Intersect(p2)); } } }
A B C D E F G H I J K L M
The output is
N
O P Q R
EnvironmentPermission.IsSubsetOf(System.Security.IPermission) Method
S [ILASM] .method public hidebysig virtual bool IsSubsetOf(class System.Security.IPermission target) [C#] public override bool IsSubsetOf(IPermission target)
T U V W
Summary
X
Determines whether the current instance is a subset of the specified object.
Y Z
1587
Contents | Index
EnvironmentPermission
System.Security.Permissions
IsSubsetOf() Method
Parameters Parameter
Description
target
A System.Security.Permissions.EnvironmentPermission instance that is to be tested for the subset relationship.
A B C D
Return Value
E
true if the current instance is a subset of target; otherwise, false. If the current instance is unrestricted, and target is not, returns false. If target is unrestricted, returns true. If target is null and no environment variables are secured by the current instance, returns true. If target is null, and the current instance secures one or more environment variables, returns false.
F G H I
Description
J
[Note: The current instance is a subset of target if the current instance specifies a set of accesses to resources that is wholly contained by target. For example, a permission that represents read access to a file is a subset of a permission that represents read and write access to the file. If this method returns true, the current instance describes a level of access to a set of environment variables that is also described by target. This method overrides System.Security.CodeAccessPermission.IsSubsetOf and is implemented to support the System.Security.IPermission interface.]
K L M N O
Exceptions
P Q
Exception
Condition
System.ArgumentException
target is not null and is not of type System.Security.Permissions.EnvironmentPermission.
R S T U
Example
V
using System; using System.Security; using System.Security.Permissions; namespace Samples { public class EnvironmentPermissionIsSubsetOf { public static void Main() {
W X Y Z
1588
Contents | Index
System.Security.Permissions
EnvironmentPermission IsUnrestricted() Method
EnvironmentPermission p1 = new EnvironmentPermission( PermissionState.Unrestricted); p1.SetPathList(EnvironmentPermissionAccess.AllAccess, "USERNAME, COMPUTERNAME"); EnvironmentPermission p2 = new EnvironmentPermission( PermissionState.Unrestricted); p1.SetPathList(EnvironmentPermissionAccess.Read, "USERNAME"); Console.WriteLine("p1.IsSubsetOf(p2) returns: {0}", p1.IsSubsetOf(p2)); Console.WriteLine("p2.IsSubsetOf(p1) returns: {0}", p2.IsSubsetOf(p1)); Console.WriteLine("p2.IsSubsetOf(p2) returns: {0}", p2.IsSubsetOf(p2));
A B C D E F G H I
} }
J
}
K
The output is
L M
p1.IsSubsetOf(p2) returns: True p2.IsSubsetOf(p1) returns: False p2.IsSubsetOf(p2) returns: True
N O P
EnvironmentPermission.IsUnrestricted() Method
Q [ILASM] .method public final hidebysig virtual bool IsUnrestricted() [C#] public bool IsUnrestricted()
R S T
Summary
U
Returns a value indicating whether the current permission is unrestricted.
V W
Return Value
X
true if the current permission is unrestricted; otherwise, false.
Y
Description
Z
An unrestricted permission represents the union of all possible states of the permission.
1589
Contents | Index
EnvironmentPermission
System.Security.Permissions
SetPathList() Method
EnvironmentPermission.SetPathList(System.Security.Permissions. EnvironmentPermissionAccess, System.String) Method [ILASM] .method public hidebysig instance void SetPathList(valuetype System.Security.Permissions.EnvironmentPermissionAccess flag, string pathList) [C#] public void SetPathList(EnvironmentPermissionAccess flag, string pathList)
A B C D
Summary
E
Sets the specified access to the specified environment variables to the existing state of the permission.
F G
Parameters
H I
Parameter
Description
flag
One of the System.Security.Permissions.EnvironmentPermissionAccess values.
pathList
A list of environment variables (semicolon-separated).
J K L M N
Description
O
The previous state of the current permission is overwritten.
P
Exceptions
Q R
Exception
Condition
System.ArgumentNullException
The pathList parameter is null.
System.ArgumentException
The flag parameter is not a valid value of System.Security.Permissions.EnvironmentPermissionAccess.
S T U V W X
EnvironmentPermission.ToXml() Method
Y [ILASM] .method public hidebysig virtual class System.Security.SecurityElement ToXml() [C#] public override SecurityElement ToXml()
Z
1590
Contents | Index
System.Security.Permissions
EnvironmentPermission Union() Method
Summary Returns the XML encoding of the current instance.
Description
A
[Note: For the XML encoding for this class, see the System.Security.Permissions.EnvironmentPermission class page. This method overrides System.Security.CodeAccessPermission.ToXml.]
B C D
Example
E
using System; using System.Security; using System.Security.Permissions; namespace Samples { public class EnvironmentPermissionToXml { public static void Main() { EnvironmentPermission p = new EnvironmentPermission( EnvironmentPermissionAccess.Read, "COMPUTERNAME"); SecurityElement s = p.ToXml(); Console.WriteLine(p); } } }
F G H I J K L M N O P Q
The output is
R
S T U V
EnvironmentPermission.Union(System.Security.IPermission) Method
W [ILASM]
X
.method public hidebysig virtual class System.Security.IPermission Union(class System.Security.IPermission other)
Y
[C#]
Z
public override IPermission Union(IPermission other)
1591
Contents | Index
EnvironmentPermission
System.Security.Permissions
Union() Method
Summary Returns a new System.Security.Permissions.EnvironmentPermission that is the union of the current instance and the specified object. A
Parameters
B C D E
Parameter
Description
other
A System.Security.Permissions.EnvironmentPermission instance to combine with the current instance.
F G
Return Value
H
A new System.Security.Permissions.EnvironmentPermission instance that represents the union of the current instance and other. If the current instance or other is unrestricted, returns a System.Security.Permissions.EnvironmentPermission instance that is unrestricted. If other is null, returns a copy of the current instance via the System.Security.IPermission.Copy method. If the current instance and other do not specify any environment variables, returns null.
I J K L M
Description
N
[Note: The result of a call to System.Security.Permissions.EnvironmentPermission.Union is a permission that represents the access to environment variables represented by the current instance as well as the access to environment variables represented by other. Any demand that passes either the current instance or other passes their union. This method overrides System.Security.CodeAccessPermission.Union and is implemented to support the System.Security.IPermission interface.]
O P Q R S
Exceptions
T U
Exception
Condition
System.ArgumentException
other is not null and is not of type System.Security.Permissions.EnvironmentPermission.
V W X Y Z
1592
Contents | Index
System.Security.Permissions
EnvironmentPermission Union() Method
Example using System; using System.Security; using System.Security.Permissions; namespace Samples { public class EnvironmentPermissionUnion { public static void Main() { EnvironmentPermission p1 = new EnvironmentPermission( EnvironmentPermissionAccess.Read, "USERNAME"); EnvironmentPermission p2 = new EnvironmentPermission( EnvironmentPermissionAccess.Read, "COMPUTERNAME"); Console.WriteLine(p1.Union(p2)); } } }
A B C D E F G H I J K L M
The output is
N
O P Q R S T U V W X Y Z
1593
Contents | Index
System.Security.Permissions EnvironmentPermissionAccess Enum
BCL
Object
A
IComparable
ValueType
B
Enum
IFormattable EnvironmentPermissionAccess
C
IConvertible
NotStandardized
D
Summary
E
Represents access to environment variables.
F G
Type Summary CF public enum EnvironmentPermissionAccess CF AllAccess = Read|Write, CF NoAccess = 0x0, CF Read = 0x1, CF Write = 0x2, }
H I J K L
{
Description
M
[Note: This enumeration is used by the System.Security.Permissions.EnvironmentPermission class.]
N O
Example
P
using System; using System.Security; using System.Security.Permissions; namespace Samples { public class EnvironmentPermissionAccessSample { public static void Main() { try { string ev = "USERNAME"; EnvironmentPermission p = new EnvironmentPermission( EnvironmentPermissionAccess.Read, ev); p.PermitOnly(); Console.WriteLine("Variable {0} is {1}", ev,
Q R S T U V W X Y Z
1594
Contents | Index
System.Security.Permissions
EnvironmentPermissionAccess Enum AllAccess Field
Environment.GetEnvironmentVariable(ev)); CodeAccessPermission.RevertPermitOnly(); p = new EnvironmentPermission( EnvironmentPermissionAccess.NoAccess, ev); p.PermitOnly(); Console.WriteLine("Variable {0} is {1}", ev, Environment.GetEnvironmentVariable(ev));
A B C D
} catch(SecurityException e) { Console.WriteLine("Exception: {0}", e); }
E F G
}
H
} }
I
The output is
J K
Variable USERNAME is damien Exception: System.Security.SecurityException: Request for the permission of type System.Security.Permissions.EnvironmentPermission, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed. at System.Security.SecurityRuntime.FrameDescHelper(FrameSecurityDescriptor secDesc, IPermission demand, PermissionToken permToken) at System.Security.CodeAccessSecurityEngine.Check(PermissionToken permToken, CodeAccessPermission demand, StackCrawlMark& stackMark, Int32 checkFrames, Int32 unrestrictedOverride) at System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark) at System.Security.CodeAccessPermission.Demand() at System.Environment.GetEnvironmentVariable(String variable) at Samples.EnvironmentPermissionAccessSample.Main() in C:\Books\BCL\Samples\ System.Security\Permissions\EnvironmentPermissionAccess\ EnvironmentPermissionAccess.cs:line 27
L M N O P Q R S T U V
EnvironmentPermissionAccess.AllAccess Field
W
[ILASM] .field public static literal valuetype System.Security.Permissions.EnvironmentPermissionAccess AllAccess = Read | Write [C#] AllAccess = Read | Write
X Y Z
1595
Contents | Index
EnvironmentPermissionAccess Enum
System.Security.Permissions
NoAccess Field
Summary Specifies read and write access to one or more environment variables. A B
EnvironmentPermissionAccess.NoAccess Field
C
[ILASM] .field public static literal valuetype System.Security.Permissions.EnvironmentPermissionAccess NoAccess = 0x0 [C#] NoAccess = 0x0
D E F G
Summary
H
Specifies no access to one or more environment variables.
I J
EnvironmentPermissionAccess.Read Field
K L
[ILASM] .field public static literal valuetype System.Security.Permissions.EnvironmentPermissionAccess Read = 0x1
M
[C#]
Read = 0x1
N O
Summary
P
Specifies read access to one or more environment variables. [Note: Changing, deleting, and creating environment variables are not included in this access level.]
Q R S
EnvironmentPermissionAccess.Write Field
T U
[ILASM] .field public static literal valuetype System.Security.Permissions.EnvironmentPermissionAccess Write = 0x2 [C#] Write = 0x2
V W X Y
Summary
Z
Specifies write access to one or more environment variables. Write access includes creating and deleting environment variables as well as changing existing values. [Note: Reading environment variables is not included in this access level.]
1596
Contents | Index
System.Security.Permissions EnvironmentPermissionAttribute
BCL
Object
A
Attribute SecurityAttribute
B
CodeAccessSecurityAttribute
C
EnvironmentPermissionAttribute
D E
Summary
F
Used to declaratively specify security actions to control access to environment variables.
G
Type Summary
H
CF public sealed class EnvironmentPermissionAttribute : CodeAccessSecurityAttribute { // Constructors CF public EnvironmentPermissionAttribute(SecurityAction action); // CF CF CF
I J K L
Properties public string All { set; } public string Read { set; get; } public string Write { set; get; }
M N O
// Methods CF public override IPermission CreatePermission ();
P
}
Q
Description
R
Environment variable names are case-insensitive. Multiple environment variable names are specified by separating the names using the System.IO.Path.PathSeparator string. [Note: The level of access to one or more environment variables is specified using the members of the current instance. For example, to specify read permissions for an environment variable, set the System.Security.Permissions.EnvironmentPermissionAttribute.Read property equal to the name of the environment variable. The security information declared by a security attribute is stored in the metadata of the attribute target, and is accessed by the system at runtime. Security attributes are used for declarative security only. For imperative security, use the corresponding permission class, System.Security.Permissions.EnvironmentPermission. The allowable System.Security.Permissions.EnvironmentPermissionAttribute targets are determined by the System.Security.Permissions.SecurityAction passed to the constructor.]
S T U V W X Y Z
1597
Contents | Index
EnvironmentPermissionAttribute
System.Security.Permissions
EnvironmentPermissionAttribute() Constructor
Example using System; using System.Security; using System.Security.Permissions; [assembly:EnvironmentPermissionAttribute( SecurityAction.RequestMinimum, Read="COMPUTERNAME;USERNAME")] namespace Samples { public class EnvironmentPermissionAttributeSample { public static void Main() { string[] v = {"USERNAME", "COMPUTERNAME"}; foreach(string s in v) Console.WriteLine("Variable {0} Value: {1}", s, Environment.GetEnvironmentVariable(s));
A B C D E F G H I J
}
K
} }
L
The output is
M N
Variable USERNAME Value: damien Variable COMPUTERNAME Value: PROJECT42
O P
EnvironmentPermissionAttribute(System.Security.Permissions. SecurityAction) Constructor
Q R
[ILASM] public rtspecialname specialname instance void .ctor(valuetype System.Security.Permissions.SecurityAction action)
S T
[C#]
U
public EnvironmentPermissionAttribute(SecurityAction action)
V
Summary
W
Constructs and initializes a new instance of the System.Security.Permissions.EnvironmentPermissionAttribute class with the specified System.Security.Permissions.SecurityAction value.
X Y Z
1598
Contents | Index
System.Security.Permissions
EnvironmentPermissionAttribute EnvironmentPermissionAttribute() Constructor
Parameters Parameter
Description
action
A System.Security.Permissions.SecurityAction value.
A B C
Exceptions
D E
Exception
Condition F
System.ArgumentException
action is not a valid System.Security.Permissions.SecurityAction value.
G H I
Example
J
using System; using System.Security; using System.Security.Permissions; namespace Samples { public class EnvironmentPermissionAttributeConstructor { [EnvironmentPermissionAttribute( SecurityAction.Assert)] public static void Main() { string[] v = {"USERNAME", "COMPUTERNAME"}; foreach(string s in v) Console.WriteLine("Variable {0} Value: {1}", s, Environment.GetEnvironmentVariable(s));
K L M N O P Q R S T
}
U
}
V
}
W
The output is
X V1ariable USERNAME Value: damien Variable COMPUTERNAME Value: PROJECT42
Y Z
1599
Contents | Index
EnvironmentPermissionAttribute
System.Security.Permissions
All Property
EnvironmentPermissionAttribute.All Property [ILASM] .property string All { public hidebysig specialname instance string get_All() public hidebysig specialname instance void set_All(string value) } [C#] public string All { get; set; }
A B C D
Summary
E
Sets the environment variables for which full access is secured.
F
Description
G
Multiple environment variable names are specified by separating the names using the System.IO.Path.PathSeparator string. Environment variable names are caseinsensitive. [Note: The security action passed to the constructor of the current instance determines how the specified environment variables are secured. For example, if the action is System.Security.Permissions.SecurityAction.RequestMinimum, then the target of the current instance requires full access to the specified variables in order to execute. If the action is System.Security.Permissions.SecurityAction.RequestRefuse, then the system does not allow the target any access to the specified variables.]
H I J K L M N
Example
O
using System; using System.Security; using System.Security.Permissions; namespace Samples { public class EnvironmentPermissionAttributeAll { [EnvironmentPermissionAttribute( SecurityAction.Assert, All="USERNAME;COMPUTERNAME")] public static void Main() { string[] v = {"USERNAME", "COMPUTERNAME"}; foreach(string s in v) Console.WriteLine("Variable {0} Value: {1}", s, Environment.GetEnvironmentVariable(s));
P Q R S T U V W X Y Z
} } }
1600
Contents | Index
System.Security.Permissions
EnvironmentPermissionAttribute Read Property
The output is Variable USERNAME Value: damien Variable COMPUTERNAME Value: PROJECT42
A B
EnvironmentPermissionAttribute.Read Property
C
[ILASM] .property string Read { public hidebysig specialname instance string get_Read() public hidebysig specialname instance void set_Read(string value) } [C#] public string Read { get; set; }
D E F G
Summary
H
Gets or sets the environment variables for which read access is secured.
I J
Description
K
Multiple environment variable names are specified by separating the names using the System.IO.Path.PathSeparator string. Environment variable names are case-insensitive. [Note: The security action passed to the constructor of the current instance determines how the specified environment variables are secured. For example, if the action is System.Security.Permissions.SecurityAction.RequestMinimum, then the target of the current instance requires read access to the specified variables in order to execute. If the action is System.Security.Permissions.SecurityAction.RequestRefuse, then the system does not allow the target to read the specified variables.]
L M N O P Q
Example
R
using System; using System.Reflection; using System.Security; using System.Security.Permissions; namespace Samples { public class EnvironmentPermissionAttributeRead { [EnvironmentPermissionAttribute( SecurityAction.Assert, Read="USERNAME;COMPUTERNAME")] public static void Main() { string[] v = {"USERNAME", "COMPUTERNAME"}; foreach(string s in v)
S T U V W X Y Z
1601
Contents | Index
EnvironmentPermissionAttribute
System.Security.Permissions
Write Property
Console.WriteLine("Variable {0} Value: {1}", s, Environment.GetEnvironmentVariable(s)); }
A
} }
B C
The output is
D Variable USERNAME Value: damien Variable COMPUTERNAME Value: PROJECT42
E F G
EnvironmentPermissionAttribute.Write Property
H
[ILASM] .property string Write { public hidebysig specialname instance string get_Write() public hidebysig specialname instance void set_Write(string value) } [C#] public string Write { get; set; }
I J K L
Summary
M
Gets or sets the environment variables for which write access is secured.
N
Description
O
Multiple environment variable names are specified by separating the names using the System.IO.Path.PathSeparator string. Environment variable names are case-insensitive. [Note: The security action passed to the constructor of the current instance determines how the specified environment variables are secured. For example, if the action is System.Security.Permissions.SecurityAction.RequestMinimum, then the target of the current instance requires write access to the specified variables in order to execute. If the action is System.Security.Permissions.SecurityAction.RequestRefuse, then the system does not allow the target to write the specified variables.]
P Q R S T U V W
EnvironmentPermissionAttribute.CreatePermission() Method
X
[ILASM] .method public hidebysig virtual class System.Security.IPermission CreatePermission()
Y Z
[C#]
public override IPermission CreatePermission()
1602
Contents | Index
System.Security.Permissions
EnvironmentPermissionAttribute CreatePermission() Method
Summary Returns a new System.Security.Permissions.EnvironmentPermission that contains the security information of the current instance. A
Description
B
[Note: Applications typically do not call this method; it is intended for use by the system. The security information described by a security attribute is stored in the metadata of the attribute target, and is accessed by the system at runtime. The system uses the object returned by this method to convert the security information of the current instance into the form stored in metadata. This method overrides System.Security.Permissions.SecurityAttribute.CreatePermission.]
C D E F G H I J K L M N O P Q R S T U V W X Y Z
1603
Contents | Index
System EventArgs
BCL
Object
A
EventArgs
B
Summary
C
EventArgs is the base class for classes containing event data.
D E
Type Summary public class EventArgs { // Constructors public EventArgs ();
F G H
// Fields public static readonly EventArgs Empty = new EventArgs();
I J
}
K L
BA Throughout the .NET Framework we encapsulate arguments to an event in
M
subclasses of EventArgs. For example we prefer:
N public delegate void AssemblyLoadEventHandler(object sender, AssemblyLoadEventArgs args);
O P
rather than
Q public delegate void AssemblyLoadEventHandler(object sender, Assembly loadedAssembly);
R S
If we want to add some new information in the event callback we can do it without breaking clients. For example, if we need to add information about the location an assembly was loaded from we would simply add a new property to the AssemblyLoadEventArgs class. If we did not have the EventArgs class we would have to create a whole new Delegate and a new event of that type with a different name. It would be really ugly. Encapsulating the event data in a subclass of EventArgs makes this scenario very smooth.
T U V W X Y
JR When raising an event, if you have no special event data to pass, you should pass EventArgs.Empty instead of null.
Z
1604
Contents | Index
System
EventArgs EventArgs Class
Description [Note: This class contains no event data; it is used by events that do not pass state information to an event handler when an event is raised. If the event handler requires state information, the application must create a subclass of this class to hold the data. For example, the System.AssemblyLoadEventArgs class is used to hold the data for assembly load events, and contains a System.Reflection.Assembly object that describes the loaded assembly. For details on events, see System.EventHandler.]
A B C D
Example
E
using System; namespace Samples { public class EventArgsSample { public delegate void MouseClickEventHandler(object sender, MouseClickEventArgs args); public class MouseClickEventArgs: EventArgs { private string s; public MouseClickEventArgs(string s) { this.s = s; } public string Label {get {return s;}} } public class MyButton { private string label; public MyButton(string label) { this.label = label; } public event MouseClickEventHandler MouseClick; public void SimulateButtonClicked() { if(MouseClick != null) MouseClick(this, new MouseClickEventArgs(label)); } } public static void Main() { MyButton b = new MyButton("Click me"); b.MouseClick += new MouseClickEventHandler(ButtonClicked); b.SimulateButtonClicked(); } public static void ButtonClicked(object sender, MouseClickEventArgs args)
F G H I J K L M N O P Q R S T U V W X Y Z
1605
Contents | Index
EventArgs
System
EventArgs() Constructor
{ Console.WriteLine("Sender is {0}", sender); Console.WriteLine("Label is {0}", args.Label); }
A
} }
B
The output is
C D
Sender is Samples.EventArgsSample+MyButton Label is Click me
E F G
EventArgs() Constructor
H
[ILASM] public rtspecialname specialname instance void .ctor() [C#] public EventArgs()
I J K
Summary
L
Constructs a new instance of the EventArgs class.
M N O
EventArgs.Empty Field
P
[ILASM]
.field public static initOnly class System.EventArgs Empty
Q
[C#]
R
public static readonly EventArgs Empty = new EventArgs()
S
Summary
T
Returns a new System.EventArgs instance for use with events that have no state information.
U V
Description
W
Accessing this field is equivalent to calling the System.EventArgs constructor.
X Y Z
1606
Contents | Index
System
EventArgs Empty Field
Example using System; namespace Samples { public class EventArgsEmpty { public delegate void MyDelegate(EventArgs e); public event MyDelegate CallMe; public void InvokeEvent() { if(CallMe !=null) CallMe(EventArgs.Empty); } public static void Main() { EventArgsEmpty e = new EventArgsEmpty(); e.CallMe += new MyDelegate(GetCalled); e.InvokeEvent(); } public static void GetCalled(EventArgs e) { Console.WriteLine("I got called with: {0}", e); } } }
A B C D E F G H I J K L M N
The output is
O P
I got called with: System.EventArgs
Q R S T U V W X Y Z
1607
Contents | Index
System EventHandler Delegate
BCL
Object ICloneable
A
Delegate ISerializable
B
MulticastDelegate
NotStandardized
NotStandardized
EventHandler
C D
Summary
E
Defines the shape of methods that are called in response to an event.
F
Type Summary
G
public delegate void EventHandler (object sender, EventArgs e);
H I
Parameters
J K
Parameter
Description
M
sender
The object that raised the event.
N
e
A System.EventArgs instance that contains the event data.
L
O P
BG Note that we have to define delegates that are similar to EventHandler for every unique type of event, each consuming its own subclass of EventArgs. Here is a very common design pattern that could theoretically benefit from generics. Instead of defining a custom event handler for every type of event we could define this:
Q R S T
public delegate void EventHandler(Object sender, T args) where T : EventArgs
U
Then events might use syntax similar to the following:
V W
public event EventHandler<MouseEventArgs> MouseMoveEvent;
X
This would avoid a proliferation of classes in our documentation and in class listings such as Intellisense. This would also give us fewer classes to load, making our working set smaller and startup time faster.
Y Z
1608
Contents | Index
System
EventHandler Delegate EventHandler Delegate
Description [Note: A System.EventHandler instance is used to specify the methods that are invoked in response to an event. To associate an instance of EventHandler with an event, add the EventHandler instance to the event. The methods referenced by the EventHandler instance are invoked whenever the event is raised, until the EventHandler instance is removed from the event. If the event does not generate data, applications use the base class System.EventArgs for the event data object e. For more information, see System.EventArgs.] [Note: For additional information about events, see Partitions I and II of the CLI Specification.]
A B C D E F
Example
G
using System; namespace Samples { public class EventHandlerSample { public class MyButton { public event EventHandler MouseClick; public void SimulateButtonClicked() { if(MouseClick != null) MouseClick(this, EventArgs.Empty); } } public static void Main() { MyButton b = new MyButton(); b.MouseClick += new EventHandler(ButtonClicked); b.SimulateButtonClicked(); } public static void ButtonClicked(object sender, EventArgs args) { Console.WriteLine("Sender is {0}", sender); } } }
H I J K L M N O P Q R S T U V W X
The output is
Y Sender is Samples.EventHandlerSample+MyButton
Z
1609
Contents | Index
System Exception
BCL
Object
A
Exception
ISerializable
B
ApplicationException
C
SystemException
NotStandardized
ArgumentException
D
ArgumentNullException
E
ArgumentOutOfRangeException
F
DuplicateWaitObjectException
G
ArithmeticException
H DivideByZeroException
I OverflowException
J NotFiniteNumberException
ExtendedNumerics
K ArrayTypeMismatchException
L
ExecutionEngineException
M
FormatException
N
IndexOutOfRangeException
O
InvalidCastException
P
InvalidOperationException
Q
ObjectDisposedException
*Continued
R
InvalidProgramException
OutOfMemoryException
S
IOException
RankException
T
DirectoryNotFoundException
SecurityException
U
EndOfStreamException
VerificationException
V
FileLoadException
StackOverflowException
FileNotFoundException
SynchronizationLockException
PathTooLongException
ThreadAbortException
W X
NotImplementedException
ThreadStateException
NotSupportedException
TypeInitializationException
NullReferenceException
UnauthorizedAccessException
Y Z *Continued
1610
Contents | Index
System
Exception Exception Class
Summary Represents errors that occur during application execution. A
Type Summary
B
public class Exception : ISerializable { // Constructors public Exception (); public Exception (string message); public Exception (string message, Exception innerException); MS CF protected Exception (SerializationInfo info, StreamingContext context);
C D E F G
// Properties MS CF public virtual string HelpLink { set; get; } MS CF protected int HResult { set; get; } public Exception InnerException { get; } public virtual string Message { get; } MS CF public virtual string Source { set; get; } CF public virtual string StackTrace { get; } MS CF public MethodBase TargetSite { get; }
H I J K L M
// Methods public virtual Exception GetBaseException (); MS CF public virtual void GetObjectData (SerializationInfo info, StreamingContext context); public override string ToString (); }
N O P Q R
BA In retrospect I would have made Exception abstract. One of the key benefits
S
of exceptions over return codes is they immediately provide some information about what the problem is just by the name of the exception. But this benefit is undermined if the developers are lazy and simply write this code:
T U V
throw new Exception();
W
Making Exception abstract would have forced them to choose a more meaningful exception.
X Y
continued
Z
1611
Contents | Index
Exception
System
Exception Class
BG I have been asked several times why we made GetBaseException a method instead of a property. To clarify, each exception can contain an inner exception, which is an exception that this exception is wrapping. In intuitive terms, the inner exception is the exception that caused this exception to be raised. However, since you could end up with a chain of exceptions wrapping other exceptions that is multiple levels deep, the GetBaseException method was added to tunnel through all the InnerException properties. Our thinking at the time told us operations that potentially take a long time should be methods, whereas properties should really be just like reading or writing to a public field with possibly one or two argument or state validation checks.
A B C D E F
JR I agree with Brad, that Exception should have been defined as an abstract base
G
class to prevent lazy developers from throwing Exception in their code. However, during development, the exact exception type name may not be known. To help with this, in my own projects, I define a ToDoException class that is marked with the ObsoleteAttribute. Then, when I feel lazy, I throw this exception, for example:
H I J
using System; [Obsolete("Replace with a better exception someday.")] sealed class ToDoException : Exception { public ToDoException() : base() {} public ToDoException(string message) : this(message, null) {} public ToDoException(string message, Exception innerException) : base(message, innerException) {} } class App { static void Main() { throw new ToDoException("Something went wrong."); } }
K L M N O P Q R
When I compile the above, I get a warning in Main: x.cs(13,17): warning CS0618: ’ToDoException’ is obsolete: ’Replace with a better exception someday.’ This is just a warning allowing me to continue to develop my application and always reminding me to replace ToDoException with another exception type when the exact name of the type is determined.
S T U V
JR A properly designed exception class should also allow for serializability. Specifically, this means that the class should have the System.SerializableAttribute applied to it and the class should implement the ISerializable interface with its GetObjectData method and special constructor. These two methods should serialize/deserialize any fields in the class and should be sure to call the base class methods so that any fields in the base class are also serialized/deserialized. If the exception class is sealed, the constructor can be marked private; otherwise, mark the constructor as protected. Since GetObjectData is an interface method, mark it as public.
W X Y Z
1612
Contents | Index
System
Exception Exception Class
Description This class is the base class for all exceptions. When an error occurs, either the system or the currently executing application reports it by throwing an exception containing information about the error. Once thrown, an exception is handled by the application or by the default exception handler. [Note: For a description of the exception handling model, see Partition I of the CLI Specification.] [Note: If an application handles exceptions that occur during the execution of a block of application code, the code is required to be placed within a try statement. Application code within a try statement is a try block. Application code that handles exceptions thrown by a try block is placed within a catch statement, and is called a catch block. Zero or more catch blocks are associated with a try block, and each catch block includes a type filter that determines the types of exceptions it handles. When an exception occurs in a try block, the system searches the associated catch blocks in the order they appear in application code, until it locates a catch block that handles the exception. A catch block handles an exception of type T, if the type filter of the catch block specifies T or any type that T derives from. The system stops searching after it finds the first catch block that handles the exception. For this reason, in application code, a catch block that handles a type must be specified before a catch block that handles its base types, as demonstrated in the example that follows this section. A catch block that handles System.Exception is specified last. If the catch blocks associated with the current try block do not handle the exception, and the current try block is nested within other try blocks in the current call, the catch blocks associated with the next enclosing try block are searched. If no catch block for the exception is found, the system searches previous nesting levels in the current call. If no catch block for the exception is found in the current call, the exception is passed up the call stack, and the previous stack frame is searched for a catch block that handles the exception. The search of the call stack continues until the exception is handled or there are no more frames in the call stack. If the top of the call stack is reached without finding a catch block that handles the exception, the default exception handler handles it and the application terminates.] System.Exception types support the following features: • •
A B C D E F G H I J K L M N O P Q R S T U
Human-readable text that describes the error. [Note: See System.Exception.Message property.] The state of the call stack when the exception was thrown. [Note: See the System.Exception.StackTrace property.]
V W X
When there is a causal relationship between two or more exceptions, this information is maintained via the System.Exception.InnerException property. The Base Class Library provides two types that inherit directly from System.Exception:
Y Z
1613
Contents | Index
Exception
System
Exception Class
• •
System.ApplicationException System.SystemException
[Note: Most user-defined exceptions derive from System.ApplicationException. For more information, see System.ApplicationException and System.SystemException.]
A B C D
Example
E
using System; namespace Samples { public class ExceptionSample { public static void Main() { try { DivideBy(42, 0); } catch(Exception e) { Console.WriteLine("Exception caught:"); Console.WriteLine("Message: {0}", e.Message); Console.WriteLine("Stack trace: {0}", e.StackTrace); Console.WriteLine("Inner exception (if any): {0}", e.InnerException); } } public static int DivideBy(int i, int j) { try { return i / j; } catch(DivideByZeroException e) { throw new DivideByZeroException( "Parameter j cannot be zero", e); } } } }
F G H I J K L M N O P Q R S T U V W X Y Z
1614
Contents | Index
System
Exception Exception() Constructor
The output is Exception caught: Message: Parameter j cannot be zero Stack trace: at Samples.ExceptionSample.DivideBy(Int32 i, Int32 j) in C:\Books\BCL\Samples\System\Exception\Exception.cs:line 30 at Samples.ExceptionSample.Main() in C:\Books\BCL\Samples\System\Exception\ Exception.cs:line 11 Inner exception (if any): System.DivideByZeroException: Attempted to divide by zero. at Samples.ExceptionSample.DivideBy(Int32 i, Int32 j) in C:\Books\BCL\Samples\ System\Exception\Exception.cs:line 26
A B C D E F G
Exception() Constructor
H
[ILASM] public rtspecialname specialname instance void .ctor() [C#] public Exception()
I J K
Summary
L
Constructs and initializes a new instance of the System.Exception class.
M
Description
N
This constructor initializes the System.Exception.Message property of the new instance to a system-supplied message that describes the error and takes into account the current system culture. The System.Exception.InnerException property is initialized to null and the System.Exception.StackTrace property is initialized to System.String.Empty.
O P Q R S T
Exception(System.String) Constructor
U
[ILASM] public rtspecialname specialname instance void .ctor(string message) [C#] public Exception(string message)
V W X
Summary
Y
Constructs a new instance of the System.Exception class.
Z
1615
Contents | Index
Exception
System
Exception() Constructor
Parameters Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
A B C D E
Description
F
This constructor initializes the System.Exception.Message property of the new instance using message. If message is null, the System.Exception.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.Exception.InnerException property is initialized to null and the System.Exception.StackTrace property is initialized to System.String.Empty.
G H I J
Example
K
The following example demonstrates localizing the string supplied to the constructor of an exception object. In this example there are localized strings for en-AU and en-US. Depending on the thread’s current culture a different string is supplied to the constructor.
L M
using System; using System.Reflection; using System.Threading; using System.Globalization; using System.Resources; namespace Samples { public class ExceptionConstructor { public static void Main() { string[] strings = {"en-AU", "en-US", "en-NZ"}; foreach(string s in strings) { Thread.CurrentThread.CurrentCulture = new CultureInfo(s); ThrowException(); } } public static void ThrowException() { try { ResourceManager rm =
N O P Q R S T U V W X Y Z
1616
Contents | Index
System
Exception Exception() Constructor
new ResourceManager("strings", Assembly.GetExecutingAssembly()); throw new Exception(rm.GetString("ExceptionMessage", Thread.CurrentThread.CurrentCulture));
A
} catch(Exception e) { Console.WriteLine("Exception: {0}", e.Message); }
B C D
} }
E
}
F
The output is
G H
Exception: "#@*&!" Exception: "Doh!" Exception: "Do not normally throw instances of System.Exception: use derived classes instead"
I J K L
Exception(System.String, System.Exception) Constructor
M
[ILASM] public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException) [C#] public Exception(string message, Exception innerException)
N O P
Summary
Q
Constructs a new instance of the System.Exception class.
R S
Parameters
T
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
U V
innerException
W X
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
Y Z
1617
Contents | Index
Exception
System
Exception() Constructor
Description This constructor initializes the System.Exception.Message property of the new instance using message, and the System.Exception.InnerException property using innerException. If message is null, the System.Exception.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.Exception.StackTrace property is initialized to System.String.Empty.
A B C D E
Exception(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
F G
[ILASM] family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context) [C#] protected Exception(SerializationInfo info, StreamingContext context)
H I J K L
Summary
M
Initializes a new instance of the System.Exception class with serialized data.
N
Parameters
O P
Parameter
Description
info
The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown.
context
The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination.
Q R S T U V
Description
W
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
X Y Z
1618
Contents | Index
System
Exception HResult Property
Exceptions Exception
Condition
System.ArgumentNullException
The info parameter is null.
System.Runtime.Serialization.SerializationException
The class name is null or System.Exception.HResult is zero (0).
A B C D E F
Exception.HelpLink Property
G [ILASM] .property string HelpLink { public hidebysig virtual specialname string get_HelpLink() public hidebysig virtual specialname void set_HelpLink(string value) } [C#] public virtual string HelpLink { get; set; }
H I J K
Summary
L
Gets or sets a link to the help file associated with this exception.
M
Description
N
The return value, which represents a help file, is a Uniform Resource Name (URN) or Uniform Resource Locator (URL). For example, the HelpLink value could be:
O P
"file:///C:/Applications/Bazzal/help.html#ErrorNum42"
Q R
Exception.HResult Property
S
[ILASM] .property instance int32 HResult() [C#] public virtual int HResult { get; set; }
T U V W
Summary
X
Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.
Y
Property Value
Z
The HRESULT value.
1619
Contents | Index
Exception
System
InnerException Property
Description HRESULT is a 32-bit value, divided into three different fields: a severity code, a facility code, and an error code. The severity code indicates whether the return value represents information, warning, or error. The facility code identifies the area of the system responsible for the error. The error code is a unique number that is assigned to represent the exception. Each exception is mapped to a distinct HRESULT. When managed code throws an exception, the runtime passes the HRESULT to the COM client. When unmanaged code returns an error, the HRESULT is converted to an exception, which is then thrown by the runtime.
A B C D E F
Exception.InnerException Property
G [ILASM] .property class System.Exception InnerException { public hidebysig specialname instance class System.Exception get_InnerException() } [C#] public Exception InnerException { get; }
H I J K
Summary
L
Gets the System.Exception instance that caused the current exception.
M
Description
N
[Note: When an exception X is thrown as a direct result of a previous exception Y, the System.Exception.InnerException property of X should contain a reference to Y.] The System.Exception.InnerException property returns the same value as was passed into the constructor or null if the inner exception value was not supplied to the constructor. [Note: Using the System.Exception.InnerException property, you can obtain the set of exceptions that led to the current exception. System.Exception.GetBaseException includes an example that demonstrates this procedure.]
O P Q R S T U
Example
V
using System; namespace Samples { public class ExceptionConstructor { public static void Main() { try { DivideBy(42, 0);
W X Y Z
1620
Contents | Index
System
Exception Message Property
} catch(Exception e) { Console.WriteLine("Inner exception (if any): {0}", e.InnerException); }
A B
} public static int DivideBy(int i, int j) { try { return i / j; } catch(DivideByZeroException e) { throw new Exception( "Parameter j cannot be zero", e); } }
C D E F G H I J
}
K
}
L
The output is
M Inner exception (if any): System.DivideByZeroException: Attempted to divide by zero. at Samples.ExceptionConstructor.DivideBy(Int32 i, Int32 j) in C:\Books\BCL\Samples\System\Exception\InnerException\Exception.cs:line 23
N O P
Exception.Message Property
Q
[ILASM] .property string Message { public hidebysig virtual specialname string get_Message() } [C#] public virtual string Message { get; }
R S T U
Summary
V
Gets a System.String containing a message that describes the current exception.
W X
Property Value
Y
A System.String that contains a detailed description of the error, or System.String.Empty. This value is intended to be understood by humans.
Z
1621
Contents | Index
Exception
System
Message Property
Description [Note: The text of System.Exception.Message should completely describe the error and should, when possible, explain how to correct it. The value of the System.Exception.Message property is included in the information returned by System.Exception.ToString.]
A B C
Behaviors
D
The System.Exception.Message property is set only when creating an exception instance. If no message was supplied to the constructor for the current instance, the system supplies a default message that is formatted using the current system culture.
E F G H
How and When to Override
I
The System.Exception.Message property is overridden in classes that require control over message content or format.
J K
Usage
L
Application code typically accesses this property when there is a need to display information about an exception that has been caught.
M N
Example
O
using System; namespace Samples { public class ExceptionMessage { public static void Main() { try { DivideBy(42, 0); } catch(Exception e) { Console.WriteLine("Message: {0}", e.Message); } } public static int DivideBy(int i, int j) { return i / j; } } }
P Q R S T U V W X Y Z
1622
Contents | Index
System
Exception StackTrace Property
The output is Message: Attempted to divide by zero.
A B
Exception.Source Property
C [ILASM] .property string Source { public hidebysig virtual specialname string get_Source() public hidebysig virtual specialname void set_Source(string value) } [C#] public virtual string Source { get; set; }
D E F G
Summary
H
Gets or sets the name of the application or the object that causes the error.
I
Description
J
If System.Exception.Source is not set, the name of the assembly where the exception originated is returned.
K L M
Exception.StackTrace Property
N
[ILASM] .property string StackTrace { public hidebysig virtual specialname string get_StackTrace() } [C#] public virtual string StackTrace { get; }
O P Q R
Summary
S
Gets a System.String representation of the frames on the call stack at the time the current exception was thrown.
T U
Description
V
[Note: System.Exception.StackTrace may not report as many method calls as expected, due to code transformations, such as inlining, that occur during optimization.]
W
Behaviors
Y
The format of the information returned by this property is required to be identical to the format of the information returned by System.Environment.StackTrace.
Z
X
1623
Contents | Index
Exception
System
TargetSite Property
How and When to Override The System.Exception.StackTrace property is overridden in classes that require control over the stack trace content or format. A B
Usage
C
Use the System.Exception.StackTrace property to obtain a string representation of the contents of the call stack at the time the exception was thrown.
D E
Example
F
using System; namespace Samples { public class ExceptionStackTrace { public static void Main() { try { DivideBy(42, 0); } catch(Exception e) { Console.WriteLine("Stack trace: {0}", e.StackTrace); } } public static int DivideBy(int i, int j) { return i/j; } } }
G H I J K L M N O P Q R S
The output is
T
Stack trace: at Samples.ExceptionStackTrace.DivideBy(Int32 i, Int32 j) in C:\Books\BCL\Samples\System\Exception\StackTrace\Exception.cs:line 20 at Samples.ExceptionStackTrace.Main() in C:\Books\BCL\Samples\System\ Exception\StackTrace\Exception.cs:line 11
U V W X
Exception.TargetSite Property
Y
[ILASM] .property class System.Reflection.MethodBase TargetSite { public hidebysig specialname instance class System.Reflection.MethodBase get_TargetSite() } [C#] public MethodBase TargetSite { get; }
Z
1624
Contents | Index
System
Exception GetBaseException() Method
Summary Gets the method that throws the current exception.
Description
A
If the method that throws this exception is not available and the stack trace is not a null reference (Nothing in Visual Basic), System.Exception.TargetSite obtains the method from the stack trace. If the stack trace is a null reference, System.Exception.TargetSite also returns a null reference.
B C D E F
Exception.GetBaseException() Method
G [ILASM]
.method public hidebysig virtual class System.Exception GetBaseException()
H
[C#]
I
public virtual Exception GetBaseException()
J
Summary
K
Returns the System.Exception that is the root cause of one or more subsequent exceptions.
L M
Return Value
N
Returns the first exception thrown in a chain of exceptions. If the System.Exception.InnerException property of the current exception is null, returns the current exception.
O
Description
Q
[Note: A chain of exceptions consists of a set of exceptions such that each exception in the chain was thrown as a direct result of the exception referenced in its System.Exception.InnerException property. For a given chain, there can be exactly one exception that is the root cause of all other exceptions in the chain. This exception is called the baseexception and its System.Exception.InnerException property always contains a null reference.]
R
P
S T U V
Behaviors
W
For all exceptions in a chain of exceptions, the System.Exception.GetBaseException method is required to return the same object (the baseexception).
X Y Z
1625
Contents | Index
Exception
System
GetBaseException() Method
How and When to Override The System.Exception.GetBaseException method is overridden in classes that require control over the exception content or format. A
Usage
B
Use the System.Exception.GetBaseException method when you want to find the root cause of an exception but do not need information about exceptions that may have occurred between the current exception and the first exception.
C D E
Example
F
using System; namespace Samples { public class ExceptionConstructor { public static void Main() { try { DivideBy(42, 0); } catch(Exception e) { Console.WriteLine("BaseException (if any): {0}", e.GetBaseException()); } } public static int DivideBy(int i, int j) { try { return i / j; } catch(DivideByZeroException e) { throw new Exception( "Parameter j cannot be zero", e); } } } }
G H I J K L M N O P Q R S T U V W X Y
The output is
Z
BaseException (if any): System.DivideByZeroException: Attempted to divide by zero. at Samples.ExceptionConstructor.DivideBy(Int32 i, Int32 j) in C:\Books\BCL\Samples\System\Exception\GetBaseException()\Exception.cs:line 23
1626
Contents | Index
System
Exception GetObjectData() Method
Exception.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Method [ILASM] .method public hidebysig virtual void GetObjectData(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context) [C#] public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
A B C D E
Summary
F
When overridden in a derived class, sets the System.Runtime.Serialization.SerializationInfo with information about the exception.
G H
Parameters
I J
Parameter
Description
info
The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown.
context
The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination.
K L M N O
Description
P
GetObjectData sets a System.Runtime.Serialization.SerializationInfo with all the exception object data targeted for serialization. During deserialization, the exception is reconstituted from the SerializationInfo transmitted over the stream.
Q
Exceptions
T
R S
U
Exception
Condition
System.ArgumentNullException
The info parameter is a null reference (Nothing in Visual Basic).
V W X Y Z
1627
Contents | Index
Exception
System
ToString() Method
Exception.ToString() Method [ILASM] .method public hidebysig virtual string ToString() [C#] public override string ToString()
A B C
Summary
D
Creates and returns a System.String representation of the current exception.
E
Behaviors
F
System.Exception.ToString returns a representation of the current exception that is intended to be understood by humans. Where the exception contains culture-sensitive data, the string representation returned by System.Exception.ToString is required to take into account the current system culture. [Note: Although there are no exact requirements for the format of the returned string, it should as much as possible reflect the value of the object as perceived by the user.] [Note: This method overrides System.Object.ToString.]
G H I J K L
Default
M
The System.Exception.ToString implementation obtains the fully qualified name of the current exception, the message, the result of calling System.Exception.ToString on the inner exception, and the result of calling System.Environment.StackTrace. If any of these members is null or equal to System.String.Empty, its value is not included in the returned string.
N O P Q R
How and When to Override
S
It is recommended, but not required, that System.Exception.ToString be overridden to return information about members declared in the derived class. For example, the System.ArgumentException class overrides System.Exception.ToString so that it returns the value of the System.ArgumentException.ParamName property, if that value is not null.
T U V W
Usage
X
Use the System.Exception.ToString method to obtain a string representation of an exception.
Y Z
1628
Contents | Index
System ExecutionEngineException
BCL
Object Exception
ISerializable
A
NotStandardized
B
SystemException ExecutionEngineException
C D
Summary
E
Represents an internal error in the execution engine.
F G
Type Summary CF public sealed class ExecutionEngineException : SystemException { // Constructors CF public ExecutionEngineException (); CF public ExecutionEngineException (string message); CF public ExecutionEngineException (string message, Exception innerException); }
H I J K L M N
BA Notice that even though this exception is not meant to be thrown by user code, we still include the pattern of exception constructors for consistency. During the standardization process we decided we would not attempt to justify following the exception constructor pattern, as we would inevitably get it wrong by missing some legitimate cases for throwing the exception. One concrete reason for needing these constructors is for testing code that wants to simulate an ExecutionEngineException being thrown.
O
BG Honestly, if you ever get an execution engine exception, you’re almost guaran-
T
teed that you won’t be able to recover from it. Common reasons for seeing this exception with the Microsoft CLI implementation include things like a corrupt unmanaged heap, meaning that the CLR’s internal data structures are broken, or possibly a bug in the GC. You should only see these if you’ve hit a bug in the CLR, or possibly if you’ve corrupted native memory with unsafe code, COM Interop, or P/Invoke.
U
P Q R S
V W X Y Z
1629
Contents | Index
ExecutionEngineException
System
ExecutionEngineException() Constructor
Description [Note: Execution engine errors are fatal errors that should never occur. Such errors occur mainly when the execution engine has been corrupted or data is missing. The system can throw this exception at any time. When possible, the system throws an exception that provides more information than the System.ExecutionEngineException exception. For information on conditions under which the CLI throws System.ExecutionEngineException exceptions, see Partition II of the CLI Specification. Applications should not throw System.ExecutionEngineException.]
A B C D E F
ExecutionEngineException() Constructor
G [ILASM] public rtspecialname specialname instance void .ctor() [C#] public ExecutionEngineException()
H I J K
Summary
L
Constructs and initializes a new instance of the System.ExecutionEngineException class.
M N
Description
O
This constructor initializes the System.ExecutionEngineException.Message property of the new instance to a system-supplied message that describes the error, such as “Internal error occurred.” This message takes into account the current system culture. The System.ExecutionEngineException.InnerException property is initialized to null.
P Q R S T
ExecutionEngineException(System.String) Constructor
U
[ILASM] public rtspecialname specialname instance void .ctor(string message) [C#] public ExecutionEngineException(string message)
V W X
Summary
Y
Constructs and initializes a new instance of the System.ExecutionEngineException class.
Z
1630
Contents | Index
System
ExecutionEngineException ExecutionEngineException() Constructor
Parameters Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
A B C D
Description
E
This constructor initializes the System.ExecutionEngineException.Message property of the new instance using message. If message is null, the System.ExecutionEngineException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.ExecutionEngineException.InnerException property is initialized to null.
F G H I J
ExecutionEngineException(System.String, System.Exception) Constructor
K L
[ILASM] public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException) [C#] public ExecutionEngineException(string message, Exception innerException)
M N O
Summary
P
Constructs and initializes a new instance of the System.ExecutionEngineException class.
Q R S
Parameters
T
Parameter
Description
U V
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
W X Y Z
1631
Contents | Index
ExecutionEngineException
System
ExecutionEngineException() Constructor
Description This constructor initializes the System.ExecutionEngineException.Message property of the new instance using message and the System.ExecutionEngineException.InnerException property using innerException. If message is null, the System.ExecutionEngineException.Message property is initialized to the systemsupplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1632
Contents | Index
System.IO File
BCL
Object
A
File
B
Summary
C
Provides information and performs operations on files.
D
Type Summary
E
public sealed class File { // Methods public static StreamWriter AppendText (string path); public static void Copy (string sourceFileName, string destFileName); public static void Copy (string sourceFileName, string destFileName, bool overwrite); public static FileStream Create (string path); public static FileStream Create (string path, int bufferSize); public static StreamWriter CreateText (string path); public static void Delete (string path); public static bool Exists (string path); MS CF public static FileAttributes GetAttributes (string path); public static DateTime GetCreationTime (string path); MS CF 1.1 public static DateTime GetCreationTimeUtc (string path); public static DateTime GetLastAccessTime (string path); MS CF 1.1 public static DateTime GetLastAccessTimeUtc (string path); public static DateTime GetLastWriteTime (string path); MS CF 1.1 public static DateTime GetLastWriteTimeUtc (string path); public static void Move (string sourceFileName, string destFileName); public static FileStream Open (string path, FileMode mode); public static FileStream Open (string path, FileMode mode, FileAccess access); public static FileStream Open (string path, FileMode mode, FileAccess access, FileShare share); public static FileStream OpenRead (string path); public static StreamReader OpenText (string path); public static FileStream OpenWrite (string path); MS CF public static void SetAttributes (string path, FileAttributes fileAttributes);
F G H I J K L M N O P Q R S T U V W X Y Z
1633
Contents | Index
File
System.IO
File Class
CF public static void SetCreationTime (string path, DateTime creationTime); MS CF 1.1 public static void SetCreationTimeUtc (string path, DateTime creationTimeUtc); CF public static void SetLastAccessTime (string path, DateTime lastAccessTime); MS CF 1.1 public static void SetLastAccessTimeUtc (string path, DateTime lastAccessTimeUtc); CF public static void SetLastWriteTime (string path, DateTime lastWriteTime); MS CF 1.1 public static void SetLastWriteTimeUtc (string path, DateTime lastWriteTimeUtc); }
A B C D E F G H
BA You will notice that the File class is not instantiable; it is merely a container for utility methods for working with a file on disk. During the design of the IO namespace we had much debate about providing a type whose instances represent a file on disk. Ultimately we decided against that design because it is very difficult to keep the state in the instance synchronized with the file system. For example, if a file gets renamed on disk we need to refresh the Name property which means we’d have to check everytime the Name property is accessed. And if the file gets deleted on disk, how would the object know that its data should be invalidated? This type of synchronization issue led us to believe that that it is a simpler model to have class with just static methods on it to perform operations on files.
I J K L M N O P
Description
Q
Implementations of this class are required to preserve the case of path strings. Implementations are required to be case sensitive if and only if the platform is case-sensitive. The following table describes the enumerations that are used to customize the behavior of various System.IO.File methods.
R S T U V
Enumeration
Description
W
System.IO.FileAccess
Specifies read and write access to a file.
System.IO.FileShare
Specifies the level of access permitted for a file that is already in use.
System.IO.FileMode
Specifies whether the contents of an existing file are preserved or overwritten, and whether requests to create an existing file cause an exception.
X Y Z
1634
Contents | Index
System.IO
File AppendText() Method
Example using System; using System.IO; namespace Samples { public class FileSample { public static void Main() { string s = @"File.txt"; if(File.Exists(s)) { Console.WriteLine("File {0} already exists", s); File.Delete(s); } using(StreamWriter sw = File.CreateText(s)) { Console.WriteLine("Can read: {0}", sw.BaseStream.CanRead); Console.WriteLine("Can write: {0}", sw.BaseStream.CanWrite); sw.WriteLine(DateTime.Now); } } } }
A B C D E F G H I J K L M N O
The output is
P
File File.txt already exists Can read: False Can write: True
Q R S T
File.AppendText(System.String) Method
U [ILASM] .method public hidebysig static class System.IO.StreamWriter AppendText(string path) [C#] public static StreamWriter AppendText(string path)
V W X Y
Summary
Z
Appends UTF-8 encoded text to an existing file.
1635
Contents | Index
File
System.IO
AppendText() Method
Parameters Parameter
Description
path
A System.String containing the name of the file to append to.
A B C
Description
D
This method is equivalent to System.IO.StreamWriter(path, true). If the file specified by path does not exist, it is created. If the file does exist, writes to the System.IO.StreamWriter append text to the file. Additional threads are permitted to read the file while it is open. The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
E F G H I J
Exceptions
K L
Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more invalid characters.
System.ArgumentNullException
path is null.
System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
System.IO.FileNotFoundException
path was not found.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
M N O P Q R S T U V W X Y Z
1636
Contents | Index
System.IO
File Copy() Method
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to write the specified file. See System.Security.Permissions.FileIOPermissionAccess.Write.
A B C D
Example
E
using System; using System.IO; namespace Samples { public class FileAppendText { public static void Main() { string s = Directory.GetCurrentDirectory() + @"\FileAppendText.txt"; using(TextWriter output = File.AppendText(s)) { Console.WriteLine("Encoding: {0}", tw.Encoding); Console.WriteLine("Format provider: {0}", tw.FormatProvider); output.WriteLine(DateTime.Now); } } } }
F G H I J K L M N O P Q R
The output is
S T
Encoding: System.Text.UTF8Encoding Format provider: en-AU
U V
File.Copy(System.String, System.String) Method
W X
[ILASM] .method public hidebysig static void Copy(string sourceFileName, string destFileName) [C#] public static void Copy(string sourceFileName, string destFileName)
Y Z
1637
Contents | Index
File
System.IO
Copy() Method
Summary Copies the specified file to a new location. A
Parameters
B C
Parameter
Description
D
sourceFileName
A System.String containing the name of the file to copy.
destFileName
A System.String containing the name of the destination file. Cannot specify a directory or an existing file.
E F G H
Description
I
This method is equivalent to System.IO.File.Copy(sourceFileName, destFileName, false). The sourceFileName and destFileName arguments are permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
J K L M
Exceptions
N O
Exception
P Q
System.ArgumentException
R S
Condition sourceFileName or destFileName is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters. -orsourceFileName or destFileName specifies a directory.
T U V
System.ArgumentNullException
sourceFileName or destFileName is null.
System.IO.DirectoryNotFoundException
Directory information in sourceFileName or destFileName was not found.
System.IO.FileNotFoundException
sourceFileName was not found.
W X Y
destFileName exists.
Z
System.IO.IOException
-orAn I/O error occurred.
1638
Contents | Index
System.IO
File Copy() Method
Exception
Condition
System.IO.PathTooLongException
The length or the absolute path information for sourceFileName or destFileName exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
A B C D E
Permissions
F
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to read the source file and write the destination file. See System.Security.Permissions.FileIOPermissionAccess.Read and System.Security.Permissions.FileIOPermissionAccess.Write.
G H I J K L
Example
M
using System; using System.IO; namespace Samples { public class FileCopy { public static void Main() { string s = Directory.GetCurrentDirectory(); string original = s + @"\original.txt"; string target = s + @"\target.txt"; if(File.Exists(target)) File.Delete(target); File.Copy(original, target); Console.WriteLine("File created at: {0}", File.GetCreationTime(target)); File.Delete(target); } } }
N O P Q R S T U V W X Y
The output is
Z
File created at: 11/06/2003 4:16:07 PM
1639
Contents | Index
File
System.IO
Copy() Method
File.Copy(System.String, System.String, System.Boolean) Method [ILASM] .method public hidebysig static void Copy(string sourceFileName, string destFileName, bool overwrite) [C#] public static void Copy(string sourceFileName, string destFileName, bool overwrite)
A B C D
Summary
E
Copies the specified file to a new location.
F G
Parameters
H I J K
Parameter
Description
sourceFileName
A System.String containing the name of the file to copy.
destFileName
A System.String containing the name of the destination file. Cannot specify the name of a directory.
overwrite
A System.Boolean value. Specify true if the destination file can be overwritten; otherwise false.
L M N O
Description
P
The sourceFileName and destFileName arguments are permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
Q R S
Exceptions
T U
Exception
V W
System.ArgumentException
X Y
Condition sourceFileName or destFileName is a zero-length string, contains only white space, or contains one or more invalid characters. -orsourceFileName or destFileName specifies a directory.
Z
System.ArgumentNullException
sourceFileName or destFileName is null.
1640
Contents | Index
System.IO
File Copy() Method
Exception
Condition
System.IO.DirectoryNotFoundException
Directory information in destFileName or sourceFileName was not found.
A B
System.IO.FileNotFoundException
System.IO.IOException
sourceFileName was not found.
C
destFileName is read-only (write-protected), or destFileName exists and overwrite is false.
D E
-or-
F
An I/O error occurred. G System.IO.PathTooLongException
The length or the absolute path information for sourceFileName or destFileName exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
H I J K
Permissions
L M
Permission
Description N
System.Security.Permissions.FileIOPermission
Requires permission to read the source file and write the destination file. See System.Security.Permissions.FileIOPermissionAccess.Read and System.Security.Permissions.FileIOPermission-Access.Write.
O P Q R S
Example
T
using System; using System.IO; namespace Samples { public class FileCopy { public static void Main() { string s = Directory.GetCurrentDirectory(); string original = s + @"\original.txt"; string target = s + @"\target.txt"; File.Copy(original, target, true);
U V W X Y Z
1641
Contents | Index
File
System.IO
Create() Method
Console.WriteLine("File created at: {0}", File.GetCreationTime(target)); } }
A
}
B
The output is
C
File created at: 8/04/2003 11:22:33 AM
D E F
File.Create(System.String) Method
G
[ILASM] .method public hidebysig static class System.IO.FileStream Create(string path) [C#] public static FileStream Create(string path)
H I J
Summary
K
Creates or overwrites the specified file.
L
Parameters
M N
Parameter
Description
path
A System.String containing the name of the file.
O P Q R
Return Value
S
A System.IO.FileStream that provides read/write access to the specified file.
T
Description
U
If the specified file does not exist, it is created; if it does exist and it is not read-only, the contents are overwritten. The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
V W X Y Z
1642
Contents | Index
System.IO
File Create() Method
Exceptions Exception
Condition A
System.ArgumentNullException
path is null.
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
System.IO.IOException
An I/O error occurred while creating the file.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
B C D E F G H I J K L
Permissions
M N
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to write the specified file. See System.Security.Permissions.FileIOPermissionAccess.Write.
O P Q R
Example
S
using System; using System.IO; namespace Samples { public class FileCreate { public static void Main() { string s = Directory.GetCurrentDirectory() + @"\filecreate.txt"; using(FileStream output = File.Create(s))
T U V W X Y Z
1643
Contents | Index
File
System.IO
Create() Method
{ Console.WriteLine("Name: {0}", output.Name); } }
A
} }
B C
The output is
D Name: C:\Books\BCL\Samples\System.IO\File\Create(System.String)\filecreate.txt
E F
File.Create(System.String, System.Int32) Method
G
[ILASM] .method public hidebysig static class System.IO.FileStream Create(string path, int32 bufferSize) [C#] public static FileStream Create(string path, int bufferSize)
H I J K
Summary
L
Creates or overwrites the specified file.
M N
Parameters
O P Q
Parameter
Description
path
A System.String containing the name of the file.
bufferSize
A System.Int32 containing the number of bytes buffered for reads and writes to the file.
R S T U
Return Value
V
A System.IO.FileStream that provides read/write access to the specified file.
W
Description
X
This method is equivalent to System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None, bufferSize). If the specified file does not exist, it is created; if it does exist and it is not read-only, the contents are overwritten.
Y Z
1644
Contents | Index
System.IO
File Create() Method
The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.] A
Exceptions
B
Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
C D E F
System.ArgumentNullException
path is null.
System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
System.IO.IOException
An I/O error occurred while creating the file.
J
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
K
System.UnauthorizedAccessException
The caller does not have the required permission.
G H I
L M N O
Permissions
P
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to write the specified file. See System.Security.Permissions.FileIOPermissionAccess.Write.
Q R S T U
Example
V
using System; using System.IO; namespace Samples { public class FileCreate { public static void Main() { string s = Directory.GetCurrentDirectory() +
W X Y Z
1645
Contents | Index
File
System.IO
CreateText() Method
@"\filecreate.txt"; using(FileStream output = File.Create(s, 512)) { Console.WriteLine("Name: {0}", output.Name); }
A }
B }
C
}
D
The output is
E Name: C:\Books\BCL\Samples\System.IO\File\Create(System.String,System.Int32)\ filecreate.txt
F G H
File.CreateText(System.String) Method
I [ILASM] .method public hidebysig static class System.IO.StreamWriter CreateText(string path) [C#] public static StreamWriter CreateText(string path)
J K L M
Summary
N
Creates or opens a new file for writing UTF-8 encoded text.
O
Parameters
P Q R S
Parameter
Description
path
The file to be opened for writing.
T U
Description
V
This method is equivalent to System.IO.StreamWriter(path, false). If the file specified by path does not exist, it is created. If the file does exist, its contents are overwritten. Additional threads are permitted to read the file while it is open. The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.
W X Y Z
1646
Contents | Index
System.IO
File CreateText() Method
Exceptions Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more invalid characters.
System.ArgumentNullException
path is null.
System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
A B C D E F G H I J K
Permissions
L
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to write the specified file. See System.Security.Permissions.FileIOPermissionAccess.Write.
M N O P Q
Example
R
using System; using System.IO; namespace Samples { public class FileCreateText { public static void Main() { string s = Directory.GetCurrentDirectory() + @"\createtext.txt"; using(StreamWriter sw = File.CreateText(s)) { Console.WriteLine("Can read: {0}", sw.BaseStream.CanRead);
S T U V W X Y Z
1647
Contents | Index
File
System.IO
Delete() Method
Console.WriteLine("Can write: {0}", sw.BaseStream.CanWrite); } }
A
} }
B C
The output is
D Can read: False Can write: True
E F G
File.Delete(System.String) Method
H
[ILASM] .method public hidebysig static void Delete(string path) [C#] public static void Delete(string path)
I J K
Summary
L
Deletes the specified file.
M N
Parameters
O P Q
Parameter
Description
path
A System.String containing the name of the file to be deleted.
R S
Description
T
The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.] [Note: Some implementations may throw System.IO.IOException to cover such platform-specific conditions as “file in use”.]
U V W X Y Z
1648
Contents | Index
System.IO
File Delete() Method
Exceptions Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.ArgumentNullException
path is null.
System.UnauthorizedAccessException
path identifies a directory.
System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
A B C D E F G H I J System.UnauthorizedAccessException
The caller does not have the required permission.
K L M
Permissions
N
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to write to the specified file. See System.Security.Permissions.FileIOPermissionAccess.Write.
O P Q R S
Example
T
using System; using System.IO; namespace Samples { public class FileDelete { public static void Main() { string s = Directory.GetCurrentDirectory() + @"\delete.txt"; if(!File.Exists(s)) {
U V W X Y Z
1649
Contents | Index
File
System.IO
Exists() Method
using(FileStream output = File.Create(s)) { Console.WriteLine("Creating: {0}", output.Name); }
A
} File.Delete(s);
B }
C
} }
D
The output is
E F
Creating: C:\Books\BCL\Samples\System.IO\File\Delete(System.String)\delete.txt
G H
File.Exists(System.String) Method
I [ILASM] .method public hidebysig static bool Exists(string path) [C#] public static bool Exists(string path)
J K L M
Summary
N
Returns a System.Boolean indicating whether the specified file exists.
O
Parameters
P Q R
Parameter
Description
path
A System.String containing the name of the file to check.
S T
Return Value
U
true if the caller has the required permissions and path contains the name of an existing file; otherwise, false. If path is null or a zero-length string, returns false.
V W
Description
X
If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path. The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
Y Z
1650
Contents | Index
System.IO
File GetAttributes() Method
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to read the specified file. See System.Security.Permissions.FileIOPermissionAccess.Read.
A B C D
Example
E
using System; using System.IO; namespace Samples { public class FileExists { public static void Main() { string s = Directory.GetCurrentDirectory() + @"\Exists.txt"; using(FileStream output = File.Create(s)) { Console.WriteLine("Creating: {0}", output.Name); } if(File.Exists(s)) Console.WriteLine("File {0} exists", s); File.Delete(s); if(!File.Exists(s)) Console.WriteLine("File {0} does not exist", s); } } }
F G H I J K L M N O P Q R
The output is
S
Creating: C:\Books\BCL\Samples\System.IO\File\Exists(System.String)\Exists.txt File C:\Books\BCL\Samples\System.IO\File\Exists(System.String)\Exists.txt exists File C:\Books\BCL\Samples\System.IO\File\Exists(System.String)\Exists.txt does not exist
T U V W
File.GetAttributes(System.String) Method
X
[ILASM] .method public hidebysig static valuetype System.IO.FileAttributes GetAttributes(string path) [C#] public static FileAttributes GetAttributes(string path)
Y Z
1651
Contents | Index
File
System.IO
GetAttributes() Method
Summary Gets the System.IO.FileAttributes of the file on the path. A
Parameters
B C
Parameter
Description
D
path
The path to the file.
E F
Return Value
G
The System.IO.FileAttributes of the file on the path, or –1 if the path or file is not found.
H I
Description
J
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.
K L M
Exceptions
N O P Q
Exception
Condition
System.ArgumentException
path is empty, contains only white spaces, or contains invalid characters.
System.IO.PathTooLongException
The specified path, file name, or both exceed the systemdefined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
System.NotSupportedException
path is in an invalid format.
System.IO.DirectoryNotFoundException
The specified path is invalid, such as being on an unmapped drive.
R S T U V W X Y Z
1652
Contents | Index
System.IO
File GetCreationTime() Method
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
For reading files. Associated enumeration: System.Security.Permissions.FileIOPermissionAccess.Read.
A B C D E
File.GetCreationTime(System.String) Method
F
[ILASM] .method public hidebysig static valuetype System.DateTime GetCreationTime(string path) [C#] public static DateTime GetCreationTime(string path)
G H I J
Summary
K
Returns the creation date and time of the specified file or directory.
L M
Parameters
N
Parameter
Description
path
A System.String containing the name of the file or directory for which to obtain creation date and time information.
O P Q R
Return Value
S
A System.DateTime structure set to the creation date and time for the specified file or directory. This value is expressed in local time. Platforms that do not support this feature return System.DateTime.MinValue.
T U V
Description
W
The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
X Y Z
1653
Contents | Index
File
System.IO
GetCreationTime() Method
Exceptions Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.ArgumentNullException
path is null.
System.IO.IOException
path was not found.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
A B C D E F G H I J K
Permissions
L M N O
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to read the specified file or directory. See System.Security.Permissions.FileIOPermissionAccess.Read.
P Q
Example
R
using System; using System.IO; namespace Samples { public class FileGetCreationTime { public static void Main() { string s = @"getcreationtime.txt"; if(!File.Exists(s)) { using(FileStream output = File.Create(s)) { Console.WriteLine("Creating: {0}", output.Name); } }
S T U V W X Y Z
1654
Contents | Index
System.IO
File GetCreationTimeUtc() Method
Console.WriteLine("File: {0} created at {1}", s, File.GetCreationTime(s)); } }
A
}
B
The output is
C
File: getcreationtime.txt created at 8/04/2003 11:46:09 AM
D E
File.GetCreationTimeUtc(System.String) Method
F
[ILASM] .method public hidebysig static valuetype System.DateTime GetCreationTimeUtc(string path) [C#] public static DateTime GetCreationTimeUtc(string path)
G H I J
Summary
K
Returns the creation date and time, in coordinated universal time (UTC), of the specified file or directory.
L M N
Parameters
O
Parameter
Description
P
path
The file or directory for which to obtain creation date and time information.
Q R S
Exceptions
T
Exception
Condition
System.UnauthorizedAccessException
The caller does not have the required permission.
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by System.IO.Path.InvalidPathChars.
System.ArgumentNullException
path is null.
U V W X Y Z
1655
Contents | Index
File
System.IO
GetLastAccessTime() Method
Exception
Condition
System.IO.PathTooLongException
The specified path, file name, or both exceed the systemdefined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
D
System.IO.IOException
path was not found.
E
System.NotSupportedException
path is in an invalid format.
A B C
F G
Permissions
H I
Permission
Description
System.Security.Permissions.FileIOPermission
For reading from the specified file. Associated enumeration: System.Security.Permissions.FileIOPermissionAccess.Read.
J K L M N
File.GetLastAccessTime(System.String) Method
O [ILASM] .method public hidebysig static valuetype System.DateTime GetLastAccessTime(string path) [C#] public static DateTime GetLastAccessTime(string path)
P Q R S
Summary
T
Returns the date and time the specified file or directory was last accessed.
U
Parameters
V W
Parameter
Description
path
A System.String containing the name of the file or directory for which to obtain access date and time information.
X Y Z
1656
Contents | Index
System.IO
File GetLastAccessTime() Method
Return Value A System.DateTime structure set to the date and time the specified file or directory was last accessed. This value is expressed in local time. Platforms that do not support this feature return System.DateTime.MinValue.
A B
Description
C
The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
D E F
Exceptions
G
Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.ArgumentNullException
path is null.
System.IO.IOException
path was not found.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
H I J K L M N O P Q R
Permissions
S
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to read the specified file or directory. See System.Security.Permissions.FileIOPermissionAccess.Read.
T U V W X Y Z
1657
Contents | Index
File
System.IO
GetLastAccessTimeUtc() Method
Example using System; using System.IO; namespace Samples { public class FileGetLastAccessTime { public static void Main() { string s = @"GetLastAccessTime.txt"; if(!File.Exists(s)) { using(FileStream output = File.Create(s)) { Console.WriteLine("Creating: {0}", output.Name); } } Console.WriteLine("File: {0} last accessed at {1}", s, File.GetLastAccessTime(s)); } } }
A B C D E F G H I J K L
The output is
M
File: GetLastAccessTime.txt last accessed at 15/05/2003 2:11:49 PM
N O
File.GetLastAccessTimeUtc(System.String) Method
P
[ILASM] .method public hidebysig static valuetype System.DateTime GetLastAccessTimeUtc(string path) [C#] public static DateTime GetLastAccessTimeUtc(string path)
Q R S T U
Summary
V
Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last accessed.
W
Parameters
X Y Z
Parameter
Description
path
The file or directory for which to obtain access date and time information.
1658
Contents | Index
System.IO
File GetLastWriteTime() Method
Description The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.
A B
Exceptions
C
Exception
Condition
System.UnauthorizedAccessException
The caller does not have the required permission.
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by System.IO.Path.InvalidPathChars.
System.ArgumentNullException
path is null.
System.IO.PathTooLongException
The specified path, file name, or both exceed the systemdefined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
System.IO.IOException
The specified path was not found.
System.NotSupportedException
path is in an invalid format.
D E F G H I J K L M N O P Q
Permissions
R
Permission
Description
S
For reading from the specified file. Associated enumeration: System.Security.Permissions.FileIOPermissionAccess.Read.
T
System.Security.Permissions.FileIOPermission
U V W
File.GetLastWriteTime(System.String) Method
X Y
[ILASM] .method public hidebysig static valuetype System.DateTime GetLastWriteTime(string path) [C#] public static DateTime GetLastWriteTime(string path)
Z
1659
Contents | Index
File
System.IO
GetLastWriteTime() Method
Summary Returns the date and time the specified file or directory was last written to. A
Parameters
B C
Parameter
Description
path
A System.String containing the name of the file for which to obtain write date and time information.
D E F
Return Value
G
A System.DateTime structure set to the date and time the specified file or directory was last written to. This value is expressed in local time. Platforms that do not support this feature return System.DateTime.MinValue.
H I J
Description
K
The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
L M N
Exceptions
O P
Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.ArgumentNullException
path is null.
U
System.IO.IOException
path was not found.
V
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
Q R S T
W X Y Z
1660
Contents | Index
System.IO
File GetLastWriteTimeUtc() Method
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to read the specified file or directory. See System.Security.Permissions.FileIOPermissionAccess.Read.
A B C D
Example
E
using System; using System.IO; namespace Samples { public class FileGetLastWriteTime { public static void Main() { string s = @"GetLastWriteTime.txt"; if(!File.Exists(s)) { using(FileStream output = File.Create(s)) { Console.WriteLine("Creating: {0}", output.Name); } } Console.WriteLine("File: {0} last written at {1}", s, File.GetLastWriteTime(s)); } } }
F G H I J K L M N O P Q R S
The output is
T File: GetLastWriteTime.txt last written at 15/12/2002 10:33:02 PM
U V
File.GetLastWriteTimeUtc(System.String) Method
W
[ILASM] .method public hidebysig static valuetype System.DateTime GetLastWriteTimeUtc(string path) [C#] public static DateTime GetLastWriteTimeUtc(string path)
X Y Z
1661
Contents | Index
File
System.IO
GetLastWriteTimeUtc() Method
Summary Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last written to. A
Parameters
B C D E
Parameter
Description
path
The file or directory for which to obtain write date and time information.
F G
Description
H
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.
I J
Exceptions
K L
Exception
Condition
System.UnauthorizedAccessException
The caller does not have the required permission.
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by System.IO.Path.InvalidPathChars.
System.ArgumentNullException
path is null.
System.IO.PathTooLongException
The specified path, file name, or both exceed the systemdefined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
W
System.IO.IOException
The specified path was not found.
X
System.NotSupportedException
path is in an invalid format.
M N O P Q R S T U V
Y Z
1662
Contents | Index
System.IO
File Move() Method
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
For reading from the specified file. Associated enumeration: System.Security.Permissions.FileIOPermissionAccess.Read.
A B C D E
File.Move(System.String, System.String) Method
F
[ILASM] .method public hidebysig static void Move(string sourceFileName, string destFileName) [C#] public static void Move(string sourceFileName, string destFileName)
G H I
Summary
J
Moves the specified file to a new location.
K L
Parameters
M
Parameter
Description
sourceFileName
A System.String containing the name of the file to move.
destFileName
A System.String containing the name of the new location for the file.
N O P Q R
Description
S
This method does not throw an exception if the source and destination are the same. The sourceFileName and destFileName arguments are permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
T U V W X Y Z
1663
Contents | Index
File
System.IO
Move() Method
Exceptions Exception
Condition
System.ArgumentException
sourceFileName or destFileName is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.ArgumentNullException
sourceFileName or destFileName is null.
System.IO.DirectoryNotFoundException
The directory information in sourceFileName or destFileName was not found.
System.IO.FileNotFoundException
sourceFileName was not found or specifies a directory.
System.IO.IOException
The destination file is read-only or destFileName is a directory.
System.IO.PathTooLongException
The length or absolute path information for sourceFileName or destFileName exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
A B C D E F G H I J K L M N O
Permissions
P Q
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to read from sourceFileName, and write to sourceFileName and destFileName. See System.Security.Permissions.FileIOPermissionAccess.Read and System.Security.Permissions.FileIOPermissionAccess.Write.
R S T U V W
Example
X
using System; using System.IO; namespace Samples { public class FileMove { public static void Main()
Y Z
1664
Contents | Index
System.IO
File Open() Method
{ string original = "move1.txt", target = "move2.txt"; if(!File.Exists(original)) { using(FileStream output = File.Create(original)) { Console.WriteLine("Creating: {0}", output.Name); } } if(File.Exists(target)) { Console.WriteLine("Deleting: {0}", target); File.Delete(target); } File.Move("move1.txt", "move2.txt");
A B C D E F G H
}
I
} }
J K
The output is
L
Creating: C:\Books\BCL\Samples\System.IO\File\ Move(System.String,System.String)\move1.txt Deleting: move2.txt
M N O
File.Open(System.String, System.IO.FileMode) Method
P
[ILASM] .method public hidebysig static class System.IO.FileStream Open(string path, valuetype System.IO.FileMode mode) [C#] public static FileStream Open(string path, FileMode mode)
Q R S T
Summary
U
Opens a System.IO.FileStream on the specified file with read/write access.
V W X Y Z
1665
Contents | Index
File
System.IO
Open() Method
Parameters Parameter
Description
path
A System.String containing the name of the file to open.
mode
A System.IO.FileMode value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.
A B C D E F
Description
G
This method is equivalent to System.IO.FileStream(path, mode, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None). The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
H I J K
Exceptions
L M N O P Q R
Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.ArgumentNullException
path is null.
System.ArgumentOutOfRangeException
mode specified an invalid value.
S
path specified a read-only file (this method attempts to open the file with read/write access).
T U
System.UnauthorizedAccessException
V
-orThis operation is not supported on the current platform. -or-
W
path specified a directory.
X Y Z
System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
System.IO.FileNotFoundException
path was not found.
1666
Contents | Index
System.IO
File Open() Method
Exception
Condition
System.IO.IOException
An I/O error occurred while opening the file.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
A B C D E F
Permissions
G
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to read and write the file. See System.Security.Permissions.FileIOPermissionAccess.Read and System.Security.Permissions.FileIOPermissionAccess.Write.
H I J K L
Example
M
using System; using System.IO; namespace Samples { public class FileOpen { public static void Main() { string s = "open.txt"; using(FileStream fs = File.Open(s, FileMode.OpenOrCreate)) { Console.WriteLine("Can read from {0}: {1}", s, fs.CanRead); Console.WriteLine("Can write to {0}: {1}", s, fs.CanWrite); Console.WriteLine("Can seek in {0}: {1}", s, fs.CanSeek); Console.WriteLine("Async access to {0}: {1}", s, fs.IsAsync); } } } }
N O P Q R S T U V W X Y Z
1667
Contents | Index
File
System.IO
Open() Method
The output is Can read from open.txt: True Can write to open.txt: True Can seek in open.txt: True Async access to open.txt: False
A B C D
File.Open(System.String, System.IO.FileMode, System.IO.FileAccess) Method
E F
[ILASM] .method public hidebysig static class System.IO.FileStream Open(string path, valuetype System.IO.FileMode mode, valuetype System.IO.FileAccess access) [C#] public static FileStream Open(string path, FileMode mode, FileAccess access)
G H I J
Summary
K
Opens a System.IO.FileStream on the specified file.
L
Parameters
M N O
Parameter
Description
path
A System.String containing the name of the file to open.
mode
A System.IO.FileMode value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.
access
A System.IO.FileAccess value that specifies the operations that can be performed on the file.
P Q R S T U
Description
V
This method is equivalent to System.IO.FileStream(path, mode, access, System.IO.FileShare.None). The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
W X Y Z
1668
Contents | Index
System.IO
File Open() Method
Exceptions Exception
Condition A
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
B
-or-
C
access specified Read and mode specified Create, CreateNew, Truncate, or Append.
D E
System.ArgumentNullException
path is null.
System.ArgumentOutOfRangeException
mode or access specified an invalid value.
System.UnauthorizedAccessException
path specified a read-only file and access is not Read, or path specified a directory.
System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
System.IO.FileNotFoundException
path was not found.
System.IO.IOException
An I/O error occurred while opening the file.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
F G H I J K L M N O P Q
System.UnauthorizedAccessException
R
The caller does not have the required permission.
S T
Permissions
U
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to read and may also require permission to write the file. See System.Security.Permissions.FileIOPermissionAccess.Read and System.Security.Permissions.FileIOPermissionAccess.Write.
V W X Y Z
1669
Contents | Index
File
System.IO
Open() Method
Example using System; using System.IO; namespace Samples { public class FileOpen { public static void Main() { string s = "open.txt"; using(FileStream fs = File.Open(s, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { Console.WriteLine("Can read from {0}: {1}", s, fs.CanRead); Console.WriteLine("Can write to {0}: {1}", s, fs.CanWrite); Console.WriteLine("Can seek in {0}: {1}", s, fs.CanSeek); Console.WriteLine("Async access to {0}: {1}", s, fs.IsAsync); } } } }
A B C D E F G H I J K L M N O
The output is
P
Can read from open.txt: True Can write to open.txt: True Can seek in open.txt: True Async access to open.txt: False
Q R S T
File.Open(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare) Method
U V
[ILASM] .method public hidebysig static class System.IO.FileStream Open(string path, valuetype System.IO.FileMode mode, valuetype System.IO.FileAccess access, valuetype System.IO.FileShare share) [C#] public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share)
W X Y Z
1670
Contents | Index
System.IO
File Open() Method
Summary Opens a System.IO.FileStream on the specified file. A
Parameters
B
Parameter
Description
C
path
A System.String containing the name of the file to open.
D
A System.IO.FileMode value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.
E
mode
access
A System.IO.FileAccess value that specifies the operations that can be performed on the file.
share
A System.IO.FileShare value specifying the type of access other threads have to the file.
F G H I J K
Description
L
This method is equivalent to System.IO.FileStream(path, mode, access, share). The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
M N O P
Exceptions
Q
Exception
Condition
R S
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters. -oraccess specified Read and mode specified Create, CreateNew, Truncate, or Append.
System.ArgumentNullException
T U V W
path is null.
X System.ArgumentOutOfRangeException
mode, access, or share specified an invalid value.
Y
System.UnauthorizedAccessException
path specified a read-only file and access is not Read, or path specified a directory.
Z
1671
Contents | Index
File
System.IO
Open() Method
Exception
Condition
System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
C
System.IO.FileNotFoundException
path was not found.
D
System.IO.IOException
An I/O error occurred while opening the file.
E
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
A B
F G H I
Permissions
J K
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to read and may also require permission to write the file. See System.Security.Permissions.FileIOPermissionAccess.Read and System.Security.Permissions.FileIOPermissionAccess.Write.
L M N O P
Example
Q
using System; using System.IO; namespace Samples { public class FileOpen { public static void Main() { string s = "open.txt"; using(FileStream fs = File.Open(s, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) { Console.WriteLine("Can read from {0}: {1}", s, fs.CanRead); Console.WriteLine("Can write to {0}: {1}",
R S T U V W X Y Z
1672
Contents | Index
System.IO
File OpenRead() Method
s, fs.CanWrite); Console.WriteLine("Can seek in {0}: {1}", s, fs.CanSeek); Console.WriteLine("Async access to {0}: {1}", s, fs.IsAsync);
A
}
B
}
C
} }
D
The output is
E F
Can read from open.txt: True Can write to open.txt: True Can seek in open.txt: True Async access to open.txt: False
G H I J
File.OpenRead(System.String) Method
K [ILASM] .method public hidebysig static class System.IO.FileStream OpenRead(string path) [C#] public static FileStream OpenRead(string path)
L M N
Summary
O
Opens an existing file for reading.
P Q
Parameters
R
Parameter
Description
S
path
A System.String containing the name of the file to be opened for reading.
T U V
Description
W
This method is equivalent to System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read). The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
X Y Z
1673
Contents | Index
File
System.IO
OpenRead() Method
Exceptions Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.ArgumentNullException
path is null.
System.UnauthorizedAccessException
path specified a directory.
System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
System.IO.FileNotFoundException
path was not found.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
A B C D E F G H I J K L M N O
Permissions
P Q R S
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to read the specified file. See System.Security.Permissions.FileIOPermissionAccess.Read.
T U
Example
V
using System; using System.IO; namespace Samples { public class FileOpenRead { public static void Main() { string s = @"read.txt"; using(FileStream fs = File.OpenRead(s))
W X Y Z
1674
Contents | Index
System.IO
File OpenText() Method
{ Console.WriteLine("Can read from {0}: {1}", s, fs.CanRead); Console.WriteLine("Can write to {0}: {1}", s, fs.CanWrite); Console.WriteLine("Can seek in {0}: {1}", s, fs.CanSeek); Console.WriteLine("Async access to {0}: {1}", s, fs.IsAsync);
A B C D
} }
E
}
F
}
G
The output is
H Can read from read.txt: True Can write to read.txt: False Can seek in read.txt: True Async access to read.txt: False
I J K L
File.OpenText(System.String) Method
M
[ILASM] .method public hidebysig static class System.IO.StreamReader OpenText(string path) [C#] public static StreamReader OpenText(string path)
N O P
Summary
Q
Opens an existing UTF-8 encoded text file for reading.
R S
Parameters
T
Parameter
Description
path
A System.String containing the name of the file to be opened for reading.
U V W X
Description
Y
This method is equivalent to System.IO.StreamReader(path). The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.]
Z
1675
Contents | Index
File
System.IO
OpenText() Method
Exceptions Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.ArgumentNullException
path is null.
System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
System.IO.FileNotFoundException
path was not found.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
A B C D E F G H I J K L M
Permissions
N O
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to write to the specified file. See System.Security.Permissions.FileIOPermissionAccess.Write.
P Q R S
Example
T
using System; using System.IO; namespace Samples { public class FileOpenText { public static void Main() { string s = @"opentext.txt"; using(StreamReader sr = File.OpenText(s)) { Console.WriteLine("Can read from {0}: {1}",
U V W X Y Z
1676
Contents | Index
System.IO
File OpenWrite() Method
s, sr.BaseStream.CanRead); Console.WriteLine("Can write to {0}: {1}", s, sr.BaseStream.CanWrite); Console.WriteLine("Can seek in {0}: {1}", s, sr.BaseStream.CanSeek); Console.WriteLine("Async access to {0}: {1}", s, ((FileStream)sr.BaseStream).IsAsync);
A B C
}
D
} }
E
}
F
The output is
G H
Can read from opentext.txt: True Can write to opentext.txt: False Can seek in opentext.txt: True Async access to opentext.txt: False
I J K
File.OpenWrite(System.String) Method
L
[ILASM] .method public hidebysig static class System.IO.FileStream OpenWrite(string path) [C#] public static FileStream OpenWrite(string path)
M N O
Summary
P
Opens an existing file for writing.
Q R
Parameters
S
Parameter
Description
path
A System.String containing the name of the file to be opened for writing.
T U V W
Description
X
This method is equivalent to System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.None).
Y Z
1677
Contents | Index
File
System.IO
OpenWrite() Method
The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.] A
Exceptions
B C
Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.ArgumentNullException
path is null.
System.UnauthorizedAccessException
path specified a read-only file or a directory.
System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
System.IO.FileNotFoundException
path was not found.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
D E F G H I J K L M N O P Q
Permissions
R S
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to write the specified file. See System.Security.Permissions.FileIOPermissionAccess.Write.
T U V W X Y Z
1678
Contents | Index
System.IO
File SetAttributes() Method
Example using System; using System.IO; namespace Samples { public class FileOpenWrite { public static void Main() { string s = @"openwrite.txt"; using(FileStream fs = File.OpenWrite(s)) { Console.WriteLine("Can read from {0}: {1}", s, fs.CanRead); Console.WriteLine("Can write to {0}: {1}", s, fs.CanWrite); Console.WriteLine("Can seek in {0}: {1}", s, fs.CanSeek); Console.WriteLine("Async access to {0}: {1}", s, fs.IsAsync); } } } }
A B C D E F G H I J K L M N
The output is
O Can read from openwrite.txt: False Can write to openwrite.txt: True Can seek in openwrite.txt: True Async access to openwrite.txt: False
P Q R S
File.SetAttributes(System.String, System.IO.FileAttributes) Method
T
[ILASM] .method public hidebysig static void SetAttributes(string path, valuetype System.IO.FileAttributes fileAttributes) [C#] public static void SetAttributes(string path, FileAttributes fileAttributes)
U V W X
Summary
Y
Sets the specified System.IO.FileAttributes of the file on the specified path.
Z
1679
Contents | Index
File
System.IO
SetAttributes() Method
Parameters Parameter
Description
path
The path to the file.
fileAttributes
The desired System.IO.FileAttributes, such as Hidden, ReadOnly, Normal, and Archive.
A B C D E
Description
F
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.
G H I
Exceptions
J K
Exception
Condition
System.ArgumentException
path is empty, contains only white spaces, contains invalid characters, or the file attribute is invalid.
System.IO.PathTooLongException
The specified path, file name, or both exceed the systemdefined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
System.NotSupportedException
path is in an invalid format.
System.IO.DirectoryNotFoundException
The specified path is invalid, such as being on an unmapped drive.
L M N O P Q R S T U
Permissions
V W
Permission
Description
System.Security.Permissions.FileIOPermission
For reading and writing files. Associated enumeration: System.Security.Permissions.FileIOPermissionAccess.Write.
X Y Z
1680
Contents | Index
System.IO
File SetCreationTime() Method
File.SetCreationTime(System.String, System.DateTime) Method [ILASM] .method public hidebysig static void SetCreationTime(string path, valuetype System.DateTime creationTime) [C#] public static void SetCreationTime(string path, DateTime creationTime)
A B C
Summary
D
Sets the creation date and time for the specified file.
E F
Parameters
G
Parameter
Description
path
A System.String containing the name of the file for which to set the creation date and time information.
creationTime
A System.DateTime containing the value to set for the creation date and time of path. This value is expressed in local time.
H I J K L M
Description
N
The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.] On platforms that do not support this feature, this method has no effect. If this feature is supported, the range of dates that is valid for this operation is implementation-specific.
O P Q R S T U V W X Y Z
1681
Contents | Index
File
System.IO
SetCreationTime() Method
Exceptions Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.ArgumentOutOfRangeException
creationTime specifies a value outside the range of date/ times permitted for this operation.
System.ArgumentNullException
path is null.
System.IO.FileNotFoundException
path was not found.
System.IO.IOException
An I/O error occurred while performing the operation.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
A B C D E F G H I J K L
Permissions
M N
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to write to the specified file or directory. See System.Security.Permissions.FileIOPermissionAccess.Write.
O P Q R
Example
S
using System; using System.IO; namespace Samples { public class FileSetCreationTime { public static void Main() { string s = @"setcreationtime.txt"; if(!File.Exists(s)) { using(TextWriter output = File.AppendText(s)) { output.WriteLine(DateTime.Now);
T U V W X Y Z
1682
Contents | Index
System.IO
File SetCreationTimeUtc() Method
} } Console.WriteLine("File: {0} created at {1}", s, File.GetCreationTime(s)); File.SetCreationTime(s, DateTime.Now); Console.WriteLine("File: {0} created at {1}", s, File.GetCreationTime(s));
A B C D
} }
E
}
F
The output is
G H
File: setcreationtime.txt created at 8/04/2003 3:41:28 PM File: setcreationtime.txt created at 11/06/2003 5:04:15 PM
I J
File.SetCreationTimeUtc(System.String, System.DateTime) Method
K
[ILASM] .method public hidebysig static void SetCreationTimeUtc(string path, valuetype System.DateTime creationTimeUtc) [C#] public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc)
L M N O
Summary
P
Sets the date and time, in coordinated universal time (UTC), that the file was created.
Q R
Parameters
S
Parameter
Description
path
The file for which to set the creation date and time information.
creationTimeUtc
A System.DateTime containing the value to set for the creation date and time of path. This value is expressed in UTC time.
T U V W X Y
Description
Z
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory. 1683
Contents | Index
File
System.IO
SetLastAccessTime() Method
Exceptions Exception
Condition
System.IO.FileNotFoundException
The specified path was not found.
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by System.IO.Path.InvalidPathChars.
System.ArgumentNullException
path is null.
System.IO.PathTooLongException
The specified path, file name, or both exceed the systemdefined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
J
System.IO.IOException
An I/O error occurred while performing the operation.
K
System.ArgumentOutOfRangeException
creationTime specifies a value outside the range of dates, times, or both permitted for this operation.
System.UnauthorizedAccessException
The caller does not have the required permission.
System.NotSupportedException
path is in an invalid format.
A B C D E F G H I
L M N O P
Permissions
Q R
Permission
Description
System.Security.Permissions.FileIOPermission
For writing to the specified file. Associated enumeration: System.Security.Permissions.FileIOPermissionAccess.Write.
S T U V W
File.SetLastAccessTime(System.String, System.DateTime) Method
X
[ILASM] .method public hidebysig static void SetLastAccessTime(string path, valuetype System.DateTime lastAccessTime) [C#] public static void SetLastAccessTime(string path, DateTime lastAccessTime)
Y Z
1684
Contents | Index
System.IO
File SetLastAccessTime() Method
Summary Sets the date and time the specified file was last accessed. A
Parameters
B
Parameter
Description
C
A System.String containing the name of the file for which to set the access date and time information.
D
path
A System.DateTime containing the value to set for the access date and time of path. This value is expressed in local time.
F
lastAccessTime
E
G H
Description
I
The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.] On platforms that do not support this feature, this method has no effect. If this feature is supported, the range of dates that is valid for this operation is implementation-specific.
J K L M
Exceptions
N O
Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
P Q R
System.ArgumentNullException
path is null.
System.IO.IOException
path was not found.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.UnauthorizedAccessException
The caller does not have the required permission.
S T U V W X Y Z
1685
Contents | Index
File
System.IO
SetLastAccessTime() Method
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to write to the specified file. See System.Security.Permissions.FileIOPermissionAccess.Write.
A B C D E
Example
F
using System; using System.IO; namespace Samples { public class FileSetLastAccessTime { public static void Main() { string s = @"setlastaccesstime.txt"; if(!File.Exists(s)) { using(TextWriter output = File.AppendText(s)) { output.WriteLine(DateTime.Now); } } Console.WriteLine("File: {0} last accessed at {1}", s, File.GetLastAccessTime(s)); File.SetLastAccessTime(s, DateTime.Now); Console.WriteLine("File: {0} last accessed at {1}", s, File.GetLastAccessTime(s)); } } }
G H I J K L M N O P Q R S T U V
The output is
W File: setlastaccesstime.txt last accessed at 15/05/2003 2:11:47 PM File: setlastaccesstime.txt last accessed at 11/06/2003 5:06:13 PM
X Y Z
1686
Contents | Index
System.IO
File SetLastAccessTimeUtc() Method
File.SetLastAccessTimeUtc(System.String, System.DateTime) Method [ILASM] .method public hidebysig static void SetLastAccessTimeUtc(string path, valuetype System.DateTime lastAccessTimeUtc) [C#] public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc)
A B C
Summary
D
Sets the date and time, in coordinated universal time (UTC), that the specified file was last accessed.
E
Parameters
G
F
H
Parameter
Description
path
The file for which to set the access date and time information.
lastAccessTimeUtc
A System.DateTime containing the value to set for the last access date and time of path. This value is expressed in UTC time.
I J K L M
Description
N
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.
O P Q
Exceptions
R S
Exception
Condition T
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by System.IO.Path.InvalidPathChars.
System.ArgumentNullException
path is null.
System.IO.PathTooLongException
The specified path, file name, or both exceed the systemdefined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
U V W X Y Z
1687
Contents | Index
File
System.IO
SetLastWriteTime() Method
A
Exception
Condition
System.IO.FileNotFoundException
The specified path was not found.
System.UnauthorizedAccessException
The caller does not have the required permission.
System.NotSupportedException
path is in an invalid format.
B C D E F G
Permissions
H I J K
Permission
Description
System.Security.Permissions.FileIOPermission
For writing to the specified file. Associated enumeration: System.Security.Permissions.FileIOPermissionAccess.Write.
L M
File.SetLastWriteTime(System.String, System.DateTime) Method
N O
[ILASM] .method public hidebysig static void SetLastWriteTime(string path, valuetype System.DateTime lastWriteTime) [C#] public static void SetLastWriteTime(string path, DateTime lastWriteTime)
P Q R S
Summary
T
Sets the date and time a file was last written to.
U
Parameters
V W
Parameter
Description
path
A System.String containing the name of the file for which to set the date and time information.
lastWriteTime
A System.DateTime containing the value to set for the last write date and time of path. This value is expressed in local time.
X Y Z
1688
Contents | Index
System.IO
File SetLastWriteTime() Method
Description The path argument is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. [Note: To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.] On platforms that do not support this feature, this method has no effect. If this feature is supported, the range of dates that is valid for this operation is implementation-specific.
A B C D
Exceptions
E
Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.ArgumentNullException
path is null.
System.IO.IOException
path was not found.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
F G H I J K L M
System.UnauthorizedAccessException
The caller does not have the required permission.
N O P
Permissions
Q
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to write to the specified file. See System.Security.Permissions.FileIOPermissionAccess.Write.
R S T U V W X Y Z
1689
Contents | Index
File
System.IO
SetLastWriteTimeUtc() Method
Example using System; using System.IO; namespace Samples { public class FileSetLastWriteTime { public static void Main() { string s = @"setlastwritetime.txt"; if(!File.Exists(s)) { using(TextWriter output = File.AppendText(s)) { output.WriteLine(DateTime.Now); } } Console.WriteLine("File: {0} last written at {1}", s, File.GetLastWriteTime(s)); File.SetLastWriteTime(s, DateTime.Now); Console.WriteLine("File: {0} last written at {1}", s, File.GetLastWriteTime(s)); } } }
A B C D E F G H I J K L M N O P
The output is
Q File: setlastwritetime.txt last written at 11/06/2003 5:08:17 PM File: setlastwritetime.txt last written at 11/06/2003 5:08:41 PM
R S T
File.SetLastWriteTimeUtc(System.String, System.DateTime) Method
U [ILASM] .method public hidebysig static void SetLastWriteTimeUtc(string path, valuetype System.DateTime lastWriteTimeUtc) [C#] public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc)
V W X Y
Summary
Z
Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to.
1690
Contents | Index
System.IO
File SetLastWriteTimeUtc() Method
Parameters Parameter
Description
path
The file for which to set the date and time information.
lastWriteTimeUtc
A System.DateTime containing the value to set for the last write date and time of path. This value is expressed in UTC time.
A B C D E
Description
F
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see System.IO.Directory.GetCurrentDirectory.
G H I
Exceptions
J
Exception
Condition
K
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by System.IO.Path.InvalidPathChars.
L
System.ArgumentNullException
path is null.
System.IO.PathTooLongException
The specified path, file name, or both exceed the systemdefined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
Q
System.IO.FileNotFoundException
The specified path was not found.
S
System.UnauthorizedAccessException
The caller does not have the required permission.
System.NotSupportedException
path is in an invalid format.
M N O P
R
T U V W X Y Z
1691
Contents | Index
File
System.IO
SetLastWriteTimeUtc() Method
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
For writing to the specified file. Associated enumeration: System.Security.Permissions.FileIOPermissionAccess.Write.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1692
Contents | Index
System.IO FileAccess Enum
BCL
Object
A
IComparable
ValueType
B
IFormattable
Enum FileAccess
IConvertible
NotStandardized
C D
Summary
E
Defines constants used to specify the level of file access being requested.
F G
Type Summary public enum FileAccess { Read = 0x1, ReadWrite = Read | Write, Write = 0x2, }
H I J K L
BA A large segment of our customers do not understand flag enums. Flag enums
M
are enums whose values are meant to be combined using the bitwise OR operation. Many users would never think about using the bitwise OR operator (|) to combine values. That is why we always provide named values for the most common combinations. ReadWrite is an example of that. It is not strictly necessary, but it is much easier to discover than FileAccess.Read | FileAccess.Write.
N O P Q R
Example
S
using System; using System.IO; namespace Samples { public class FileAccessSample { public static void Main() { string s = @"FileAccess.txt"; FileAccess[] fa = {FileAccess.Read, FileAccess.ReadWrite, FileAccess.Write }; foreach(FileAccess a in fa) {
T U V W X Y Z
1693
Contents | Index
FileAccess Enum
System.IO
FileAccess Enum
using(FileStream fs = File.Open(s, FileMode.OpenOrCreate, a)) { Display(fs, s, a); Console.WriteLine(); }
A B C
} } private static void Display(FileStream fs, string s, FileAccess a) { Console.WriteLine( "Can read from {0} when opened with {1}: {2}", s, a, fs.CanRead); Console.WriteLine( "Can write to {0} when opened with {1}: {2}", s, a, fs.CanWrite); Console.WriteLine( "Can seek in {0} when opened with {1}: {2}", s, a, fs.CanSeek); Console.WriteLine( "Async access to {0} when opened with {1}: {2}", s, a, fs.IsAsync); }
D E F G H I J K L M N }
O
}
P
The output is
Q
Can read from FileAccess.txt when opened with Read: True Can write to FileAccess.txt when opened with Read: False Can seek in FileAccess.txt when opened with Read: True Async access to FileAccess.txt when opened with Read: False Can read from FileAccess.txt when opened with ReadWrite: True Can write to FileAccess.txt when opened with ReadWrite: True Can seek in FileAccess.txt when opened with ReadWrite: True Async access to FileAccess.txt when opened with ReadWrite: False Can read from FileAccess.txt when opened with Write: False Can write to FileAccess.txt when opened with Write: True Can seek in FileAccess.txt when opened with Write: True Async access to FileAccess.txt when opened with Write: False
R S T U V W X Y Z
1694
Contents | Index
System.IO
FileAccess Enum Write Field
FileAccess.Read Field [ILASM] .field public static literal valuetype System.IO.FileAccess Read [C#] Read = 0x1
A B C
Summary
D
Specifies read access for a file.
E F
FileAccess.ReadWrite Field
G
[ILASM] .field public static literal valuetype System.IO.FileAccess ReadWrite [C#] ReadWrite = Read | Write
H I J
Summary
K
Specifies read and write access for a file.
L M N
FileAccess.Write Field
O
[ILASM] .field public static literal valuetype System.IO.FileAccess Write [C#] Write = 0x2
P Q R
Summary
S
Specifies write access for a file.
T U V W X Y Z
1695
Contents | Index
System.Security.Permissions FileIOPermission
BCL
IStackWalk
A
NotStandardized
ISecurityEncodable
Object
B
CodeAccessPermission
C
FileIOPermission
NotStandardized
IPermission IUnrestrictedPermission
NotStandardized
D
Summary
E
Secures access to files and directories.
F
Type Summary
G
CF public sealed class FileIOPermission : CodeAccessPermission, IUnrestrictedPermission { // Constructors CF public FileIOPermission(PermissionState state) CF public FileIOPermission(FileIOPermissionAccess access, string path) MS CF public FileIOPermission(FileIOPermissionAccess access, string[] pathList)
H I J K L
// Methods MS CF public void AddPathList (FileIOPermissionAccess access, string path); MS CF public void AddPathList (FileIOPermissionAccess access, string[] pathList); CF public override IPermission Copy (); CF public override void FromXml (SecurityElement esd); MS CF public string[] GetPathList (FileIOPermissionAccess access); CF public override IPermission Intersect (IPermission target); CF public override bool IsSubsetOf (IPermission target); MS CF public bool IsUnrestricted (); MS CF public void SetPathList (FileIOPermissionAccess access, string path); MS CF public void SetPathList (FileIOPermissionAccess access, string[] pathList); CF public override SecurityElement ToXml (); CF public override IPermission Union (IPermission other); }
M N O P Q R S T U V W
BG FileIOPermission is a great idea. However, the implementation of this security check (and in our case, all the code that uses this security check) requires great care. This permission is based on string comparisons for determining whether a file is in or out of one of the sets of allowed or denied files. This has a couple of surprising properties:
X Y Z
continued
1696
Contents | Index
System.Security.Permissions
FileIOPermission FileIOPermission Class
1. Since access is granted to a file based on its name and which directory it lives in, aliases for that file’s data aren’t covered by the security permission. Examples include cases like mapping a file as another drive (i.e., using the DOS subst command to make X: refer to a directory on C:) or more obscure features such as hard links, UNIX mount points, or NTFS reparse points. 2. Beyond aliases, some common file systems have some very loose rules for how to access files. For example, FAT and NTFS are case-insensitive, and allow you to add a period to the end of file names. Almost all file systems will allow you to go up a directory then back down to a different directory (i.e., “C:\foo\..\tmp\bar.txt” refers to the file “C:\tmp\bar.txt”). 3. String comparison in the file system often works in a slightly surprising way.
A B C D E F G
We consider the first issue to be by design. If a user, such as the system administrator, has sufficient permissions to share out a portion of a drive and this can be used to circumvent permission checks, this may be intentional and useful. A great example is that you might want to deny code access to all of C:\; however, a particular directory on that drive has been shared out as a world-writable directory for logging, shared documents, or just a public drop folder. In this case, the administrator created the alias, possibly with the express purpose of creating a separate conceptual permission space.
H I J K L
The second issue is very tricky. It would ideally require that you obtain file names in a canonicalized form before doing the string comparisons. On Windows, getting a canonical name for a file (ignoring the aliasing issue above) requires that you open the file and get a handle to it. This can be expensive, especially for remote file systems. Instead, we are relying on path normalization to cover us. Any implementation of Path.GetFullPathName should be reviewed and tested against real file system behavior extremely closely.
M
The third issue is a bit more subtle. For a file system like NTFS, the file names can contain almost any Unicode character, and the file names are case-insensitive. However, the casing table used by a CLI implementation may differ from the casing table used by the file system. For example, NTFS writes the current OS’s casing table to the file system when the file system is formatted, then all future OS’s use that casing table for all caseinsensitive comparisons. If an OS’s casing table changes in a future release, to account for new Unicode characters or to correct mistakes, then it may be nearly impossible to do case-insensitive comparisons in exactly the same manner as the file system.
R
N O P Q
S T U V W X
You might think this is a gaping security hole. In practice, changes to an OS’s casing table are somewhat rare and generally limited to obscure Unicode characters that are not commonly in use. But a thorough CLI implementation should at least be aware of this problem and investigate whether it could cause problems for the file systems most commonly used with that CLI.
Y Z
1697
Contents | Index
FileIOPermission
System.Security.Permissions
FileIOPermission Class
Description System.Security.Permissions.FileIOPermission objects describe protected operations on files and directories. Files and directories are specified using absolute paths. Case-sensitivity of files and directories is platform- and file system-dependent. [Note: This permission distinguishes between the following types of file I/O access provided by System.Security.Permissions.FileIOPermissionAccess: These access levels are independent, meaning that rights to one do not imply rights to another. For example, Write permission does not imply permission to Read or Append. System.Security.Permissions.FileIOPermissionAccess values can be combined using a bitwise OR operator. For information on security considerations when accessing files, see System.IO.FileStream.] The XML encoding of a FileIOPermission instance is defined below in EBNF format. The following conventions are used:
A B C D E F G H
• • •
V
All non-literals in the grammar below are shown in normal type. All literals are in bold font. The following meta-language symbols are used: – '*' represents a meta-language symbol suffixing an expression that can appear zero or more times. – '?' represents a meta-language symbol suffixing an expression that can appear zero or one time. – '+' represents a meta-language symbol suffixing an expression that can appear one or more times. – '(',')' is used to group literals, non-literals or a mixture of literals and non-literals. – '|' denotes an exclusive disjunction between two expressions. – '::= ' denotes a production rule where a left-hand non-literal is replaced by a righthand expression containing literals, non-literals, or both. BuildVersion refers to the build version of the shipping CLI. This is specified as a dotted build number such as '2412.0'. ECMAPubKeyToken ::= b77a5c561934e089 FileName refers to the full path and file name of a file, or to a path name, such as “C:\Temp\test.exe” or “C:\”.
W
The XML encoding of a FileIOPermission instance is as follows:
I J K L M N O P Q R
•
S T
• •
U
X FileIOPermissionXML ::=
Y Z
1698
Contents | Index
System.Security.Permissions
FileIOPermission FileIOPermission Class
Culture=neutral, PublicKeyToken=ECMAPubKeyToken" version="1" ( Unrestricted="true" ) | ( (Read="FileName (; FileName )*" ) ? (Write="FileName (; FileName )*" ) ? (Append="FileName (; FileName )*" ) ? (PathDiscovery="FileName (; FileName )*" ) ? ) />
A B C D E F G
Example
H
using System; using System.IO; using System.Security.Permissions; using System.Security; namespace Samples { public class FileIOPermissionSample { public static void Main() { string s = Path.GetFullPath("FileIOPermission.txt"); FileIOPermission p = new FileIOPermission( FileIOPermissionAccess.Read | FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, s); p.Assert(); TestAccess(s); CodeAccessPermission.RevertAssert(); p.Deny(); TestAccess(s); CodeAccessPermission.RevertDeny(); p.PermitOnly(); TestAccess(s); CodeAccessPermission.RevertPermitOnly(); } static public void TestAccess(String s) { try
I J K L M N O P Q R S T U V W X Y Z
1699
Contents | Index
FileIOPermission
System.Security.Permissions
FileIOPermission() Constructor
{ FileStream fs = new FileStream( s, FileMode.OpenOrCreate); Console.WriteLine("File {0} opened or created", s); fs.Close();
A B
} catch(Exception e) { Console.WriteLine( "File {0} cannot be opened or created " + Environment.NewLine + "Reason was: {1}", s, e.Message); }
C D E F G
} }
H }
I
The output is
J K
File C:\Books\BCL\Samples\System.Security\Permissions\ FileIOPermission\FileIOPermission.txt opened or created File C:\Books\BCL\Samples\System.Security\Permissions\FileIOPermission\ FileIOPermission.txt cannot be opened or created Reason was: Request for the permission of type System.Security.Permissions.FileIOPermission, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed. File C:\Books\BCL\Samples\System.Security\Permissions\FileIOPermission\ FileIOPermission.txt opened or created
L M N O P Q R
FileIOPermission(System.Security.Permissions.PermissionState) Constructor
S T
[ILASM] public rtspecialname specialname instance void .ctor(valuetype System.Security.Permissions.PermissionState state) [C#] public FileIOPermission(PermissionState state)
U V W X
Summary
Y
Constructs and initializes a new instance of the System.Security.Permissions.FileIOPermission class with the specified System.Security.Permissions.PermissionState value.
Z
1700
Contents | Index
System.Security.Permissions
FileIOPermission FileIOPermission() Constructor
Parameters Parameter
Description
state
A System.Security.Permissions.PermissionState value.
A B C
Description
D
[Note: This constructor creates either fully restricted (System.Security.Permissions.PermissionState.None) or System.Security.Permissions.PermissionState.Unrestricted access to files and directories.]
E F G
Exceptions
H
Exception
Condition
System.ArgumentException
state is not a valid System.Security.Permissions.PermissionState value.
I J K L M
Example
N
using System; using System.IO; using System.Security.Permissions; using System.Security; namespace Samples { public class FileIOPermissionConstructor { public static void Main() { string s = Path.GetFullPath("FileIOPermission.txt"); FileIOPermission p = new FileIOPermission( PermissionState.Unrestricted); p.Assert(); TestAccess(s); CodeAccessPermission.RevertAssert(); p.Deny(); TestAccess(s); } static public void TestAccess(String s) { try {
O P Q R S T U V W X Y Z
1701
Contents | Index
FileIOPermission
System.Security.Permissions
FileIOPermission() Constructor
FileStream fs = new FileStream( s, FileMode.OpenOrCreate); Console.WriteLine("File {0} opened or created", s); fs.Close();
A
} catch(Exception e) { Console.WriteLine( "File {0} cannot be opened or created " + Environment.NewLine + "Reason was: {1}", s, e.Message); }
B C D E F }
G
}
H
}
I
The output is
J File C:\Books\BCL\Samples\System.Security\Permissions\FileIOPermission\ FileIOPermission(System.Security.Permissions.PermissionState)\FileIOPermission.txt opened or created File C:\Books\BCL\Samples\System.Security\Permissions\FileIOPermission\ FileIOPermission(System.Security.Permissions.PermissionState)\FileIOPermission.txt cannot be opened or created Reason was: Request for the permission of type System.Security.Permissions.FileIOPermission, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed.
K L M N O P Q
FileIOPermission(System.Security.Permissions.FileIOPermissionAccess, System.String) Constructor
R S
[ILASM] public rtspecialname specialname instance void .ctor(valuetype System.Security.Permissions.FileIOPermissionAccess access, string path) [C#] public FileIOPermission(FileIOPermissionAccess access, string path)
T U V W
Summary
X
Constructs and initializes a new instance of the System.Security.Permissions.FileIOPermission class with the specified access to the specified file or directory.
Y Z
1702
Contents | Index
System.Security.Permissions
FileIOPermission FileIOPermission() Constructor
Parameters Parameter
Description
access
One or more values defined in System.Security.Permissions.FileIOPermissionAccess. Specify multiple values using the bitwise OR operator.
path
The absolute path of the file or directory.
A B C D E
Description
F
The set of characters that are invalid for use in file or directory names is platform specific.
G H
Exceptions
I
Exception
Condition
J K
access specifies values not defined in System.Security.Permissions.FileIOPermissionAccess. System.ArgumentException
L
path contains one or more characters that are invalid for use in files or directory names.
M
path did not specify the absolute path to the file or directory.
N O
Example
P
using System; using System.IO; using System.Security.Permissions; using System.Security; namespace Samples { public class FileIOPermissionConstructor { public static void Main() { string s = Path.GetFullPath("FileIOPermission.txt"); FileIOPermission p = new FileIOPermission( FileIOPermissionAccess.Read | FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, s); p.Assert(); TestAccess(s);
Q R S T U V W X Y Z
1703
Contents | Index
FileIOPermission
System.Security.Permissions
FileIOPermission() Constructor
CodeAccessPermission.RevertAssert(); p.Deny(); TestAccess(s); CodeAccessPermission.RevertDeny(); p.PermitOnly(); TestAccess(s); CodeAccessPermission.RevertPermitOnly();
A B C
} static public void TestAccess(String s) { try { FileStream fs = new FileStream( s, FileMode.OpenOrCreate); Console.WriteLine("File {0} opened or created", s); fs.Close(); } catch(Exception e) { Console.WriteLine( "File {0} cannot be opened or created " + Environment.NewLine + "Reason was: {1}", s, e.Message); } }
D E F G H I J K L M N }
O
}
P
The output is
Q
File C:\Books\BCL\Samples\System.Security\Permissions\FileIOPermission\ FileIOPermission(System.Security.Permissions.FileIOPermissionAccess,System.String) \FileIOPermission.txt opened or created File C:\Books\BCL\Samples\System.Security\Permissions\FileIOPermission\ FileIOPermission(System.Security.Permissions.FileIOPermissionAccess,System.String) \FileIOPermission.txt cannot be opened or created Reason was: Request for the permission of type System.Security.Permissions.FileIOPermission, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed. File C:\Books\BCL\Samples\System.Security\Permissions\FileIOPermission\ FileIOPermission(System.Security.Permissions.FileIOPermissionAccess,System.String) \FileIOPermission.txt opened or created
R S T U V W X Y Z
1704
Contents | Index
System.Security.Permissions
FileIOPermission FileIOPermission() Constructor
FileIOPermission(System.Security.Permissions.FileIOPermissionAccess, System.String[]) Constructor [ILASM]
A
public rtspecialname specialname instance void .ctor(valuetype System.Security. Permissions.FileIOPermissionAccess access, class System.String[] pathList)
B
[C#]
C
public FileIOPermission(FileIOPermissionAccess access, string[] pathList)
D
Summary
E
Initializes a new instance of the System.Security.Permissions.FileIOPermission class with the specified access to the specified files and directories.
F G
Parameters
H I
Parameter
Description J
access
A bitwise combination of the System.Security.Permissions.FileIOPermissionAccess values.
pathList
An array containing the absolute paths of the files and directories.
K L M N
Description
O
This constructor only allows one System.Security.Permissions.FileIOPermissionAccess value to be specified for the specified files and directories. Use System.Security.Permissions.FileIOPermission.AddPathList to define complex permissions.
P Q R S
Exceptions Exception
T
Condition
U V
The access parameter is not a valid value of System.Security.Permissions.FileIOPermissionAccess. System.ArgumentException
W
-or-
X
An entry in the pathList array is not a valid string.
Y Z
1705
Contents | Index
FileIOPermission
System.Security.Permissions
AddPathList() Method
FileIOPermission.AddPathList(System.Security.Permissions. FileIOPermissionAccess, System.String) Method [ILASM] .method public hidebysig instance void AddPathList(valuetype System.Security. Permissions.FileIOPermissionAccess access, string path) [C#] public void AddPathList(FileIOPermissionAccess access, string path)
A B C D
Summary
E
Adds access for the specified file or directory to the existing state of the permission.
F G
Parameters
H I J
Parameter
Description
access
A bitwise combination of the System.Security.Permissions.FileIOPermissionAccess values.
path
The absolute path of a file or directory.
K L M N
Description
O
Use this method to modify file and directory access by adding to the state of the current permission.
P Q
Exceptions
R
Exception
S T
Condition The access parameter is not a valid value of System.Security.Permissions.FileIOPermissionAccess.
U V
-orSystem.ArgumentException
W
The path parameter is not a valid string.
X
-or-
Y
The path parameter did not specify the absolute path to the file or directory.
Z System.ArgumentNullException
The path parameter is null.
1706
Contents | Index
System.Security.Permissions
FileIOPermission AddPathList() Method
FileIOPermission.AddPathList(System.Security.Permissions. FileIOPermissionAccess, System.String[]) Method [ILASM] .method public hidebysig instance void AddPathList(valuetype System.Security. Permissions.FileIOPermissionAccess access, class System.String[] pathList) [C#] public void AddPathList(FileIOPermissionAccess access, string[] pathList)
A B C D
Summary
E
Adds access for the specified files and directories to the existing state of the permission.
F G
Parameters
H
Parameter
Description
I
access
A bitwise combination of the System.Security.Permissions.FileIOPermissionAccess values.
J
pathList
K
An array containing the absolute paths of the files and directories.
L M
Description
N
Use this method to modify file and directory access by adding to the state of the current permission.
O
Exceptions
Q
P
R
Exception
System.ArgumentException
System.ArgumentNullException
Condition
S
The access parameter is not a valid value of System.Security.Permissions.FileIOPermissionAccess.
T U
-or-
V
An entry in the pathList array is not valid.
W
The pathList parameter is null.
X Y Z
1707
Contents | Index
FileIOPermission
System.Security.Permissions
Copy() Method
FileIOPermission.Copy() Method [ILASM] .method public hidebysig virtual class System.Security.IPermission Copy() [C#] public override IPermission Copy()
A B C
Summary
D
Returns a new System.Security.Permissions.FileIOPermission object containing the same values as the current instance.
E F
Description
G
[Note: The object returned by this method represents the same level of access to files and directories as the current instance. This method overrides System.Security.CodeAccessPermission.Copy and is implemented to support the System.Security.IPermission interface.]
H I J K
Example
L
using System; using System.IO; using System.Security.Permissions; using System.Security; namespace Samples { public class FileIOPermissionCopy { public static void Main() { string s = Path.GetFullPath("FileIOPermission.txt"); FileIOPermission p1 = new FileIOPermission( FileIOPermissionAccess.Read, s); FileIOPermission p2 = (FileIOPermission) p1.Copy(); string [] a = new string[2]; a[0] = Path.GetFullPath("FileIOPermission.cs"); a[1] = Path.GetFullPath("FileIOPermission.exe"); p2.AddPathList(FileIOPermissionAccess.Read, a); a = p1.GetPathList( FileIOPermissionAccess.Read); foreach(string f in a) Console.WriteLine("From p1: {0}", f); a = p2.GetPathList( FileIOPermissionAccess.Read); foreach(string f in a)
M N O P Q R S T U V W X Y Z
1708
Contents | Index
System.Security.Permissions
FileIOPermission FromXml() Method
Console.WriteLine("From p2: {0}", f); } } }
A
The output is
B C
From p1: C:\Books\BCL\Samples\System.Security\Permissions\FileIOPermission\Copy()\ FileIOPermission.txt From p2: C:\Books\BCL\Samples\System.Security\Permissions\FileIOPermission\Copy()\ FileIOPermission.txt From p2: C:\Books\BCL\Samples\System.Security\Permissions\FileIOPermission\Copy()\ FileIOPermission.cs From p2: C:\Books\BCL\Samples\System.Security\Permissions\FileIOPermission\Copy()\ FileIOPermission.exe
D E F G H I
FileIOPermission.FromXml(System.Security.SecurityElement) Method
J
[ILASM] .method public hidebysig virtual void FromXml(class System.Security.SecurityElement esd) [C#] public override void FromXml(SecurityElement esd)
K L M N
Summary
O
Reconstructs the state of a System.Security.Permissions.FileIOPermission object using the specified XML encoding.
P Q
Parameters
R S
Parameter
Description T
esd
A System.Security.SecurityElement instance containing the XML encoding to use to reconstruct the state of a System.Security.Permissions.FileIOPermission object.
U V W
Description
X
The state of the current instance is changed to the state encoded in esd. [Note: For the XML encoding for this class, see the System.Security.Permissions.FileIOPermission class page. This method overrides System.Security.CodeAccessPermission.FromXml.]
Y Z
1709
Contents | Index
FileIOPermission
System.Security.Permissions
FromXml() Method
Exceptions Exception
Condition
System.ArgumentNullException
esd is null.
System.ArgumentException
esd does not contain the encoding for a System.Security.Permissions.FileIOPermission instance.
A B C D
The version number of esd is not valid.
E F G
Example
H
using System; using System.IO; using System.Security.Permissions; using System.Security; namespace Samples { public class FileIOPermissionFromXml { public static void Main() { FileIOPermission p1 = new FileIOPermission( PermissionState.Unrestricted); p1.AddPathList(FileIOPermissionAccess.Read, Path.GetFullPath("FileIOPermission.txt")); p1.AddPathList(FileIOPermissionAccess.Write, Path.GetFullPath("FileIOPermission.cs")); p1.AddPathList(FileIOPermissionAccess.PathDiscovery, Path.GetFullPath("FileIOPermission.exe")); p1.AddPathList(FileIOPermissionAccess.AllAccess, Path.GetFullPath("FileIOPermission.exe")); SecurityElement s = p1.ToXml(); FileIOPermission p2 = new FileIOPermission( PermissionState.Unrestricted); p2.FromXml(s); Console.WriteLine(p2); } } }
I J K L M N O P Q R S T U V W X
The output is
Y Z
1710
Contents | Index
System.Security.Permissions
FileIOPermission GetPathList() Method
Read="C:\Books\BCL\Samples\System.Security\Permissions\FileIOPermission\FromXml()\ FileIOPermission.txt;C:\Books\BCL\Samples\System.Security\Permissions\ FileIOPermission\FromXml()\FileIOPermission.exe"
A
Write="C:\Books\BCL\Samples\System.Security\Permissions\FileIOPermission\FromXml()\ FileIOPermission.cs;C:\Books\BCL\Samples\System.Security\Permissions\ FileIOPermission\FromXml()\FileIOPermission.exe"
B C
Append="C:\Books\BCL\Samples\System.Security\Permissions\FileIOPermission\FromXml()\ FileIOPermission.exe"
D E
PathDiscovery="C:\Books\BCL\Samples\System.Security\Permissions\FileIOPermission\ FromXml()\FileIOPermission.exe"/>
F G H
FileIOPermission.GetPathList(System.Security.Permissions. FileIOPermissionAccess) Method
I J
[ILASM] .method public hidebysig instance class System.String[] GetPathList(valuetype System.Security.Permissions.FileIOPermissionAccess access) [C#] public string[] GetPathList(FileIOPermissionAccess access)
K L M
Summary
N
Gets all files and directories with the specified System.Security.Permissions.FileIOPermissionAccess.
O P Q
Parameters
R
Parameter
Description
access
One of the System.Security.Permissions.FileIOPermissionAccess values that represents a single type of file access.
S T U V
Return Value
W
An array containing the paths of the files and directories to which access specified by the access parameter is granted.
X Y Z
1711
Contents | Index
FileIOPermission
System.Security.Permissions
Intersect() Method
Description Use this method to get the state of the current permission. To get the state of both Read and Write access, two calls to this method are required. The access parameter is limited to the values of System.Security.Permissions.FileIOPermissionAccess, which represent single types of file access. Those values are System.Security.Permissions.FileIOPermissionAccess.Read, System.Security.Permissions.FileIOPermissionAccess.Write, System.Security.Permissions.FileIOPermissionAccess.Append, and System.Security.Permissions.FileIOPermissionAccess.PathDiscovery. The values acceptable to access do not include System.Security.Permissions.FileIOPermissionAccess.NoAccess and System.Security.Permissions.FileIOPermissionAccess.AllAccess, which do not represent single types of file access.
A B C D E F G H
Exceptions
I J
Exception
K
Condition access is not a valid value of System.Security.Permissions.FileIOPermissionAccess.
L
-or-
M System.ArgumentException
N O P
access is System.Security.Permissions.FileIOPermissionAccess.AllAccess, which represents more than one type of file access, or System.Security.Permissions.FileIOPermissionAccess.NoAccess, which does not represent any type of file access.
Q R
FileIOPermission.Intersect(System.Security.IPermission) Method
S
[ILASM] .method public hidebysig virtual class System.Security.IPermission Intersect(class System.Security.IPermission target) [C#] public override IPermission Intersect(IPermission target)
T U V W
Summary
X
Returns a new System.Security.Permissions.FileIOPermission object that is the intersection of the current instance and the specified object.
Y Z
1712
Contents | Index
System.Security.Permissions
FileIOPermission Intersect() Method
Parameters Parameter
Description
target
A System.Security.Permissions.FileIOPermission instance to intersect with the current instance.
A B C D
Return Value
E
A new System.Security.Permissions.FileIOPermission instance that represents the intersection of the current instance and target. If the intersection is empty or target is null, returns null. If the current instance is unrestricted, returns a copy of target. If target is unrestricted, returns a copy of the current instance.
F G H
Description
I
[Note: The intersection of two permissions is a permission that secures the resources and operations secured by both permissions. Specifically, it represents the minimum permission such that any demand that passes both permissions will also pass their intersection. This method overrides System.Security.CodeAccessPermission.Intersect and is implemented to support the System.Security.IPermission interface.]
J K L M N
Exceptions
O
Exception
Condition
System.ArgumentException
target is not null and is not of type System.Security.Permissions.FileIOPermission.
P Q R S
Example
T
using System; using System.IO; using System.Security.Permissions; using System.Security; namespace Samples { public class FileIOPermissionIntersect { public static void Main() { FileIOPermission p1 = new FileIOPermission( PermissionState.Unrestricted);
U V W X Y Z
1713
Contents | Index
FileIOPermission
System.Security.Permissions
IsSubsetOf() Method
p1.AddPathList(FileIOPermissionAccess.Read, Path.GetFullPath("FileIOPermission.txt")); p1.AddPathList(FileIOPermissionAccess.Write, Path.GetFullPath("FileIOPermission.cs")); p1.AddPathList(FileIOPermissionAccess.PathDiscovery, Path.GetFullPath("FileIOPermission.exe")); p1.AddPathList(FileIOPermissionAccess.AllAccess, Path.GetFullPath("FileIOPermission.exe")); SecurityElement s = p1.ToXml(); FileIOPermission p2 = new FileIOPermission( PermissionState.Unrestricted); p2.AddPathList(FileIOPermissionAccess.Read, Path.GetFullPath("FileIOPermission.txt")); p2.AddPathList(FileIOPermissionAccess.Write, Path.GetFullPath("FileIOPermission.cs")); p1.AddPathList(FileIOPermissionAccess.Read, Path.GetFullPath("FileIOPermission.exe")); Console.WriteLine(p1.Intersect(p2));
A B C D E F G H I }
J }
K
}
L
The output is
M
N O P
Read="C:\Books\BCL\Samples\System.Security\Permissions\FileIOPermission\ Intersect(System.Security.IPermission)\FileIOPermission.txt"
Q
Write="C:\Books\BCL\Samples\System.Security\Permissions\FileIOPermission\ Intersect(System.Security.IPermission)\FileIOPermission.cs"/>
R S T
FileIOPermission.IsSubsetOf(System.Security.IPermission) Method
U
[ILASM] .method public hidebysig virtual bool IsSubsetOf(class System.Security.IPermission target) [C#] public override bool IsSubsetOf(IPermission target)
V W X Y
Summary
Z
Determines whether the current instance is a subset of the specified object.
1714
Contents | Index
System.Security.Permissions
FileIOPermission IsSubsetOf() Method
Parameters Parameter
Description
target
A System.Security.Permissions.FileIOPermission instance that is to be tested for the subset relationship.
A B C D
Return Value
E
true if the current instance is a subset of target; otherwise, false. If the current instance is unrestricted, and target is not, returns false. If target is unrestricted, returns true. If target is null and no files or directories are secured by the current instance, returns true. If target is null, and the current instance secures one or more files or directories, returns false.
F G H
Description
I
[Note: The current instance is a subset of target if the current instance specifies a set of accesses to resources that is wholly contained by target. For example, a permission that represents read access to a file is a subset of a permission that represents read and write access to the file. If this method returns true, the current instance describes a level of access to files and directories that is also described by target. This method overrides System.Security.CodeAccessPermission.IsSubsetOf and is implemented to support the System.Security.IPermission interface.]
J K L M N O
Exceptions
P
Exception
Condition
System.ArgumentException
target is not null and is not of type System.Security.Permissions.FileIOPermission.
Q R S T U
Example
V
using System; using System.IO; using System.Security.Permissions; using System.Security; namespace Samples { public class FileIOPermissionIsSubsetOf { public static void Main()
W X Y Z
1715
Contents | Index
FileIOPermission
System.Security.Permissions
IsUnrestricted() Method
{ FileIOPermission p1 = new FileIOPermission( PermissionState.Unrestricted); p1.AddPathList(FileIOPermissionAccess.Read, Path.GetFullPath("FileIOPermission.txt")); p1.AddPathList(FileIOPermissionAccess.Write, Path.GetFullPath("FileIOPermission.cs")); p1.AddPathList(FileIOPermissionAccess.PathDiscovery, Path.GetFullPath("FileIOPermission.exe")); p1.AddPathList(FileIOPermissionAccess.AllAccess, Path.GetFullPath("FileIOPermission.exe")); FileIOPermission p2 = new FileIOPermission( PermissionState.Unrestricted); p2.AddPathList(FileIOPermissionAccess.PathDiscovery, Path.GetFullPath("FileIOPermission.exe")); p2.AddPathList(FileIOPermissionAccess.AllAccess, Path.GetFullPath("FileIOPermission.exe")); Console.WriteLine("p1.IsSubsetOf(p2) yeilds: {0}", p1.IsSubsetOf(p2)); Console.WriteLine("p2.IsSubsetof(p1) yeilds: {0}", p2.IsSubsetOf(p1)); Console.WriteLine("p1.IsSubsetOf(p1) yeilds: {0}", p1.IsSubsetOf(p1));
A B C D E F G H I J K L }
M }
N
}
O
The output is
P p1.IsSubsetOf(p2) yeilds: False p2.IsSubsetof(p1) yeilds: True p1.IsSubsetOf(p1) yeilds: True
Q R S
FileIOPermission.IsUnrestricted() Method
T U
[ILASM] .method public final hidebysig virtual bool IsUnrestricted() [C#] public bool IsUnrestricted()
V W X
Summary
Y
Returns a value indicating whether the current permission is unrestricted.
Z
1716
Contents | Index
System.Security.Permissions
FileIOPermission SetPathList() Method
Return Value true if the current permission is unrestricted; otherwise, false.
Description
A
An unrestricted permission represents access to all resources protected by the permission.
B C D
FileIOPermission.SetPathList(System.Security.Permissions. FileIOPermissionAccess, System.String) Method
E F
[ILASM] .method public hidebysig instance void SetPathList(valuetype System.Security.Permissions.FileIOPermissionAccess access, string path) [C#] public void SetPathList(FileIOPermissionAccess access, string path)
G H I
Summary
J
Sets the specified access to the specified file or directory, replacing the existing state of the permission.
K L M
Parameters
N O
Parameter
Description
access
A bitwise combination of the System.Security.Permissions.FileIOPermissionAccess values.
Q
path
The absolute path of the file or directory.
R
P
S T
Description
U
The previous state of the current permission for the specified access type is overwritten. The following code sets the access for C:\temp to System.Security.Permissions.FileIOPermissionAccess.Read.
V W
SetPathList(FileIOPermissionAccess.Read, "C:\\temp");
X
This access will not be overwritten by the following code because the access types are not the same.
Y Z
SetPathList(FileIOPermissionAccess.Write, "C:\\documents");
1717
Contents | Index
FileIOPermission
System.Security.Permissions
SetPathList() Method
Exceptions Exception
Condition
A
The access parameter is not a valid value of System. Security.Permissions.FileIOPermissionAccess.
B C
-or-
D
System.ArgumentException
E
The path parameter is not a valid string. -or-
F
The path parameter did not specify the absolute path to the file or directory.
G H I
FileIOPermission.SetPathList(System.Security.Permissions. FileIOPermissionAccess, System.String[]) Method
J K
[ILASM] .method public hidebysig instance void SetPathList(valuetype System.Security.Permissions.FileIOPermissionAccess access, class System.String[] pathList) [C#] public void SetPathList(FileIOPermissionAccess access, string[] pathList)
L M N O P
Summary
Q
Sets the specified access to the specified files and directories, replacing the current state for the specified access with the new set of paths.
R S
Parameters
T U V
Parameter
Description
access
A bitwise combination of the System.Security.Permissions.FileIOPermissionAccess values.
pathList
An array containing the absolute paths of the files and directories.
W X Y Z
1718
Contents | Index
System.Security.Permissions
FileIOPermission ToXml() Method
Description The previous state of the current permission for the specified access type is overwritten. The following code sets the access for C:\temp to System.Security.Permissions.FileIOPermissionAccess.Read.
A B
SetPathList(FileIOPermissionAccess.Read, "C:\\temp");
C
This access will not be overwritten by the following code because the access types are not the same.
D E
SetPathList(FileIOPermissionAccess.Write, "C:\\documents");
F G
Exceptions
H
Exception
System.ArgumentException
Condition
I
The access parameter is not a valid value of System. Security.Permissions.FileIOPermissionAccess.
J K
-or-
L
An entry in the pathList parameter is not a valid string.
M N O
FileIOPermission.ToXml() Method
P
[ILASM] .method public hidebysig virtual class System.Security.SecurityElement ToXml() [C#] public override SecurityElement ToXml()
Q
Summary
T
Returns the XML encoding of the current instance.
U
R S
V
Description
W
[Note: For the XML encoding for this class, see the System.Security.Permissions.FileIOPermission class page. This method overrides System.Security.CodeAccessPermission.ToXml.]
X Y Z
1719
Contents | Index
FileIOPermission
System.Security.Permissions
ToXml() Method
Example using System; using System.IO; using System.Security.Permissions; using System.Security; namespace Samples { public class FileIOPermissionToXml { public static void Main() { FileIOPermission p = new FileIOPermission( PermissionState.Unrestricted); p.AddPathList(FileIOPermissionAccess.Read, Path.GetFullPath("FileIOPermission.txt")); p.AddPathList(FileIOPermissionAccess.Write, Path.GetFullPath("FileIOPermission.cs")); p.AddPathList(FileIOPermissionAccess.PathDiscovery, Path.GetFullPath("FileIOPermission.exe")); p.AddPathList(FileIOPermissionAccess.AllAccess, Path.GetFullPath("FileIOPermission.exe")); Console.WriteLine(p.ToXml()); } } }
A B C D E F G H I J K L M N
The output is
O P
Q R S T U V W X Y Z
1720
Contents | Index
System.Security.Permissions
FileIOPermission Union() Method
FileIOPermission.Union(System.Security.IPermission) Method [ILASM] .method public hidebysig virtual class System.Security.IPermission Union(class System.Security.IPermission other) [C#] public override IPermission Union(IPermission other)
A B C
Summary
D
Returns a new System.Security.Permissions.FileIOPermission that is the union of the current instance and the specified object.
E F
Parameters
G H
Parameter
Description
other
A System.Security.Permissions.FileIOPermission instance to combine with the current instance.
I J K
Return Value
L
A new System.Security.Permissions.FileIOPermission instance that represents the union of the current instance and other. If the current instance or other is unrestricted, returns a System.Security.Permissions.FileIOPermission instance that is unrestricted. If other is null, returns a copy of the current instance via the System.Security.IPermission.Copy method. If the current instance and other do not specify any file or directory names, returns null.
M N O P Q
Description
R
[Note: The result of a call to System.Security.Permissions.FileIOPermission.Union is a permission that represents all of the access to files and directories represented by the current instance as well as the access to files and directories represented by other. Any demand that passes either the current instance or other passes their union. This method overrides System.Security.CodeAccessPermission.Union and is implemented to support the System.Security.IPermission interface.]
S T U V W
Exceptions
X
Exception
Condition
System.ArgumentException
other is not null and is not of type System.Security.Permissions.FileIOPermission.
Y Z
1721
Contents | Index
FileIOPermission
System.Security.Permissions
Union() Method
Example using System; using System.IO; using System.Security.Permissions; using System.Security; namespace Samples { public class FileIOPermissionUnion { public static void Main() { FileIOPermission p1 = new FileIOPermission( PermissionState.Unrestricted); p1.AddPathList(FileIOPermissionAccess.Read, Path.GetFullPath("FileIOPermission.txt")); p1.AddPathList(FileIOPermissionAccess.Write, Path.GetFullPath("FileIOPermission.cs")); FileIOPermission p2 = new FileIOPermission( PermissionState.Unrestricted); p2.AddPathList(FileIOPermissionAccess.Read, Path.GetFullPath("FileIOPermission.txt")); p2.AddPathList(FileIOPermissionAccess.AllAccess, Path.GetFullPath("FileIOPermission.cs")); p1.AddPathList(FileIOPermissionAccess.Read, Path.GetFullPath("FileIOPermission.exe")); Console.WriteLine(p1.Union(p2)); } } }
A B C D E F G H I J K L M N O P
The output is
Q
R S T U V W X Y Z
1722
Contents | Index
System.Security.Permissions FileIOPermissionAccess Enum
BCL
Object
A
IComparable
ValueType Enum
B
IFormattable FileIOPermissionAccess
IConvertible
NotStandardized
C D
Summary
E
Represents access to files and directories.
F
Type Summary
G
CF public enum FileIOPermissionAccess { CF AllAccess = Read | Write | Append | PathDiscovery, CF Append = 0x4, CF NoAccess = 0x0, CF PathDiscovery = 0x8, CF Read = 0x1, CF Write = 0x2, }
H I J K L M
Description
N
[Note: This enumeration is used by the System.Security.Permissions.FileIOPermission class. ]
O P
Example using using using using
Q
System; System.IO; System.Security.Permissions; System.Security;
R S T
namespace Samples { public class FileIOPermissionAccessSample { public static void Main() { string s = Path.GetFullPath("FileIOPermission.txt"); FileIOPermission p = new FileIOPermission( FileIOPermissionAccess.Read | FileIOPermissionAccess.Write | FileIOPermissionAccess.Append | FileIOPermissionAccess.PathDiscovery,
U V W X Y Z
1723
Contents | Index
FileIOPermissionAccess Enum
System.Security.Permissions
AllAccess Field
s); Console.WriteLine(p.ToXml()); } }
A
}
B
The output is
C
D E F G H I J K L
FileIOPermissionAccess.AllAccess Field
M
[ILASM]
N
.field public static literal valuetype System.Security.Permissions.FileIOPermissionAccess AllAccess [C#]
O
AllAccess = Read | Write | Append | PathDiscovery
P
Summary
Q
Specifies System.Security.Permissions.FileIOPermissionAccess.Append, System.Security.Permissions.FileIOPermissionAccess.Read, System.Security.Permissions.FileIOPermissionAccess.Write, and System.Security.Permissions.FileIOPermissionAccess.PathDiscovery access to a file or directory.
R S T U V
FileIOPermissionAccess.Append Field
W
[ILASM]
X
.field public static literal valuetype System.Security.Permissions.FileIOPermissionAccess Append
Y
[C#]
Z
Append = 0x4
1724
Contents | Index
System.Security.Permissions
FileIOPermissionAccess Enum Read Field
Summary Specifies append access to a file or directory. Append access includes the ability to create a new file or directory. A B
FileIOPermissionAccess.NoAccess Field
C
[ILASM]
D
.field public static literal valuetype System.Security.Permissions.FileIOPermissionAccess NoAccess
E
[C#]
F
NoAccess = 0x0
G
Summary
H
Specifies no access to a file or directory.
I J
FileIOPermissionAccess.PathDiscovery Field
K
[ILASM]
L
.field public static literal valuetype System.Security.Permissions.FileIOPermissionAccess PathDiscovery
M
[C#]
N
PathDiscovery = 0x8
O
Summary
P
Specifies access to the path information for a file or directory. System.Security.Permissions.FileIOPermissionAccess.PathDiscovery does not include access to the contents of a file or directory. [Note: This permission is used to protect sensitive information in the path, such as user names, as well as information about the directory structure revealed in the path.]
Q R S T U
FileIOPermissionAccess.Read Field
V
[ILASM]
W
.field public static literal valuetype System.Security.Permissions.FileIOPermissionAccess Read
X
[C#]
Y
Read = 0x1
Z
1725
Contents | Index
FileIOPermissionAccess Enum
System.Security.Permissions
Write Field
Summary Specifies read access to a file or directory. A B
FileIOPermissionAccess.Write Field
C
[ILASM]
D
.field public static literal valuetype System.Security.Permissions.FileIOPermissionAccess Write
E
[C#]
Write = 0x2
F G
Summary
H
Specifies write access to a file or directory. Write access includes deleting and overwriting files or directories.
I J K L M N O P Q R S T U V W X Y Z
1726
Contents | Index
System.Security.Permissions FileIOPermissionAttribute
BCL
Object
A
Attribute SecurityAttribute
B
CodeAccessSecurityAttribute
C
FileIOPermissionAttribute
D E
Summary
F
Used to declaratively specify security actions to control access to files and directories.
G
Type Summary
H
CF public sealed class FileIOPermissionAttribute : CodeAccessSecurityAttribute { // Constructors CF public FileIOPermissionAttribute(SecurityAction action)
I J K
// CF CF CF CF CF
Properties public string public string public string public string public string
All { get; set; } Append { get; set; } PathDiscovery { get; set; Read { get; set; } Write { get; set; }
L M }
N O P
// Methods CF public override IPermission CreatePermission ();
Q
}
R
Description
S
[Note: The level of access to a file or directory is specified using the members of the current instance. For example, to specify read permissions for a file, set the System.Security.Permissions.FileIOPermissionAttribute.Read property equal to the name of the file. The security information declared by a security attribute is stored in the metadata of the attribute target, and is accessed by the system at runtime. Security attributes are used for declarative security only. For imperative security, use the corresponding permission class, System.Security.Permissions.FileIOPermission. The allowable System.Security.Permissions.FileIOPermissionAttribute targets are determined by the System.Security.Permissions.SecurityAction passed to the constructor.] Casesensitivity of file and directory names is platform dependent. The set of characters that are valid for use in file and directory names is determined by the current file system.
T U V W X Y Z
1727
Contents | Index
FileIOPermissionAttribute
System.Security.Permissions
FileIOPermissionAttribute() Constructor
Example Please note the use of an absolute path, as opposed to a relative path, in the following example. A using using using using
B C
System; System.IO; System.Security; System.Security.Permissions;
D [assembly:FileIOPermissionAttribute( SecurityAction.RequestMinimum, All=@"C:\Temp\BCL")]
E F
namespace Samples { public class FileIOPermissionAttributeSample { public static void Main() { using(FileStream output = File.Create(@"c:\Temp\BCL\file.txt")) { Console.WriteLine("Name: {0}", output.Name); } } } }
G H I J K L M N O
The output is
P Q
Name: c:\Temp\BCL\file.txt
R S T
FileIOPermissionAttribute(System.Security.Permissions.SecurityAction) Constructor
U
[ILASM]
V
public rtspecialname specialname instance void .ctor(valuetype System.Security.Permissions.SecurityAction action)
W
[C#]
public FileIOPermissionAttribute(SecurityAction action)
X Y
Summary
Z
Constructs and initializes a new instance of the System.Security.Permissions.FileIOPermissionAttribute class with the specified System.Security.Permissions.SecurityAction value. 1728
Contents | Index
System.Security.Permissions
FileIOPermissionAttribute FileIOPermissionAttribute() Constructor
Parameters Parameter
Description
action
A System.Security.Permissions.SecurityAction value.
A B C
Exceptions
D E
Exception
Condition F
System.ArgumentException
action is not a valid System.Security.Permissions.SecurityAction value.
G H I
Example
J
Please note the use of an absolute path, as opposed to a relative path, in the following example.
K using using using using
System; System.IO; System.Security; System.Security.Permissions;
L M N
[assembly:FileIOPermissionAttribute( SecurityAction.RequestMinimum, All=@"C:\Temp\BCL")]
O P Q
namespace Samples { public class FileIOPermissionAttributeConstructor { public static void Main() { using(FileStream output = File.Create(@"c:\Temp\BCL\file.txt")) { Console.WriteLine("Name: {0}", output.Name); } } } }
R S T U V W X Y Z
The output is Name: c:\Temp\BCL\file.txt
1729
Contents | Index
FileIOPermissionAttribute
System.Security.Permissions
All Property
FileIOPermissionAttribute.All Property [ILASM]
A
.property string All { public hidebysig specialname instance string get_All() public hidebysig specialname instance void set_All(string value) }
B
[C#]
public string All { get; set; }
C D
Summary
E
Sets the name of a file or directory for which full access is secured.
F
Description
G
[Note: This property sets full access for a single file or directory; use additional System.Security.Permissions.FileIOPermissionAttribute attributes to specify additional files and directories.]
H I
Exceptions
J K L M
Exception
Condition
System.ArgumentException
The path information specified for a set operation contains invalid characters or wild card specifiers.
N O
Example
P
Please note the use of an absolute path, as opposed to a relative path, in the following example.
Q R
using using using using
S T
System; System.IO; System.Security; System.Security.Permissions;
U [assembly:FileIOPermissionAttribute( SecurityAction.RequestMinimum, All=@"C:\Temp\BCL")]
V W
namespace Samples {
X Y
public class FileIOPermissionAttributeAll { public static void Main() {
Z
1730
Contents | Index
System.Security.Permissions
FileIOPermissionAttribute Append Property
using(FileStream output = File.Create(@"c:\Temp\BCL\file.txt")) { Console.WriteLine("Name: {0}", output.Name); }
A
}
B
}
C
}
D
The output is
E Name: c:\Temp\BCL\file.txt
F G
FileIOPermissionAttribute.Append Property
H
[ILASM]
I
.property string Append { public hidebysig specialname instance string get_Append() public hidebysig specialname instance void set_Append(string value) }
J
[C#]
K
public string Append { get; set; }
L
Summary
M
Gets or sets the name of a file or directory for which append access is secured.
N O
Description
P
[Note: This property sets append access for a single file or directory; use additional System.Security.Permissions.FileIOPermissionAttribute attributes to specify additional files and directories.]
Q R S
Exceptions
T
Exception
Condition
U
The path information specified for a set operation contains invalid characters or wild card specifiers.
V
System.ArgumentException
W X
Example
Y
Please note the use of an absolute path, as opposed to a relative path, in the following example.
Z
using System; using System.IO;
1731
Contents | Index
FileIOPermissionAttribute
System.Security.Permissions
PathDiscovery Property
using System.Security; using System.Security.Permissions; [assembly:FileIOPermissionAttribute( SecurityAction.RequestMinimum, Append=@"C:\Temp\BCL\Append.txt")]
A B C
namespace Samples { public class FileIOPermissionAttributeAppend { public static void Main() { using(StreamWriter output = File.AppendText( @"c:\Temp\BCL\Append.txt")) { Console.WriteLine("Name: {0}", output); } } } }
D E F G H I J K L
The output is
M Name: System.IO.StreamWriter
N O
FileIOPermissionAttribute.PathDiscovery Property
P
[ILASM]
Q R
.property string PathDiscovery { public hidebysig specialname instance string get_PathDiscovery() public hidebysig specialname instance void set_PathDiscovery(string value) }
S
[C#]
public string PathDiscovery { get; set; }
T U
Summary
V
Gets or sets the name of a file or directory for which path discovery access is secured.
W
Description
X
[Note: This property sets path discovery access for a single file or directory; use additional System.Security.Permissions.FileIOPermissionAttribute attributes to specify additional files and directories. Path discovery controls access to the information in the path itself. This protects sensitive information in the path, such as user names, as well
Y Z
1732
Contents | Index
System.Security.Permissions
FileIOPermissionAttribute PathDiscovery Property
as information about the directory structure revealed in the path. This value does not secure access to files or folders represented by the path.] A
Exceptions
B
Exception
Condition
System.ArgumentException
The path information specified for a set operation contains invalid characters or wild card specifiers.
C D E F
Example
G
Please note the use of an absolute path, as opposed to a relative path, in the following example. using using using using using
H
System; System.IO; System.Security; System.Security.Permissions; System.Reflection;
I J K L
[assembly:FileIOPermissionAttribute( SecurityAction.RequestMinimum, PathDiscovery=@"C:\Temp")]
M N O
namespace Samples { public class FileIOPermissionAttributePathDiscovery { public static void Main() { string[] directories = Directory.GetDirectories("C:\\Temp"); foreach(string s in directories) Console.WriteLine("Subdirectory: {0}", s); } } }
P Q R S T U V W
The output is Subdirectory: Subdirectory: Subdirectory: Subdirectory:
X
C:\Temp\BCL C:\Temp\brad C:\Temp\damien C:\Temp\mark
Y Z
1733
Contents | Index
FileIOPermissionAttribute
System.Security.Permissions
Read Property
FileIOPermissionAttribute.Read Property [ILASM]
A
.property string Read { public hidebysig specialname instance string get_Read() public hidebysig specialname instance void set_Read(string value) }
B
[C#]
public string Read { get; set; }
C D
Summary
E
Gets or sets the name of a file or directory for which read access is secured.
F
Description
G
[Note: This property sets read access for a single file or directory; use additional System.Security.Permissions.FileIOPermissionAttribute attributes to specify additional files and directories.]
H I J
Exceptions
K L M
Exception
Condition
System.ArgumentException
The path information specified for a set operation contains invalid characters or wild card specifiers.
N O
Example
P
Please note the use of an absolute path, as opposed to a relative path, in the following example.
Q R
using using using using
S T U
System; System.IO; System.Security; System.Security.Permissions;
[assembly:FileIOPermissionAttribute( SecurityAction.RequestMinimum, Read=@"C:\Temp\BCL\read.txt")]
V W
namespace Samples { public class FileIOPermissionAttributeRead { public static void Main() { string s = @"C:\Temp\BCL\read.txt"; using(StreamReader sr = new StreamReader(s))
X Y Z
1734
Contents | Index
System.Security.Permissions
FileIOPermissionAttribute Write Property
{ Console.WriteLine(sr.ReadToEnd()); } }
A
} }
B C
The output is
D 15/05/2003 6:36:51 PM
E F
FileIOPermissionAttribute.Write Property
G [ILASM]
H
.property string Write { public hidebysig specialname instance string get_Write() public hidebysig specialname instance void set_Write(string value) }
I
[C#]
J
public string Write { get; set; }
K
Summary
L
Gets or sets the name of a file or directory for which write access is secured.
M
Description
N
[Note: This property sets write access for a single file or directory; use additional System.Security.Permissions.FileIOPermissionAttribute attributes to specify additional files and directories.]
O P Q
Exceptions
R
Exception
Condition
System.ArgumentException
The path information specified for a set operation contains invalid characters or wild card specifiers.
S T U V W
Example
X
Please note the use of an absolute path, as opposed to a relative path, in the following example.
Y Z
using System; using System.IO; using System.Security;
1735
Contents | Index
FileIOPermissionAttribute
System.Security.Permissions
CreatePermission() Method
using System.Security.Permissions; [assembly:FileIOPermissionAttribute( SecurityAction.RequestMinimum, Write=@"C:\Temp\BCL\Read.txt")]
A B
namespace Samples { public class FileIOPermissionAttributeWrite { public static void Main() { using(TextWriter tw = new StreamWriter(@"C:\Temp\BCL\Read.txt")) { tw.WriteLine(DateTime.Now.ToString()); } } } }
C D E F G H I J K
There is no output from this program.
L M N
FileIOPermissionAttribute.CreatePermission() Method
O
[ILASM]
P
.method public hidebysig virtual class System.Security.IPermission CreatePermission()
Q
[C#]
public override IPermission CreatePermission()
R S
Summary
T
Returns a new System.Security.Permissions.FileIOPermission that contains the security information of the current instance.
U V
Description
W
[Note: Applications typically do not call this method; it is intended for use by the system. The security information declared by a security attribute is stored in the metadata of the attribute target, and is accessed by the system at runtime. The system uses the object returned by this method to convert the security information of the current instance into the form stored in metadata. This method overrides System.Security.Permissions.SecurityAttribute.CreatePermission.]
X Y Z
1736
Contents | Index
System.IO FileLoadException
BCL
Object Exception
ISerializable
NotStandardized
A B
SystemException IOException
C
FileLoadException
D E
Summary
F
Represents the error that occurs when a System.Reflection.Assembly file is found but cannot be loaded.
G H
Type Summary
I
CF public class FileLoadException : IOException { // Constructors CF public FileLoadException() MS CF protected FileLoadException (SerializationInfo info, StreamingContext context); CF public FileLoadException(string message) CF public FileLoadException(string message, Exception inner) CF public FileLoadException(string message, string fileName) CF public FileLoadException(string message, string fileName, Exception inner) // CF MS CF CF
J K L M N O P
Properties public string FileName { get; } public string FusionLog { get; } public override string Message { get; }
Q R S
// Methods MS CF public override void GetObjectData (SerializationInfo info, StreamingContext context); CF public override string ToString (); }
T U V W
BA See my comments on FileNotFoundException.
X Y Z
1737
Contents | Index
FileLoadException
System.IO
FileLoadException Class
Description [Note: The System.IO.FileLoadException exception is thrown when the file fails to load because it cannot be located. If the file is located, but cannot be loaded due to insufficient permissions, a System.Security.SecurityException is thrown.]
A B
Example
C
using System; using System.IO; using System.Reflection;
D E F
namespace Samples { public class FileLoadExceptionSample { public static void Main() { try { Assembly a = Assembly.LoadFrom( "ModuleOnly.netmodule"); Console.WriteLine(a.Location); } catch(FileLoadException e) { Console.WriteLine("Exception: {0}", e); } } } }
G H I J K L M N O P Q R
The output is
S Exception: System.IO.FileLoadException: The module 'ModuleOnly.netmodule' was expected to contain an assembly manifest. File name: "ModuleOnly.netmodule" at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Boolean isStringized, Evidence assemblySecurity, Boolean throwOnFileNotFound, Assembly locationHint, StackCrawlMark& stackMark) at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Boolean stringized, Evidence assemblySecurity, StackCrawlMark& stackMark) at System.Reflection.Assembly.LoadFrom(String assemblyFile, Evidence securityEvidence) at System.Reflection.Assembly.LoadFrom(String assemblyFile) at Samples.FileLoadExceptionSample.Main() in C:\Books\BCL\Samples\System.IO\ FileLoadException\FileLoadException.cs:line 13
T U V W X Y Z
1738
Contents | Index
System.IO
FileLoadException FileLoadException() Constructor
Fusion log follows: === Pre-bind state information === LOG: Where-ref bind. Location = C:\Books\BCL\Samples\System.IO\FileLoadException\ ModuleOnly.netmodule LOG: Appbase = C:\Books\BCL\Samples\System.IO\FileLoadException\ LOG: Initial PrivatePath = NULL Calling assembly : (Unknown). ===
A B C D
LOG: Application configuration file does not exist. LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind). LOG: Attempting download of new URL file:///C:/Books/BCL/Samples/System.IO/ FileLoadException/ModuleOnly.netmodule.
E F G H
FileLoadException() Constructor
I
[ILASM]
J
public rtspecialname specialname instance void .ctor()
K
[C#]
public FileLoadException()
L M
Summary
N
Constructs and initializes a new instance of the System.IO.FileLoadException class.
O
Description
P
This constructor initializes the System.IO.FileLoadException.Message property of the new instance to a system-supplied message that describes the error, such as “Could not load the specified file.” This message takes into account the current system culture. The System.IO.FileLoadException.InnerException property and System.IO.FileLoadException.FileName property of the new instance are initialized to null.
Q R S T U V
FileLoadException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
W X
[ILASM]
Y
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
Z
[C#]
protected FileLoadException(SerializationInfo info, StreamingContext context)
1739
Contents | Index
FileLoadException
System.IO
FileLoadException() Constructor
Summary Initializes a new instance of the System.IO.FileLoadException class with serialized data. A
Parameters
B C D E
Parameter
Description
info
The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown.
context
The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination.
F G H I J
FileLoadException(System.String) Constructor
K
[ILASM]
L
public rtspecialname specialname instance void .ctor(string message)
M
public FileLoadException(string message)
[C#]
N
Summary
O
Constructs and initializes a new instance of the System.IO.FileLoadException class with the specified error message.
P Q
Parameters
R S
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
T U V W
Description
X
This constructor initializes the System.IO.FileLoadException.Message property of the new instance using message. If message is null, the System.IO.FileLoadException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments.
Y Z
1740
Contents | Index
System.IO
FileLoadException FileLoadException() Constructor
The System.IO.FileLoadException.InnerException property and System.IO.FileLoadException.FileName property of the new instance are initialized to null. A B
FileLoadException(System.String, System.Exception) Constructor
C
[ILASM]
D
public rtspecialname specialname instance void .ctor(string message, class System.Exception inner)
E
[C#]
F
public FileLoadException(string message, Exception inner)
G
Summary
H
Constructs and initializes a new instance of the System.IO.FileLoadException class.
I J
Parameters
K
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
inner
An instance of System.Exception that is the cause of the current exception. If inner is non-null, then the current exception was raised in a catch block handling inner.
L M N O P Q R
Description
S
This constructor initializes the System.IO.FileLoadException.Message property of the new instance using message and the System.IO.FileLoadException.InnerException property using inner. If message is null, the System.IO.FileLoadException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.IO.FileLoadException.FileName property of the new instance is initialized to null. [Note: For more information on inner exceptions, see System.Exception.InnerException.]
T U V W X Y Z
1741
Contents | Index
FileLoadException
System.IO
FileLoadException() Constructor
FileLoadException(System.String, System.String) Constructor [ILASM]
public rtspecialname specialname instance void .ctor(string message, string fileName)
A
[C#]
public FileLoadException(string message, string fileName)
B C
Summary
D
Constructs and initializes a new instance of the System.IO.FileLoadException class.
E
Parameters
F G
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
fileName
A System.String containing the name of the file that was not loaded.
H I J K L M
Description
N
This constructor initializes the System.IO.FileLoadException.Message property of the new instance using message and the System.IO.FileLoadException.FileName property using fileName. If message is null, the System.IO.FileLoadException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.IO.FileLoadException.InnerException property of the new instance is initialized to null. [Note: System.IO.FileLoadException.FileName is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device.]
O P Q R S T U V
FileLoadException(System.String, System.String, System.Exception) Constructor
W X
[ILASM]
Y
public rtspecialname specialname instance void .ctor(string message, string fileName, class System.Exception inner)
Z
[C#]
public FileLoadException(string message, string fileName, Exception inner)
1742
Contents | Index
System.IO
FileLoadException FileName Property
Summary Constructs and initializes a new instance of the System.IO.FileLoadException class. A
Parameters
B
Parameter
Description
C
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
D
message
fileName
A System.String containing the name of the file that was not loaded.
inner
An instance of System.Exception that is the cause of the current exception. If inner is non-null, then the current exception was raised in a catch block handling inner.
E F G H I J
Description
K
This constructor initializes the System.IO.FileLoadException.Message property of the new instance using message, the System.IO.FileLoadException.InnerException property using inner, and the System.IO.FileLoadException.FileName property using fileName. If message is null, the System.IO.FileLoadException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: System.IO.FileLoadException.FileName is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device. For more information on inner exceptions, see System.Exception.InnerException.]
L M N O P Q R S T
FileLoadException.FileName Property
U
[ILASM]
V
.property string FileName { public hidebysig specialname instance string get_FileName() }
W
[C#]
X
public string FileName { get; }
Y
Summary
Z
Gets the name of the file that caused the current exception.
1743
Contents | Index
FileLoadException
System.IO
FusionLog Property
Description This property returns the name of the file supplied to the constructor for the current instance, if any. If the file name was not specified or is a null reference, this property returns null.
A B C
FileLoadException.FusionLog Property
D [ILASM]
E
.property string FusionLog { public hidebysig specialname instance string get_FusionLog() }
F
[C#]
G
public string FusionLog { get; }
H
Summary
I
Gets the log file that describes why an assembly load failed.
J K
Property Value
L
A string containing errors reported by the assembly cache.
M
Exceptions
N O P
Exception
Condition
System.Security.SecurityException
The caller does not have the required permission.
Q R
Permissions
S T
Permission
Description
System.Security.Permissions.SecurityPermission
To provide evidence and view and modify policy. Associated enumerations: System.Security.Permissions.SecurityPermissionFlag. ControlEvidence, System.Security.Permissions.SecurityPermissionFlag.ControlPolicy.
U V W X Y Z
1744
Contents | Index
System.IO
FileLoadException GetObjectData() Method
FileLoadException.Message Property [ILASM]
.property string Message { public hidebysig virtual specialname string get_Message() } [C#]
A
public override string Message { get; }
B C
Summary
D
Gets the error message that describes the current exception.
E
Description
F
If the message supplied to the constructor for the current instance was not null, this property returns that message. Otherwise, this property returns a system-supplied message that includes the name of the file that was not loaded, for example, “Unable to load file a FileName.” (FileName represents the value returned by System.IO.FileLoadException.FileName.) If System.IO.FileLoadException.FileName is null, this is indicated in the system-supplied message as “(null)”. The system-supplied message takes into account the current system culture. [Note: This property overrides System.Exception.Message.]
G H I J K L M
FileLoadException.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Method
O
[ILASM]
P
.method public hidebysig virtual void GetObjectData(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
Q
N
R
[C#]
S
public override void GetObjectData(SerializationInfo info, StreamingContext context)
T
Summary
U
Sets the System.Runtime.Serialization.SerializationInfo with the file name and additional exception information.
V W X Y Z
1745
Contents | Index
FileLoadException
System.IO
ToString() Method
Parameters Parameter
Description
info
The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown.
context
The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination.
A B C D E F
Exceptions
G H
Exception
Condition
I
System.Security.SecurityException
The caller does not have the required permission.
J K
Permissions
L M
Permission
Description
System.Security.Permissions.SecurityPermission
To provide evidence and view and modify policy. Associated enumerations: System.Security.Permissions.SecurityPermissionFlag. ControlEvidence, System.Security.Permissions.SecurityPermissionFlag.ControlPolicy.
N O P Q R
FileLoadException.ToString() Method
S
[ILASM]
T
.method public hidebysig virtual string ToString()
U
[C#]
public override string ToString()
V W
Summary
X
Returns a string representation of the current exception.
Y Z
1746
Contents | Index
System.IO
FileLoadException ToString() Method
Description The string representation returned by this method includes the value of the System.IO.FileLoadException.Message property, the value of the System.IO.FileLoadException.FileName property, the result of calling ToString on the exception returned by System.IO.FileLoadException.InnerException, and the result of calling System.Environment.StackTrace. If any of these members is null, its value is not included in the returned string. [Note: This method overrides System.Object.ToString.]
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1747
Contents | Index
System.IO FileMode Enum
BCL
Object
A
IComparable
ValueType
B
IFormattable
Enum FileMode
C
IConvertible
NotStandardized
D
Summary
E
Specifies how the operating system opens a file.
F G
Type Summary public enum FileMode { Append = 6, Create = 2, CreateNew = 1, Open = 3, OpenOrCreate = 4, Truncate = 5, }
H I J K L M N
Description
O
System.IO.FileMode values specify whether a file is created if one does not exist, and determine whether the contents of existing files are retained or overwritten.
P Q
Example
R
using System; using System.IO;
S namespace Samples { public class FileModeSample { public static void Main() { string s = @"FileMode.txt"; FileMode[] filemodes = {FileMode.Append, FileMode.Create, FileMode.CreateNew, FileMode.Open, FileMode.OpenOrCreate, FileMode.Truncate}; foreach(FileMode fm in filemodes)
T U V W X Y Z
1748
Contents | Index
System.IO
FileMode Enum Append Field
{ OpenFile(s, fm,FileAccess.Write); } } private static void OpenFile(string s, FileMode fm, FileAccess a) { try { using(FileStream fs = File.Open(s, fm, a)) { Console.WriteLine( "Can seek in {0} when opened with {1} and {2}: {3}", s, a, fm, fs.CanSeek); } } catch(Exception e) { Console.WriteLine( "Cannot open {0} with {1}, reason {2}", s, fm, e.Message); } }
A B C D E F G H I J K L M
}
N
}
O
The output is
P Can seek in FileMode.txt when opened with Write and Append: True Can seek in FileMode.txt when opened with Write and Create: True Cannot open FileMode.txt with CreateNew, reason The file "C:\Books\BCL\Samples\System.IO\FileMode\FileMode.txt" already exists. Can seek in FileMode.txt when opened with Write and Open: True Can seek in FileMode.txt when opened with Write and OpenOrCreate: True Can seek in FileMode.txt when opened with Write and Truncate: True
Q R S T U V
FileMode.Append Field
W
[ILASM]
.field public static literal valuetype System.IO.FileMode Append
X
[C#]
Y
Append = 6
Z
1749
Contents | Index
FileMode Enum
System.IO
Create Field
Summary Requests a file be opened. If the file exists, its contents are preserved. This value is valid only for System.IO.FileAccess.Write access. Attempts to read from a file opened with Append cause an exception.
A B C
FileMode.Create Field
D [ILASM]
E
.field public static literal valuetype System.IO.FileMode Create
F
[C#]
Create = 2
G
Summary
H
Requests a new file be created if it does not exist. The file contents are overwritten if it does exist. This value is equivalent to requesting that if the file does not exist, use System.IO.FileMode.CreateNew; otherwise, use System.IO.FileMode.Truncate.
I J K L
FileMode.CreateNew Field
M
[ILASM]
N
.field public static literal valuetype System.IO.FileMode CreateNew [C#]
O
CreateNew = 1
P Q
Summary
R
Requests a new file be created. An exception is thrown if the file already exists.
S T
FileMode.Open Field
U
[ILASM]
.field public static literal valuetype System.IO.FileMode Open
V
[C#]
W
Open = 3
X
Summary
Y
Requests an existing file be opened. An exception is thrown if the file does not exist.
Z
1750
Contents | Index
System.IO
FileMode Enum Truncate Field
FileMode.OpenOrCreate Field [ILASM]
.field public static literal valuetype System.IO.FileMode OpenOrCreate [C#]
A
OpenOrCreate = 4
B C
Summary
D
Requests a file be opened. The file is created if it does not exist.
E F
FileMode.Truncate Field
G
[ILASM]
H
.field public static literal valuetype System.IO.FileMode Truncate [C#]
I
Truncate = 5
J
Summary
K
Requests an existing file be opened; existing contents are deleted. This value is valid only for System.IO.FileAccess.Write access. Attempts to read from a file opened with Truncate cause an exception.
L M N O P Q R S T U V W X Y Z
1751
Contents | Index
System.IO FileNotFoundException
BCL
Object
A
Exception
B
ISerializable
NotStandardized
SystemException IOException
C
FileNotFoundException
D E
Summary
F
Represents the error that occurs when a file path argument specifies a file that does not exist.
G H
Type Summary
I
public class FileNotFoundException : IOException { // Constructors public FileNotFoundException() MS CF protected FileNotFoundException (SerializationInfo info, StreamingContext context); public FileNotFoundException(string message) CF public FileNotFoundException(string message, Exception innerException) CF public FileNotFoundException(string message, string fileName) CF public FileNotFoundException(string message, string fileName, Exception innerException)
J K L M N O P
// CF MS CF CF
Q R S
Properties public string FileName { get; } public string FusionLog { get; } public override string Message { get; }
// Methods MS CF public override void GetObjectData (SerializationInfo info, StreamingContext context); CF public override string ToString (); }
T U V W X Y Z
1752
Contents | Index
System.IO
FileNotFoundException FileNotFoundException Class
BA You might think there are not any security issues associated with an exception. However, an exception such as this one can contain personally identifiable information in the file path (such as a user name). Exceptions by their nature pass information between layers of the call stack. Therefore if semi-trusted code calls a fully trusted library, the semi-trusted code can find out all the public information in the exception raised by the library. That is why it is always a good idea to carefully scrutinize any information visible via an exception. For example with the FileNotFoundException we are interested in protecting the discovery of a file path. Path discovery can be used by a hacker to tell the type and version of software installed on a machine and can often be used to locate user names and other personally identifiable information.
A B C D E F G
Example
H
using System; using System.IO;
I J
namespace Samples { public class FileNotFoundExceptionSample { public static void Main() { try { string s = "NotExists.txt"; using(FileStream fs = File.Open(s, FileMode.Open)) { Console.WriteLine("File opened: {0}", s); } } catch(FileNotFoundException e) { Console.WriteLine("Exception: {0}", e); } } } }
K L M N O P Q R S T U V W
The output is
X Y
Exception: System.IO.FileNotFoundException: Could not find file "C:\Books\BCL\ Samples\System.IO\FileNotFoundException\NotExists.txt". File name: "C:\Books\BCL\Samples\System.IO\FileNotFoundException\NotExists.txt" at System.IO.__Error.WinIOError(Int32 errorCode, String str)
Z
1753
Contents | Index
FileNotFoundException
System.IO
FileNotFoundException() Constructor
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean useAsync, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) at System.IO.File.Open(String path, FileMode mode) at Samples.FileNotFoundExceptionSample.Main() in C:\Books\BCL\Samples\ System.IO\FileNotFoundException\FileNotFoundException.cs:line 13
A B C D E
FileNotFoundException() Constructor
F
[ILASM]
public rtspecialname specialname instance void .ctor()
G
[C#]
H
public FileNotFoundException()
I
Summary
J
Constructs and initializes a new instance of the System.IO.FileNotFoundException class.
K L
Description
M
This constructor initializes the System.IO.FileNotFoundException.Message property of the new instance to a system-supplied message that describes the error, such as “Could not find the specified file.” This message takes into account the current system culture. The System.IO.FileNotFoundException.InnerException and System.IO.FileNotFoundException.FileName properties of the new instance are initialized to null.
N O P Q R S
FileNotFoundException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
T U
[ILASM]
V
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
W
[C#]
X
protected FileNotFoundException(SerializationInfo info, StreamingContext context)
Y
Summary
Z
Initializes a new instance of the System.IO.FileNotFoundException class with the specified serialization and context information. 1754
Contents | Index
System.IO
FileNotFoundException FileNotFoundException() Constructor
Parameters Parameter
Description
info
The data for serializing or deserializing the file.
context
The source and destination for the file.
A B C D E
FileNotFoundException(System.String) Constructor
F
[ILASM]
G
public rtspecialname specialname instance void .ctor(string message)
H
[C#]
public FileNotFoundException(string message)
I
Summary
J
Constructs and initializes a new instance of the System.IO.FileNotFoundException class.
K L M
Parameters
N
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
O P Q R S
Description
T
This constructor initializes the System.IO.FileNotFoundException.Message property of the new instance using message. If message is null, the System.IO.FileNotFoundException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.IO.FileNotFoundException.InnerException and System.IO.FileNotFoundException.FileName properties of the new instance are initialized to null.
U V W X Y Z
1755
Contents | Index
FileNotFoundException
System.IO
FileNotFoundException() Constructor
FileNotFoundException(System.String, System.Exception) Constructor [ILASM]
A
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
B
[C#]
public FileNotFoundException(string message, Exception innerException)
C D
Summary
E
Constructs and initializes a new instance of the System.IO.FileNotFoundException class.
F G
Parameters
H I
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
J K L M N O
Description
P
This constructor initializes the System.IO.FileNotFoundException.Message property of the new instance using message and the System.IO.FileNotFoundException.InnerException property using innerException. If message is null, the System.IO.FileNotFoundException.Message property is initialized to the systemsupplied message provided by the constructor that takes no arguments. The System.IO.FileNotFoundException.FileName property of the new instance is initialized to null. [Note: For more information on inner exceptions, see System.Exception.InnerException.]
Q R S T U V W X
FileNotFoundException(System.String, System.String) Constructor
Y [ILASM]
Z
public rtspecialname specialname instance void .ctor(string message, string fileName) [C#]
public FileNotFoundException(string message, string fileName)
1756
Contents | Index
System.IO
FileNotFoundException FileNotFoundException() Constructor
Summary Constructs and initializes a new instance of the System.IO.FileNotFoundException class. A
Parameters
B C
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
fileName
D E F G
A System.String containing the name of the file that was not found.
H I
Description
J
The constructor initializes the System.IO.FileNotFoundException.Message property of the new instance using message and the System.IO.FileNotFoundException.FileName property using fileName. If message is null, the System.IO.FileNotFoundException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.IO.FileNotFoundException.InnerException property of the new instance is initialized to null.
K L M N O P
FileNotFoundException(System.String, System.String, System.Exception) Constructor
Q R
[ILASM]
S
public rtspecialname specialname instance void .ctor(string message, string fileName, class System.Exception innerException)
T
[C#]
U
public FileNotFoundException(string message, string fileName, Exception innerException)
V W
Summary
X
Constructs and initializes a new instance of the System.IO.FileNotFoundException class.
Y Z
1757
Contents | Index
FileNotFoundException
System.IO
FileName Property
Parameters Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
fileName
The name of the file that was not found.
innerException
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
A B C D E F G H
Description
I
This constructor initializes the System.IO.FileNotFoundException.Message property of the new instance using message, the System.IO.FileNotFoundException.FileName property using fileName, and the System.IO.FileNotFoundException.InnerException property using innerException. If message is null, the System.IO.FileNotFoundException.Message property is initialized to the systemsupplied message provided by the constructor that takes no arguments. [Note: For more information on inner exceptions, see System.Exception.InnerException.]
J K L M N O P Q
FileNotFoundException.FileName Property
R
[ILASM]
S
.property string FileName { public hidebysig specialname instance string get_FileName() } [C#]
T
public string FileName { get; }
U V
Summary
W
Gets the name of the file that cannot be found.
X
Property Value
Y
A System.String containing the name of the file, or null if no file name was passed to the constructor for the current instance.
Z
1758
Contents | Index
System.IO
FileNotFoundException Message Property
FileNotFoundException.FusionLog Property [ILASM]
.property string FusionLog { public hidebysig specialname instance string get_FusionLog() }
A
[C#]
B
public string FusionLog { get; }
C
Summary
D
Gets the log file that describes why loading of an assembly failed.
E F
Property Value
G
A String containing errors reported by the assembly cache.
H
Exceptions
I
Exception
Condition
System.Security.SecurityException
The caller does not have the required permission.
J K L M
Permissions
N O
Permission
Description
System.Security.Permissions.SecurityPermission
To provide evidence and view and modify policy. Associated enumerations: System.Security.Permissions.SecurityPermissionFlag.ControlEvidence, System.Security.Permissions.SecurityPermissionFlag.ControlPolicy.
P Q R S T U
FileNotFoundException.Message Property
V
[ILASM]
.property string Message { public hidebysig virtual specialname string get_Message() }
W
[C#]
X
public override string Message { get; }
Y Z
Summary Gets the error message that explains the reason for the exception.
1759
Contents | Index
FileNotFoundException
System.IO
GetObjectData() Method
Property Value A System.String containing the error message. This string includes the System.IO.FileNotFoundException.FileName if a value for that property was supplied to the constructor for the current instance.
A B C
FileNotFoundException.GetObjectData(System.Runtime.Serialization. SerializationInfo, System.Runtime.Serialization.StreamingContext) Method
D E
[ILASM]
.method public hidebysig virtual void GetObjectData(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
F G
[C#]
H
public override void GetObjectData(SerializationInfo info, StreamingContext context)
I J
Summary
K
Sets the System.Runtime.Serialization.SerializationInfo object with the file name and additional exception information.
L M
Parameters
N O
Parameter
Description
info
The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown.
context
The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination.
P Q R S T U
FileNotFoundException.ToString() Method
V
[ILASM]
W
.method public hidebysig virtual string ToString()
X
[C#]
public override string ToString()
Y Z
Summary Returns a System.String representation of the current instance.
1760
Contents | Index
System.IO
FileNotFoundException ToString() Method
Description The string representation returned by this method includes the fully qualified name of the current exception, the message, the result of calling ToString on the inner exception, the file name, and the result of calling System.Environment.StackTrace. Null values are omitted from the returned string. [Note: This method overrides System.Object.ToString.]
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1761
Contents | Index
System.IO FileShare Enum
BCL
Object
A
IComparable
ValueType
B
Enum
IFormattable FileShare
C
IConvertible
NotStandardized
D
Summary
E
Specifies the level of access permitted for a file that is already in use.
F G
Type Summary public enum FileShare { MS CF Inheritable = 0x10, None = 0x0, Read = 0x1, ReadWrite = Read | Write, Write = 0x2, }
H I J K L M
Description
N
This enumeration is used to specify the way in which multiple threads access the same file. The level of access is set by the first thread that requests access to the file. For example, if a thread opens a file and specifies FileShare.Read, other threads are permitted to open the file for reading but not for writing.
O P Q
Example
R
using System; using System.IO;
S T
namespace Samples { public class FileShareSample { public static void Main() { string s = @"open.txt"; FileShare[] fileShares = { FileShare.None, FileShare.Read, FileShare.ReadWrite, FileShare.Write}; foreach(FileShare fs in fileShares)
U V W X Y Z
1762
Contents | Index
System.IO
FileShare Enum FileShare Enum
{ using(FileStream a = File.Open(s, FileMode.OpenOrCreate, FileAccess.ReadWrite, fs)) { Console.WriteLine("Opened with FileShare: {0}", fs); OpenAgain(s); Console.WriteLine(); }
A B C D
} } public static void OpenAgain(string s) { try { using(FileStream a = File.Open(s, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { Console.WriteLine("Can open file again to read"); } } catch(Exception) { Console.WriteLine("Can not open file again to read"); } }
E F G H I J K L M N O P
}
Q
}
R
The output is
S Opened with FileShare: None Can not open file again to read
T U
Opened with FileShare: Read Can open file again to read
V W
Opened with FileShare: ReadWrite Can open file again to read
X Y
Opened with FileShare: Write Can not open file again to read
Z
1763
Contents | Index
FileShare Enum
System.IO
Inheritable Field
FileShare.Inheritable Field [ILASM]
.field public static literal valuetype System.IO.FileShare Inheritable
A
[C#]
Inheritable = 0x10
B C
Summary
D
Makes the file handle inheritable by child processes. This is not directly supported by Win32.
E F
FileShare.None Field
G
[ILASM]
H
.field public static literal valuetype System.IO.FileShare None [C#]
I
None = 0x0
J K
Summary
L
Specifies that the file may not be accessed by additional threads.
M N
FileShare.Read Field
O
[ILASM]
.field public static literal valuetype System.IO.FileShare Read
P
[C#]
Q
Read = 0x1
R
Summary
S
Specifies that additional threads can share read access to the file. This value does not determine whether such access is granted, however.
T U V
FileShare.ReadWrite Field
W
[ILASM]
X
.field public static literal valuetype System.IO.FileShare ReadWrite [C#]
Y
ReadWrite = Read | Write
Z
1764
Contents | Index
System.IO
FileShare Enum Write Field
Summary Specifies that additional threads can share read and/or write access to the file. This value does not determine whether such access is granted, however. A B
FileShare.Write Field
C
[ILASM]
D
.field public static literal valuetype System.IO.FileShare Write
E
[C#]
Write = 0x2
F
Summary
G
Specifies that additional threads can share write access to the file. This value does not determine whether such access is granted, however.
H I J K L M N O P Q R S T U V W X Y Z
1765
Contents | Index
System.IO FileStream
BCL
Object
A
MarshalByRefObject
B
Stream
IDisposable
FileStream
C D
Summary
E
Exposes a System.IO.Stream around a file, supporting both synchronous and asynchronous read and write operations.
F G
Type Summary
H
public class FileStream : Stream { // Constructors public FileStream(string path, FileMode mode) public FileStream(string path, FileMode mode, FileAccess access) public FileStream(string path, FileMode mode, FileAccess access, FileShare share) public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) MS CF public FileStream(IntPtr handle, FileAccess access) MS CF public FileStream(IntPtr handle, FileAccess access, bool ownsHandle) MS CF public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize) MS CF public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync)
I J K L M N O P Q R S T U
// Properties public override bool CanRead { get; } public override bool CanSeek { get; } public override bool CanWrite { get; } MS CF public virtual IntPtr Handle { get; } public virtual bool IsAsync { get; } public override long Length { get; } MS public string Name { get; } public override long Position { set; get; }
V W X Y Z
1766
Contents | Index
System.IO
FileStream FileStream Class
// Methods CF public override IAsyncResult BeginRead (byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject); CF public override IAsyncResult BeginWrite (byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject); public override void Close (); protected virtual void Dispose (bool disposing); CF public override int EndRead (IAsyncResult asyncResult); CF public override void EndWrite (IAsyncResult asyncResult); ~FileStream () {} public override void Flush (); MS CF public virtual void Lock (long position, long length); public override int Read (byte[] array, int offset, int count); public override int ReadByte (); public override long Seek (long offset, SeekOrigin origin); public override void SetLength (long value); MS CF public virtual void Unlock (long position, long length); public override void Write (byte[] array, int offset, int count); public override void WriteByte (byte value); }
A B C D E F G H I J K L M N O P Q R S
BA Notice that FileStream implements IDisposable in order to signal that
T
there is a scarce resource (an OS file handle in this case) encapsulated in this type that the client code may need to explicitly free rather than waiting for the GC to free it eventually. This interface also enables C#’s using(…) statement.
U V
When we introduced the IDisposable interface to the system the FileStream class had a single Close() method to close the OS file handle. We wanted the nice language support implementing IDisposable gave us but we did not want to have just a Dispose() method on this class as there are years of prior art teaching developers to expect to be able to “Close” a file. We also did not want there to be both a
W X Y Z
continued
1767
Contents | Index
FileStream
System.IO
FileStream Class
Close() and Dispose() method on the class that do exactly the same thing as that would undoubtedly confuse developers. That is why we decided to explicitly implement the Dispose method such that it does not show up as part of the public contract of FileStream, but is available only when the class is cast to the IDisposable interface. This design enables both the using() style support as well as an explicit Close() style.
A B C D
//using style using (FileStream f = new FileStream (“foo.txt”, FileMode.Open)) { //read from f here… } //guaranteed f is closed here
E F G
//Close style FileStream f = new FileStream (“foo.txt”, FileMode.Open); try { //read from f here… } finally { if (f != null) f.Close();
H I J K L
}
M
BG One of the nicer features of our Stream classes is that they all support one API for synchronous and asynchronous reads and writes. However, some OS’s limit I/O operations on a given file handle to only synchronous or only asynchronous operations at one time. In Windows, you must open a file handle normally with CreateFile or in overlapped mode, via a somewhat obscure parameter to CreateFile. The useAsync parameter to the constructor exists to allow users to tell us which way they want the file opened.
N O P Q R S
However, CLI implementers still have the option (and I’d say the responsibility) to provide implementations of the synchronous read and write methods in terms of the async methods, and vice versa. Performance may be worse in these cases and async callbacks may be run synchronously, but the point is that the APIs must be usable at all times.
T U V
KG A great name for a great class. The problem is that this is not the class that should be in the most common scenario: reading and writing text in a file. For that usage people should be using StreamReader and StreamWriter. This class invariably leads people to rat-hole for a while before discovering the more appropriate, but less well-named alternates. It might have been better if StreamReader and StreamWriter were called FileReader and FileWriter.
W X Y Z
continued
1768
Contents | Index
System.IO
FileStream FileStream Class
JR As Brian points out, the asynchronous support of streams is a really nice feature. However, as Kit points out, FileStreams should typically be used with a StreamReader, StreamWriter, BinaryReader, or BinaryWriter class. Unfortunately, these classes do not expose the asynchronous support so you must perform synchronous I/O when using any of these “helper” classes.
A B C
Description
D
System.IO.FileStream is used for reading and writing files on a file system, as well as other file-related operating system handles such as pipes, standard input, standard output. System.IO.FileStream buffers input and output for better performance. The System.IO.FileStream class can open a file in one of two modes, either synchronously or asynchronously, with significant performance consequences for the synchronous methods (System.IO.FileStream.Read and System.IO.FileStream.Write) and the asynchronous methods (System.IO.FileStream.BeginRead and System.IO.FileStream.BeginWrite). Both sets of methods will work in either mode; however, the mode will affect the performance of these methods. System.IO.FileStream defaults to opening files synchronously, but provides a constructor to open files asynchronously. When accessing files, a security check is performed when the file is created or opened. The security check is typically not done again unless the file is closed and reopened. [Note: Checking permissions when the file is first accessed minimizes the impact of the security check on application performance (since opening a file happens once, while reading and writing can happen multiple times).] Note that if an opened file is passed to an untrusted caller, the security system can, but is not required to, prevent the caller from accessing the file. System.IO.FileStream objects support random access to files using the System.IO.FileStream.Seek method, and the System.IO.Stream.CanSeek properties of System.IO.FileStream instances encapsulating files are set to true. The System.IO.FileStream.Seek method allows the read/write position to be moved to any position within the file. This is done with byte offset reference point parameters. The byte offset is relative to the seek reference point, which can be the beginning, the current position, or the end of the underlying file, as represented by the three values of the System.IO.SeekOrigin enumeration. If a System.IO.FileStream encapsulates a device that does not support seeking, its System.IO.FileStream.CanSeek property is false. [Note: For additional information, see System.IO.Stream.CanSeek.] [Note: The System.IO.File class provides methods for the creation of System. IO.FileStream objects based on file paths. The System.IO.MemoryStream class creates a stream from a byte array and functions similarly to a System.IO.FileStream.]
E F G H I J K L M N O P Q R S T U V W X Y Z
1769
Contents | Index
FileStream
System.IO
FileStream Class
Example using System; using System.IO; using System.Text;
A B
namespace Samples { public class FileStreamSample { public static void Main() { string s = "filestream.txt"; using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate, FileAccess.Write)) { Console.WriteLine("FileStream opened on {0} ", fs.Name); DisplayInformationAboutStream(fs); string ds = String.Format("Written at: {0}\n", DateTime.Now.ToString()); UTF8Encoding e = new UTF8Encoding(); int count = e.GetByteCount(ds.ToCharArray(), 0, ds.Length); Byte[] bytes = new Byte[count]; e.GetBytes(ds, 0, ds.Length, bytes, 0); fs.Seek(0, SeekOrigin.End); fs.Write(bytes, 0, bytes.Length); } using(FileStream fs = new FileStream(s, FileMode.Open, FileAccess.Read)) { Console.WriteLine("FileStream opened on {0}", fs.Name); DisplayInformationAboutStream(fs); const int limit = 80; Byte[] bytes = new byte[limit]; Decoder d = Encoding.UTF8.GetDecoder(); char[] chars = null; for(int i = fs.Read(bytes, 0, limit); i != 0; i = fs.Read(bytes, 0, limit)) { int count = d.GetCharCount(bytes, 0, i); chars = new Char[count]; count = d.GetChars(bytes, 0, i, chars, 0); Console.Write(new string(chars)); } } } public static void DisplayInformationAboutStream( FileStream fs) {
C D E F G H I J K L M N O P Q R S T U V W X Y Z
1770
Contents | Index
System.IO
FileStream FileStream() Constructor
Console.WriteLine("Can read from stream: {0}", fs.CanRead); Console.WriteLine("Can write to stream: {0}", fs.CanWrite); Console.WriteLine("Can seek in stream: {0}", fs.CanSeek); Console.WriteLine("Async access to stream: {0}", fs.IsAsync);
A B C
}
D
} }
E
The output is
F G
FileStream opened on C:\Books\BCL\Samples\System.IO\FileStream\filestream.txt Can read from stream: False Can write to stream: True Can seek in stream: True Async access to stream: False FileStream opened on C:\Books\BCL\Samples\System.IO\FileStream\filestream.txt Can read from stream: True Can write to stream: False Can seek in stream: True Async access to stream: False Written at: 26/12/2002 10:53:22 AM Written at: 26/12/2002 10:55:36 AM Written at: 26/12/2002 10:55:39 AM Written at: 26/12/2002 10:55:41 AM Written at: 26/12/2002 10:55:43 AM Written at: 9/03/2003 3:47:16 PM Written at: 15/06/2003 10:52:58 AM Written at: 15/06/2003 10:58:11 AM Written at: 15/06/2003 10:58:20 AM
H I J K L M N O P Q R S T
FileStream(System.String, System.IO.FileMode) Constructor
U [ILASM]
V
public rtspecialname specialname instance void .ctor(string path, valuetype System.IO.FileMode mode) [C#]
W
public FileStream(string path, FileMode mode)
X Y
Summary
Z
Constructs and initializes a new instance of the System.IO.FileStream class with the specified path and creation mode.
1771
Contents | Index
FileStream
System.IO
FileStream() Constructor
Parameters Parameter
Description
path
A System.String containing the relative or absolute path for the file that the current System.IO.FileStream object will encapsulate.
mode
A System.IO.FileMode value that determines how to open or create the file.
A B C D E
Description
F
This constructor sets System.IO.FileAccess.ReadWrite access to the file, and the System.IO.Stream.CanRead and System.IO.Stream.CanWrite properties of the current instance are set to true. [Note: path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device.] System.IO.Stream.CanSeek is true for all System.IO.FileStream objects that encapsulate files. If path specifies a device that does not support seeking, the System.IO.FileStream.CanSeek property of the resulting System.IO.FileStream is required to be false. [Note: For additional information, see System.IO.Stream.CanSeek.] Requests to open the file for writing by the current or another thread will fail until the System.IO.FileStream object has been closed. Read attempts will succeed.
G H I J K L M N O P
Exceptions
Q R
Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.ArgumentNullException
path is null.
System.Security.SecurityException
The caller does not have the required permission.
System.IO.FileNotFoundException
mode is System.IO.FileMode.Truncate or System.IO.FileMode.Open, but the specified file cannot be found. If a different mode is specified and the file cannot be found, a new one is created.
S T U V W X Y Z
1772
Contents | Index
System.IO
FileStream FileStream() Constructor
Exception
Condition
System.IO.IOException
An I/O error occurred, such as specifying System.IO.FileMode.CreateNew when the file specified by path already exists.
System.IO.DirectoryNotFoundException
The directory information specified in path does not exist.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
D
System.ArgumentOutOfRangeException
mode contains an invalid value.
F
A B C
E
G H
Permissions
I
Permission
Description
J
Requires permission to read, write, and append to files. See System.Security.Permissions.FileIOPermissionAccess.Read, System.Security.Permissions.FileIOPermissionAccess.Write, and System.Security.Permissions.FileIOPermissionAccess.Append.
K
System.Security.Permissions.FileIOPermission
L M N
Example
O
using System; using System.IO; using System.Text;
P Q R
namespace Samples { public class FileStreamConstructor { public static void Main() { string s = "filestream.txt"; using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate)) { Console.WriteLine("FileStream opened on {0} ", fs.Name); Console.WriteLine("Can read from stream: {0}", fs.CanRead); Console.WriteLine("Can write to stream: {0}", fs.CanWrite);
S T U V W X Y Z
1773
Contents | Index
FileStream
System.IO
FileStream() Constructor
Console.WriteLine("Can seek in stream: {0}", fs.CanSeek); Console.WriteLine("Async access to stream: {0}", fs.IsAsync);
A
} }
B }
C
}
D
The output is
E FileStream opened on C:\Books\BCL\Samples\System.IO\FileStream\ FileStream(System.String,System.IO.FileMode)\filestream.txt Can read from stream: True Can write to stream: True Can seek in stream: True Async access to stream: False
F G H I J
FileStream(System.String, System.IO.FileMode, System.IO.FileAccess) Constructor
K L
[ILASM]
M
public rtspecialname specialname instance void .ctor(string path, valuetype System.IO.FileMode mode, valuetype System.IO.FileAccess access)
N
[C#]
O
public FileStream(string path, FileMode mode, FileAccess access)
P
Summary
Q
Constructs and initializes a new instance of the System.IO.FileStream class with the specified path, creation mode, and access type.
R S
Parameters
T U
Parameter
Description
W
path
A System.String containing the relative or absolute path for the file that the current System.IO.FileStream object will encapsulate.
X
mode
A System.IO.FileMode value that determines how to open or create the file.
access
A System.IO.FileAccess value that determines how the file may be accessed by the System.IO.FileStream object. This parameter is used to specify the initial values of the System.IO.FileStream.CanRead and System.IO.FileStream.CanWrite properties.
V
Y Z
1774
Contents | Index
System.IO
FileStream FileStream() Constructor
Description This constructor sets read/write access to the file. Requests to open the file for writing by the current or another thread will fail until the System.IO.FileStream object has been closed. Read attempts will succeed. [Note: path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device.] System.IO.Stream.CanSeek is true for all System.IO.FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the System.IO.FileStream.CanSeek property on the resulting System.IO.FileStream is required to be false. For additional information, see System.IO.Stream.CanSeek.
A B C D E F G
Exceptions Exception
H I
Condition
J System.ArgumentNullException
path is null.
K
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
L
System.IO.FileNotFoundException
mode is System.IO.FileMode.Truncate or System.IO.FileMode.Open, but the specified file was not found. If a different mode is specified and the file was not found, a new one is created.
System.IO.IOException
M N O P
An I/O error occurred, such as specifying System.IO.FileMode.CreateNew when the file specified by path already exists.
Q R S
System.Security.SecurityException
The caller does not have the required permission.
System.IO.DirectoryNotFoundException
The directory information specified by path does not exist.
System.UnauthorizedAccessException
The access requested is not permitted by the operating system for the specified path.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
X
System.ArgumentOutOfRangeException
mode or access contains an invalid value.
Z
T U V W
Y
1775
Contents | Index
FileStream
System.IO
FileStream() Constructor
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to read, write, and append to files. See System.Security.Permissions.FileIOPermissionAccess.Read, System.Security.Permissions.FileIOPermissionAccess.Write, and System.Security.Permissions.FileIOPermissionAccess.Append.
A B C D E F
Example
G
using System; using System.IO; using System.Text;
H I
namespace Samples { public class FileStreamConstructor { public static void Main() { string s = "filestream.txt"; using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate, FileAccess.Write)) { Console.WriteLine("FileStream opened on {0} ", fs.Name); Console.WriteLine("Can read from stream: {0}", fs.CanRead); Console.WriteLine("Can write to stream: {0}", fs.CanWrite); Console.WriteLine("Can seek in stream: {0}", fs.CanSeek); Console.WriteLine("Async access to stream: {0}", fs.IsAsync); } } } }
J K L M N O P Q R S T U V W X Y Z
1776
Contents | Index
System.IO
FileStream FileStream() Constructor
The output is FileStream opened on C:\Books\BCL\Samples\System.IO\FileStream\ FileStream(System.String,System.IO.FileMode,System.IO.FileAccess)\filestream.txt Can read from stream: False Can write to stream: True Can seek in stream: True Async access to stream: False
A B C D E
FileStream(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare) Constructor
F G
[ILASM]
public rtspecialname specialname instance void .ctor(string path, valuetype System.IO.FileMode mode, valuetype System.IO.FileAccess access, valuetype System.IO.FileShare share)
H
[C#]
J
I
public FileStream(string path, FileMode mode, FileAccess access, FileShare share)
K
Summary
L
Constructs and initializes a new instance of the System.IO.FileStream class with the specified path, creation mode, access type, and sharing permission.
M N O
Parameters
P
Parameter
Description
path
A System.String containing a relative or absolute path for the file that the current System.IO.FileStream object will encapsulate.
mode
A System.IO.FileMode value that determines how to open or create the file.
T U
access
A System.IO.FileAccess value that determines how the file may be accessed by the System.IO.FileStream object. This parameter is used to specify the initial values of the System.IO.FileStream.CanRead and System.IO.FileStream.CanWrite properties. For additional information, see System.IO.Stream.CanRead and System.IO.Stream.CanWrite.
Q R S
V W X
share
A System.IO.FileShare value that determines how the file will be shared by processes.
Y Z
1777
Contents | Index
FileStream
System.IO
FileStream() Constructor
Description This constructor sets read/write access to the file. [Note: path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device.] System.IO.Stream.CanSeek is true for all System.IO.FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the System.IO.FileStream.CanSeek property on the resulting System.IO.FileStream is required to be false. For additional information, see System.IO.Stream.CanSeek.
A B C D E F
Exceptions
G H I J K L M N
Exception
Condition
System.ArgumentNullException
path is null.
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
System.IO.FileNotFoundException
mode is System.IO.FileMode.Truncate or System.IO.FileMode.Open, but the specified file cannot be found. If a different mode is specified and the file cannot be found, a new one is created.
System.IO.IOException
An I/O error occurred, such as specifying System.IO.FileMode.CreateNew and the file specified by path already exists.
System.Security.SecurityException
The caller does not have the required permission.
System.IO.DirectoryNotFoundException
The directory information specified by path does not exist.
System.UnauthorizedAccessException
The access requested is not permitted by the operating system for the specified path.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
System.ArgumentOutOfRangeException
mode, access, or share contains an invalid value.
O P Q R S T U V W X Y Z
1778
Contents | Index
System.IO
FileStream FileStream() Constructor
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to read, write, and append to files. See System.Security.Permissions.FileIOPermissionAccess.Read, System.Security.Permissions.FileIOPermissionAccess.Write, and System.Security.Permissions.FileIOPermissionAccess.Append.
A B C D E F
Example
G
using System; using System.IO; using System.Text;
H I
namespace Samples { public class FileStreamConstructor { public static void Main() { string s = "filestream.txt"; using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)) { Console.WriteLine("FileStream opened on {0} ", fs.Name); Console.WriteLine("Can read from stream: {0}", fs.CanRead); Console.WriteLine("Can write to stream: {0}", fs.CanWrite); Console.WriteLine("Can seek in stream: {0}", fs.CanSeek); Console.WriteLine("Async access to stream: {0}", fs.IsAsync); } } } }
J K L M N O P Q R S T U V W X Y Z
1779
Contents | Index
FileStream
System.IO
FileStream() Constructor
The output is FileStream opened on C:\Books\BCL\Samples\System.IO\FileStream\ FileStream(System.String,System.IO.FileMode,System.IO.FileAccess,System.IO. FileShare)\filestream.txt Can read from stream: False Can write to stream: True Can seek in stream: True Async access to stream: False
A B C D E
G
FileStream(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare, System.Int32) Constructor
H
[ILASM]
I
public rtspecialname specialname instance void .ctor(string path, valuetype System.IO.FileMode mode, valuetype System.IO.FileAccess access, valuetype System.IO.FileShare share, int32 bufferSize)
F
J
[C#]
K
public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
L M
Summary
N
Constructs and initializes a new instance of the System.IO.FileStream class.
O
Parameters
P Q
Parameter
Description
path
A System.String containing the relative or absolute path for the file that the current System.IO.FileStream object will encapsulate.
mode
A System.IO.FileMode constant that determines how to open or create the file.
access
A System.IO.FileAccess value that determines how the file may be accessed by the System.IO.FileStream object. This parameter is used to specify the initial values of the System.IO.FileStream.CanRead and System.IO.FileStream.CanWrite properties. For additional information, see System.IO.Stream.CanRead and System.IO.Stream.CanWrite.
share
A System.IO.FileShare constant that determines how the file will be shared by processes.
bufferSize
A System.Int32 containing the desired buffer size in bytes.
R S T U V W X Y Z
1780
Contents | Index
System.IO
FileStream FileStream() Constructor
Description [Note: path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device.] System.IO.Stream.CanSeek is true for all System.IO.FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the System.IO.FileStream.CanSeek property on the resulting System.IO.FileStream is required to be false. For additional information, see System.IO.Stream.CanSeek.
A B C D E
Exceptions Exception
F G
Condition
H System.ArgumentNullException
The path parameter is null.
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
K
bufferSize is less than or equal to zero.
L
-or-
M
mode, access, or share contains an invalid value.
N
mode is System.IO.FileMode.Truncate or System.IO.FileMode.Open, but the specified file cannot be found. If a different mode is specified and the file cannot be found, a new one is created.
O
An I/O error occurred, such as specifying System.IO.FileMode.CreateNew and the file specified by path already exists.
R
System.ArgumentOutOfRangeException
System.IO.FileNotFoundException
System.IO.IOException
I J
P Q
S T
System.Security.SecurityException
The caller does not have the required permission.
System.IO.DirectoryNotFoundException
The directory information specified in path does not exist.
System.UnauthorizedAccessException
The access requested is not permitted by the operating system for the specified path.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
U V W X Y Z
1781
Contents | Index
FileStream
System.IO
FileStream() Constructor
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to read, write, and append to files. See System.Security.Permissions.FileIOPermissionAccess.Read, System.Security.Permissions.FileIOPermissionAccess.Write, and System.Security.Permissions.FileIOPermissionAccess.Append.
A B C D E F
Example
G
using System; using System.IO; using System.Text;
H I
namespace Samples { public class FileStreamConstructor { public static void Main() { string s = "filestream.txt"; using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 512)) { Console.WriteLine("FileStream opened on {0} ", fs.Name); Console.WriteLine("Can read from stream: {0}", fs.CanRead); Console.WriteLine("Can write to stream: {0}", fs.CanWrite); Console.WriteLine("Can seek in stream: {0}", fs.CanSeek); Console.WriteLine("Async access to stream: {0}", fs.IsAsync); } } } }
J K L M N O P Q R S T U V W X
The output is
Y Z
FileStream opened on C:\Books\BCL\Samples\System.IO\FileStream\ FileStream(System.String,System.IO.FileMode,System.IO.FileAccess,System.IO. FileShare,System.Int32)\filestream.txt
1782
Contents | Index
System.IO
FileStream FileStream() Constructor
Can read from stream: False Can write to stream: True Can seek in stream: True Async access to stream: False
A B
FileStream(System.String, System.IO.FileMode, System.IO.FileAccess, System.IO.FileShare, System.Int32, System.Boolean) Constructor
C D
[ILASM]
E
public rtspecialname specialname instance void .ctor(string path, valuetype System.IO.FileMode mode, valuetype System.IO.FileAccess access, valuetype System.IO.FileShare share, int32 bufferSize, bool useAsync)
F G
[C#]
public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync)
H I
Summary
J
Constructs and initializes a new instance of the System.IO.FileStream class.
K L
Parameters
M
Parameter
Description
N
path
A System.String containing the relative or absolute path for the file that the new System.IO.FileStream object will encapsulate.
O
mode
A System.IO.FileMode value that determines how to open or create the file.
Q R
access
A System.IO.FileAccess value that determines how the file may be accessed by the System.IO.FileStream object. This parameter is used to specify the initial values of the System.IO.FileStream.CanRead and System.IO.FileStream.CanWrite properties.
share
A System.IO.FileShare value that determines how the file will be shared by processes.
bufferSize
A System.Int32 containing the desired buffer size in bytes.
useAsync
A System.Boolean value that specifies whether to use asynchronous I/O or synchronous I/O. If the underlying operating system does not support asynchronous I/O, the System.IO.FileStream ignores this parameter and uses synchronous I/O.
P
S T U V W X Y Z
1783
Contents | Index
FileStream
System.IO
FileStream() Constructor
Description This constructor sets read/write access to the file. [Note: path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device.] System.IO.Stream.CanSeek is true for all System.IO.FileStream objects that encapsulate files. If path indicates a device that does not support seeking, the System.IO.FileStream.CanSeek property on the resulting System.IO.FileStream is required to be false. For additional information, see System.IO.Stream.CanSeek.
A B C D E F
Exceptions
G H
Exception
Condition
I
System.ArgumentNullException
path is null.
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementation-defined invalid characters.
J K L
bufferSize is less than or equal to zero.
M
System.ArgumentOutOfRangeException
N
-ormode, access, or share contains an invalid value.
O P Q
System.IO.FileNotFoundException
mode is System.IO.FileMode.Truncate or System.IO.FileMode.Open, but the specified file cannot be found. If a different mode is specified and the file cannot be found, a new one is created.
System.IO.IOException
An I/O error occurred, such as specifying System.IO.FileMode.CreateNew and the file specified by path already exists.
System.Security.SecurityException
The caller does not have the required permission.
System.IO.DirectoryNotFoundException
The directory information specified by path does not exist.
System.UnauthorizedAccessException
The access requested is not permitted by the operating system for the specified path.
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
R S T U V W X Y Z
1784
Contents | Index
System.IO
FileStream FileStream() Constructor
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to read, write, and append to files. See System.Security.Permissions.FileIOPermissionAccess.Read, System.Security.Permissions.FileIOPermissionAccess.Write, and System.Security.Permissions.FileIOPermissionAccess.Append.
A B C D E F
Example
G
using System; using System.IO; using System.Text;
H I
namespace Samples { public class FileStreamConstructor { public static void Main() { string s = "filestream.txt"; using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 512, true)) { Console.WriteLine("FileStream opened on {0} ", fs.Name); Console.WriteLine("Can read from stream: {0}", fs.CanRead); Console.WriteLine("Can write to stream: {0}", fs.CanWrite); Console.WriteLine("Can seek in stream: {0}", fs.CanSeek); Console.WriteLine("Async access to stream: {0}", fs.IsAsync); } } } }
J K L M N O P Q R S T U V W X Y Z
1785
Contents | Index
FileStream
System.IO
FileStream() Constructor
The output is FileStream opened on C:\Books\BCL\Samples\System.IO\FileStream\ FileStream(System.String,System.IO.FileMode,System.IO.FileAccess, System.IO.FileShare,System.Int32,System.Boolean)\filestream.txt Can read from stream: False Can write to stream: True Can seek in stream: True Async access to stream: True
A B C D E F
FileStream(System.IntPtr, System.IO.FileAccess) Constructor
G
[ILASM]
H
public rtspecialname specialname instance void .ctor(valuetype System.IntPtr handle, valuetype System.IO.FileAccess access)
I
[C#]
public FileStream(IntPtr handle, FileAccess access)
J K
Summary
L
Initializes a new instance of the System.IO.FileStream class for the specified file handle, with the specified read/write permission.
M N
Parameters
O P
Parameter
Description
Q
handle
A file handle for the file that the current FileStream object will encapsulate.
access
A System.IO.FileAccess constant that gets the System.IO.FileStream.CanRead and System.IO.FileStream.CanWrite properties of the FileStream object.
R S T U
Description
V
When System.IO.FileStream.Close is called, the handle is also closed and the file’s handle count is decremented. FileStream assumes that it has exclusive control over the handle. Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. For data safety, call System.IO.FileStream.Flush before using the handle, and avoid calling any methods other than Close after you are done using the handle. When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could
W X Y Z
1786
Contents | Index
System.IO
FileStream FileStream() Constructor
cause an exception to be thrown. FileShare.Read is the default for those System.IO.FileStream constructors without a FileShare parameter. A
Exceptions
B
Exception
Condition
System.ArgumentException
access is not a field of System.IO.FileAccess.
System.Security.SecurityException
The caller does not have the required permission.
System.IO.IOException
An I/O error occurs, such as a disk error.
System.UnauthorizedAccessException
The access requested is not permitted by the operating system for the specified file handle, such as when access is Write or ReadWrite and the file handle is set for read-only access.
C D E F G H I J K
Permissions
L
Permission
Description
System.Security.Permissions.FileIOPermission
For reading, writing, and appending to files. Associated enumerations: System.Security.Permissions.FileIOPermissionAccess.Read, System.Security.Permissions.FileIOPermission-Access.Write, and System.Security.Permissions.FileIOPermissionAccess.Append.
M N O P Q R S
FileStream(System.IntPtr, System.IO.FileAccess, System.Boolean) Constructor
T U
[ILASM]
V
public rtspecialname specialname instance void .ctor(valuetype System.IntPtr handle, valuetype System.IO.FileAccess access, bool ownsHandle)
W
[C#]
X
public FileStream(IntPtr handle, FileAccess access, bool ownsHandle)
Y
Summary
Z
Initializes a new instance of the System.IO.FileStream class for the specified file handle, with the specified read/write permission and FileStream instance ownership.
1787
Contents | Index
FileStream
System.IO
FileStream() Constructor
Parameters Parameter
Description
handle
A file handle for the file that the current FileStream object will encapsulate.
access
A System.IO.FileAccess constant that gets the System.IO.FileStream.CanRead and System.IO.FileStream.CanWrite properties of the FileStream object.
ownsHandle
true if the file handle will be owned by this FileStream instance; otherwise, false.
A B C D E F G
Description
H
The FileStream object is given the specified access to the file. The ownership of the handle will be as specified. If this process owns the handle, a call to the System.IO.FileStream.Close method will also close the handle and the file’s handle count is decremented. The FileStream object is given the default buffer size of 8192 bytes. FileStream assumes that it has exclusive control over the handle. Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. For data safety, call System.IO.FileStream.Flush before using the handle, and avoid calling methods other than Close after you are done using the handle. FileShare.Read is the default for those System.IO.FileStream constructors without a FileShare parameter. When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.
I J K L M N O P Q R
Exceptions
S T
Exception
Condition
System.ArgumentException
access is not a field of System.IO.FileAccess.
W
System.Security.SecurityException
The caller does not have the required permission.
X
System.IO.IOException
An I/O error occurs, such as a disk error.
System.UnauthorizedAccessException
The access requested is not permitted by the operating system for the specified file handle, such as when access is Write or ReadWrite and the file handle is set for read-only access.
U V
Y Z
1788
Contents | Index
System.IO
FileStream FileStream() Constructor
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
For reading, writing, and appending to files. Associated enumerations: System.Security.Permissions.FileIOPermissionAccess.Read, System.Security.Permissions.FileIOPermissionAccess.Write, and System.Security.Permissions.FileIOPermissionAccess.Append.
A B C D E F G
FileStream(System.IntPtr, System.IO.FileAccess, System.Boolean, System.Int32) Constructor
H
[ILASM]
I
public rtspecialname specialname instance void .ctor(valuetype System.IntPtr handle, valuetype System.IO.FileAccess access, bool ownsHandle, int32 bufferSize)
J
[C#]
K
public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize)
L M
Summary
N
Initializes a new instance of the System.IO.FileStream class for the specified file handle, with the specified read/write permission, FileStream instance ownership, and buffer size.
O P Q
Parameters
R
Parameter
Description
handle
A file handle for the file that this FileStream object will encapsulate.
access
A System.IO.FileAccess constant that gets the System.IO.FileStream.CanRead and System.IO.FileStream.CanWrite properties of the FileStream object.
S T
ownsHandle bufferSize
U V W
true if the file handle will be owned by this FileStream instance; otherwise, false.
X
The size of the buffer in bytes.
Z
Y
1789
Contents | Index
FileStream
System.IO
FileStream() Constructor
Description The FileStream object is given the specified access to the file. The ownership of the handle will be as specified. If this FileStream owns the handle, a call to the System.IO.FileStream.Close method will also close the handle. In particular, the file’s handle count is decremented. The FileStream object is given the specified buffer size. FileStream assumes that it has exclusive control over the handle. Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. For data safety, call System.IO.FileStream.Flush before using the handle, and avoid calling any methods other than Close after you are done using the handle. Alternately, read and write to the handle before calling this FileStream constructor. FileShare.Read is the default for those System.IO.FileStream constructors without a FileShare parameter. When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable and could cause an exception to be thrown.
A B C D E F G H I J
Exceptions
K L
Exception
Condition
N
System.ArgumentOutOfRangeException
bufferSize is negative.
O
System.IO.IOException
An I/O error occurs, such as a disk error.
System.Security. SecurityException
The caller does not have the required permission.
System.UnauthorizedAccessException
The access requested is not permitted by the operating system for the specified file handle, such as when access is Write or ReadWrite and the file handle is set for read-only access.
M
P Q R S T U
Permissions
V W
Permission
Description
System.Security.Permissions.FileIOPermission
For reading, writing, and appending to files. Associated enumerations: System.Security.Permissions.FileIOPermissionAccess.Read,System.Security.Permissions.FileIOPermissionAccess.Write, and System.Security.Permissions.FileIOPermissionAccess.Append.
X Y Z
1790
Contents | Index
System.IO
FileStream FileStream() Constructor
FileStream(System.IntPtr, System.IO.FileAccess, System.Boolean, System.Int32, System.Boolean) Constructor [ILASM]
A
public rtspecialname specialname instance void .ctor(valuetype System.IntPtr handle, valuetype System.IO.FileAccess access, bool ownsHandle, int32 bufferSize, bool isAsync)
B C
[C#]
public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync)
D E
Summary
F
Initializes a new instance of the System.IO.FileStream class for the specified file handle, with the specified read/write permission, FileStream instance ownership, buffer size, and synchronous or asynchronous state.
G H I
Parameters Parameter
J K
Description
L
handle
A file handle for the file that this FileStream object will encapsulate.
M
A System.IO.FileAccess constant that gets the System.IO.FileStream.CanRead and System.IO.FileStream.CanWrite properties of the FileStream object.
N
access
ownsHandle
true if the file handle will be owned by this FileStream instance; otherwise, false. true if the handle was opened asynchronously (that is, in overlapped I/O mode); otherwise, false.
R
isAsync
The size of the buffer in bytes.
T
bufferSize
O P Q
S
U
Description
V
The FileStream object is given the specified access to the file. The ownership of the handle will be as specified. If this FileStream owns the handle, a call to the System.IO.FileStream.Close method will also close the handle. In particular, the file’s handle count is decremented. The FileStream object is given the specified buffer size. FileStream assumes that it has exclusive control over the handle. Reading, writing, or seeking while a FileStream is also holding a handle could result in data corruption. For data safety, call System.IO.FileStream.Flush before using the handle, and avoid
W X Y Z
1791
Contents | Index
FileStream
System.IO
CanRead Property
calling any methods other than Close after you are done using the handle. Alternately, read and write to the handle before calling this FileStream constructor. FileShare.Read is the default for those System.IO.FileStream constructors without a FileShare parameter. When you compile a set of characters with a particular cultural setting and retrieve those same characters with a different cultural setting, the characters might not be interpretable, and could cause an exception to be thrown.
A B C D
Exceptions
E F
Exception
Condition
System.ArgumentOutOfRangeException
access is less than FileAccess.Read or greater than FileAccess.ReadWrite or bufferSize is less than or equal to 0.
J
System.ArgumentException
The handle is invalid.
K
System.IO.IOException
An I/O error occurs, such as a disk error.
L
System.Security.SecurityException
The caller does not have the required permission.
System.UnauthorizedAccessException
The access requested is not permitted by the operating system for the specified file handle, such as when access is Write or ReadWrite and the file handle is set for read-only access.
G H I
M N O P Q
Permissions
R S
Permission
Description
System.Security.Permissions.SecurityPermission
For access to unmanaged code. Associated enumeration: System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode.
T U V W X
FileStream.CanRead Property
Y
[ILASM]
Z
.property bool CanRead { public hidebysig virtual specialname bool get_CanRead() } [C#]
public override bool CanRead { get; }
1792
Contents | Index
System.IO
FileStream CanRead Property
Summary Gets a System.Boolean value indicating whether the current stream supports reading.
Property Value
A
true if the stream supports reading; false if the stream is closed or was opened with write-only access.
B C D
Description
E
[Note: This property overrides System.IO.Stream.CanRead. If a class derived from System.IO.Stream does not support reading, the Read method throws a System.NotSupportedException.]
F G H
Example
I
using System; using System.IO; using System.Text;
J K
namespace Samples { public class FileStreamCanRead { public static void Main() { string s = "filestream.txt"; FileAccess[] fas = {FileAccess.Write, FileAccess.Read, FileAccess.ReadWrite}; foreach(FileAccess fa in fas) { using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate, fa)) { DisplayInformationAboutStream(fa, fs); } } } public static void DisplayInformationAboutStream( FileAccess fa, FileStream fs) { Console.Write("If opened with: \"{0}\" you can? ", fa); Console.Write("Read: {0} ", fs.CanRead); Console.Write("Write: {0} ", fs.CanWrite);
L M N O P Q R S T U V W X Y Z
1793
Contents | Index
FileStream
System.IO
CanSeek Property
Console.WriteLine("Seek: {0}", fs.CanSeek); } }
A
}
B
The output is
C
If opened with: "Write" you can? Read: False Write: True Seek: True If opened with: "Read" you can? Read: True Write: False Seek: True If opened with: "ReadWrite" you can? Read: True Write: True Seek: True
D E F G
FileStream.CanSeek Property
H
[ILASM]
I
.property bool CanSeek { public hidebysig virtual specialname bool get_CanSeek() } [C#]
J
public override bool CanSeek { get; }
K
Summary
L
Gets a System.Boolean value indicating whether the current stream supports seeking.
M N
Property Value
O
true if the stream supports seeking; false if the stream is closed or if the System.IO.FileStream was constructed from an operating-system handle such as a pipe or output to the console.
P Q R
Description
S
[Note: If a class derived from System.IO.Stream does not support seeking, a call to System.IO.FileStream.Length (both get and set), System.IO.FileStream.Position, or System.IO.FileStream.Seek throws a System.NotSupportedException. This property overrides System.IO.Stream.CanSeek.]
T U V
Example
W
using System; using System.IO; using System.Text;
X Y
namespace Samples { public class FileStreamCanSeek
Z
1794
Contents | Index
System.IO
FileStream CanWrite Property
{ public static void Main() { string s = "filestream.txt"; FileAccess[] fas = {FileAccess.Write, FileAccess.Read, FileAccess.ReadWrite}; foreach(FileAccess fa in fas) { using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate, fa)) { DisplayInformationAboutStream(fa, fs); } }
A B C D E F G H
}
I
public static void DisplayInformationAboutStream( FileAccess fa, FileStream fs) { Console.Write("If opened with: \"{0}\" you can? ", fa); Console.Write("Read: {0} ", fs.CanRead); Console.Write("Write: {0} ", fs.CanWrite); Console.WriteLine("Seek: {0}", fs.CanSeek);
J K L M N
}
O
} }
P Q
The output is
R If opened with: "Write" you can? Read: False Write: True Seek: True If opened with: "Read" you can? Read: True Write: False Seek: True If opened with: "ReadWrite" you can? Read: True Write: True Seek: True
S T U
FileStream.CanWrite Property
V
[ILASM]
W
.property bool CanWrite { public hidebysig virtual specialname bool get_CanWrite() } [C#]
X
public override bool CanWrite { get; }
Y Z
Summary Gets a System.Boolean value indicating whether the current stream supports writing.
1795
Contents | Index
FileStream
System.IO
CanWrite Property
Property Value true if the stream supports writing; false if the stream is closed or was opened with read-only access. A B
Description
C
If a class derived from System.IO.Stream does not support writing, a call to System.IO.FileStream.Write or System.IO.FileStream.BeginWrite will throw a System.NotSupportedException. [Note: This property overrides System.IO.Stream.CanWrite.]
D E F
Example
G
using System; using System.IO; using System.Text;
H I
namespace Samples { public class FileStreamCanWrite { public static void Main() { string s = "filestream.txt"; FileAccess[] fas = {FileAccess.Write, FileAccess.Read, FileAccess.ReadWrite}; foreach(FileAccess fa in fas) { using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate, fa)) { DisplayInformationAboutStream(fa, fs); } } } public static void DisplayInformationAboutStream( FileAccess fa, FileStream fs) { Console.Write("If opened with: \"{0}\" you can? ", fa); Console.Write("Read: {0} ", fs.CanRead); Console.Write("Write: {0} ", fs.CanWrite); Console.WriteLine("Seek: {0}", fs.CanSeek);
J K L M N O P Q R S T U V W X Y Z
} } }
1796
Contents | Index
System.IO
FileStream Handle Property
The output is If opened with: "Write" you can? Read: False Write: True Seek: True If opened with: "Read" you can? Read: True Write: False Seek: True If opened with: "ReadWrite" you can? Read: True Write: True Seek: True
A B C
FileStream.Handle Property
D
[ILASM]
E
.property valuetype System.IntPtr Handle { public hidebysig virtual specialname valuetype System.IntPtr get_Handle() }
F
[C#]
G
public virtual IntPtr Handle { get; }
H
Summary
I
Gets the operating system file handle for the file that the current FileStream object encapsulates.
J K
Property Value
L
The operating system file handle for the file encapsulated by this FileStream object, or –1 if the FileStream has been closed.
M N
Description
O
This property is an operating system handle for use with operating-system-provided system calls (such as ReadFile on Windows). It will not work with C library functions that expect a file descriptor, such as fread. The operating system handle might have been opened synchronously or asynchronously, depending on which FileStream constructor was called. Use the System.IO.FileStream.IsAsync property to discover whether this handle was opened asynchronously. In Win32, this means the handle was opened for overlapped IO, and it requires different parameters to ReadFile and WriteFile. Data corruption might occur if a FileStream is created, its handle is passed, some operation moves the handle’s file pointer, and then the FileStream is used again. Multiple threads cannot safely write to the same file simultaneously, and FileStream buffering code assumes that it exclusively controls the handle. FileStream might throw a System.IO.IOException if FileStream detects that some other process has moved the file pointer. To avoid this, do not write any data into a portion of the file that FileStream might have buffered, and restore the file pointer to the location it had when methods were last called on FileStream.
P Q R S T U V W X Y Z
1797
Contents | Index
FileStream
System.IO
IsAsync Property
Exceptions Exception
Condition
System.Security.SecurityException
The caller does not have the required permission.
A B C
Permissions
D E
Permission
Description
System.Security.Permissions.SecurityPermission
For calling unmanaged code, such as calling native code with PInvoke or COM integration. Associated enumeration: System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode.
F G H I J K
FileStream.IsAsync Property
L
[ILASM]
M
.property bool IsAsync { public hidebysig virtual specialname bool get_IsAsync() } [C#]
N
public virtual bool IsAsync { get; }
O P
Summary
Q
Gets a System.Boolean value indicating whether the current instance was opened asynchronously or synchronously.
R S
Property Value
T
true if the current System.IO.FileStream was opened asynchronously; otherwise, false.
U V
Example
W
using System; using System.IO; using System.Text;
X Y
namespace Samples { public class FileStreamIsAsync {
Z
1798
Contents | Index
System.IO
FileStream Length Property
public static void Main() { string s = "filestream.txt"; bool[] bs = {true, false}; foreach(bool b in bs) { FileStream fs = new FileStream(s, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 512, b); Console.WriteLine("FileStream opened on {0} with {1}", fs.Name, b); Console.WriteLine("Async access to stream: {0}", fs.IsAsync); fs.Close(); } }
A B C D E F G H I J K
} }
L
The output is
M N
FileStream opened on C:\Books\BCL\Samples\System.IO\FileStream\IsAysnc\ filestream.txt with True Async access to stream: True FileStream opened on C:\Books\BCL\Samples\System.IO\FileStream\IsAysnc\ filestream.txt with False Async access to stream: False
O P Q R S
FileStream.Length Property
T [ILASM]
U
.property int64 Length { public hidebysig virtual specialname int64 get_Length() } [C#]
V
public override long Length { get; }
W
Summary
X
Gets the length in bytes of the stream.
Y Z
1799
Contents | Index
FileStream
System.IO
Length Property
Exceptions Exception
Condition
System.NotSupportedException
System.IO.FileStream.CanSeek for this stream is false.
System.IO.IOException
An I/O error occurred, such as the file being closed.
A B C D E
Example
F
using System; using System.IO; using System.Text;
G H I
namespace Samples { public class FileStreamLength { public static void Main() { string s = "filestream.txt"; using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate, FileAccess.Write)) { Console.WriteLine("FileStream opened on {0}", fs.Name); Console.WriteLine("Length is : {0}", fs.Length); if(fs.CanWrite && fs.CanSeek) { fs.SetLength(fs.Length + 42); Console.WriteLine("Length is : {0}", fs.Length); } } } } }
J K L M N O P Q R S T U V W
The output is
X
FileStream opened on C:\Books\BCL\Samples\System.IO\FileStream\Length\ filestream.txt Length is : 126 Length is : 168
Y Z
1800
Contents | Index
System.IO
FileStream Position Property
FileStream.Name Property [ILASM]
.property string Name { public hidebysig specialname instance string get_Name() } [C#]
A
public string Name { get; }
B C
Summary
D
Gets the name of the FileStream that was passed to the constructor.
E
Permissions
F
Permission
Description
System.Security.Permissions.FileIOPermission
For access to the path. Associated enumeration: System.Security.Permissions.FileIOPermissionAccess.PathDiscovery
G H I J K L
FileStream.Position Property
M
[ILASM] .property int64 Position { public hidebysig virtual specialname int64 get_position() public hidebysig virtual specialname void set_Position(int64) value) } [C#]
N O P
public override long Position { get; set; }
Q
Summary
R
Gets or sets the current position of this stream.
S
Description
T
The position cannot be set to more than one byte beyond the end of the stream.
U V W X Y Z
1801
Contents | Index
FileStream
System.IO
Position Property
Exceptions Exception
Condition
B
System.NotSupportedException
The current stream does not support seeking.
C
System.IO.IOException
An I/O error occurred.
System.IO.EndOfStreamException
Attempted seeking past the end of a stream that does not support this.
System.ArgumentOutOfRangeException
The value specified for a set operation is negative.
A
D E F G H
Example
I
using System; using System.IO; using System.Text;
J K L
namespace Samples { public class FileStreamPosition { public static void Main() { string s = "filestream.txt"; using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate, FileAccess.Read)) { Console.WriteLine("FileStream opened on {0}", fs.Name); Console.WriteLine("Postion on open: {0}", fs.Position); Console.WriteLine("Read first byte: {0}", Convert.ToChar(fs.ReadByte())); Console.WriteLine("Postion after read: {0}", fs.Position); fs.Seek(0, SeekOrigin.End); Console.WriteLine("Postion after seeking to end {0}", fs.Position); } } } }
M N O P Q R S T U V W X Y Z
1802
Contents | Index
System.IO
FileStream BeginRead() Method
The output is FileStream opened on C:\Books\BCL\Samples\System.IO\FileStream\Position\ filestream.txt Postion on open: 0 Read first byte: H Postion after read: 1 Postion after seeking to end 32
A B C D E
FileStream.BeginRead(System.Byte[], System.Int32, System.Int32, System.AsyncCallback, System.Object) Method
F G
[ILASM]
.method public hidebysig virtual class System.IAsyncResult BeginRead(class System.Byte[] array, int32 offset, int32 numBytes, class System.AsyncCallback userCallback, object stateObject)
H
[C#]
J
I
public override IAsyncResult BeginRead(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject)
K L
Summary
M
Begins an asynchronous read.
N
Parameters
O
Parameter
Description
array
A System.Byte array that specifies the buffer to read data into.
offset
A System.Int32 containing the zero-based byte offset in array at which to begin writing data read from the stream.
numBytes
A System.Int32 containing the maximum number of bytes to read.
userCallback
A System.AsyncCallback delegate that references the method to be called when the asynchronous read operation is completed.
stateObject
An application-defined object containing the status of the asynchronous read.
P Q R S T U V W X Y
Description
Z
To determine the number of bytes read, call System.IO.Stream.EndRead with the returned System.IAsyncResult.
1803
Contents | Index
FileStream
System.IO
BeginRead() Method
Multiple simultaneous asynchronous requests render the request completion order uncertain. [Note: Use the System.IO.FileStream.CanRead property to determine whether the current instance supports reading. For additional information, see System.IO.Stream.CanRead. This method overrides System.IO.Stream.BeginRead. ]
A B C
Exceptions
D E
Exception
Condition
System.ArgumentException
The sum of offset and numBytes is greater than the length of array.
System.ArgumentNullException
array is null.
System.ArgumentOutOfRangeException
offset or numBytes is negative.
System.IO.IOException
The asynchronous read operation attempted to read past the end of the file.
F G H I J K L M N
Example
O
using using using using
P Q R
System; System.IO; System.Text; System.Threading;
namespace Samples { public class FileStreamBeginRead { const int limit = 512; const int readlimit = 15; public class StateHolder { public byte[] bytes ; public FileStream fs ; } public static void Main() { string s = "filestream.txt"; FileStream fs = new FileStream(s, FileMode.Open,
S T U V W X Y Z
1804
Contents | Index
System.IO
FileStream BeginRead() Method
FileAccess.Read, FileShare.None, 512, true); StateHolder sh = new StateHolder(); sh.fs = fs; sh.bytes = new Byte[limit]; AsyncCallback ac = new AsyncCallback(CallMe); fs.BeginRead(sh.bytes, 0, readlimit, ac, sh); for(int i = 0; i < 50; i++) { Thread.Sleep(5); Console.Write('_'); }
A B C D E F G
} public static void CallMe(IAsyncResult asyncResult) { StateHolder sh = (StateHolder) asyncResult.AsyncState; FileStream fs = sh.fs; int count = fs.EndRead(asyncResult); Console.Write("Bytes read: {0} ", count); if(count != 0) { Decoder d = Encoding.UTF8.GetDecoder(); char[] chars = null; int i = d.GetCharCount(sh.bytes, 0, count); chars = new Char[i]; count = d.GetChars(sh.bytes, 0, count, chars, 0); Console.WriteLine(new string(chars)); fs.BeginRead(sh.bytes, 0, readlimit, new AsyncCallback(CallMe), sh); } else { fs.Close() ; } }
H I J K L M N O P Q R S T
}
U
}
V
The output is
W
__Bytes read: 15 Hello world...
X
Bytes read: 15 Goodbye world. Bytes read: 2
Y Z
________________________________________Bytes read: 0 ________
1805
Contents | Index
FileStream
System.IO
BeginWrite() Method
FileStream.BeginWrite(System.Byte[], System.Int32, System.Int32, System.AsyncCallback, System.Object) Method A
[ILASM]
B
.method public hidebysig virtual class System.IAsyncResult BeginWrite(class System.Byte[] array, int32 offset, int32 numBytes, class System.AsyncCallback userCallback, object stateObject)
C
[C#]
public override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback userCallback, object stateObject)
D E F
Summary
G
Begins an asynchronous write operation.
H
Parameters
I J K
Parameter
Description
array
A System.Byte array buffer containing data to write to the current stream.
offset
A System.Int32 containing the zero-based byte offset in array, which marks the beginning of the data to be written to the current stream.
numBytes
A System.Int32 containing the maximum number of bytes to write.
userCallback
A System.AsyncCallback delegate that references the method to be called when the asynchronous write operation is completed.
stateObject
An application-defined object containing the status of the asynchronous write.
L M N O P Q R S
Description
T
Multiple simultaneous asynchronous requests render the request completion order uncertain. [Note: Use the System.IO.FileStream.CanWrite property to determine whether the current instance supports writing. For additional information, see System.IO.Stream.CanWrite. This method overrides System.IO.Stream.BeginWrite.]
U V W X Y Z
1806
Contents | Index
System.IO
FileStream BeginWrite() Method
Exceptions Exception
Condition
System.ArgumentException
The sum of offset and numBytes is greater than the length of array.
System.ArgumentNullException
array is null.
System.ArgumentOutOfRangeException
offset or numBytes is negative.
A B C D E F System.NotSupportedException
The stream does not support writing.
System.IO.IOException
An I/O error occurred.
G H I J
Example using using using using
K
System; System.IO; System.Text; System.Threading;
L M N
namespace Samples { public class FileStreamBeginWrite { public class StateHolder { public byte[] bytes; public FileStream fs; public int writes = 5; } public static void Main() { string filename = "filestream.txt"; FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Write, FileShare.None, 512, true); string s = DateTime.Now.ToString(); StateHolder sh = new StateHolder(); sh.fs = fs; UTF8Encoding e = new UTF8Encoding(); int count = e.GetByteCount(s);
O P Q R S T U V W X Y Z
1807
Contents | Index
FileStream
System.IO
Close() Method
sh.bytes = new Byte[count]; e.GetBytes(s, 0, sh.bytes.Length, sh.bytes, 0); fs.BeginWrite(sh.bytes, 0, sh.bytes.Length, new AsyncCallback(CallMe), sh); for(int i = 0; i < 50; i++) { Thread.Sleep(5); Console.Write('_'); }
A B C D
} public static void CallMe(IAsyncResult asyncResult) { StateHolder sh = (StateHolder) asyncResult.AsyncState; sh.fs.EndWrite(asyncResult); Console.WriteLine("Write ended"); if(--sh.writes > 0) { sh.fs.BeginWrite(sh.bytes, 0, sh.bytes.Length, new AsyncCallback(CallMe), sh); } else { sh.fs.Close() ; } }
E F G H I J K L M
} }
N O
The output is
P
_Write ended Write ended Write ended Write ended Write ended _________________________________________________
Q R S T U
FileStream.Close() Method
V [ILASM]
W
.method public hidebysig virtual void Close()
X
[C#]
public override void Close()
Y
Summary
Z
Closes the file and releases any resources associated with the current file stream.
1808
Contents | Index
System.IO
FileStream Close() Method
Description This method is equivalent to System.IO.FileStream.Dispose(true). Any data previously written to the buffer is copied to the file before the file stream is closed, so it is not necessary to call System.IO.FileStream.Flush before invoking Close. Following a call to Close, any operations on the file stream might raise exceptions. Invoking this method on the same instance multiple times does not result in an exception.
A B C
Usage
D
The System.IO.FileStream.Finalize method invokes Close so that the file stream is closed before the garbage collector finalizes the object. However, objects writing to the System.IO.FileStream, such as System.IO.StreamWriter, might not have flushed the data from their internal buffers to the System.IO.FileStream when the call to Finalize closes the stream. To prevent data loss, always call Close on the highest-level object. [Note: This method overrides System.IO.Stream.Close.]
E F G H I J
Example
K
using System; using System.IO; using System.Text;
L M N
namespace Samples { public class FileStreamClose { public static void Main() { string s = "filestream.txt"; FileStream fs = new FileStream(s, FileMode.OpenOrCreate); Console.WriteLine("FileStream opened on {0} ", fs.Name); Console.WriteLine("Can read from stream: {0}", fs.CanRead); Console.WriteLine("Can write to stream: {0}", fs.CanWrite); Console.WriteLine("Can seek in stream: {0}", fs.CanSeek); Console.WriteLine("Async access to stream: {0}", fs.IsAsync); fs.Close(); } } }
O P Q R S T U V W X Y Z
1809
Contents | Index
FileStream
System.IO
Dispose() Method
The output is FileStream opened on C:\Books\BCL\Samples\System.IO\FileStream\Close()\filestream.txt Can read from stream: True Can write to stream: True Can seek in stream: True Async access to stream: False
A B C D
FileStream.Dispose(System.Boolean) Method
E F
[ILASM]
G
[C#]
.method family hidebysig virtual void Dispose(bool disposing) protected virtual void Dispose(bool disposing)
H I
Summary
J
Releases the unmanaged resources used by the System.IO.FileStream and optionally releases the managed resources.
K L
Parameters
M N
Parameter
Description
disposing
Specify true to release both managed and unmanaged resources, or specify false to release only unmanaged resources.
O P Q
Description
R
When the disposing parameter is true, this method releases all resources held by any managed objects that this System.IO.FileStream references. [Note: System.IO.FileStream.Dispose may be called multiple times by other objects. When overriding System.IO.FileStream.Dispose(System.Boolean), be careful not to reference objects that have been previously disposed in an earlier call to System.IO.FileStream.Dispose.]
S T U V W
Exceptions
X Y Z
Exception
Condition
System.IO.IOException
An I/O error occurred.
1810
Contents | Index
System.IO
FileStream EndRead() Method
FileStream.EndRead(System.IAsyncResult) Method [ILASM]
.method public hidebysig virtual int32 EndRead(class System.IAsyncResult asyncResult)
A
[C#]
B
public override int EndRead(IAsyncResult asyncResult)
C
Summary
D
Ends a pending asynchronous read request, and blocks until the read request has completed.
E F
Parameters
G H
Parameter
Description
asyncResult
The System.IAsyncResult object for the pending asynchronous request.
I J K
Return Value
L
A System.Int32 containing the number of bytes read from the stream. Returns 0 only if the end of the file has been reached; otherwise, this method blocks until at least one byte is available.
M N O
Description
P
EndRead will block until the I/O operation has completed. [Note: This method overrides System.IO.Stream.EndRead.]
Q R
Exceptions
S
Exception
Condition
System.ArgumentNullException
asyncResult is null.
System.ArgumentException
asyncResult was not returned by a call to System.IO.FileStream.BeginRead.
System.InvalidOperationException
System.IO.FileStream.EndRead was called multiple times with asyncResult.
T U V W X Y Z
1811
Contents | Index
FileStream
System.IO
EndRead() Method
Example using using using using
A
System; System.IO; System.Text; System.Threading;
B namespace Samples { public class FileStreamEndRead { const int limit = 512; const int readlimit = 15; public class StateHolder { public byte[] bytes ; public FileStream fs ; } public static void Main() { string s = "filestream.txt"; FileStream fs = new FileStream(s, FileMode.Open, FileAccess.Read, FileShare.None, 512, true); StateHolder sh = new StateHolder(); sh.fs = fs; sh.bytes = new Byte[limit]; AsyncCallback ac = new AsyncCallback(CallMe); fs.BeginRead(sh.bytes, 0, readlimit, ac, sh); for(int i = 0; i < 50; i++) { Thread.Sleep(5); Console.Write('_'); } } public static void CallMe(IAsyncResult asyncResult) { StateHolder sh = (StateHolder) asyncResult.AsyncState; FileStream fs = sh.fs; int count = fs.EndRead(asyncResult); Console.Write("Bytes read: {0} ", count); if(count != 0) { Decoder d = Encoding.UTF8.GetDecoder(); char[] chars = null; int i = d.GetCharCount(sh.bytes, 0, count);
C D E F G H I J K L M N O P Q R S T U V W X Y Z
1812
Contents | Index
System.IO
FileStream EndWrite() Method
chars = new Char[i]; count = d.GetChars(sh.bytes, 0, count, chars, 0); Console.WriteLine(new string(chars)); fs.BeginRead(sh.bytes, 0, readlimit, new AsyncCallback(CallMe), sh);
A
} else { fs.Close() ; }
B C D
}
E
}
F
}
G
The output is
H Bytes read: 15 Hello world...
I
Bytes read: 15 Goodbye world. _Bytes read: 2
J K L
_____________________________________________Bytes read: 0 ____
M N
FileStream.EndWrite(System.IAsyncResult) Method
O
[ILASM]
P
.method public hidebysig virtual void EndWrite(class System.IAsyncResult asyncResult)
Q
[C#]
R
public override void EndWrite(IAsyncResult asyncResult)
S
Summary
T
Ends an asynchronous write, blocking until the I/O operation has completed.
U V
Parameters
W
Parameter
Description
asyncResult
The System.IAsyncResult object for the pending asynchronous request.
X Y Z
1813
Contents | Index
FileStream
System.IO
EndWrite() Method
Description System.IO.FileStream.EndWrite will block until the I/O operation has completed. [Note: This method overrides System.IO.Stream.EndWrite.] A
Exceptions
B C D E
Exception
Condition
System.ArgumentNullException
asyncResult is null.
System.ArgumentException
asyncResult was not returned by a call to System.IO.FileStream.BeginWrite.
System.InvalidOperationException
System.IO.FileStream.EndWrite was called multiple times with asyncResult.
F G H I J
Example
K
using using using using
L M
System; System.IO; System.Text; System.Threading;
N namespace Samples { public class FileStreamEndWrite { public class StateHolder { public byte[] bytes; public FileStream fs; public int writes = 5; } public static void Main() { string filename = "filestream.txt"; FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Write, FileShare.None, 512, true); string s = DateTime.Now.ToString(); StateHolder sh = new StateHolder(); sh.fs = fs;
O P Q R S T U V W X Y Z
1814
Contents | Index
System.IO
FileStream Finalize() Method
UTF8Encoding e = new UTF8Encoding(); int count = e.GetByteCount(s); sh.bytes = new Byte[count]; e.GetBytes(s, 0, sh.bytes.Length, sh.bytes, 0); fs.BeginWrite(sh.bytes, 0, sh.bytes.Length, new AsyncCallback(CallMe), sh); for(int i = 0; i < 50; i++) { Thread.Sleep(5); Console.Write('_'); }
A B C D E
} public static void CallMe(IAsyncResult asyncResult) { StateHolder sh = (StateHolder) asyncResult.AsyncState; sh.fs.EndWrite(asyncResult); Console.WriteLine("Write ended"); if(--sh.writes > 0) { sh.fs.BeginWrite(sh.bytes, 0, sh.bytes.Length, new AsyncCallback(CallMe), sh); } else { sh.fs.Close() ; } }
F G H I J K L M N O
} }
P Q
The output is
R _Write ended Write ended Write ended Write ended Write ended _________________________________________________
S T U V W
FileStream.Finalize() Method
X
[ILASM]
Y
.method family hidebysig virtual void Finalize()
Z
[C#]
~FileStream()
1815
Contents | Index
FileStream
System.IO
Flush() Method
Summary Releases the resources held by the current instance. A
Description
B
System.IO.FileStream.Finalize closes the System.IO.FileStream. [Note: Application code does not call this method; it is automatically invoked during garbage collection unless finalization by the garbage collector has been disabled. For more information, see System.GC.SuppressFinalize, and System.Object.Finalize. This method overrides System.Object.Finalize.]
C D E F G
FileStream.Flush() Method
H [ILASM]
I
.method public hidebysig virtual void Flush() [C#]
J
public override void Flush()
K L
Summary
M
Updates the underlying file with the current state of the buffer and subsequently clears the buffer.
N O
Description
P
A System.IO.FileStream buffer can be used either for reading or writing. If data was copied to the buffer for writing, it is written to the file and the buffer is cleared. If data was copied to the buffer for reading, and the System.IO.Stream.CanSeek property is true, the current position within the file is decremented by the number of unread bytes in the buffer. The buffer is then cleared. [Note: This method overrides System.IO.Stream.Flush.]
Q R S T
Exceptions
U V
Exception
Condition
X
System.IO.IOException
An I/O error occurred.
Y
System.ObjectDisposedException
The current instance has already been closed.
W
Z
1816
Contents | Index
System.IO
FileStream Lock() Method
Example using System; using System.IO; using System.Text;
A B
namespace Samples { public class FileStreamFlush { public static void Main() { string s = "filestream.txt"; FileStream fs = new FileStream(s, FileMode.OpenOrCreate, FileAccess.Write); Console.WriteLine("FileStream opened on {0} ", fs.Name); WriteDateTime(fs); fs.Flush(); WriteDateTime(fs); fs.Close(); } public static void WriteDateTime( FileStream fs) { string ds = String.Format("Written at: {0}\n", DateTime.Now.ToString()); UTF8Encoding e = new UTF8Encoding(); int count = e.GetByteCount(ds.ToCharArray(), 0, ds.Length); Byte[] bytes = new Byte[count]; e.GetBytes(ds, 0, ds.Length, bytes, 0); fs.Seek(0, SeekOrigin.End); fs.Write(bytes, 0, bytes.Length); } } }
C D E F G H I J K L M N O P Q R S T
The output is
U
FileStream opened on C:\Books\BCL\Samples\System.IO\FileStream\ Flush()\filestream.txt
V W X
FileStream.Lock(System.Int64, System.Int64) Method
Y
[ILASM]
Z
.method public hidebysig virtual void Lock(int64 position, int64 length) [C#]
public virtual void Lock(long position, long length)
1817
Contents | Index
FileStream
System.IO
Read() Method
Summary Prevents other processes from changing the System.IO.FileStream while permitting read access. A
Parameters
B C D E
Parameter
Description
position
The beginning of the range to lock. The value of this parameter must be equal to or greater than zero (0).
length
The range to be locked.
F G H
Exceptions
I J
Exception
Condition
L
System.ArgumentOutOfRangeException
position or length is negative.
M
System.ObjectDisposedException
The file is closed.
K
N O P
FileStream.Read(System.Byte[], System.Int32, System.Int32) Method
Q
[ILASM]
R
.method public hidebysig virtual int32 Read(class System.Byte[] array, int32 offset, int32 count) [C#]
S
public override int Read(byte[] array, int offset, int count)
T U
Summary
V
Reads a block of bytes from the stream and returns the data in the specified buffer.
W X Y Z
1818
Contents | Index
System.IO
FileStream Read() Method
Parameters Parameter
Description
array
A System.Byte array. When this method returns, the bytes between offset and (offset + count – 1) in array are replaced by the bytes read from the current stream.
offset
A System.Int32 containing the byte offset in array at which to begin writing data read from the current stream.
count
A System.Int32 containing the maximum number of bytes to read.
A B C D E F G
Return Value
H
A System.Int32 containing the total number of bytes read into the buffer, or zero if the end of the stream is reached.
I J
Description
K
The System.IO.FileStream.Read method returns zero only after reaching the end of the stream. Otherwise, System.IO.FileStream.Read always reads at least one byte from the stream before returning. If no data is available from the stream, this method blocks until at least one byte of data can be returned. If the read operation is successful, the current position of the stream is advanced by the number of bytes read. If an exception occurs, the current position of the stream is unchanged. [Note: Use the System.IO.FileStream.CanRead property to determine whether the current instance supports reading. For additional information, see System.IO.Stream.CanRead.] [Note: This method overrides System.IO.Stream.Read.]
L M N O P Q R S T
Exceptions
U
Exception
Condition
V
System.ArgumentNullException
array is null.
W
System.ArgumentException
offset + count is greater than the length of array.
System.ArgumentOutOfRangeException
offset or count is negative.
X Y Z
1819
Contents | Index
FileStream
System.IO
Read() Method
Exception
Condition
A
System.NotSupportedException
The current stream does not support reading.
B
System.IO.IOException
An I/O error occurred.
System.ObjectDisposedException
The current stream is closed.
C D E
Example
F
using System; using System.IO; using System.Text;
G H
namespace Samples { public class FileStreamRead { private const int limit = 80; public static void Main() { string s = "filestream.txt"; using(FileStream fs = new FileStream(s, FileMode.Open, FileAccess.Read)) { Console.WriteLine("FileStream opened on {0}", fs.Name); DisplayInformationAboutStream(fs); byte[] bytes = new byte[limit]; Decoder d = Encoding.UTF8.GetDecoder(); char[] chars = null; for(int i = fs.Read(bytes, 0, limit); i != 0; i = fs.Read(bytes, 0, limit)) { int count = d.GetCharCount(bytes, 0, i); chars = new Char[count]; count = d.GetChars(bytes, 0, i, chars, 0); Console.Write(new string(chars)); } } } public static void DisplayInformationAboutStream( FileStream fs) { Console.WriteLine("Can read from stream: {0}", fs.CanRead);
I J K L M N O P Q R S T U V W X Y Z
1820
Contents | Index
System.IO
FileStream ReadByte() Method
Console.WriteLine("Can write to stream: {0}", fs.CanWrite); Console.WriteLine("Can seek in stream: {0}", fs.CanSeek); Console.WriteLine("Async access to stream: {0}", fs.IsAsync);
A B
}
C
} }
D
The output is
E F
FileStream opened on C:\Books\BCL\Samples\System.IO\FileStream\ Read(System.Byte[],System.Int32,System.Int32)\filestream.txt Can read from stream: True Can write to stream: False Can seek in stream: True Async access to stream: False Hello world... Goodbye world.
G H I J K L
FileStream.ReadByte() Method
M
[ILASM]
N
.method public hidebysig virtual int32 ReadByte()
O
[C#]
public override int ReadByte()
P
Summary
Q
Reads a byte from the file and advances the read position one byte.
R S
Return Value
T
The byte cast to a System.Int32, or –1 if the end of the stream has been reached.
U
Description
V
[Note: Use the System.IO.FileStream.CanRead property to determine whether the current instance supports reading. For additional information, see System.IO.Stream.CanRead. This method overrides System.IO.Stream.ReadByte.]
W X Y Z
1821
Contents | Index
FileStream
System.IO
ReadByte() Method
Exceptions Exception
Condition
B
System.ObjectDisposedException
The current stream is closed.
C
System.NotSupportedException
The current stream does not support reading.
A
D E
Example
F
using System; using System.IO; using System.Text;
G H
namespace Samples { public class FileStreamReadByte { public static void Main() { string s = "filestream.txt"; using(FileStream fs = new FileStream(s, FileMode.Open, FileAccess.Read)) { Console.WriteLine("FileStream opened on {0}", fs.Name); for(int i = fs.ReadByte(); i > 0; i = fs.ReadByte()) { Console.Write(Convert.ToChar(i)); } } } } }
I J K L M N O P Q R S T U V
The output is
W
FileStream opened on C:\Books\BCL\Samples\System.IO\FileStream\ Read(System.Byte)\filestream.txt Hello world... Goodbye world.
X Y Z
1822
Contents | Index
System.IO
FileStream Seek() Method
FileStream.Seek(System.Int64, System.IO.SeekOrigin) Method [ILASM]
.method public hidebysig virtual int64 Seek(int64 offset, valuetype System.IO.SeekOrigin origin)
A
[C#]
B
public override long Seek(long offset, SeekOrigin origin)
C
Summary
D
Sets the current position of the current stream to the specified value.
E F
Parameters
G
Parameter
Description
H
offset
A System.Int64 containing the position relative to origin from which to begin seeking.
I
A System.IO.SeekOrigin value specifying the beginning, the end, or the current position as a reference point for offset.
K
origin
J
L M
Description
N
[Note: Use the System.IO.FileStream.CanSeek property to determine whether the current instance supports seeking. For additional information, see System.IO.Stream.CanSeek.]
O P
Usage
Q
The position cannot be set to more than one byte beyond the end of the stream. [Note: This method overrides System.IO.Stream.Seek.]
R S
Exceptions
T
Exception
Condition
System.IO.IOException
An I/O error occurred.
System.NotSupportedException
The stream does not support seeking.
System.ArgumentException
Attempted seeking before the beginning of the stream or to more than one byte past the end of the stream.
U V W
System.ObjectDisposedException
X Y Z
The current stream is closed.
1823
Contents | Index
FileStream
System.IO
SetLength() Method
Example using System; using System.IO; using System.Text;
A B
namespace Samples { public class FileStreamSeek { public static void Main() { string s = "filestream.txt"; using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate, FileAccess.Write)) { Console.WriteLine("FileStream opened on {0} ", fs.Name); string ds = String.Format("Written at: {0}\n", DateTime.Now.ToString()); UTF8Encoding e = new UTF8Encoding(); int count = e.GetByteCount(ds.ToCharArray(), 0, ds.Length); Byte[] bytes = new Byte[count]; e.GetBytes(ds, 0, ds.Length, bytes, 0); fs.Seek(0, SeekOrigin.End); fs.Write(bytes, 0, bytes.Length); } } } }
C D E F G H I J K L M N O P Q R S
The output is
T FileStream opened on C:\Books\BCL\Samples\System.IO\FileStream\ Seek(System.Int32,System.IO.SeekOrigin)\filestream.txt
U V W
FileStream.SetLength(System.Int64) Method
X [ILASM]
Y
.method public hidebysig virtual void SetLength(int64 value) [C#]
Z
public override void SetLength(long value)
1824
Contents | Index
System.IO
FileStream SetLength() Method
Summary Sets the length of the current stream to the specified value. A
Parameters
B
Parameter
Description
value
A System.Int64 that specifies the new length of the stream.
C D E
Description
F
If value is less than the current length of the stream, the stream is truncated. If value is greater than the current length of the stream, the stream is expanded, and the contents of the stream between the old and the new length are undefined. A stream is required to support both writing and seeking to implement System.IO.FileStream.SetLength. [Note: Use the System.IO.FileStream.CanWrite property to determine whether the current instance supports writing, and the System.IO.FileStream.CanSeek property to determine whether seeking is supported. For additional information, see System.IO.Stream.CanWrite and System.IO.Stream.CanSeek. This method overrides System.IO.Stream.SetLength.]
G H I J K L M N
Exceptions
O
Exception
Condition
System.IO.IOException
An I/O error occurred.
Q
System.NotSupportedException
The current stream does not support writing and seeking.
R
System.ArgumentOutOfRangeException
value is less than zero.
T
P
S
U
Example
V
using System; using System.IO; using System.Text;
W X Y
namespace Samples { public class FileStreamSetLength { public static void Main()
Z
1825
Contents | Index
FileStream
System.IO
Unlock() Method
{ string s = "filestream.txt"; using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate, FileAccess.Write)) { Console.WriteLine("FileStream opened on {0} ", fs.Name); if(fs.CanWrite && fs.CanSeek) { Console.WriteLine("Length is : {0}", fs.Length); fs.SetLength(fs.Length + 42); Console.WriteLine("Length is : {0}", fs.Length); } }
A B C D E F G H
} }
I
}
J
The output is
K FileStream opened on C:\Books\BCL\Samples\System.IO\FileStream\ SetLength(System.Int64)\filestream.txt Length is : 84 Length is : 126
L M N O P
FileStream.Unlock(System.Int64, System.Int64) Method
Q
[ILASM]
.method public hidebysig virtual void Unlock(int64 position, int64 length)
R
[C#]
public virtual void Unlock(long position, long length)
S T
Summary
U
Allows access by other processes to all or part of a file that was previously locked.
V
Parameters
W X
Parameter
Description
position
The beginning of the range to unlock.
length
The range to be unlocked.
Y Z
1826
Contents | Index
System.IO
FileStream Write() Method
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
position or length is negative.
A B C D
FileStream.Write(System.Byte[], System.Int32, System.Int32) Method
E
[ILASM]
F
.method public hidebysig virtual void Write(class System.Byte[] array, int32 offset, int32 count)
G
[C#]
H
public override void Write(byte[] array, int offset, int count)
I
Summary
J
Writes a block of bytes from a specified byte array to the current stream.
K
Parameters
L M
Parameter
Description
array
The System.Byte array to read.
O
offset
A System.Int32 that specifies the byte offset in array at which to begin reading.
P
count
A System.Int32 that specifies the maximum number of bytes to write to the current stream.
N
Q R S
Description
T
If the write operation is successful, the current position of the stream is advanced by the number of bytes written. If an exception occurs, the current position of the stream is unchanged. [Note: Use the System.IO.FileStream.CanWrite property to determine whether the current instance supports writing. For additional information, see System.IO.Stream.CanWrite. This method overrides System.IO.Stream.Write.]
U V W X Y Z
1827
Contents | Index
FileStream
System.IO
Write() Method
Exceptions Exception
Condition
B
System.ArgumentNullException
array is null.
C
System.ArgumentException
offset + count is greater than the length of array.
D
System.ArgumentOutOfRangeException
offset or count is negative.
System.IO.IOException
An I/O error occurred.
System.NotSupportedException
The current stream does not support writing.
A
E F G H
Example
I
using using using using
J K
System; System.IO; System.Text; System.Threading;
L namespace Samples { public class FileStreamWrite { public static void Main() { string filename = "filestream.txt"; using(FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write)) { string s = DateTime.Now.ToString(); UTF8Encoding e = new UTF8Encoding(); int count = e.GetByteCount(s); Byte[] bytes = new Byte[count]; e.GetBytes(s, 0, bytes.Length, bytes, 0); fs.Write(bytes, 0, bytes.Length); } } } }
M N O P Q R S T U V W X Y Z
This program has no console output.
1828
Contents | Index
System.IO
FileStream WriteByte() Method
FileStream.WriteByte(System.Byte) Method [ILASM]
.method public hidebysig virtual void WriteByte(unsigned int8 value) [C#]
A
public override void WriteByte(byte value)
B C
Summary
D
Writes a byte to the current position in the file stream.
E
Parameters
F G
Parameter
Description
value
A System.Byte to write to the stream.
H I J
Usage
K
Use System.IO.FileStream.WriteByte method to write a byte to a System.IO.FileStream efficiently. [Note: Use the System.IO.FileStream.CanWrite property to determine whether the current instance supports writing. For additional information, see System.IO. Stream.CanWrite. This method overrides System.IO.Stream.WriteByte.]
L M N O P
Exceptions
Q
Exception
Condition
R
System.IO.IOException
The current stream is closed.
S
System.NotSupportedException
The current stream does not support writing.
T U V
Example using using using using
W
System; System.IO; System.Text; System.Threading;
X Y Z
namespace Samples { public class FileStreamWriteByte
1829
Contents | Index
FileStream
System.IO
WriteByte() Method
{ public static void Main() { string filename = "filestream.txt"; using(FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write)) { string s = DateTime.Now.ToString(); foreach(char c in s) { fs.WriteByte(Convert.ToByte(c)); } } }
A B C D E F G H
} }
I
This program has no console output.
J K L M N O P Q R S T U V W X Y Z
1830
Contents | Index
System FlagsAttribute
BCL
Object
A
Attribute
B
FlagsAttribute
C
Summary
D
Indicates that the System.Enum targeted by the current attribute is declared as a bit-field.
E F
Type Summary public class FlagsAttribute : Attribute { // Constructors public FlagsAttribute (); }
G H I J K
BA Enums in the runtime are just like enums in the C++ programming language.
L
That is, they are really just aliases for integral types. There is no enforcement in the runtime, languages, or verifier that ensures that a value stored in an enum has a valid name associated with it. For example, this is legal code:
M N O
FileMode f = (FileMode) 42;
P
The implication of this is that a robust library should always check to see if the value being passed in is legal. The Flags attribute indicates that the enum was designed such that not all the legal values have a name; some legal values are combinations of values with names. For example, in the AttributeTargets enum it is legal to combine values to specify that an attribute can be applied to a field or method:
Q R S T U
AttributeTargets.Field | AttributeTargets.Method
V
BA One of our design guidelines is to name flag enums in the plural form to differentiate them at the call site from regular enums. For example, we have AttributeTargets rather than AttributeTarget.
W X
BG See my comments on the Enum class.
Y Z
1831
Contents | Index
FlagsAttribute
System
FlagsAttribute Class
Description The System.FlagsAttribute class provides the consumer of a System.Enum with the information that the enumeration is to be used as a bit-field. Additionally, when formatting a System.Enum, using the System.FlagsAttribute causes a value that is a bitwise OR combination of multiple fields to print correctly. [Note: Bit-fields are generally used for lists of elements that might occur in combination, whereas enumeration constants are generally used for lists of mutually exclusive elements. Therefore, bit-fields are designed to be combined with the bitwise OR operator to generate unnamed values, whereas enumerated constants are not. Languages vary in their usage of bit-fields compared to enumeration constants. This attribute can only be applied to enumerations.]
A B C D E F G
Example
H
using System;
I namespace Samples { public class FlagsAttributeSample { [Flags] enum DayOfWeek {Sunday = 0x1, Monday = 0x2, Tuesday = 0x4, Wednesday = 0x8, Thursday = 0x10, Friday = 0x20, Saturday = 0x40}; public static void Main() { DayOfWeek weekDays = DayOfWeek.Monday | DayOfWeek.Tuesday | DayOfWeek.Wednesday | DayOfWeek.Thursday | DayOfWeek.Friday; Console.WriteLine("Week days: {0}", weekDays); DayOfWeek weekendDays = DayOfWeek.Sunday | DayOfWeek.Saturday; Console.WriteLine("Weekend days: {0}", weekendDays); } } }
J K L M N O P Q R S T U V W X
The output is
Y
Week days: Monday, Tuesday, Wednesday, Thursday, Friday Weekend days: Sunday, Saturday
Z
1832
Contents | Index
System
FlagsAttribute FlagsAttribute() Constructor
FlagsAttribute() Constructor [ILASM]
public rtspecialname specialname instance void .ctor() [C#]
A
public FlagsAttribute()
B C
Summary
D
Constructs a new instance of the System.FlagsAttribute class.
E F G H I J K L M N O P Q R S T U V W X Y Z
1833
Contents | Index
System FormatException
BCL
Object
A
Exception
B
ISerializable
NotStandardized
SystemException FormatException
C D
Summary
E
Represents errors caused by passing incorrectly formatted arguments or invalid format specifiers to methods.
F G
Type Summary
H
public class FormatException : SystemException { // Constructors public FormatException (); MS CF protected FormatException (SerializationInfo info, StreamingContext context); public FormatException (string message); public FormatException (string message, Exception innerException); }
I J K L M N O
Description
P
[Note: System.FormatException is thrown from Parse methods when a System.String being parsed contains characters that are not valid according to the specified style (passed via the style parameter) or default style. System.FormatException is thrown from ToString methods when a format specifier (passed via the format parameter) is not a valid format for the type of the current instance.]
Q R S T
Example
U
using System;
V namespace Samples { public class FormatExceptionSample { public static void Main() { try { string s = "12.34";
W X Y Z
1834
Contents | Index
System
FormatException FormatException() Constructor
int i = Convert.ToInt32(s); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); }
A B
}
C
} }
D
The output is
E F
Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt32(String value) at Samples.FormatExceptionSample.Main() in C:\Books\BCL\Samples\System\ FormatException\FormatException.cs:line 12
G H I J
FormatException() Constructor
K
[ILASM]
L
public rtspecialname specialname instance void .ctor()
M
[C#]
public FormatException()
N
Summary
O
Constructs and initializes a new instance of the System.FormatException class.
P Q
Description
R
This constructor initializes the System.FormatException.Message property of the new instance to a system-supplied message that describes the error, such as “Invalid format.” This message takes into account the current system culture. The System.FormatException.InnerException property is initialized to null.
S T U V
FormatException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
W X
[ILASM]
Y
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
Z
[C#]
protected FormatException(SerializationInfo info, StreamingContext context)
1835
Contents | Index
FormatException
System
FormatException() Constructor
Summary Initializes a new instance of the System.FormatException class with serialized data. A
Parameters
B C
Parameter
Description
D
info
The object that holds the serialized object data.
context
The contextual information about the source or destination.
E F G
Description
H
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
I J K
FormatException(System.String) Constructor
L
[ILASM]
M
public rtspecialname specialname instance void .ctor(string message) [C#]
N
public FormatException(string message)
O P
Summary
Q
Constructs and initializes a new instance of the System.FormatException class.
R
Parameters
S T
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
U V W X
Description
Y
This constructor initializes the System.FormatException.Message property of the new instance using message. If message is null, the System.FormatException.Mes-
Z
1836
Contents | Index
System
FormatException FormatException() Constructor
sage property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.FormatException.InnerException property is initialized to null. A B
FormatException(System.String, System.Exception) Constructor
C
[ILASM]
D
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
E
[C#]
F
public FormatException(string message, Exception innerException)
G
Summary
H
Constructs and initializes a new instance of the System.FormatException class.
I J
Parameters
K
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
L M N O P Q R
Description
S
This constructor initializes the System.FormatException.Message property of the new instance using message, and the System.FormatException.InnerException property using innerException. If message is null, the System.FormatException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
T U V W X Y Z
1837
Contents | Index
System GC
BCL
Object
A
GC
B
Summary
C
Provides a mechanism for programmatic control of the garbage collector.
D E
Type Summary public sealed class GC { // Properties MS public static int MaxGeneration { get; } // MS MS CF MS CF MS CF MS
Methods public static public static public static public static public static public static public static public static public static
F G H I
void Collect (); void Collect (int generation); int GetGeneration (object obj); int GetGeneration (WeakReference wo); long GetTotalMemory (bool forceFullCollection); void KeepAlive (object obj); void ReRegisterForFinalize (object obj); void SuppressFinalize (object obj); void WaitForPendingFinalizers ();
J K L M N O
}
P Q
JM You will notice that there is neither a Collect method nor a Generation property in this class. They were there originally, but were removed, after much discussion and debate, because they offer an inadequate mechanism for specifying such behavior in a platform-independent way.
R
JR When I started consulting on the .NET Framework team in October of 1999,
U
S T
the WaitForPendingFinalizers method was called RunFinalizers. I didn’t like this name because it implied that finalize methods were only executed when this was called. In reality, finalize methods are called when necessary and this method suspends the calling thread until all pending finalize methods have completed execution. I am responsible for the naming of the WaitForPendingFinalizers method.
V W X Y Z
1839
Contents | Index
GC
System
GC Class
Description [Note: The garbage collector is responsible for tracking and reclaiming objects allocated in managed memory. Periodically, the garbage collector performs a garbage collection to reclaim memory allocated to objects for which there are no valid references. Garbage collections happen automatically when a request for memory cannot be satisfied using available free memory. A garbage collection consists of the following steps: During a collection, the garbage collector will not free an object if it finds one or more references to the object in managed code. However, the garbage collector does not recognize references to an object from unmanaged code, and may free objects that are being used exclusively in unmanaged code unless explicitly prevented from doing so. The System.GC.KeepAlive method provides a mechanism that prevents the garbage collector from collecting objects that are still in use in unmanaged code. Implementations of the garbage collector should track the following information: Other than managed memory allocations, implementations of the garbage collector should not maintain information about resources held by an object, such as file handles or database connections. When a type uses unmanaged resources that must be released before instances of the type are reclaimed, the type should implement a finalizer. In most cases, finalizers are implemented by overriding the System.Object.Finalize method; however, types written in C# or C++ implement destructors, which compilers turn into an override of System.Object.Finalize. In most cases, if an object has a finalizer, the garbage collector calls it prior to freeing the object. However, the garbage collector is not required to call finalizers in all situations. Also, the garbage collector is not required to use a specific thread to finalize objects, or guarantee the order in which finalizers are called for objects that reference each other but are otherwise available for garbage collection. In scenarios where resources must be released at a specific time, classes should implement the System.IDisposable interface, which contains a single method (System.IDisposable.Dispose) that is used to perform resource management and cleanup tasks. Classes that implement System.IDisposable.Dispose must specify, as part of their class contract, if and when class consumers call the method to clean up the object. The garbage collector does not, by default, call the System.IDisposable.Dispose method; however, implementations of the System.IDisposable.Dispose method can call methods in the System.GC class to customize the finalization behavior of the garbage collector.]
A B C D E F G H I J K L M N O P Q R S T U V W
Example
X
using System;
Y namespace Samples { public class GCSample {
Z
1840
Contents | Index
System
GC MaxGeneration Property
private readonly string message; private int i; public GCSample(string s, int i) { message = s; this.i = i; } ~GCSample() { Console.WriteLine("In Finalize for \"{0}\"", message); if(--i > 0) GC.ReRegisterForFinalize(this); } public static void Main() { GCSample g1 = new GCSample("First", 5); GCSample g2 = new GCSample("Second", 5); GC.SuppressFinalize(g2); g1 = g2 = null; GC.WaitForPendingFinalizers(); }
A B C D E F G H I J K
}
L
}
M
The output is
N
In Finalize for "First"
O P
GC.MaxGeneration Property
Q
[ILASM]
R
.property int32 MaxGeneration { public hidebysig static specialname int32 get_MaxGeneration() }
S
[C#]
T
public static int MaxGeneration { get; }
U
Summary
V
Gets the maximum number of generations the system currently supports.
W X
Description
Y
The generation number, or age, of an object is an implementation-defined relative measure of an object’s lifespan. The most recently created objects are in generation zero and the oldest objects are in a generation less than or equal to the generation returned by the System.GC.MaxGeneration property.
Z
1841
Contents | Index
GC
System
Collect() Method
The garbage collector assumes that newer memory is more likely to be eligible for garbage collection than older memory. Therefore, the garbage collector improves its performance by adjusting generation numbers each time it reclaims memory, and the System.GC.MaxGeneration property value can grow over time. If object aging is implemented, the System.GC.MaxGeneration property returns the maximum generation number used by the system; otherwise, this property returns zero. For this implementation, the value returned by the System.GC.MaxGeneration property is guaranteed to remain constant for the lifetime of an executing application. Use the System.GC.MaxGeneration property to determine the maximum value you can specify when calling the System.GC.Collect method that takes a generation parameter.
A B C D E F G
GC.Collect() Method
H [ILASM]
I
.method public hidebysig static void Collect()
J
[C#]
public static void Collect()
K L
Summary
M
Forces garbage collection of all generations.
N
Description
O
Use this method to attempt to reclaim all memory that is inaccessible. However, the System.GC.Collect method does not guarantee that all inaccessible memory is reclaimed. All objects, regardless of how long they have been in memory, are considered for collection; however, objects that are referenced in managed code are not collected. Use this method to force the system to attempt to reclaim the maximum amount of available memory.
P Q R S T U
GC.Collect(System.Int32) Method
V
[ILASM]
.method public hidebysig static void Collect(int32 generation)
W
[C#]
public static void Collect(int generation)
X Y
Summary
Z
Forces garbage collection from generation zero through a specified generation.
1842
Contents | Index
System
GC GetGeneration() Method
Parameters Parameter
Description
generation
The maximum garbage-collected generation.
A B C
Description
D
Use this method to attempt to reclaim memory that is inaccessible. However, it does not guarantee that all inaccessible memory in the specified generation is reclaimed. If object aging is implemented, the garbage collector does not collect objects with a generation number higher than the specified generation. If object aging is not implemented, the garbage collector considers all objects during the garbage collection. Use the System.GC.MaxGeneration property to determine the maximum valid value of generation. To have the garbage collector consider all objects regardless of their generation, use the version of this method that takes no arguments.
E F G H I J K L
Exceptions
M
Exception
Condition
System.ArgumentOutOfRangeException
generation is less than zero or greater than the number of generations that exist.
N O P Q R
GC.GetGeneration(System.Object) Method
S [ILASM]
.method public hidebysig static int32 GetGeneration(object obj)
T
[C#]
U
public static int GetGeneration(object obj)
V
Summary
W
Returns the current generation number of the specified object.
X Y Z
1843
Contents | Index
GC
System
GetGeneration() Method
Parameters Parameter
Description
obj
The object for which generation information is retrieved.
A B C
Description
D
Use this method to determine the age of an object, then use that information with the System.GC.Collect method to force the garbage collector to collect objects in the same generation. For example, use this method when you have a set of objects that are created as a group and become inaccessible at the same time.
E F G H I
GC.GetGeneration(System.WeakReference) Method
J
[ILASM]
K
.method public hidebysig static int32 GetGeneration(class System.WeakReference wo) [C#]
L
public static int GetGeneration(WeakReference wo)
M
Summary
N
Returns the current generation number of the target of a specified weak reference.
O P
Parameters
Q R S
Parameter
Description
wo
The weak reference of a target.
T U
Exceptions
V W
Exception
Condition
X
System.ArgumentException
wo has already been garbage collected.
Y Z
1844
Contents | Index
System
GC KeepAlive() Method
GC.GetTotalMemory(System.Boolean) Method [ILASM]
.method public hidebysig static int64 GetTotalMemory(bool forceFullCollection) [C#]
A
public static long GetTotalMemory(bool forceFullCollection)
B C
Summary Retrieves the number of bytes currently thought to be allocated. A parameter indicates whether this method can wait a short interval before returning while the system collects garbage and finalizes objects.
D
Parameters
G
E F
H
Parameter
Description
I
A Boolean value that, if true, indicates this method can wait awhile for garbage collection before returning.
J
forceFullCollection
K L
Description
M
If forceFullCollection is true, this method waits a short interval before returning while the system collects garbage and finalizes objects. The duration of the interval is an internally specified limit determined by the number of garbage collection cycles completed and the change in the amount of memory recovered between cycles. The garbage collector does not guarantee that all inaccessible memory is collected.
N O P Q R
GC.KeepAlive(System.Object) Method
S
[ILASM]
T
.method public hidebysig static void KeepAlive(object obj)
U
[C#]
public static void KeepAlive(object obj)
V W
Summary
X
Creates a reference to the specified object.
Y Z
1845
Contents | Index
GC
System
ReRegisterForFinalize() Method
Parameters Parameter
Description
obj
A System.Object that is not to be reclaimed by the garbage collector.
A B C
Description
D
The purpose of the System.GC.KeepAlive method is to ensure the existence of a reference to an object that is at risk of being reclaimed by the garbage collector prematurely. The System.GC.KeepAlive method performs no operations and does not produce any side effects. This method is required to be implemented in such a way as to prevent optimizing tools from omitting the method call from the executable code. During program execution, after the call to the System.GC.KeepAlive method is executed, if there are no additional references to obj in managed code or data, obj is eligible for garbage collection.
E F G H I J K L M
GC.ReRegisterForFinalize(System.Object) Method
N
[ILASM]
.method public hidebysig static void ReRegisterForFinalize(object obj)
O
[C#]
public static void ReRegisterForFinalize(object obj)
P Q
Summary
R
Requests that the specified object be added to the list of objects that require finalization.
S
Parameters
T U
Parameter
Description
obj
The System.Object to add to the set of objects that require finalization.
V W X
Description
Y
The System.GC.ReRegisterForFinalize method adds obj to the list of objects that request finalization before the garbage collector frees the object. obj is required to be the caller of this method.
Z
1846
Contents | Index
System
GC ReRegisterForFinalize() Method
Calling the System.GC.ReRegisterForFinalize method does not guarantee that the garbage collector will call an object’s finalizer. [Note: For more information, see System.Object.Finalize.] [Note: By default, all objects that implement finalizers are added to the list of objects that require finalization; however, an object may have already been finalized, or may have disabled finalization by calling the System.GC.SuppressFinalize method.]
A B C D
Exceptions
E
Exception
Condition
System.ArgumentNullException
obj is a null reference.
G
The caller of this method is not the same as the object passed to this method.
H
System.ExecutionEngineException
F
I J
Example
K
using System;
L
namespace Samples { public class GCReRegisterForFinalize { private int i; public GCReRegisterForFinalize(int i) { this.i = i; } ~GCReRegisterForFinalize() { Console.WriteLine("In Finalizer"); if(--i > 0) GC.ReRegisterForFinalize(this); } public static void Main() { GCReRegisterForFinalize g1 = new GCReRegisterForFinalize(5); g1 = null; GC.WaitForPendingFinalizers(); } } }
M N O P Q R S T U V W X Y Z
1847
Contents | Index
GC
System
SuppressFinalize() Method
The output is In In In In In
A B
Finalizer Finalizer Finalizer Finalizer Finalizer
C D
GC.SuppressFinalize(System.Object) Method
E
[ILASM]
F
.method public hidebysig static void SuppressFinalize(object obj) [C#]
G
public static void SuppressFinalize(object obj)
H I
Summary
J
Instructs the garbage collector not to call the System.Object.Finalize method on the specified object.
K
Parameters
L M
Parameter
Description
obj
The System.Object whose System.Object.Finalize method will not be called.
N O P Q
Description
R
The method removes obj from the set of objects that require finalization. obj is required to be the caller of this method. [Note: Objects that implement the System.IDisposable interface should call this method from the System.IDisposable.Dispose method to prevent the garbage collector from calling System.Object.Finalize on an object that does not require it.]
S T U V
Exceptions
W X
Exception
Condition
Y
System.ArgumentNullException
obj is a null reference.
System.InvalidOperationException
The caller of this method is not the same as the object passed to this method.
Z
1848
Contents | Index
System
GC WaitForPendingFinalizers() Method
Example using System; namespace Samples { public class GCSuppressFinalize { private readonly string message; private int i; public GCSuppressFinalize(string s, int i) { message = s; this.i = i; } ~GCSuppressFinalize() { Console.WriteLine("In Finalize for \"{0}\"", message); if(--i > 0) GC.ReRegisterForFinalize(this); } public static void Main() { GCSuppressFinalize g1 = new GCSuppressFinalize("First", 5); GCSuppressFinalize g2 = new GCSuppressFinalize("Second", 5); GC.SuppressFinalize(g2); g1 = g2 = null; GC.WaitForPendingFinalizers(); } } }
A B C D E F G H I J K L M N O P Q R
The output is In In In In In
Finalize Finalize Finalize Finalize Finalize
for for for for for
S T
"First" "First" "First" "First" "First"
U V W X
GC.WaitForPendingFinalizers() Method
Y
[ILASM]
Z
.method public hidebysig static void WaitForPendingFinalizers() [C#]
public static void WaitForPendingFinalizers()
1849
Contents | Index
GC
System
WaitForPendingFinalizers() Method
Summary Suspends the current thread until the set of objects waiting for finalization is empty. A
Description
B
System.GC.WaitForPendingFinalizers blocks an application until all objects that are awaiting finalization have been finalized. When the garbage collector finds objects that can be reclaimed, it checks each object to determine the object’s finalization requirements. If an object implements a finalizer and has not disabled finalization by calling System.GC.SuppressFinalize, the object is passed to the thread that handles finalization. The System.GC.WaitForPendingFinalizers method blocks until all finalizers have run to completion.
C D E F G
Example
H
using System;
I namespace Samples { public class GCWaitForPendingFinalizers { private int i; public GCWaitForPendingFinalizers(int i) { this.i = i; } ~GCWaitForPendingFinalizers() { Console.WriteLine("In Finalizer"); if(--i > 0) GC.ReRegisterForFinalize(this); } public static void Main() { GCWaitForPendingFinalizers g1 = new GCWaitForPendingFinalizers(5); g1 = null; GC.WaitForPendingFinalizers(); } } }
J K L M N O P Q R S T U V W X
The output is
Y
In In In In In
Z
Finalizer Finalizer Finalizer Finalizer Finalizer
1850
Contents | Index
System.Collections Hashtable
BCL
IDictionary ICollection
A
IEnumerable
B
Object Hashtable
C
ICloneable ISerializable
D
NotStandardized
IDeserializationCallback
E
NotStandardized
F
Summary
G
Represents a hash table.
H
Type Summary
I
public class Hashtable : IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable { // Constructors public Hashtable (); public Hashtable (int capacity); MS public Hashtable (int capacity, float loadFactor); MS CF public Hashtable (int capacity, float loadFactor, IHashCodeProvider hcp, IComparer comparer); public Hashtable (int capacity, IHashCodeProvider hcp, IComparer comparer); public Hashtable (IDictionary d); MS CF public Hashtable (IDictionary d, float loadFactor); MS CF public Hashtable (IDictionary d, float loadFactor, IHashCodeProvider hcp, IComparer comparer); public Hashtable (IDictionary d, IHashCodeProvider hcp, IComparer comparer); public Hashtable (IHashCodeProvider hcp, IComparer comparer); MS CF protected Hashtable (SerializationInfo info, StreamingContext context);
J K L M N O P Q R S T U V W X
// Properties MS protected IComparer comparer { set; get; } public virtual int Count { get; } MS protected IHashCodeProvider hcp { set; get; } public virtual bool IsFixedSize { get; } public virtual bool IsReadOnly { get; } public virtual bool IsSynchronized { get; }
Y Z
1851
Contents | Index
Hashtable
System.Collections
Hashtable Class
public public public public
virtual virtual virtual virtual
object this[object key] { set; get; } ICollection Keys { get; } object SyncRoot { get; } ICollection Values { get; }
A // Methods public virtual public virtual public virtual public virtual public virtual public virtual public virtual
B
void Add (object key, object value); void Clear (); object Clone (); bool Contains (object key); bool ContainsKey (object key); bool ContainsValue (object value); void CopyTo (Array array, int arrayIndex); public virtual IDictionaryEnumerator GetEnumerator (); protected virtual int GetHash (object key); MS CF public virtual void GetObjectData (SerializationInfo info, StreamingContext context); protected virtual bool KeyEquals (object item, object key); MS CF public virtual void OnDeserialization (object sender); public virtual void Remove (object key); public static Hashtable Synchronized (Hashtable table);
C D E F G H I J K L
// Explicit Interface Members IEnumerator IEnumerable.GetEnumerator()
M
}
N O
BA In the early days of the BCL design we heavily debated the name of this class.
P
Some felt it should be HashTable and others felt it should be Hashtable (lowercase t in table). There was ample prior art for both choices, so it really came down to what fit best in our library. The Pascal naming convention we adopted suggests that each word should begin with an initial uppercase character. So the debate boiled down to the question of what this class is. Is this class a table of hashes, that is, a Hash Table, or is it a single entity, a Hashtable? I think it is likely that the history of the data structure is as a special kind of table, but in the end we decided the data structure had entered the common lexicon as a single word—Hashtable.
Q R S T U V
BG Hashtable is currently subclassable, but we see little reason for users to subclass Hashtable themselves. All the interesting points of extensibility are already presented in other ways, by allowing users to pass in an IHashCodeProvider and IComparer for their keys. The only really good reason for subclassing Hashtable today is to add thread safety, to implement the Synchronized method. We did this by using an internal nested wrapper class that also subclasses Hashtable.
W X Y Z
continued
1852
Contents | Index
System.Collections
Hashtable Hashtable Class
However, it turns out this is not a great idea. It means a JIT will not be able to easily inline any of the method calls on Hashtable because they’re all virtual. If we were starting over from scratch or designing a generic Hashtable-like class, we would probably make it sealed for performance reasons and sacrifice a little bit of usability. We could do this by making a thread-safe variant of Hashtable, or by recommending that all users of the type take a lock on the Hashtable’s SyncRoot object before editing it. For a collection like an ArrayList, Stack, or Queue, the latter solution is really most likely what people want because they often either have another piece of state that must be updated along with the collection or they require doing two operations on the collection (such as checking for the number of elements in a queue, then popping one if it’s not empty). [See my comments in ArrayList for more details.]
A B C D E F G
KC Hashtable’s indexer returns null if the key is not found in the Hashtable. This is a design mistake. First, it’s not possible to distinguish between a non-existent key and a null value at an existing key. Second, using null to represent an error condition is bad when moving to generic-based design; generic methods parameterized with a value type cannot return null.
H I J K L
Description
M
A System.Collections.Hashtable represents a dictionary with a constant lookup time that contains entries of associated keys and values. The type of each entry in a System.Collections.Hashtable is System.Collections.DictionaryEntry. A statement that exposes each element in the collection is required to iterate over this type. [Note: See example.] Objects used as keys in a System.Collections.Hashtable are required to either implement both System.Object.GetHashCode and System.Object.Equals or neither. Furthermore, for a particular key, these methods are required to produce the same results when called with the same parameters while that key exists in a particular System.Collections.Hashtable. Keys cannot be mutated while they are used in the table. Every key in a System.Collections.Hashtable is required to be unique compared to every other key in the table. An object that implements System.Collections.IComparer can determine whether two keys are unequal. The default comparer for a key is the key’s implementation of System.Object.Equals. Each value in a System.Collections.Hashtable is required to provide its own hash function, which can be accessed by calling System.Collections.Hashtable.GetHash. Alternatively, if an object that implements System.Collections.IHashCodeProvider is passed to a System.Collections.Hashtable constructor, the custom hash function provided by that object is used for every value in the table. [Note: The default capacity (i.e., the default number of entries that can be contained) of a System.Collections.Hashtable is zero. When an entry is added to the
N O P Q R S T U V W X Y Z
1853
Contents | Index
Hashtable
System.Collections
Hashtable Class
System.Collections.Hashtable, the entry is placed into a bucket based on the hash code obtained from the System.Collections.IHashCodeProvider implementation of the table, or the System.Object.GetHashCode if no specific System.Collections.IHashCodeProvider was provided. Subsequent lookups of the key use the hash code of the key to search in only one particular bucket, substantially reducing the number of key comparisons required to find an entry. As entries are added to a System.Collections.Hashtable and the maximum capacity of the table is reached, the number of buckets in the table is automatically increased to the smallest prime number that is larger than twice the current number of buckets. A System.Collections.Hashtable can safely support one writer and multiple readers concurrently. To support multiple writers, all operations are required to be done through the wrapper returned by the System.Collections.Hashtable.Synchronized method.]
A B C D E F G H
Example
I
using System; using System.Collections;
J K
namespace Samples { public class HashtableSample { public static void Main() { Hashtable ht = new Hashtable(); ht.Add(1, "damien"); ht.Add(4, "maire"); ht.Add(2, "mark"); ht.Add(5, "sacha"); ht.Add(3, "brad"); ht.Add(6, "tamara"); DisplayHashtable(ht); } public static void DisplayHashtable(Hashtable ht) { Console.WriteLine("Count: {0}", ht.Count ); IDictionaryEnumerator de = ht.GetEnumerator(); while(de.MoveNext()) Console.WriteLine("Key: {0} : Value: {1}", de.Key, de.Value); } } }
L M N O P Q R S T U V W X Y Z
1854
Contents | Index
System.Collections
Hashtable Hashtable() Constructor
The output is Count: Key: 6 Key: 5 Key: 4 Key: 3 Key: 2 Key: 1
6 : : : : : :
Value: Value: Value: Value: Value: Value:
tamara sacha maire brad mark damien
A B C D E
Hashtable() Constructor
F
[ILASM]
G
public rtspecialname specialname instance void .ctor()
H
[C#]
I
public Hashtable()
J
Summary
K
Constructs and initializes a new instance of the System.Collections.Hashtable class.
L M
Description
N
The new instance is initialized with the default capacity, System.Collections.IHashCodeProvider, and System.Collections.IComparer.
O P
Example
Q
using System; using System.Collections;
R S
namespace Samples { public class HashtableConstructor { public static void Main() { Hashtable ht = new Hashtable(); Console.WriteLine("Count: {0}", ht.Count); for(int i = 0; i < 100; i++) ht.Add(i, i.ToString()); Console.WriteLine("Count: {0}", ht.Count ); } } }
T U V W X Y Z
1855
Contents | Index
Hashtable
System.Collections
Hashtable() Constructor
The output is Count: 0 Count: 100
A B C
Hashtable(System.Int32) Constructor
D
[ILASM]
public rtspecialname specialname instance void .ctor(int32 capacity)
E
[C#]
public Hashtable(int capacity)
F G
Summary
H
Constructs and initializes a new instance of the System.Collections.Hashtable class with the specified initial capacity.
I J
Parameters
K L
Parameter
Description
capacity
A System.Int32 that specifies the number of entries that the new System.Collections.Hashtable instance can initially contain.
M N O P
Description
Q
The new instance is initialized with the default System.Collections.IHashCodeProvider and System.Collections.IComparer.
R S
Exceptions
T U V
Exception
Condition
System.ArgumentOutOfRangeException
capacity < 0.
W X Y Z
1856
Contents | Index
System.Collections
Hashtable Hashtable() Constructor
Example using System; using System.Collections;
A
namespace Samples { public class HashtableConstructor { public static void Main() { Hashtable ht = new Hashtable(42); Console.WriteLine("Count: {0}", ht.Count); for(int i = 0; i < 100; i++) ht.Add(i, i.ToString()); Console.WriteLine("Count: {0}", ht.Count ); } } }
B C D E F G H I J
The output is
K
Count: 0 Count: 100
L M
Hashtable(System.Int32, System.Single) Constructor
N
[ILASM]
O
public rtspecialname specialname instance void .ctor(int32 capacity, float32 loadFactor)
P
[C#]
Q
public Hashtable(int capacity, float loadFactor)
R
Summary
S
Creates an empty System.Collections.Hashtable with the specified initial capacity and using the specified load factor, the default hash code provider, and the default comparer.
T U
Parameters
V W
Parameter
Description
capacity
The approximate number of elements that the System.Collections.Hashtable can initially contain.
loadFactor
A number in the range from 0.1 through 1.0 indicating the maximum ratio of elements to buckets.
X Y Z
1857
Contents | Index
Hashtable
System.Collections
Hashtable() Constructor
Description Specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the System.Collections.Hashtable. Capacity is automatically increased as required based on the load factor. The load factor is the maximum ratio of elements to buckets. A smaller load factor means faster lookup at the cost of increased memory consumption. A load factor of 1.0 is the best balance between speed and size. When the actual load factor reaches the load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets. The hash code provider dispenses hash codes for keys in the System.Collections.Hashtable. The default hash code provider is the key’s implementation of System.Object.GetHashCode. The comparer determines whether two keys are equal. Every key in a System.Collections.Hashtable must be unique. The default comparer is the key’s implementation of System.Object.Equals.
A B C D E F G H I J K
Exceptions
L
Exception
M
Condition
N
capacity is less than zero.
O
-orSystem.ArgumentOutOfRangeException
P
loadFactor is less than 0.1. -or-
Q
loadFactor is greater than 1.0.
R S
U
Hashtable(System.Int32, System.Single, System.Collections. IHashCodeProvider, System.Collections.IComparer) Constructor
V
[ILASM]
T
public rtspecialname specialname instance void .ctor(int32 capacity, float32 loadFactor, class System.Collections.IHashCodeProvider hcp, class System.Collections.IComparer comparer)
W X
[C#]
Y
public Hashtable(int capacity, float loadFactor, IHashCodeProvider hcp, IComparer comparer)
Z
1858
Contents | Index
System.Collections
Hashtable Hashtable() Constructor
Summary Creates an empty System.Collections.Hashtable with the specified initial capacity and using the specified load factor, the specified hash code provider, and the specified comparer.
A B
Parameters
C
Parameter
Description
capacity
The approximate number of elements that the System.Collections.Hashtable can initially contain.
loadFactor
A number in the range from 0.1 through 1.0 indicating the maximum ratio of elements to buckets.
D E F G H I
The System.Collections.IHashCodeProvider that supplies the hash codes for all keys in the System.Collections.Hashtable. hcp
J
-or-
K
null to use the default hash code provider, which is each key’s implementation of System.Object.GetHashCode.
L M
The System.Collections.IComparer to use to determine whether two keys are equal. comparer
N
-or-
O
null to use the default comparer, which is each key’s implementation of System.Object.Equals.
P Q
Description
R
Specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the System.Collections.Hashtable. Capacity is automatically increased as required based on the load factor. The load factor is the maximum ratio of elements to buckets. A smaller load factor means faster lookup at the cost of increased memory consumption. A load factor of 1.0 is the best balance between speed and size. When the actual load factor reaches the load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets. The hash code provider dispenses hash codes for keys in the System.Collections.Hashtable. The default hash code provider is the key’s implementation of System.Object.GetHashCode.
S T U V W X Y Z
1859
Contents | Index
Hashtable
System.Collections
Hashtable() Constructor
The comparer determines whether two keys are equal. Every key in a System.Collections.Hashtable must be unique. The default comparer is the key’s implementation of System.Object.Equals. The custom hash code provider and the custom comparer enable such scenarios as doing lookups with case-insensitive strings.
A B C
Exceptions
D
Exception
E
Condition
F
capacity is less than zero.
G
-orSystem.ArgumentOutOfRangeException
H
loadFactor is less than 0.1. -or-
I
loadFactor is greater than 1.0.
J K L M
Hashtable(System.Int32, System.Collections.IHashCodeProvider, System.Collections.IComparer) Constructor
N
[ILASM]
public rtspecialname specialname instance void .ctor(int32 capacity, class System.Collections.IHashCodeProvider hcp, class System.Collections.IComparer comparer)
O P
[C#]
Q
public Hashtable(int capacity, IHashCodeProvider hcp, IComparer comparer)
R
Summary
S
Constructs and initializes a new instance of the System.Collections.Hashtable class with the specified initial capacity, the specified System.Collections.IHashCodeProvider, and the specified System.Collections.IComparer.
T U V W X Y Z
1860
Contents | Index
System.Collections
Hashtable Hashtable() Constructor
Parameters Parameter
Description
capacity
A System.Int32 that specifies the number of entries that the new System.Collections.Hashtable instance can initially contain.
hcp
The System.Collections.IHashCodeProvider that supplies the hash codes for all keys in the System.Collections.Hashtable; or null to use the default hash code provider.
D
comparer
The System.Collections.IComparer to use to determine whether two keys are equal, or null to use the default comparer.
F
A B C
E
G H
Example
I
using System; using System.Collections;
J K
namespace Samples { public class HashtableConstructor { public class MyComparer: IComparer { public int Compare(Object a, Object b) { return ((IComparable)a).CompareTo(b); } } public class MyHashCodeProvider: IHashCodeProvider { public int GetHashCode(Object o) { return o.GetHashCode(); } }
L M N O P Q R S T U V
public static void Main() { Hashtable ht = new Hashtable(2, new MyHashCodeProvider(), new MyComparer()); Console.WriteLine("Count: {0}", ht.Count); ht.Add("one", "damien"); ht.Add("three", "brad"); ht.Add("two", "mark");
W X Y Z
1861
Contents | Index
Hashtable
System.Collections
Hashtable() Constructor
Console.WriteLine("Count: {0}", ht.Count ); } } }
A
The output is
B C
Count: 0 Count: 3
D E
Hashtable(System.Collections.IDictionary) Constructor
F
[ILASM]
G
public rtspecialname specialname instance void .ctor(class System.Collections.IDictionary d)
H
[C#]
I
public Hashtable(IDictionary d)
J
Summary
K
Constructs and initializes a new instance of the System.Collections.Hashtable class using the values of the specified System.Collections.IDictionary.
L M
Parameters
N O
Parameter
Description
d
The System.Collections.IDictionary used to initialize the elements of the new instance.
P Q R S
Description
T
The initial capacity of the new instance is set to the number of entries in d. The new instance is initialized with the default System.Collections.IHashCodeProvider and System.Collections.IComparer.
U V W
Exceptions
X Y Z
Exception
Condition
System.ArgumentNullException
d is null.
1862
Contents | Index
System.Collections
Hashtable Hashtable() Constructor
Example using System; using System.Collections;
A
namespace Samples { public class HashtableConstructor { public static void Main() { SortedList sl = new SortedList(); sl.Add("one", "damien"); sl.Add("three", "brad"); sl.Add("two", "mark"); Hashtable ht = new Hashtable(sl); Console.WriteLine("Count: {0}", ht.Count ); IDictionaryEnumerator de = ht.GetEnumerator(); while(de.MoveNext()) Console.WriteLine("Key: {0} Value: {1}", de.Key, de.Value); } } }
B C D E F G H I J K L M
The output is
N O
Count: 3 Key: three Value: brad Key: two Value: mark Key: one Value: damien
P Q R
Hashtable(System.Collections.IDictionary, System.Single) Constructor
S
[ILASM]
T
public rtspecialname specialname instance void .ctor(class System.Collections.IDictionary d, float32 loadFactor)
U
[C#]
V
public Hashtable(IDictionary d, float loadFactor)
W
Summary
X
Copies the elements from the specified dictionary to a new System.Collections.Hashtable with the same initial capacity as the number of elements copied and using the specified load factor, the default hash code provider, and the default comparer.
Y Z
1863
Contents | Index
Hashtable
System.Collections
Hashtable() Constructor
Parameters Parameter
Description
d
The System.Collections.IDictionary to copy to a new System.Collections.Hashtable.
loadFactor
A number in the range from 0.1 through 1.0 indicating the maximum ratio of elements to buckets.
A B C D E F
Description
G
The initial capacity is set to the number of elements in the source dictionary. Capacity is automatically increased as required based on the load factor. The load factor is the maximum ratio of elements to buckets. A smaller load factor means faster lookup at the cost of increased memory consumption. A load factor of 1.0 is the best balance between speed and size. When the actual load factor reaches the load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets. The hash code provider dispenses hash codes for keys in the System.Collections.Hashtable. The default hash code provider is the key’s implementation of System.Object.GetHashCode. The comparer determines whether two keys are equal. Every key in a System.Collections.Hashtable must be unique. The default comparer is the key’s implementation of System.Object.Equals. The elements of the new System.Collections.Hashtable are sorted in the same order in which the enumerator iterates through the System.Collections.IDictionary.
H I J K L M N O P Q R S T
Exceptions
U V
Exception
Condition
W
System.ArgumentNullException
d is null.
X
loadFactor is less than 0.1.
Y
System.ArgumentOutOfRangeException
Z
-orloadFactor is greater than 1.0.
1864
Contents | Index
System.Collections
Hashtable Hashtable() Constructor
Hashtable(System.Collections.IDictionary, System.Single, System.Collections.IHashCodeProvider, System.Collections.IComparer) Constructor A [ILASM]
B
public rtspecialname specialname instance void .ctor(class System.Collections.IDictionary d, float32 loadFactor, class System.Collections.IHashCodeProvider hcp, class System.Collections.IComparer comparer)
C D
[C#]
E
public Hashtable(IDictionary d, float loadFactor, IHashCodeProvider hcp, IComparer comparer)
F G
Summary Copies the elements from the specified dictionary to a new System.Collections.Hashtable with the same initial capacity as the number of elements copied and using the specified load factor, the specified hash code provider, and the specified comparer.
H
Parameters
K
I J
L
Parameter
Description
M
The System.Collections.IDictionary to copy to a new System.Collections.Hashtable.
N
d
loadFactor
hcp
comparer
O
A number in the range from 0.1 through 1.0 indicating the maximum ratio of elements to buckets.
P Q
The System.Collections.IHashCodeProvider that supplies the hash codes for all keys in the System.Collections.Hashtable.
R
-or-
S
null to use the default hash code provider, which is each key’s implementation of System.Object.GetHashCode.
T U
The System.Collections.IComparer to use to determine whether two keys are equal.
V
-or-
W
null to use the default comparer, which is each key’s implementation of System.Object.Equals.
X Y Z
1865
Contents | Index
Hashtable
System.Collections
Hashtable() Constructor
Description The initial capacity is set to the number of elements in the source dictionary. Capacity is automatically increased as required based on the load factor. The load factor is the maximum ratio of elements to buckets. A smaller load factor means faster lookup at the cost of increased memory consumption. A load factor of 1.0 is the best balance between speed and size. When the actual load factor reaches the load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets. The hash code provider dispenses hash codes for keys in the System.Collections.Hashtable. The default hash code provider is the key’s implementation of System.Object.GetHashCode. The comparer determines whether two keys are equal. Every key in a System.Collections.Hashtable must be unique. The default comparer is the key’s implementation of System.Object.Equals. The custom hash code provider and the custom comparer enable such scenarios as doing lookups with case-insensitive strings. The elements of the new System.Collections.Hashtable are sorted in the same order in which the enumerator iterates through the System.Collections.IDictionary.
A B C D E F G H I J K L M
Exceptions
N O
Exception
Condition
System.ArgumentNullException
d is null.
System.ArgumentOutOfRangeException
-or-
P Q
loadFactor is less than 0.1.
R S
loadFactor is greater than 1.0.
T U V W
Hashtable(System.Collections.IDictionary,System.Collections. IHashCodeProvider, System.Collections.IComparer) Constructor
X
[ILASM]
public rtspecialname specialname instance void .ctor(class System.Collections.IDictionary d, class System.Collections.IHashCodeProvider hcp, class System.Collections.IComparer comparer)
Y Z
[C#]
public Hashtable(IDictionary d, IHashCodeProvider hcp, IComparer comparer)
1866
Contents | Index
System.Collections
Hashtable Hashtable() Constructor
Summary Constructs and initializes a new instance of the System.Collections.Hashtable class using the values of the specified System.Collections.IDictionary, the specified System.Collections.IHashCodeProvider, and the specified System.Collections.IComparer.
A B C
Parameters
D
Parameter
Description
E
The System.Collections.IDictionary used to initialize the elements of the new instance.
F
d
hcp
comparer
G
The System.Collections.IHashCodeProvider that supplies the hash codes for all keys in the new instance, or null to use the default hash code provider.
H
The System.Collections.IComparer to use to determine whether two keys are equal in the new instance, or null to use the default comparer.
J
I
K L
Description
M
The initial capacity of the new instance is set to the number of entries in d.
N O
Exceptions
P
Exception
Condition
Q
System.ArgumentNullException
d is null.
R S T
Example
U
using System; using System.Collections;
V W
namespace Samples { public class HashtableConstructor { public class MyComparer: IComparer { public int Compare(Object a, Object b) {
X Y Z
1867
Contents | Index
Hashtable
System.Collections
Hashtable() Constructor
return ((IComparable)a).CompareTo(b); } } public class MyHashCodeProvider: IHashCodeProvider { public int GetHashCode(Object o) { return o.GetHashCode(); } }
A B C D E
public static void Main() { SortedList sl = new SortedList(); sl.Add("one", "damien"); sl.Add("three", "brad"); sl.Add("two", "mark"); Hashtable ht = new Hashtable(sl, new MyHashCodeProvider(), new MyComparer()); Console.WriteLine("Count: {0}", ht.Count ); IDictionaryEnumerator de = ht.GetEnumerator(); while(de.MoveNext()) Console.WriteLine("Key: {0} Value: {1}", de.Key, de.Value); }
F G H I J K L M N O
} }
P Q
The output is
R Count: 3 Key: three Value: brad Key: two Value: mark Key: one Value: damien
S T U V
Hashtable(System.Collections.IHashCodeProvider, System.Collections.IComparer) Constructor
W X
[ILASM]
Y
public rtspecialname specialname instance void .ctor(class System.Collections.IHashCodeProvider hcp, class System.Collections.IComparer comparer)
Z
[C#]
public Hashtable(IHashCodeProvider hcp, IComparer comparer)
1868
Contents | Index
System.Collections
Hashtable Hashtable() Constructor
Summary Constructs and initializes a new instance of the System.Collections.Hashtable class with the specified System.Collections.IHashCodeProvider and the specified System.Collections.IComparer.
A B
Parameters
C
Parameter
Description
hcp
The System.Collections.IHashCodeProvider that supplies the hash codes for all keys in the System.Collections.Hashtable, or null to use the default hash code provider.
D E
comparer
F G
The System.Collections.IComparer to use to determine whether two keys are equal, or null to use the default comparer.
H I J
Description
K
The new instance is initialized with the default capacity.
L
Example
M
using System; using System.Collections;
N O
namespace Samples { public class HashtableConstructor { public class MyComparer: IComparer { public int Compare(Object a, Object b) { return ((IComparable)a).CompareTo(b); } } public class MyHashCodeProvider: IHashCodeProvider { public int GetHashCode(Object o) { return o.GetHashCode(); } } public static void Main() {
P Q R S T U V W X Y Z
1869
Contents | Index
Hashtable
System.Collections
Hashtable() Constructor
Hashtable ht = new Hashtable(new MyHashCodeProvider(), new MyComparer()); ht.Add(-1, "damien"); ht.Add(0, "brad"); ht.Add(1, "mark"); Console.WriteLine("Count: {0}", ht.Count ); IDictionaryEnumerator de = ht.GetEnumerator(); while(de.MoveNext()) Console.WriteLine("Key: {0} Value: {1}", de.Key, de.Value);
A B C D E }
F
} }
G
The output is
H I
Count: 3 Key: 1 Value: mark Key: -1 Value: damien Key: 0 Value: brad
J K L M N
Hashtable(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
O
[ILASM]
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
P Q
[C#]
R
protected Hashtable(SerializationInfo info, StreamingContext context)
S
Summary
T
Creates an empty System.Collections.Hashtable that is serializable with the specified System.Runtime.Serialization.SerializationInfo and System.Runtime.Serialization.StreamingContext.
U V W X Y Z
1870
Contents | Index
System.Collections
Hashtable Comparer Property
Parameters Parameter
Description
info
A System.Runtime.Serialization.SerializationInfo object containing the information required to serialize the System.Collections.Hashtable.
A
context
B C
A System.Runtime.Serialization.StreamingContext object containing the source and destination of the serialized stream associated with the System.Collections.Hashtable.
D E F
Description
G
A hashtable’s capacity is used to calculate the optimal number of hashtable buckets based on the load factor. The default initial capacity is zero. Capacity is automatically increased as required. The load factor is the maximum ratio of elements to buckets. A smaller load factor means faster lookup at the cost of increased memory consumption. The default load factor is 1.0, which is the best balance between speed and size. When the actual load factor reaches the load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets. The hash code provider dispenses hash codes for keys in the System.Collections.Hashtable. The default hash code provider is the key’s implementation of System.Object.GetHashCode. The comparer determines whether two keys are equal. Every key in a System.Collections.Hashtable must be unique. The default comparer is the key’s implementation of System.Object.Equals.
H I J K L M N O P Q R
Exceptions
S T
Exception
Condition
System.ArgumentNullException
info is null.
U V W X
Hashtable.Comparer Property
Y
[ILASM]
Z
.property instance class System.Collections.IComparer comparer() [C#] protected IComparer comparer {get; set;}
1871
Contents | Index
Hashtable
System.Collections
Count Property
Summary Gets or sets the comparer to use for the hashtable. A B
Hashtable.Count Property
C
[ILASM]
.property int32 Count { public hidebysig virtual specialname int32 get_Count() }
D
[C#]
public virtual int Count { get; }
E F
Summary
G
Gets the number of key-and-value pairs contained in the current instance.
H I
Example
J
using System; using System.Collections;
K namespace Samples { public class HashtableCount { public static void Main() { Hashtable ht = new Hashtable(3); Console.WriteLine("Count for ht: {0}", ht.Count ); ht.Add("one", "damien"); ht.Add("two", "mark"); ht.Add("three", "brad"); Console.WriteLine("Count for ht: {0}", ht.Count ); ht.Add("four", "maire"); ht.Add("five", "sacha"); ht.Add("six", "tamara"); Console.WriteLine("Count for ht: {0}", ht.Count ); } } }
L M N O P Q R S T U V W
The output is
X Y
Count for ht: 0 Count for ht: 3 Count for ht: 6
Z
1872
Contents | Index
System.Collections
Hashtable IsFixedSize Property
Hashtable.hcp Property [ILASM]
.property instance class System.Collections.IHashCodeProvider hcp()
A
[C#]
protected IHashCodeProvider hcp {get; set;}
B C
Summary
D
Gets or sets the object that can dispense hash codes.
E F
Hashtable.IsFixedSize Property
G [ILASM]
H
.property bool IsFixedSize { public hidebysig virtual specialname bool get_IsFixedSize() }
I
[C#]
J
public virtual bool IsFixedSize { get; }
K
Summary
L
Gets a System.Boolean indicating whether the current instance has a fixed size.
M
Property Value
N
true if the current instance has a fixed size; otherwise, false.
O P
Description
Q
[Note: Elements can be modified in, but not added to or removed from a System.Collections.Hashtable with a fixed size.]
R S
Default
T
The default value of this property is false.
U
How and When to Override
V
Override this property, setting it to true, to prevent the addition or removal of entries in the current instance.
W X Y Z
1873
Contents | Index
Hashtable
System.Collections
IsReadOnly Property
Example using System; using System.Collections;
A namespace Samples { public class HashtableIsFixedSize { public static void Main() { Hashtable ht = new Hashtable(); Console.WriteLine("Is fixed size: {0}", ht.IsFixedSize); } } }
B C D E F G H I
The output is
J Is fixed size: False
K L M
Hashtable.IsReadOnly Property
N
[ILASM]
O
.property bool IsReadOnly { public hidebysig virtual specialname bool get_IsReadOnly() }
P
[C#]
public virtual bool IsReadOnly { get; }
Q R
Summary
S
Gets a System.Boolean value indicating whether the current instance is read-only.
T
Property Value
U
true if the current instance is read-only; otherwise, false.
V W
Description
X
[Note: Elements cannot be modified in, added to, or removed from a System.Collections.Hashtable that is read-only.]
Y Z
Default The default value of this property is false.
1874
Contents | Index
System.Collections
Hashtable IsSynchronized Property
How and When to Override Override this property, setting it to true, in order to prevent the addition, removal, or modification of entries in the current instance. A
Example
B
using System; using System.Collections;
C D
namespace Samples { public class HashtableIsReadOnly { public static void Main() { Hashtable ht = new Hashtable(); Console.WriteLine("Is fixed size: {0}", ht.IsReadOnly); } } }
E F G H I J K L
The output is
M
Is fixed size: False
N O
Hashtable.IsSynchronized Property
P
[ILASM]
Q
.property bool IsSynchronized { public hidebysig virtual specialname bool get_IsSynchronized() }
R
[C#]
S
public virtual bool IsSynchronized { get; }
T
Summary
U
Gets a System.Boolean value indicating whether access to the current instance is synchronized (thread-safe).
V W X
Property Value
Y
true if access to the current instance is synchronized (thread-safe); otherwise, false.
Z
1875
Contents | Index
Hashtable
System.Collections
IsSynchronized Property
Description [Note: This property is implemented to support the System.Collections.ICollection interface. For more information regarding synchronization of access to a System.Collections.Hashtable, see System.Collections.Hashtable.Synchronized.]
A B C
Default
D
The default value of this property is false.
E
How and When to Override
F
Override this property, setting it to true, if thread safety can be guaranteed for the current instance. In order to obtain this safety, use System.Collections.Hashtable.SyncRoot or System.Collections.Hashtable.Synchronized.
G H I J
Example
K
using System; using System.Collections;
L namespace Samples { public class HashtableSynchronized { public static void Main() { Hashtable ht = new Hashtable(); ht.Add(0, "damien" ); ht.Add(1, "mark" ); ht.Add(2, "brad" ); Hashtable sht = Hashtable.Synchronized(ht); Console.WriteLine("ht is Synchronized?: {0}", ht.IsSynchronized); Console.WriteLine("sht is Synchronized?: {0}", sht.IsSynchronized); } } }
M N O P Q R S T U V W X
The output is
Y
ht is Synchronized?: False sht is Synchronized?: True
Z
1876
Contents | Index
System.Collections
Hashtable Item Property
Hashtable.Item Property [ILASM]
.property object Item[object key] { public hidebysig virtual specialname object get_Item(object key) public hidebysig virtual specialname void set_Item(object key, object value) }
A B
[C#]
C
public virtual object this[object key] { get; set; }
D
Summary
E
Gets or sets the value in the current instance that is associated with the specified key.
F G
Parameters
H
Parameter
Description
key
The key whose value to get or set.
I J K
Property Value
L
The value in the current instance that is associated with key. If key is not contained in the current instance, attempting to get it returns null, and attempting to set it creates a new entry using key.
M N O
Description
P
[Note: This property provides the ability to access a specific element in the current instance using the following notation: myCollection[key].]
Q
Default
S
If this property is being set and key is already contained in the current instance, the value associated with the old key is replaced.
T
R
U V W X Y Z
1877
Contents | Index
Hashtable
System.Collections
Keys Property
Exceptions Exception
Condition
System.ArgumentNullException
key is null.
A B
The property is being set and the current instance is read-only.
C D
System.NotSupportedException
E
The property is being set, key is not contained in the current instance, and the current instance has a fixed size.
F G
Example
H
using System; using System.Collections;
I J
namespace Samples { public class HashtableItem { public static void Main() { Hashtable ht = new Hashtable(3); ht.Add("one", "damien"); ht.Add("two", "mark"); ht.Add("three", "brad"); Console.WriteLine(ht["one"]); Console.WriteLine(ht["two"]); Console.WriteLine(ht["three"]); } } }
K L M N O P Q R S
The output is
T
damien mark brad
U V W X
Hashtable.Keys Property
Y
[ILASM]
Z
.property class System.Collections.ICollection Keys { public hidebysig virtual specialname class System.Collections.ICollection get_Keys() } [C#]
public virtual ICollection Keys { get; }
1878
Contents | Index
System.Collections
Hashtable Keys Property
Summary Gets a System.Collections.ICollection containing the keys of the current instance. A
Default
B
The order of the keys in the System.Collections.ICollection is unspecified, but it is the same order as the associated values in the System.Collections.ICollection returned by the System.Collections.Hashtable.Values method. The returned System.Collections.ICollection is a reference to the current instance, not a static copy. Therefore, changes to the current instance continue to be reflected in the System.Collections.ICollection.
C D E F G
Example
H
using System; using System.Collections;
I J
namespace Samples { public class HashtableKeys { public static void Main() { Hashtable ht = new Hashtable(3); ht.Add("one", "damien"); ht.Add("two", "mark"); ht.Add("three", "brad"); ICollection ic = ht.Keys; IEnumerator ie = ic.GetEnumerator(); while(ie.MoveNext()) Console.WriteLine(ie.Current); } } }
K L M N O P Q R S T U
The output is
V
three two one
W X Y Z
1879
Contents | Index
Hashtable
System.Collections
SyncRoot Property
Hashtable.SyncRoot Property [ILASM]
A
.property object SyncRoot { public hidebysig virtual specialname object get_SyncRoot() }
B
[C#]
public virtual object SyncRoot { get; }
C D
Summary
E
Gets a System.Object that can be used to synchronize access to the current instance.
F
Description
G
A thread is required to perform synchronized operations only on the System.Collections.Hashtable.SyncRoot of a System.Collections.Hashtable, not directly on the table itself. This maintains proper synchronization with any other threads concurrently modifying the table. [Note: This property is implemented to support the System.Collections.ICollection interface.]
H I J K L
Default
M
This method returns a reference to the current instance.
N O
How and When to Override
P
Override this property to return an object on which to lock when implementing a collection that wraps another collection (using a subset of it, for example). This is useful when providing synchronized access through two or more wrapper collections to the same underlying collection. Typically, this property returns a reference to the current instance.
Q R S
Usage
T
Use this property to obtain a System.Object that can be used to synchronize access to the current instance.
U V W
Example
X
using System; using System.Collections;
Y
namespace Samples { public class HashtableSyncRoot {
Z
1880
Contents | Index
System.Collections
Hashtable Values Property
public static void Main() { Hashtable ht = new Hashtable(3); lock(ht.SyncRoot) { ht.Add("one", "damien"); ht.Add("two", "mark"); ht.Add("three", "brad"); foreach(DictionaryEntry de in ht) Console.WriteLine(de.Key); } }
A B C D E F
} }
G
The output is
H I
three two one
J K L
Hashtable.Values Property
M
[ILASM]
N
.property class System.Collections.ICollection Values { public hidebysig virtual specialname class System.Collections.ICollection get_Values() }
O
[C#]
P
public virtual ICollection Values { get; }
Q
Summary
R
Gets a System.Collections.ICollection containing the values of the current instance.
S T
Default
U
The order of the values in the System.Collections.ICollection is unspecified, but it is the same order as the associated keys in the System.Collections.ICollection returned by the System.Collections.Hashtable.Keys method. The returned System.Collections.ICollection is a reference to the current instance, not a static copy. Therefore, changes to the current instance continue to be reflected in the System.Collections.ICollection.
V W X Y Z
1881
Contents | Index
Hashtable
System.Collections
Add() Method
Example using System; using System.Collections;
A
namespace Samples { public class HashtableValues { public static void Main() { Hashtable ht = new Hashtable(3); ht.Add("one", "damien"); ht.Add("two", "mark"); ht.Add("three", "brad"); ICollection ic = ht.Values; IEnumerator ie = ic.GetEnumerator(); while(ie.MoveNext()) Console.WriteLine(ie.Current); } } }
B C D E F G H I J K
The output is
L
brad mark damien
M N O P
Hashtable.Add(System.Object, System.Object) Method
Q
[ILASM]
.method public hidebysig virtual void Add(object key, object value)
R
[C#]
S
public virtual void Add(object key, object value)
T
Summary
U
Adds an entry with the specified key and value into the current instance.
V
Parameters
W X Y Z
Parameter
Description
key
The key of the entry to add.
value
The value of the entry to add.
1882
Contents | Index
System.Collections
Hashtable Clear() Method
Exceptions Exception
Condition
System.ArgumentNullException
key is null.
System.ArgumentException
An entry with the same key already exists in the current instance.
System.NotSupportedException
The current instance is read-only or has a fixed size.
A B C D E F
Example
G
using System; using System.Collections;
H I
namespace Samples { public class HashtableAdd { public static void Main() { Hashtable ht = new Hashtable(); Console.WriteLine("Count: {0}", ht.Count); for(int i = 0; i < 100; i++) ht.Add(i, i.ToString()); Console.WriteLine("Count: {0}", ht.Count ); } } }
J K L M N O P Q R
The output is
S T
Count: 0 Count: 100
U V
Hashtable.Clear() Method
W
[ILASM]
X
.method public hidebysig virtual void Clear() [C#]
Y
public virtual void Clear()
Z
1883
Contents | Index
Hashtable
System.Collections
Clear() Method
Summary Removes all entries from the current instance. A
Description
B
[Note: This method is implemented to support the System.Collections.IDictionary interface.]
C D
Default
E
The value of each key and value in the current instance is set to null. The System.Collections.Hashtable.Count property of the current instance is set to zero. The capacity of the current instance remains unchanged. If the current instance is empty, it remains unchanged and no exception is thrown.
F G H
Exceptions
I J
Exception
Condition
System.NotSupportedException
The current instance is read-only.
K L M N
Example
O
using System; using System.Collections;
P
namespace Samples { public class HashtableClear { public static void Main() { Hashtable ht = new Hashtable(); for(int i = 0; i < 100; i++) ht.Add(i, i.ToString()); Console.WriteLine("Count: {0}", ht.Count ); ht.Clear(); Console.WriteLine("Count: {0}", ht.Count ); } } }
Q R S T U V W X Y
The output is
Z
Count: 100 Count: 0
1884
Contents | Index
System.Collections
Hashtable Clone() Method
Hashtable.Clone() Method [ILASM]
.method public hidebysig virtual object Clone() [C#]
A
public virtual object Clone()
B C
Summary
D
Creates a System.Object that is a copy of the current instance.
E
Description
F
[Note: This method is implemented to support the System.ICloneable interface.]
G
Default
H
This method creates a new System.Collections.Hashtable instance initialized with the same count, System.Collections.IHashCodeProvider implementation, and System.Collections.IComparer implementation as the current instance. The references to the objects contained by the current instance are copied to the new instance.
I J K L
Example
M
using System; using System.Collections;
N O
namespace Samples { public class HashtableClone { public static void Main() { Hashtable ht1 = new Hashtable(); ht1.Add("one", "damien"); ht1.Add("two", "mark"); ht1.Add("three", "brad"); Console.WriteLine("Count for ht1: {0}", ht1.Count ); Hashtable ht2 = (Hashtable) ht1.Clone(); ht2.Add("four", "maire"); ht2.Add("five", "sacha"); ht2.Add("six", "tamara"); Console.WriteLine("Count for ht1: {0}", ht1.Count ); Console.WriteLine("Count for ht2: {0}", ht2.Count ); } } }
P Q R S T U V W X Y Z
1885
Contents | Index
Hashtable
System.Collections
Contains() Method
The output is Count for ht1: 3 Count for ht1: 3 Count for ht2: 6
A B C
Hashtable.Contains(System.Object) Method
D
[ILASM]
E
.method public hidebysig virtual bool Contains(object key)
F
[C#]
public virtual bool Contains(object key)
G H
Summary
I
Determines whether the current instance contains the specified key.
J
Parameters
K L M
Parameter
Description
key
The key to locate in the current instance.
N O
Return Value
P
true if the current instance contains key; otherwise, false.
Q R
Description
S
[Note: This method is implemented to support the System.Collections.IDictionary interface.]
T U
Default
V
This method is equivalent to System.Collections.Hashtable.ContainsKey. [Note: For the default implementation, this method has a constant (O(1)) lookup time.]
W X
Exceptions
Y Z
Exception
Condition
System.ArgumentNullException
key is null.
1886
Contents | Index
System.Collections
Hashtable ContainsKey() Method
Example using System; using System.Collections;
A namespace Samples { public class HashtableContains { public static void Main() { Hashtable ht = new Hashtable(); for(int i = 1; i < 3; i++) ht.Add(i, i.ToString()); for(int i = 0; i < 4; i++) Console.WriteLine("Contains {0}: {1}", i, ht.Contains(i)); } } }
B C D E F G H I J K
The output is Contains Contains Contains Contains
0: 1: 2: 3:
L M
False True True False
N O P Q
Hashtable.ContainsKey(System.Object) Method
R
[ILASM]
S
.method public hidebysig virtual bool ContainsKey(object key) [C#]
T
public virtual bool ContainsKey(object key)
U
Summary
V
Determines whether the current instance contains an entry with the specified key.
W X
Parameters
Y
Parameter
Description
key
The key of the entry to locate in the current instance.
Z
1887
Contents | Index
Hashtable
System.Collections
ContainsKey() Method
Return Value true if the current instance contains an entry with key; otherwise, false. A
Default
B
This method uses System.Collections.Hashtable.KeyEquals to compare key to the keys in the current instance. [Note: For the default implementation, this method has a constant (O(1)) lookup time.]
C D E
Exceptions
F G H
Exception
Condition
System.ArgumentNullException
key is null.
I J
Example
K
using System; using System.Collections;
L
namespace Samples { public class HashtableContainsKey { public static void Main() { Hashtable ht = new Hashtable(); for(int i = 1; i < 3; i++) ht.Add(i, i.ToString()); for(int i = 0; i < 4; i++) Console.WriteLine("Contains {0} as a key: {1}", i, ht.ContainsKey(i)); } } }
M N O P Q R S T U V W
The output is
X Contains Contains Contains Contains
Y Z
0 1 2 3
as as as as
a a a a
key: key: key: key:
False True True False
1888
Contents | Index
System.Collections
Hashtable ContainsValue() Method
Hashtable.ContainsValue(System.Object) Method [ILASM]
.method public hidebysig virtual bool ContainsValue(object value) [C#]
A
public virtual bool ContainsValue(object value)
B C
Summary
D
Determines whether the current instance contains an entry with the specified value.
E
Parameters
F
Parameter
Description
value
The value to locate in the current instance.
G H I J
Return Value
K
true if the current instance contains an entry with value; otherwise, false.
L M
Description
N
[Note: This method is implemented to support the System.Collections.IDictionary interface.]
O P
Default
Q
This method is equivalent to System.Collections.Hashtable.ContainsKey. [Note: For the default implementation, this method has a constant (O(1)) lookup time.]
R S
Example
T
using System; using System.Collections;
U V
namespace Samples { public class HashtableContainsValue { public static void Main() { Hashtable ht = new Hashtable(); for(int i = 1; i < 3; i++) ht.Add(i, i.ToString()); for(int i = 0; i < 4; i++)
W X Y Z
1889
Contents | Index
Hashtable
System.Collections
CopyTo() Method
Console.WriteLine("Contains {0} as a value: {1}", i, ht.ContainsValue(i)); for(int i = 0; i < 4; i++) Console.WriteLine("Contains \"{0}\" as a value: {1}", i, ht.ContainsValue(i.ToString()));
A B }
C }
D
}
E
The output is
F
Contains Contains Contains Contains Contains Contains Contains Contains
G H I J K
0 as a 1 as a 2 as a 3 as a "0" as "1" as "2" as "3" as
value: False value: False value: False value: False a value: False a value: True a value: True a value: False
L M
Hashtable.CopyTo(System.Array, System.Int32) Method
N
[ILASM]
O
.method public hidebysig virtual void CopyTo(class System.Array array, int32 arrayIndex)
P
[C#]
public virtual void CopyTo(Array array, int arrayIndex)
Q R
Summary
S
Copies the entries of the current instance to a one-dimensional System.Array starting at the specified index.
T U
Parameters
V W X
Parameter
Description
array
The one-dimensional, zero-indexed System.Array that is the destination of the objects copied from the current instance.
arrayIndex
A System.Int32 that specifies the zero-based index in array at which copying begins. This value is between 0 and array.Length minus the System.Collections.Hashtable.Count of the current instance, inclusive.
Y Z
1890
Contents | Index
System.Collections
Hashtable CopyTo() Method
Default The System.Collections.DictionaryEntry elements in the current instance are copied to the System.Array in the same order in which they are contained the current instance. If System.Collections.DictionaryEntry is not assignment-compatible with the type of array, a System.InvalidCastException is thrown. If an exception is thrown while copying, the state of the current instance is undefined.
A B C D
Exceptions
E
Exception
Condition
System.ArgumentNullException
array is null.
System.ArgumentOutOfRangeException
arrayIndex < 0.
System.ArgumentException
System.InvalidCastException
F G H I
array has more than one dimension.
J
arrayIndex > array.Length minus the System.Collections.Hashtable.Count of the current instance.
K
The type of the current instance is not assignmentcompatible with the type of array.
M
L
N O
Example
P
using System; using System.Collections;
Q R
namespace Samples { public class HashtableCopyTo { public static void Main() { Hashtable ht = new Hashtable(); ht.Add("1", "damien"); ht.Add("2", "mark"); ht.Add("3", "brad"); Array a = Array.CreateInstance(typeof(string),3); ht.Values.CopyTo(a, 0); Console.WriteLine("The contents of the array are:"); for(int i = 0; i < a.Length; i++) Console.WriteLine("{0} ",a.GetValue(i)); ht.Keys.CopyTo(a, 0);
S T U V W X Y Z
1891
Contents | Index
Hashtable
System.Collections
GetEnumerator() Method
Console.WriteLine("The contents of the array are:"); for(int i = 0; i < a.Length; i++) Console.WriteLine("{0} ",a.GetValue(i)); }
A
} }
B C
The output is
D The contents of the array are: mark brad damien The contents of the array are: 2 3 1
E F G H I J K
Hashtable.GetEnumerator() Method
L
[ILASM]
M
.method public hidebysig virtual class System.Collections.IDictionaryEnumerator GetEnumerator()
N
[C#]
public virtual IDictionaryEnumerator GetEnumerator()
O P
Summary
Q
Returns a System.Collections.IDictionaryEnumerator for the current instance.
R
Description
S
If the current instance is modified while an enumeration is in progress, a call to System.Collections.IEnumerator.MoveNext or System.Collections.IEnumerator.Reset throws System.InvalidOperationException. [Note: For detailed information regarding the use of an enumerator, see System.Collections.IEnumerator. This property is implemented to support the System.Collections.IList interface.]
T U V W X
Example
Y
using System; using System.Collections;
Z
namespace Samples
1892
Contents | Index
System.Collections
Hashtable GetHash() Method
{ public class HashtableGetEnumerator { public static void Main() { Hashtable ht = new Hashtable(); ht.Add(1, "damien"); ht.Add(2, "mark"); ht.Add(3, "brad"); Console.WriteLine("Count: {0}", ht.Count ); IDictionaryEnumerator de = ht.GetEnumerator(); while(de.MoveNext()) Console.WriteLine("Key: {0} : Value: {1}", de.Key, de.Value); } }
A B C D E F G H I
}
J
The output is
K Count: Key: 3 Key: 2 Key: 1
3 : : :
L
Value: brad Value: mark Value: damien
M N O
Hashtable.GetHash(System.Object) Method
P
[ILASM]
Q
.method family hidebysig virtual int32 GetHash(object key)
R
[C#]
protected virtual int GetHash(object key)
S
Summary
T
Generates a hash code for the specified key in the current instance.
U V
Parameters
W
Parameter
Description
key
The System.Object whose hash code is to be generated.
X Y Z
1893
Contents | Index
Hashtable
System.Collections
GetObjectData() Method
Description This method is accessible only through this class or a derived class. A
Default
B
If the current instance was instantiated with a specific System.Collections.IHashCodeProvider implementation, this method uses that hash code provider; otherwise, it uses the System.Object.GetHashCode implementation of key.
C D E
Exceptions
F G H
Exception
Condition
System.ArgumentNullException
key is null.
I J
Hashtable.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Method
K L
[ILASM]
M N
.method public hidebysig virtual void GetObjectData(class System.Runtime. Serialization.SerializationInfo info, valuetype System.Runtime.Serialization. StreamingContext context)
O
[C#]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
P Q
Summary
R
Implements the System.Runtime.Serialization.ISerializable interface and returns the data needed to serialize the System.Collections.Hashtable.
S T
Parameters
U V
Parameter
Description
info
A System.Runtime.Serialization.SerializationInfo object containing the information required to serialize the System.Collections.Hashtable.
context
A System.Runtime.Serialization.StreamingContext object containing the source and destination of the serialized stream associated with the System.Collections.Hashtable.
W X Y Z
1894
Contents | Index
System.Collections
Hashtable KeyEquals() Method
Exceptions Exception
Condition
System.ArgumentNullException
info is null.
A B C D
Hashtable.KeyEquals(System.Object, System.Object) Method
E
[ILASM]
F
.method family hidebysig virtual bool KeyEquals(object item, object key) [C#]
G
protected virtual bool KeyEquals(object item, object key)
H
Summary
I
Determines whether the specified System.Object and the specified key in the current instance represent the same value.
J K L
Parameters
M
Parameter
Description
item
The System.Object to compare with key.
key
The key in the current instance to compare with item.
N O P Q R
Return Value
S
true if item and key represent the same value; otherwise, false.
T
Description
U
This method is accessible only through this class or a derived class.
V W
Default
X
If the current instance was initialized with a specified System.Collections.IComparer implementation, this method uses that implementation to perform the comparison; otherwise, the System.Object.Equals implementation of item is used.
Y Z
1895
Contents | Index
Hashtable
System.Collections
OnDeserialization() Method
Exceptions Exception
Condition
System.ArgumentNullException
item is null. -orkey is null.
A B C D E
Hashtable.OnDeserialization(System.Object) Method
F G
[ILASM]
H
[C#]
.method public hidebysig virtual void OnDeserialization(object sender) public virtual void OnDeserialization(object sender)
I J
Summary
K
Implements the System.Runtime.Serialization.ISerializable interface and raises the deserialization event when the deserialization is complete.
L M
Parameters
N O P
Parameter
Description
sender
The source of the deserialization event.
Q
Exceptions
R S
Exception
Condition
System.Runtime.Serialization.SerializationException
The System.Runtime.Serialization.SerializationInfo object associated with the current System. Collections.Hashtable is invalid.
T U V W X
Hashtable.Remove(System.Object) Method
Y [ILASM]
Z
.method public hidebysig virtual void Remove(object key) [C#]
public virtual void Remove(object key)
1896
Contents | Index
System.Collections
Hashtable Remove() Method
Summary Removes the entry with the specified key from the current instance. A
Parameters
B
Parameter
Description
C
key
The key of the entry to remove.
D E F
Description
G
[Note: This method is implemented to support the System.Collections.IDictionary interface.]
H I
Default
J
This method uses the System.Object.Equals implementation of key to locate it in the current instance. If key is found in the current instance, the values of both key and its associated value are set to null. If key is not found in the current instance, no exception is thrown and the current instance remains unchanged.
K L M
Exceptions
N O
Exception
Condition P
System.ArgumentNullException
key is null.
Q
System.NotSupportedException
The current instance is read-only or has a fixed size.
R S
Example
T
using System; using System.Collections;
U
namespace Samples { public class HashtableRemove { public static void Main() { Hashtable ht = new Hashtable(); for(int i = 0; i < 100; i++)
W
V
X Y Z
1897
Contents | Index
Hashtable
System.Collections
Synchronized() Method
ht.Add(i, i.ToString()); Console.WriteLine("Count: {0}", ht.Count ); for(int i = 0; i < 100; i += 2) ht.Remove(i); Console.WriteLine("Count: {0}", ht.Count );
A }
B }
C
}
D
The output is
E Count: 100 Count: 50
F G H
Hashtable.Synchronized(System.Collections.Hashtable) Method
I [ILASM]
J
.method public hidebysig static class System.Collections.Hashtable Synchronized(class System.Collections.Hashtable table)
K
[C#]
L
public static Hashtable Synchronized(Hashtable table)
M
Summary
N
Returns a synchronized (thread-safe) wrapper for the specified System.Collections.Hashtable.
O P
Parameters
Q R
Parameter
Description
table
The System.Collections.Hashtable to synchronize.
S T U
Description
V
This method returns a new System.Collections.Hashtable instance that contains values equal to the values of table, and provides synchronized access to those values. If more than one thread is to write to a System.Collections.Hashtable concurrently, all write operations are required to be done through this wrapper. [Note: A System.Collections.Hashtable can safely support one writer and multiple readers concurrently.]
W X Y Z
1898
Contents | Index
System.Collections
Hashtable GetEnumerator() Method
Exceptions Exception
Condition
System.ArgumentNullException
table is null.
A B C
Example
D
Please see SyncRoot property.
E
using System; using System.Collections;
F G
namespace Samples { public class HashtableSynchronized { public static void Main() { Hashtable ht = new Hashtable(); ht.Add(0, "damien" ); ht.Add(1, "mark" ); ht.Add(2, "brad" ); Hashtable sht = Hashtable.Synchronized(ht); Console.WriteLine("ht is Synchronized?: {0}", ht.IsSynchronized); Console.WriteLine("sht is Synchronized?: {0}", sht.IsSynchronized); } } }
H I J K L M N O P Q R
The output is
S T
ht is Synchronized?: False sht is Synchronized?: True
U V
IEnumerable.GetEnumerator() Method
W
[ILASM]
X
.method private final hidebysig virtual class System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
Y
[C#]
Z
IEnumerator IEnumerable.GetEnumerator()
1899
Contents | Index
Hashtable
System.Collections
GetEnumerator() Method
Summary Implemented to support the System.Collections.IEnumerable interface. [Note: For more information, see System.Collections.IEnumerable.GetEnumerator.] A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1900
Contents | Index
System IAsyncResult Interface
BCL
IAsyncResult
A
Summary
B
Supported by objects that represent the state of an asynchronous operation.
C D
Type Summary
E
public interface IAsyncResult { // Properties object AsyncState { get; } WaitHandle AsyncWaitHandle { get; } bool CompletedSynchronously { get; } bool IsCompleted { get; } }
F G H I J K
KC Cancel is a very often-requested member. We decided not to add it as not all
L
async operations can reliably support cancellations. It’s bad to have interface members that cannot be implemented by a large percentage of types implementing the interface. Interface design is extremely difficult. It requires perfect balance between too few members (which makes the interface useless) and too many members, which makes the interface too hard or even impossible to implement in many cases.
M N O P
JR I like the asynchronous programming model a lot and I recommend that every-
Q
one learn it and apply it where appropriate to improve the performance and scalability to their applications.
R S
The object obtainable via the AsyncWaitHandle property is lazily constructed. That is, it isn’t created unless you specifically query this property. You should avoid writing code to query this property since it is more efficient to use the asynchronous programming model with callback methods anyway. However, if you do query this property, you might want to explicitly close the underlying kernel object’s handle by calling WaitHandle’s Close or Dispose method.
T U V W X Y Z
1901
Contents | Index
IAsyncResult Interface
System
IAsyncResult Interface
Description An object that supports the System.IAsyncResult interface stores state information for an asynchronous operation, and provides a synchronization object to allow threads to be signaled when the operation completes. System.IAsyncResult objects are returned by methods that begin asynchronous operations, such as System.IO.FileStream.BeginRead, and are passed to methods used to complete asynchronous operations, such as System.IO.FileStream.EndRead. System.IAsyncResult objects are also passed to methods invoked by System.AsyncCallback delegates when an asynchronous operation completes.
A B C D E F
Example
G
using System; using System.Threading;
H I
namespace Samples { public class MyIAsyncResultSample { internal class MyIAsyncResult: IAsyncResult { internal Object stateObject; internal bool complete = false; internal AutoResetEvent jobDone; internal MyIAsyncResult(Object stateObject) { this.stateObject = stateObject; this.jobDone = new AutoResetEvent(false); } public virtual Object AsyncState {get { return stateObject; }} public bool IsCompleted { get {return complete; }} public WaitHandle AsyncWaitHandle {get {return jobDone; }} public bool CompletedSynchronously {get {return false; }} } internal class RandomNumberProvider { private static Random r = new Random(); private void FillWithRandoms(object o) { MyIAsyncResult m = (MyIAsyncResult) o; int[] integers = (int[]) m.AsyncState; for(int i = 0; i < integers.Length; i++) integers[i] = r.Next(); Thread.Sleep(1000); m.complete = true; m.jobDone.Set(); }
J K L M N O P Q R S T U V W X Y Z
1902
Contents | Index
System
IAsyncResult Interface IAsyncResult Interface
public IAsyncResult BeginFillWithRandoms(int[] integers) { MyIAsyncResult m = new MyIAsyncResult(integers); ThreadPool.QueueUserWorkItem( new WaitCallback(FillWithRandoms), m); return m; }
A B C
} public static void Main() { RandomNumberProvider r = new RandomNumberProvider(); int[] integers = new int[5]; IAsyncResult iar = r.BeginFillWithRandoms(integers); while(!iar.IsCompleted) { Console.WriteLine("Not complete yet"); Thread.Sleep(500); } Console.WriteLine("Now complete"); foreach(int i in integers) Console.WriteLine(i); iar = r.BeginFillWithRandoms(integers); Console.WriteLine("Will wait"); iar.AsyncWaitHandle.WaitOne(); foreach(int i in integers) Console.WriteLine(i); }
D E F G H I J K L M N O
}
P
}
Q
The output is
R S
Not complete yet Not complete yet Not complete yet Now complete 1795940024 1936965058 337589761 1038014204 727149687 Will wait 847972885 1839223938 210272409 1187767220 1116260647
T U V W X Y Z
1903
Contents | Index
IAsyncResult Interface
System
AsyncState Property
IAsyncResult.AsyncState Property [ILASM]
A
.property object AsyncState { public hidebysig virtual abstract specialname object get_AsyncState() }
B
[C#]
object AsyncState { get; }
C D
Summary
E
Gets the user-provided state object supplied at the time the asynchronous operation was started.
F G
Behaviors
H
The object returned by this property is required to be the object specified as the last parameter to methods that begin asynchronous operations, such as System.IO.FileStream.BeginRead.
I J K
How and When to Override
L
Implement this property to allow the caller of an asynchronous operation to obtain an application-defined object specified at the start of the operation.
M N
Usage
O
The object returned by this property can be used to pass state information for the asynchronous operation to a System.AsyncCallback delegate.
P Q
Example
R
using using using using
S T U
System; System.IO; System.Text; System.Threading;
namespace Samples { public class IAsyncResultAsyncState { const int limit = 512; const int readlimit = 15; public class StateHolder { public byte[] bytes ; public FileStream fs ; } public static void Main()
V W X Y Z
1904
Contents | Index
System
IAsyncResult Interface AsyncState Property
{ string s = "filestream.txt"; FileStream fs = new FileStream(s, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None, 512, true); StateHolder sh = new StateHolder(); sh.fs = fs; sh.bytes = new Byte[limit]; AsyncCallback ac = new AsyncCallback(CallMe); fs.BeginRead(sh.bytes, 0, readlimit, ac, sh); for(int i = 0; i < 50; i++) { Thread.Sleep(5); Console.Write('*'); }
A B C D E F G H I
} public static void CallMe(IAsyncResult asyncResult) { StateHolder sh = (StateHolder) asyncResult.AsyncState; FileStream fs = sh.fs; int count = fs.EndRead(asyncResult); Console.Write("\nBytes read: {0} ", count); if(count != 0) { Decoder d = Encoding.UTF8.GetDecoder(); char[] chars = null; int i = d.GetCharCount(sh.bytes, 0, count); chars = new Char[i]; count = d.GetChars(sh.bytes, 0, count, chars, 0); Console.WriteLine(new string(chars)); fs.BeginRead(sh.bytes, 0, readlimit, new AsyncCallback(CallMe), sh); } else { fs.Close() ; } }
J K L M N O P Q R S T U V
}
W
}
X
The output is
Y
***** Bytes read: 15 *ABCDEFGHIJKLMNO ** Bytes read: 15 PQRSTUVWXYZ
Z
1905
Contents | Index
IAsyncResult Interface
System
AsyncWaitHandle Property
ab Bytes read: 15 cdefghijklmnopq
A
Bytes read: 11 rstuvwxyz
B ******************* Bytes read: 0 ***********************
C D E
IAsyncResult.AsyncWaitHandle Property
F [ILASM]
G H
.property class System.Threading.WaitHandle AsyncWaitHandle { public hidebysig virtual abstract specialname class System.Threading.WaitHandle get_AsyncWaitHandle() }
I
[C#]
WaitHandle AsyncWaitHandle { get; }
J K
Summary
L
Gets a System.Threading.WaitHandle that can be used to block a thread until an asynchronous operation completes.
M N
Behaviors
O
The object returned by System.IAsyncResult.AsyncWaitHandle can be allocated in advance or on demand. However, once allocated it is required to be kept alive until the user calls a method that ends the asynchronous operation, such as System.IO.FileStream.EndRead. Only after the operation completes or is canceled can the object be disposed of. [Note: WaitHandle supplies methods that support waiting for synchronization objects to become signaled, such as System.Threading.WaitHandle.WaitOne.]
P Q R S T U
Usage
V
Clients that wait for the operation to complete (as opposed to polling), use this property to obtain a synchronization object to wait on.
W X
Example
Y
using System; using System.Threading;
Z namespace Samples { public class IAsyncResultAsyncWaitHandle
1906
Contents | Index
System
IAsyncResult Interface CompletedSynchronously Property
{ public delegate int D(); public static int MethodToCall() { Console.WriteLine("\"MethodToCall()\" called"); Thread.Sleep(10000); Console.WriteLine("\"MethodToCall()\" returning"); return 42; } public static void Main() { Console.WriteLine("Synchronous call"); Console.WriteLine("Returnd value {0}", MethodToCall()); D myD = new D(MethodToCall); Console.WriteLine("Asynchronous call"); IAsyncResult iar = myD.BeginInvoke(null, null); Console.WriteLine("Asynchronous call executing"); iar.AsyncWaitHandle.WaitOne(); Console.WriteLine("Asynchronous call returned"); Console.WriteLine("Returnd value {0}", myD.EndInvoke(iar)); }
A B C D E F G H I J K L
} }
M
The output is
N O
Synchronous call "MethodToCall()" called "MethodToCall()" returning Returnd value 42 Asynchronous call Asynchronous call executing "MethodToCall()" called "MethodToCall()" returning Asynchronous call returned Returnd value 42
P Q R S T U V
IAsyncResult.CompletedSynchronously Property
W
[ILASM]
X
.property bool CompletedSynchronously { public hidebysig virtual abstract specialname bool get_CompletedSynchronously() }
Y
[C#]
Z
bool CompletedSynchronously { get; }
1907
Contents | Index
IAsyncResult Interface
System
CompletedSynchronously Property
Summary Gets a System.Boolean value that specifies whether the asynchronous operation completed synchronously. A B
Property Value
C
true if the operation completed synchronously; otherwise false.
D
Behaviors
E
[Note: Most implementations of the System.IAsyncResult interface will not use this property, and should return false.]
F G
Usage
H
Use this property to determine if the asynchronous operation completed synchronously. For example, this property can return true for an asynchronous IO operation if the IO request was small.
I J K
Example
L
using System; using System.Threading;
M N
namespace Samples { public class IAsyncResultCompletedSynchronously { public delegate int D(); public static int MethodToCall() { Console.WriteLine("\"MethodToCall()\" called"); Thread.Sleep(10000); Console.WriteLine("\"MethodToCall()\" returning"); return 42; } public static void Main() { Console.WriteLine("Synchronous call"); Console.WriteLine("Returnd value {0}", MethodToCall()); D myD = new D(MethodToCall); Console.WriteLine("Asynchronous call"); IAsyncResult iar = myD.BeginInvoke(null, null); Console.WriteLine("Asynchronous call executing"); iar.AsyncWaitHandle.WaitOne(); Console.WriteLine("Asynchronous call returned");
O P Q R S T U V W X Y Z
1908
Contents | Index
System
IAsyncResult Interface IsCompleted Property
Console.WriteLine("Returnd value {0}", myD.EndInvoke(iar)); Console.WriteLine("Completed synchronously?: {0}", iar.CompletedSynchronously);
A
} }
B
}
C
The output is
D E
Synchronous call "MethodToCall()" called "MethodToCall()" returning Returnd value 42 Asynchronous call Asynchronous call executing "MethodToCall()" called "MethodToCall()" returning Asynchronous call returned Returnd value 42 Completed synchronously?: False
F G H I J K L M
IAsyncResult.IsCompleted Property
N [ILASM]
O
.property bool IsCompleted { public hidebysig virtual abstract specialname bool get_IsCompleted() }
P
[C#]
bool IsCompleted { get; }
Q R
Summary
S
Gets a System.Boolean value that specifies whether an asynchronous operation has completed.
T U
Property Value
V
true if the operation has completed; otherwise false.
W
Usage
X
Clients that poll for operation status (as opposed to waiting on a synchronization object) use this property to determine the status of the operation.
Y Z
1909
Contents | Index
IAsyncResult Interface
System
IsCompleted Property
Example using System; using System.Threading;
A namespace Samples { public class IAsyncResultIsCompleted { public delegate int D(); public static int MethodToCall() { Console.WriteLine("\"MethodToCall()\" called"); Thread.Sleep(10000); Console.WriteLine("\"MethodToCall()\" returning"); return 42; } public static void Main() { D myD = new D(MethodToCall); Console.WriteLine("Asynchronous call"); IAsyncResult iar = myD.BeginInvoke(null, null); Console.WriteLine("Asynchronous call executing"); Console.WriteLine("Is Completed?: {0}", iar.IsCompleted); iar.AsyncWaitHandle.WaitOne(); Console.WriteLine("Asynchronous call returned"); Console.WriteLine("Returnd value {0}", myD.EndInvoke(iar)); Console.WriteLine("Is Completed?: {0}", iar.IsCompleted); } } }
B C D E F G H I J K L M N O P Q R S
The output is
T U
Asynchronous call Asynchronous call executing Is Completed?: False "MethodToCall()" called
V W X Y Z
1910
Contents | Index
System ICloneable Interface
BCL
ICloneable Array
A
AsyncCallback
B
CharEnumerator
C
ArrayList
D
Hashtable
E
Delegate
F
EventHandler
G
DateTimeFormatInfo
H NumberFormatInfo
I String
J ThreadStart
K
TimerCallback
L
Version
M
Summary
N
Implemented by classes that require control over the way in which copies of instances are constructed.
O P
Type Summary
Q
public interface ICloneable { // Methods object Clone (); }
R S T U V
JR The documentation for this interface states that Clone can make either a shal-
W
low or deep copy. This is ridiculous; the standard should have defined Clone as making a deep copy. Without a guarantee of the type of copy, you must be careful how you use a cloned object and have intimate knowledge of what Clone does for a type; this information is usually not documented, leading to problems.
X Y Z
continued
1911
Contents | Index
ICloneable Interface
System
ICloneable Interface
KG Echoing Jeffrey’s comment, without a contract for ICloneable, which specifies whether it is deep or shallow, this interface is close to unusable. Defining a deepcopy version would have definitely been the most useful approach here.
A B
Because of this loose contract, anyone utilizing the ICloneable aspect of a class really has no idea what he or she can then do with the class. Users can’t assume that it’s a tearaway version (the result of a deep copy), because if they manipulate the resulting “Clone” at all, then they may also be affecting the original. This may have unwanted side effects.
C D E F
Unfortunately, the disparate implementations of this interface throughout the framework make it next to impossible to fix at this stage. You can just define a Copy method on classes in order to support your own deep-cloning; however, I do urge caution since this can be very difficult to guarantee. As soon as you have a reference to something which does not itself define a deep-clone mechanism, you cannot successfully define your own.
G H I J K L
Description
M
[Note: System.ICloneable contains the System.ICloneable.Clone method. The consumer of an object should call this method when a copy of the object is needed.]
N O
Example
P
using System; using System.Collections;
Q R
namespace Samples { public class ICloneableSample: ICloneable { private int i; private Hashtable h; public int AnInteger { get { return i;} set { i = value;} } public Hashtable AHashtable { get { return h;} set { h = value;} }
S T U V W X Y Z
1912
Contents | Index
System
ICloneable Interface Clone() Method
public ICloneableSample() { i = 42; h = new Hashtable(); } private ICloneableSample(int i, Hashtable ht) { this.i = i; h = (Hashtable) ht.Clone(); } public object Clone() { return new ICloneableSample(i, h); } public static void Main() { ICloneableSample i1 = new ICloneableSample(); i1.AHashtable.Add("one", "damien"); ICloneableSample i2 = (ICloneableSample) i1.Clone(); i2.AnInteger = 22; i2.AHashtable.Add("two", "brad"); Console.WriteLine("i1.AnInteger {0} i1.AHashtable.Count {1}", i1.AnInteger, i1.AHashtable.Count); Console.WriteLine("i2.AnInteger {0} i2.AHashtable.Count {1}", i2.AnInteger, i2.AHashtable.Count); }
A B C D E F G H I J K L M N
}
O
}
P
The output is
Q
i1.AnInteger 42 i1.AHashtable.Count 1 i2.AnInteger 22 i2.AHashtable.Count 2
R S T
ICloneable.Clone() Method
U
[ILASM]
V
.method public hidebysig virtual abstract object Clone()
W
[C#]
object Clone()
X
Summary
Y
Creates a copy of the current instance.
Z
1913
Contents | Index
ICloneable Interface
System
Clone() Method
Return Value A System.Object of the same type as the current instance, containing copies of the nonstatic members of the current instance. A B
Description
C
The exact behavior of this method is unspecified. The intent of the method is to provide a mechanism that constructs instances that are copies of the current instance, without regard for class-specific definitions of the term “copy.” [Note: Use the System.Object.MemberwiseClone method to create a shallow copy of an object. For more information, see System.Object.MemberwiseClone.]
D E F G
Behaviors
H
This method is required to return an instance of the same type as the current instance.
I J K L M N O P Q R S T U V W X Y Z
1914
Contents | Index
System.Collections ICollection Interface
BCL
ICollection
IEnumerable
A Array
B ArrayList
C
Hashtable
D
PermissionSet
E
Summary
F
Serves as the base interface for implementing collection classes. Defines size, enumeration, and synchronization methods for all system collections.
G H
Type Summary
I
public interface ICollection : IEnumerable { // Properties int Count { get; } bool IsSynchronized { get; } object SyncRoot { get; }
J K L M
// Methods void CopyTo (Array array, int index);
N O
}
P Q
BG In a future release of the Microsoft .NET Framework, we will be adding a new
R
generic collections namespace that is similar to the existing one. We will not replace the current classes, but the new generic classes should provide most of the interesting functionality from what we did in V1. We have made a few changes to the generic collection interfaces, but they are small. The generic collections will implement our nongeneric interfaces as well; as long as you are using our V1 interfaces in your public API’s, you will be able to consume and return generic collections in the future if you want, albeit with some loss of efficiency.
S T U V W
Our eventual goal is to add generics into the CLS, which may enable us to do things such as writing new libraries that only use generics, as well as adding generic interfaces and/or methods to the base data types.
X Y Z
continued
1915
Contents | Index
ICollection Interface
System.Collections
ICollection Interface
KC This interface is causing some headaches. Not all collections can implement Count—for example, collections that get items on demand (pretty common). Also, IsSynchronized and SyncRoot members are rarely used (they should probably be on a separate interface). On the other hand, ICollection should probably have some methods to allow adding items to a collection.
A B C
JR The SyncRoot property is a bad idea. It exposes the object’s lock object to the
D
outside world where, in reality, the object should always be private to an object. In addition, the lock is expected to be manipulated via Monitor’s methods or C#’s lock statement. This means that a collection cannot be made thread-safe using a read-write lock mechanism.
E F G H
Description
I
[Note: System.Collections.ICollection contains the System.Collections.ICollection.CopyTo method. The consumer of a collection object that implements this interface should call this method when copying the elements of that object to a System.Array.]
J K L M
Example
N
using System; using System.Collections;
O
namespace Samples { public class ICollectionSample { public static void Main() { ArrayList al = new ArrayList(); al.Add("damien"); al.Add("mark"); al.Add("brad"); Array a = Array.CreateInstance(typeof(string), al.Count); al.CopyTo(a, 0); Console.WriteLine("The contents of the array are:"); for(int i = 0; i < a.Length; i++) Console.WriteLine("{0} ",a.GetValue(i)); } } }
P Q R S T U V W X Y Z
1916
Contents | Index
System.Collections
ICollection Interface Count Property
The output is The contents of the array are: damien mark brad
A B C D
ICollection.Count Property
E
[ILASM]
.property int32 Count { public hidebysig virtual abstract specialname int32 get_Count() }
F G
[C#]
int Count { get; }
H
Summary
I
Gets the number of elements contained in the current instance.
J K
Behaviors
L
The System.Collections.ICollection.Count property is required to return the total number of elements contained in the current instance.
M N
Example
O
using System; using System.Collections;
P Q
namespace Samples { public class ICollectionCount { public static void Main() { ArrayList al = new ArrayList(); al.Add("damien"); al.Add("mark"); al.Add("brad"); Console.WriteLine("Items in ArrayList: {0} ",al.Count); } } }
R S T U V W X Y Z
The output is Items in ArrayList: 3
1917
Contents | Index
ICollection Interface
System.Collections
IsSynchronized Property
ICollection.IsSynchronized Property [ILASM]
A
.property bool IsSynchronized { public hidebysig virtual abstract specialname bool get_IsSynchronized() }
B
[C#]
bool IsSynchronized { get; }
C D
Summary
E
Gets a System.Boolean indicating whether access to the current instance is synchronized (thread-safe).
F G
Property Value
H
true if access to the current instance is synchronized (thread-safe); otherwise, false.
I
Usage
J
To synchronize a collection, use System.Collections.ICollection.SyncRoot to obtain a System.Object with which to synchronize the collection.
K L M
Example
N
using System; using System.Collections;
O
namespace Samples { public class ICollectionIsSynchronized { public static void Main() { Hashtable ht = new Hashtable(); Console.WriteLine("Is hashtable Synchronized: {0}", ht.IsSynchronized); ht = Hashtable.Synchronized(ht); Console.WriteLine("Is hashtable Synchronized: {0}", ht.IsSynchronized); } } }
P Q R S T U V W X
The output is
Y Z
Is hashtable Synchronized: False Is hashtable Synchronized: True
1918
Contents | Index
System.Collections
ICollection Interface SyncRoot Property
ICollection.SyncRoot Property [ILASM]
.property object SyncRoot { public hidebysig virtual abstract specialname object get_SyncRoot() }
A
[C#]
B
object SyncRoot { get; }
C
Summary
D
Gets a System.Object that can be used for thread-safe synchronized access to the current instance.
E F
Description
G
[Note: For collections with no publicly available underlying store, the expected implementation is to simply return the current instance. Note that this might not be sufficient for collections that wrap other collections; those should return the underlying collection’s System.Collections.ICollection.SyncRoot property.]
H I J K
Example
L
using System; using System.Collections;
M
namespace Samples { public class ICollectionSyncRoot { public static void Main() { Hashtable ht = new Hashtable(3); lock(ht.SyncRoot) { ht.Add("one", "damien"); ht.Add("two", "mark"); ht.Add("three", "brad"); foreach(DictionaryEntry de in ht) Console.WriteLine(de.Key); } } } }
N O P Q R S T U V W X Y
The output is
Z
three two one
1919
Contents | Index
ICollection Interface
System.Collections
CopyTo() Method
ICollection.CopyTo(System.Array, System.Int32) Method [ILASM]
A
.method public hidebysig virtual abstract void CopyTo(class System.Array array, int32 index)
B
[C#]
void CopyTo(Array array, int index)
C D
Summary
E
Copies the elements from the current instance to the specified System.Array, starting at the specified index in the array.
F G
Parameters
H I J
Parameter
Description
array
A one-dimensional, zero-based System.Array that is the destination of the elements copied from the current instance.
index
A System.Int32 that specifies the zero-based index in array at which copying begins.
K L M N
Usage
O
Use this method to copy from a collection to a System.Array.
P
Exceptions
Q R
Exception
Condition
System.ArgumentNullException
array is null.
System.ArgumentOutOfRangeException
index < 0.
S T U V
array has more than one dimension.
W
index is greater than or equal to array.Length. System.ArgumentException
X Y Z
System.InvalidCastException
The sum of index and the System.Collections.ICollection.Count of the current instance is greater than array.Length. At least one element in the current instance is not assignment-compatible with the type of array.
1920
Contents | Index
System.Collections
ICollection Interface CopyTo() Method
Example using System; using System.Collections;
A namespace Samples { public class ICollectionCopyTo { public static void Main() { ArrayList al = new ArrayList(); al.Add("damien"); al.Add("mark"); al.Add("brad"); Array a = Array.CreateInstance(typeof(string), al.Count); al.CopyTo(a, 0); Console.WriteLine("The contents of the array are:"); for(int i = 0; i < a.Length; i++) Console.WriteLine("{0} ",a.GetValue(i)); } } }
B C D E F G H I J K L M
The output is
N The contents of the array are: damien mark brad
O P Q R S T U V W X Y Z
1921
Contents | Index
System IComparable Interface
BCL
IComparable AttributeTargets
A
Boolean
B
Byte
C Char
D
DateTime
E
DateTimeStyles
F
Decimal
ExtendedNumerics
G
Double
ExtendedNumerics
Enum
H
EnvironmentPermissionAccess
I FileAccess
J
FileIOPermissionAccess
K
FileMode
L
FileShare
M
Int16 Int32
N
Int64
O NumberStyles
P
PermissionState
Q
SByte
R
SecurityActions
S
SecurityPermissionFlag SeekOrigin
T
Single
U
ExtendedNumerics
String
V
ThreadPriority
W
ThreadState
X
TimeSpan
Y
UInt16 UInt32
Z UInt64 UnicodeCategory Version
1922
Contents | Index
System
IComparable Interface IComparable Interface
Summary Implemented by classes that support an ordering of instances of the class. A
Type Summary
B
public interface IComparable { // Methods int CompareTo (object obj); }
C D E F
BA There is a natural tension between modeling a concept as an interface and as a base class. In this case it is clear that requiring developers to inherit from a Comparable base class to be comparable would have been too restrictive. However, this class does illustrate good design principles for any interface. It is simple; there are no complex contracts to be maintained between the members of the interface (because there is only one member). The concept is clearly an additive element of the class design rather than the center point of the design.
G H I J K L
JR When defining a value type that implements IComparable, you should define
M
a type-safe version of the method and you should apply C#’s explicit interface method implementation feature to the CompareTo method that takes Object as a parameter. This will reduce boxing (improving performance) and will give you more compiletime safety as well!
N O P Q
Description
R
[Note: System.IComparable contains the System.IComparable.CompareTo method. The consumer of an object should call this method when sorting instances of a class.]
S T
Example
U
using System;
V
namespace Samples { public class MyNameClass: IComparable { private string name; public MyNameClass(string name) { this.name = name;
W X Y Z
1923
Contents | Index
IComparable Interface
System
IComparable Interface
} public override string ToString() { return String.Format("Type: MyNameClass Value: {0}", name); } public override bool Equals(object o) { if(null == o) return false; if(this.GetType() != o.GetType()) return false; MyNameClass other = (MyNameClass) o; return name.Equals(other.name); } public override int GetHashCode() { return name.GetHashCode(); } public int CompareTo(object o) { if(o is MyNameClass) { MyNameClass other = (MyNameClass) o; return name.CompareTo(other.name); } throw new ArgumentException("Different Types"); }
A B C D E F G H I J K L M N O
} public class IComparableSample { public static void Main() { MyNameClass[] names = new MyNameClass[]{ new MyNameClass("damien"), new MyNameClass("maire"), new MyNameClass("mark"), new MyNameClass("sacha"), new MyNameClass("brad"), new MyNameClass("sarah")}; Array.Sort(names); foreach(MyNameClass m in names) Console.WriteLine(m); } }
P Q R S T U V W X Y Z }
1924
Contents | Index
System
IComparable Interface CompareTo() Method
The output is Type: Type: Type: Type: Type: Type:
MyNameClass MyNameClass MyNameClass MyNameClass MyNameClass MyNameClass
Value: Value: Value: Value: Value: Value:
brad damien maire mark sacha sarah
A B C D E
IComparable.CompareTo(System.Object) Method
F [ILASM]
.method public hidebysig virtual abstract int32 CompareTo(object obj)
G
[C#]
H
int CompareTo(object obj)
I
Summary
J
Returns the sort order of the current instance compared to the specified object.
K L
Parameters
M
Parameter
Description
obj
The System.Object to compare to the current instance.
N O P Q
Return Value
R
A System.Int32 containing a value that reflects the sort order of the current instance as compared to obj. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number.
S T U
Returned Value
Description
Any negative value
The current instance is < obj.
Zero
The current instance is == obj.
any positive value
The current instance is > than obj or obj is a null reference.
V W X Y Z
1925
Contents | Index
IComparable Interface
System
CompareTo() Method
Behaviors For any objects A, B, and C, the following are required to be true: • • •
A B C D
•
E
•
F G H
•
I J
A.CompareTo(A) is required to return zero. If A.CompareTo(B) returns zero, then B.CompareTo(A) is required to return zero. If A.CompareTo(B) returns zero and B.CompareTo(C) returns zero, then A.CompareTo(C) is required to return zero. If A.CompareTo(B) returns a value other than zero, then B.CompareTo(A) is required to return a value of the opposite sign. If A.CompareTo(B) returns a value x not equal to zero, and B.CompareTo(C) returns a value y of the same sign as x, then A.CompareTo(C) is required to return a value of the same sign as x and y. The exact behavior of this method is unspecified. The intent of this method is to provide a mechanism that orders instances of a class in a manner that is consistent with the mathematical definitions of the relational operators (<, >, and ==), without regard for class-specific definitions of the operators.
K L
Usage
M
Use the System.IComparable.CompareTo method to determine the ordering of instances of a class.
N O P Q R S T U V W X Y Z
1926
Contents | Index
System.Collections IComparer Interface
BCL
IComparer
A
Compare
B
Summary
C
Provides a mechanism to customize the sort ordering of a collection.
D E
Type Summary public interface IComparer { // Methods int Compare (object x, object y); }
F G H I J
BG Note that the IComparer interface allows you to define your own ordering
K
over types, when the original author may not have envisioned a need to sort the class. It’s a great hook for comparison and sorting. Combined with IHashCodeProvider, you can use types as keys in a Hashtable even if the original class author neglected to override Equals and GetHashCode for their type.
L M N O
Description
P
The default implementation of this interface is System.Collections.Comparer. [Note: System.Collections.IComparer contains the System.Collections.IComparer.Compare method. The consumer of an object should call this method when sorting members of a collection.]
Q R S T
Example using System; using System.Collections;
U
namespace Samples { public class IComparerSample { public class ToStringComparer: IComparer { public int Compare(Object a, Object b) { string s1 = a.ToString();
W
V
X Y Z
1927
Contents | Index
IComparer Interface
System.Collections
IComparer Interface
string s2 = b.ToString(); return s1.CompareTo(s2); } } public static void Main() { ArrayList a = new ArrayList(); a.Add (0); a.Add("1"); a.Add(2); a.Add(3); a.Add("4"); a.Add(5); a.Add("6"); SearchFor(a, "2"); SearchFor(a, 1); SearchFor(a, 9); } public static void SearchFor(ArrayList a, object o) { int i = a.BinarySearch(o, new ToStringComparer()); if(i > 0) { Console.WriteLine( "Object: {0}, was found at: {1}", o, i ); } else if(~i == a.Count) { Console.WriteLine("Object: {0}, was not found", o); Console.WriteLine( "No object in the array had a greater value."); } else { Console.WriteLine("Object: {0}, was not found", o); Console.WriteLine( "The next larger object is at index: {0}.", ~i ); } }
A B C D E F G H I J K L M N O P Q R S T U V
} }
W
The output is
X Y
Object: 2, was found at: 2 Object: 1, was found at: 1 Object: 9, was not found No object in the array had a greater value.
Z
1928
Contents | Index
System.Collections
IComparer Interface Compare() Method
IComparer.Compare(System.Object, System.Object) Method [ILASM]
.method public hidebysig virtual abstract int32 Compare(object x, object y) [C#]
A
int Compare(object x, object y)
B C
Summary
D
Returns the sort order of two System.Object instances.
E
Parameters
F G
Parameter
Description
x
First System.Object to compare.
I
y
Second System.Object to compare.
J
H
K
Return Value
L
A System.Int32 containing a value that reflects the sort order of x as compared to y. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number.
M N O P
Value
Condition
Q
any negative number
x < y.
R
zero
x == y.
any positive number
x > y.
S T U V
Behaviors
W
For any objects A, B, and C, the following are required to be true: • •
X
System.Collections.IComparer.Compare(A,A) is required to return zero. If System.Collections.IComparer.Compare(A,B) returns zero, then System.Collections.IComparer.Compare(B,A) is required to return zero.
Y Z
1929
Contents | Index
IComparer Interface
System.Collections
Compare() Method
•
A
•
B C
•
D E F
If System.Collections.IComparer.Compare(A,B) returns zero and System.Collections.IComparer.Compare(B,C) returns zero, then System.Collections.IComparer.Compare(A,C) is required to return zero. If System.Collections.IComparer.Compare(A,B) returns a value other than zero, then System.Collections.IComparer.Compare(B,A) is required to return a value of the opposite sign. If System.Collections.IComparer.Compare(A,B) returns a value x not equal to zero, and System.Collections.IComparer.Compare(B,C) returns a value y of the same sign as x, then System.Collections.IComparer.Compare(A,C) is required to return a value of the same sign as x and y.
[Note: The exact ordering of this method is unspecified. The intent of the method is to provide a mechanism that orders instances of a class in a manner that is consistent with the mathematical definitions of the relational operators (<, >, and ==), without regard for class-specific definitions of the operators.]
G H I J
Usage
K
This interface is used in conjunction with the System.Array.Sort and System.Array.BinarySearch methods.
L M N O P Q R S T U V W X Y Z
1930
Contents | Index
System.Collections IDictionary Interface
BCL
ICollection IDictionary
A
IEnumerable Hashtable
B
Summary
C
Implemented by classes that support collections of associated keys and values (i.e., dictionaries).
D E F
Type Summary
G
public interface IDictionary : ICollection, IEnumerable { // Properties bool IsFixedSize { get; } bool IsReadOnly { get; } object this[object key] { set; get; } ICollection Keys { get; } ICollection Values { get; }
H I J K L
// Methods void Add (object key, object value); void Clear (); bool Contains (object key); IDictionaryEnumerator GetEnumerator (); void Remove (object key);
M N O P
}
Q
Description
R
[Note: Each key-value pair must have a unique non-null key, but the value of an association can be any object reference, including a null reference. The System.Collections.IDictionary interface allows the contained keys and values to be enumerated, but it does not imply any particular sort order. System.Collections.IDictionary implementations fall into three categories: read-only, fixed-size, and variable-size. A readonly implementation cannot be modified. A fixed-size implementation does not allow the addition or removal of elements, but it allows the modification of existing elements. A variable-size implementation allows the addition, removal, and modification of elements.]
S T U V W X
Example
Y
using System; using System.Collections;
Z
namespace Samples
1931
Contents | Index
IDictionary Interface
System.Collections
IDictionary Interface
{ public class IDictionarySample { public static void Main() { IDictionary id = new Hashtable(); id.Add(1, "damien"); id.Add(2, "mark"); id.Add(3, "brad"); DisplayDictionary(id); SortedList sl = new SortedList(); sl.Add(1, "maire"); sl.Add(2, "sacha"); sl.Add(3, "tamara"); DisplayDictionary(sl); } public static void DisplayDictionary(IDictionary id) { Console.WriteLine("Is fixed size: {0}", id.IsFixedSize); Console.WriteLine("Is read only: {0}", id.IsReadOnly); Console.WriteLine("Count: {0}", id.Count ); Console.WriteLine("Number of keys: {0}", id.Keys.Count); foreach(DictionaryEntry de in id) Console.WriteLine("Key: {0} Value: {1}", de.Key, de.Value); } }
A B C D E F G H I J K L M N O }
P Q
The output is
R Is fixed size: False Is read only: False Count: 3 Number of keys: 3 Key: 3 Value: brad Key: 2 Value: mark Key: 1 Value: damien Is fixed size: False Is read only: False Count: 3 Number of keys: 3 Key: 1 Value: maire Key: 2 Value: sacha Key: 3 Value: tamara
S T U V W X Y Z
1932
Contents | Index
System.Collections
IDictionary Interface IsFixedSize Property
IDictionary.IsFixedSize Property [ILASM]
.property bool IsFixedSize { public hidebysig virtual abstract specialname bool get_IsFixedSize() }
A
[C#]
B
bool IsFixedSize { get; }
C
Summary
D
Gets a value indicating whether the current instance has a fixed size.
E F
Property Value
G
true if the current instance has a fixed size; otherwise, false.
H
Description
I
[Note: A collection with a fixed size does not allow the addition or removal of elements, but does allow the modification of existing elements.]
J K
Default
L
The default of this property is false.
M N
How and When to Override
O
Override this method, setting the value as true, to prevent the addition and removal of the elements in the current instance.
P Q
Example
R
using System; using System.Collections;
S T
namespace Samples { public class IDictionaryIsFixedSize { public static void Main() { IDictionary id = new Hashtable(); id.Add("one", "damien"); id.Add("two", "mark"); id.Add("three", "brad"); Console.WriteLine("Is fixed size: {0}", id.IsFixedSize); } } }
U V W X Y Z
1933
Contents | Index
IDictionary Interface
System.Collections
IsReadOnly Property
The output is Is fixed size: False
A B
IDictionary.IsReadOnly Property
C [ILASM]
D
.property bool IsReadOnly { public hidebysig virtual abstract specialname bool get_IsReadOnly() }
E
[C#]
bool IsReadOnly { get; }
F G
Summary
H
Gets a value indicating whether the current instance is read-only.
I J
Property Value
K
true if the current instance is read-only; otherwise, false.
L
Description
M
[Note: A collection that is read-only does not allow the addition, removal, or modification of elements.]
N O
Default
P
The default of this property is false.
Q R
How and When to Override
S
Override this method, setting the value as true, to prevent the addition, removal, and modification of the elements in the current instance.
T U
Example
V
using System; using System.Collections;
W namespace Samples { public class IDictionaryIsReadOnly { public static void Main() { IDictionary id = new Hashtable();
X Y Z
1934
Contents | Index
System.Collections
IDictionary Interface Item Property
id.Add("one", "damien"); id.Add("two", "mark"); id.Add("three", "brad"); Console.WriteLine("Is read only: {0}", id.IsReadOnly);
A
}
B
}
C
}
D
The output is
E Is read only: False
F G
IDictionary.Item Property
H
[ILASM]
I
.property object Item[object key] { public hidebysig virtual abstract specialname object get_Item(object key) public hidebysig virtual abstract specialname void set_Item(object key, object value) }
J K
[C#]
L
object this[object key] { get; set; }
M
Summary
N
Gets or sets the element in the current instance that is associated with the specified key.
O
Parameters
P Q
Parameter
Description
key
The key of the element to get or set.
R S T
Description
U
[Note: This property provides the ability to access a specific element in the collection by using the following syntax: myCollection[index].]
V W
Behaviors
X
When setting this property, if the specified key already exists in the current instance, the value is required to be replaced; otherwise, a new element is required to be created.
Y Z
1935
Contents | Index
IDictionary Interface
System.Collections
Keys Property
Exceptions Exception
Condition
System.ArgumentNullException
key is null.
A B
The property is set and the current instance is read-only.
C
System.NotSupportedException
D
The property is set, key does not exist in the collection, and the current instance has a fixed size.
E F
Example
G
using System; using System.Collections;
H
namespace Samples { public class IDictionaryItem { public static void Main() { IDictionary id = new Hashtable(); id.Add(1, "damien"); id.Add(2, "mark"); id.Add(3, "brad"); for(int i = 1; i <= id.Count; i++) Console.WriteLine("Key: {0} Value: {1}", i, id[i]); } } }
I J K L M N O P Q R S
The output is
T Key: 1 Value: damien Key: 2 Value: mark Key: 3 Value: brad
U V W X
IDictionary.Keys Property
Y
[ILASM]
Z
.property class System.Collections.ICollection Keys { public hidebysig virtual abstract specialname class System.Collections.ICollection get_Keys() } [C#]
ICollection Keys { get; }
1936
Contents | Index
System.Collections
IDictionary Interface Values Property
Summary Gets a System.Collections.ICollection containing the keys of the current instance. A
Example using System; using System.Collections;
B
namespace Samples { public class IDictionaryKeys { public static void Main() { IDictionary id = new Hashtable(); id.Add(1, "damien"); id.Add(2, "mark"); id.Add(3, "brad"); ICollection ic = id.Keys; IEnumerator e = ic.GetEnumerator(); while(e.MoveNext()) Console.WriteLine("Key: {0}", e.Current); } } }
D
C
E F G H I J K L M N
The output is
O P
Key: 3 Key: 2 Key: 1
Q R S
IDictionary.Values Property
T [ILASM]
U
.property class System.Collections.ICollection Values { public hidebysig virtual abstract specialname class System.Collections.ICollection get_Values() } [C#]
V
ICollection Values { get; }
W X
Summary
Y
Gets a System.Collections.ICollection containing the values in the current instance.
Z
1937
Contents | Index
IDictionary Interface
System.Collections
Add() Method
Example using System; using System.Collections;
A namespace Samples { public class IDictionaryValues { public static void Main() { IDictionary id = new Hashtable(); id.Add(1, "damien"); id.Add(2, "mark"); id.Add(3, "brad"); foreach(string s in id.Values) Console.WriteLine("Value: {0}", s); } } }
B C D E F G H I J K
The output is
L Value: brad Value: mark Value: damien
M N O P
IDictionary.Add(System.Object, System.Object) Method
Q
[ILASM]
R
.method public hidebysig virtual abstract void Add(object key, object value)
S
void Add(object key, object value)
[C#]
T
Summary
U
Adds an entry with the provided key and value to the current instance.
V
Parameters
W X
Parameter
Description
key
The System.Object to use as the key of the entry to add.
value
The System.Object to use as the value of the entry to add.
Y Z
1938
Contents | Index
System.Collections
IDictionary Interface Add() Method
Description If the specified key already exists in the current instance, this method throws a System.ArgumentException exception but does not modify the associated value. A
Exceptions
B C
Exception
Condition
System.ArgumentNullException
key is null.
E
An entry with the same key already exists in the current instance.
F
System.ArgumentException System.NotSupportedException
D
G
The current instance is read-only or has a fixed size.
H I
Example
J
using System; using System.Collections;
K L
namespace Samples { public class IDictionaryAdd { public static void Main() { IDictionary id = new Hashtable(); id.Add(1, "damien"); id.Add(2, "mark"); id.Add(3, "brad"); DisplayDictionary(id); } public static void DisplayDictionary(IDictionary id) { Console.WriteLine("Count: {0}", id.Count ); foreach(DictionaryEntry de in id) Console.WriteLine("Key: {0} Value: {1}", de.Key, de.Value); } } }
M N O P Q R S T U V W X Y Z
1939
Contents | Index
IDictionary Interface
System.Collections
Clear() Method
The output is Count: Key: 3 Key: 2 Key: 1
A B
3 Value: brad Value: mark Value: damien
C D
IDictionary.Clear() Method
E
[ILASM]
.method public hidebysig virtual abstract void Clear()
F
[C#]
G
void Clear()
H
Summary
I
Removes all key and value pairs from the current instance.
J K
Exceptions
L M N
Exception
Condition
System.NotSupportedException
The System.Collections.IDictionary is read-only.
O P Q
Example
R
using System; using System.Collections;
S
namespace Samples { public class IDictionaryClear { public static void Main() { IDictionary id = new Hashtable(); id.Add(1, "damien"); id.Add(2, "mark"); id.Add(3, "brad"); DisplayDictionary(id); id.Clear(); DisplayDictionary(id); }
T U V W X Y Z
1940
Contents | Index
System.Collections
IDictionary Interface Contains() Method
public static void DisplayDictionary(IDictionary id) { Console.WriteLine("Count: {0}", id.Count ); Console.WriteLine("Count: {0}", id.Count ); foreach(DictionaryEntry de in id) Console.WriteLine("Key: {0} Value: {1}", de.Key, de.Value); }
A B C D
} }
E F
The output is
G Count: Count: Key: 3 Key: 2 Key: 1 Count: Count:
3 3 Value: brad Value: mark Value: damien 0 0
H I J K L M
IDictionary.Contains(System.Object) Method
N [ILASM]
O
.method public hidebysig virtual abstract bool Contains(object key) [C#]
P
bool Contains(object key)
Q
Summary
R
Determines whether the current instance contains an entry with the specified key.
S T
Parameters
U
Parameter
Description
V
key
The key to locate in the System.Collections.IDictionary.
W X
Return Value
Y
true if the System.Collections.IDictionary contains an entry with the key; otherwise, false.
Z
1941
Contents | Index
IDictionary Interface
System.Collections
GetEnumerator() Method
Exceptions Exception
Condition
System.ArgumentNullException
key is null.
A B C
Example
D
using System; using System.Collections;
E F
namespace Samples { public class IDictionaryContains { public static void Main() { IDictionary id = new Hashtable(); id.Add(1, "damien"); id.Add(2, "mark"); id.Add(3, "brad"); int i = 2; Console.WriteLine("Contains a key of {0}: {1}", i, id.Contains(i)); id.Clear(); Console.WriteLine("Contains a key of {0}: {1}", i, id.Contains(i)); } } }
G H I J K L M N O P Q
The output is
R
Contains a key of 2: True Contains a key of 2: False
S T U
IDictionary.GetEnumerator() Method
V
[ILASM]
W
.method public hidebysig virtual abstract class System.Collections.IDictionaryEnumerator GetEnumerator()
X
[C#]
Y
IDictionaryEnumerator GetEnumerator()
Z
Summary Returns a System.Collections.IDictionaryEnumerator for the current instance. 1942
Contents | Index
System.Collections
IDictionary Interface GetEnumerator() Method
Description If the current instance is modified while an enumeration is in progress, a call to System.Collections.IEnumerator.MoveNext or System.Collections.IEnumerator.Reset will throw System.InvalidOperationException. [Note: For detailed information regarding the use of an enumerator, see System.Collections.IEnumerator.]
A B C
Example
D
using System; using System.Collections;
E F
namespace Samples { public class IDictionaryGetEnumerator { public static void Main() { IDictionary id = new Hashtable(); id.Add(1, "damien"); id.Add(2, "mark"); id.Add(3, "brad"); DisplayDictionary(id); } public static void DisplayDictionary(IDictionary id) { Console.WriteLine("Count: {0}", id.Count ); IDictionaryEnumerator de = id.GetEnumerator(); while(de.MoveNext()) Console.WriteLine("Key: {0} Value: {1}", de.Key, de.Value); } } }
G H I J K L M N O P Q R S T U
The output is Count: Key: 3 Key: 2 Key: 1
V
3 Value: brad Value: mark Value: damien
W X Y Z
1943
Contents | Index
IDictionary Interface
System.Collections
Remove() Method
IDictionary.Remove(System.Object) Method [ILASM]
.method public hidebysig virtual abstract void Remove(object key)
A
[C#]
void Remove(object key)
B C
Summary
D
Removes the entry with the specified key from the current instance.
E
Parameters
F G
Parameter
Description
key
The key of the entry to remove.
H I J K
Behaviors
L
If key is not found in the current instance, no exception is thrown and the current instance remains unchanged.
M N
Exceptions
O
Exception
Condition
Q
System.ArgumentNullException
key is null.
R
System.NotSupportedException
The current instance is read-only or has a fixed size.
P
S T
Example
U
using System; using System.Collections;
V W
namespace Samples { public class IDictionaryRemove { public static void Main() { IDictionary id = new Hashtable(); id.Add(1, "damien");
X Y Z
1944
Contents | Index
System.Collections
IDictionary Interface Remove() Method
id.Add(2, "mark"); id.Add(3, "brad"); DisplayDictionary(id); id.Remove(2); DisplayDictionary(id);
A
} public static void DisplayDictionary(IDictionary id) { Console.WriteLine("Count: {0}", id.Count ); IDictionaryEnumerator de = id.GetEnumerator(); while(de.MoveNext()) Console.WriteLine("Key: {0} Value: {1}", de.Key, de.Value); Console.WriteLine(); }
B C D E F G H
}
I
}
J
The output is
K Count: Key: 3 Key: 2 Key: 1
3 Value: brad Value: mark Value: damien
L M N
Count: 2 Key: 3 Value: brad Key: 1 Value: damien
O P Q R S T U V W X Y Z
1945
Contents | Index
System.Collections IDictionaryEnumerator Interface IDictionaryEnumerator
BCL
IEnumerator
A
Summary
B
Implemented by classes that support the use of an enumerator over a dictionary (i.e., a collection of System.Collections.DictionaryEntry objects).
C D
Type Summary
E
public interface IDictionaryEnumerator : IEnumerator { // Properties DictionaryEntry Entry { get; } object Key { get; } object Value { get; } }
F G H I J K
JR IDictionaryEnumerator’s Current property returns an object of DictionaryEntry type. This is what you work with when using C#’s foreach statement with a type that implements the IDictionary interface.
L M N O
Description
P
[Note: System.Collections.IDictionaryEnumerator contains members that get the properties of System.Collections.DictionaryEntry objects. For detailed information regarding the use of an enumerator, see System.Collections.IEnumerator.]
Q R S
Example
T
using System; using System.Collections;
U
namespace Samples { public class IDictionarySample { public static void Main() { IDictionary id = new Hashtable(); id.Add(1, "damien"); id.Add(2, "mark"); id.Add(3, "brad");
V W X Y Z
1946
Contents | Index
System.Collections
IDictionaryEnumerator Interface Entry Property
DisplayDictionary(id); } public static void DisplayDictionary(IDictionary id) { Console.WriteLine("Count: {0}", id.Count ); IDictionaryEnumerator ide = id.GetEnumerator(); while(ide.MoveNext()) { DictionaryEntry de = ide.Entry; Console.WriteLine("Key: {0} Value: {1}", de.Key, de.Value); } }
A B C D E F G
} }
H I
The output is
J Count: Key: 3 Key: 2 Key: 1
3 Value: brad Value: mark Value: damien
K L M N
IDictionaryEnumerator.Entry Property
O
[ILASM]
P
.property valuetype System.Collections.DictionaryEntry Entry { public hidebysig virtual abstract specialname valuetype System.Collections.DictionaryEntry get_Entry() }
Q
[C#]
R
DictionaryEntry Entry { get; }
S
Summary
T
Gets the System.Collections.DictionaryEntry in the collection over which the current instance is positioned.
U V W
Behaviors
X
It is required that a call to System.Collections.IDictionaryEnumerator.Entry leave the position of the enumerator unchanged: Consecutive calls to this property are required to return the same System.Object until System.Collections.IEnumerator.MoveNext or System.Collections.IEnumerator.Reset is called.
Y Z
1947
Contents | Index
IDictionaryEnumerator Interface
System.Collections
Key Property
Usage Use System.Collections.IDictionaryEnumerator.Entry to get the same data that would be provided by a call to System.Collections.IEnumerator.Current. Because this property is a System.Collections.DictionaryEntry, boxing is not required as it is for System.Collections.IEnumerator.Current; therefore, for this operation, System.Collections.IDictionaryEnumerator.Entry has reduced overhead compared to System.Collections.IEnumerator.Current.
A B C D
Exceptions
E F
Exception
Condition
G H I
System.InvalidOperationException
J
The System.Collections.IDictionaryEnumerator is positioned before the first element of the dictionary or after the last element. -orThe dictionary was modified after the System.Collections.IDictionaryEnumerator was created.
K L M N
IDictionaryEnumerator.Key Property
O
[ILASM]
P
.property object Key { public hidebysig virtual abstract specialname object get_Key() }
Q
[C#]
object Key { get; }
R S
Summary
T
Gets the System.Collections.DictionaryEntry.Key of the System.Collections.DictionaryEntry in the collection over which the current instance is positioned.
U V
Behaviors
W
It is required that reading System.Collections.IDictionaryEnumerator.Key leave the position of the enumerator unchanged: consecutive calls to this property are required to return the same System.Object until System.Collections.IEnumerator.MoveNext or System.Collections.IEnumerator.Reset is called.
X Y Z
1948
Contents | Index
System.Collections
IDictionaryEnumerator Interface Value Property
Exceptions Exception
Condition A
System.InvalidOperationException
The System.Collections.IDictionaryEnumerator is positioned before the first element of the dictionary or after the last element.
B C
-orD
The dictionary was modified after the System.Collections.IDictionaryEnumerator was instantiated.
E F G
IDictionaryEnumerator.Value Property
H
[ILASM]
I
.property object Value { public hidebysig virtual abstract specialname object get_Value() }
J
[C#]
K
object Value { get; }
L
Summary
M
Gets the System.Collections.DictionaryEntry.Value of the System.Collections.DictionaryEntry in the collection over which the current instance is positioned.
N O
Behaviors
P
It is required that a call to System.Collections.IDictionaryEnumerator.Value leave the position of the enumerator unchanged: consecutive calls to this property are required to return the same System.Object until System.Collections.IEnumerator.MoveNext or System.Collections.IEnumerator.Reset is called.
Q R S T
Exceptions
U
Exception
System.InvalidOperationException
Condition
V
The System.Collections.IDictionaryEnumerator is positioned before the first element of the dictionary or after the last element.
W
-or-
Y
The dictionary was modified after the System.Collections.IDictionaryEnumerator was created.
Z
X
1949
Contents | Index
System IDisposable Interface
BCL
IDisposable
A
FileStream
B
MemoryStream
C
Stream
D
StreamReader
E
StreamWriter StringReader
F
StringWriter
G
TextReader
H TextWriter
I Timer
J WaitHandle
K L
Summary
M
Implemented by classes that require explicit control over resource cleanup.
N
Type Summary
O
public interface IDisposable { // Methods void Dispose (); }
P Q R S T
BA Credit for the IDisposable concept should go to the .NET Framework early beta testers for providing quite strong and vocal feedback on early pre-releases that such a concept was a requirement. Moving away from the deterministic finalization world of COM, VB, and Win32 development was always perceived as one of the biggest bets we made with the runtime. However, we rejected early attempts to add deterministic finalization to the CLR because of its performance and programming model implications.
U V W X Y
continued Z
1950
Contents | Index
System
IDisposable Interface IDisposable Interface
The issues did not resurface in a serious way until shortly after our beta1 release. Customers gave us very clear feedback that some sort of mitigation of this problem was required. Through many hours of design meetings the IDisposable plan emerged as the winner. The combination of library support and language support (e.g., C#’s using statement), which didn’t require us to change the guts of the runtime so late in the cycle, made it a winner. Clearly it is not a perfect solution, but it does address the 80% scenario quite nicely.
A B C D
JR I was heavily involved in the creation of the IDisposable pattern and while it was not my first choice for a solution, it did meet a lot of the team’s goals (which Brad pointed out). Note that any type that has an IDisposable type as a member should be IDisposable itself and, in its Dispose method, the member should be disposed. This makes the IDisposable pattern more difficult to work with than originally thought when it was first accepted.
E F G H I J
Description
K
Objects that need to free resources that cannot safely be reclaimed by the garbage collector implement the System.IDisposable interface. It is a version-breaking change to add the System.IDisposable interface to an existing class, as it changes the semantics of the class. [Note: System.IDisposable contains the System.IDisposable.Dispose method. The consumer of an object should call this method when the object is no longer needed. The System.IDisposable interface is generally provided for the release of unmanaged resources that need to be reclaimed in some order or time-dependent manner. It is important to note that the actual release of these resources happens at the first call to System.IDisposable.Dispose for any given object that supports this interface. Programmers should take care to pair the creation of objects that implement IDisposable with at most one invocation of the Dispose method. Though it is legal to invoke Dispose more than once, if this happens it may indicate the presence of a bug since such an object is usually rendered otherwise unusable after the first Dispose invocation.]
L M N O P Q R S T U V
Example
W
using System;
X namespace Samples { public class IDisposableSample: IDisposable { private bool disposed = false; public void Dispose()
Y Z
1951
Contents | Index
IDisposable Interface
System
IDisposable Interface
{ lock(this) { if(disposed) return; GC.SuppressFinalize(this); Dispose(true); disposed = true; }
A B C D
} public void Close() { Dispose(); } public void Dispose(bool b) { if(b) { Console.WriteLine("Dispose()/Close() called " + "explicitly by user code"); Console.WriteLine("Do cleanup necessary for " + "this case"); } Console.WriteLine("Do cleanup necessary for finalization"); } ~IDisposableSample() { Dispose(false); } public static void Main() { IDisposableSample ids1 = new IDisposableSample(); IDisposableSample ids2 = new IDisposableSample(); IDisposableSample ids3 = new IDisposableSample(); ids1.Close(); ids2.Dispose(); ids3 = null; GC.WaitForPendingFinalizers(); }
E F G H I J K L M N O P Q R S T U
} }
V
The output is
W X
Dispose()/Close() called Do cleanup necessary for Do cleanup necessary for Dispose()/Close() called Do cleanup necessary for Do cleanup necessary for Do cleanup necessary for
Y Z
explicitly by user code this case finalization explicitly by user code this case finalization finalization
1952
Contents | Index
System
IDisposable Interface Dispose() Method
IDisposable.Dispose() Method [ILASM]
.method public hidebysig virtual abstract void Dispose() [C#]
A
void Dispose()
B C
Summary
D
Performs application-defined tasks associated with freeing or resetting resources.
E
Description
F
[Note: This method is, by convention, used for all tasks associated with freeing resources held by an object, or preparing an object for reuse. When implementing the System.IDisposable.Dispose method, objects should seek to ensure that all held resources are freed by propagating the call through the containment hierarchy. For example, if an object A allocates an object B, and B allocates an object C, then A’s System.IDisposable.Dispose implementation should call System.IDisposable.Dispose on B, which should in turn call System.IDisposable.Dispose on C. Objects should also call the System.IDisposable.Dispose method of their base class if the base class implements System.IDisposable. If an object’s System.IDisposable.Dispose method is called more than once, the object should ignore all calls after the first one. The object should not throw an exception if its System.IDisposable.Dispose method is called multiple times. System.IDisposable.Dispose may throw an exception if an error occurs because a resource has already been freed and System.IDisposable.Dispose had not been called previously. A resource type may use a particular convention to denote an allocated state versus a freed state. An example of this is stream classes, which are traditionally thought of as open or closed. Classes that have such conventions may choose to implement a public method with a customized name, which calls the System.IDisposable.Dispose method. Because the System.IDisposable.Dispose method must be called explicitly, objects that implement System.IDisposable should also implement a finalizer to handle freeing resources when System.IDisposable.Dispose is not called. By default, the garbage collector will automatically call an object’s finalizer prior to reclaiming its memory. However, once the System.IDisposable.Dispose method has been called, it is typically unnecessary and/ or undesirable for the garbage collector to call the disposed object’s finalizer. To prevent automatic finalization, System.IDisposable.Dispose implementations can call System.GC.SuppressFinalize. For additional information on implementing finalizers, see System.GC and System.Object.Finalize.]
G H I J K L M N O P Q R S T U V W X Y Z
1953
Contents | Index
System.Collections IEnumerable Interface
BCL
IEnumerable
A
Array
B
ArrayList
C
Hashtable
D
PermissionSet
E
Stirng
F
Summary
G
Implemented by classes that support a simple iteration over instances of the collection.
H
Type Summary
I
public interface IEnumerable { // Methods IEnumerator GetEnumerator (); }
J K L M N
BA It is interesting to look at how the C# foreach support works with types that
O
implement IEnumerable.
P
For a C# program that looks like this:
Q R
foreach (int v in collection) { ... }
S
The C# compiler generates code that looks something like this:
T 1: 2: 3: 4: 5: 6: 7: 8: 9:
U V W X Y
IEnumerable ie = (IEnumerable) collection; IEnumerator e = ie.GetEnumerator(); try { while (e.MoveNext()) { int v = (int) e.Current; ... } } finally {
Z
continued
1954
Contents | Index
System.Collections
IEnumerable Interface IEnumerable Interface
10: if (e is IDisposable) { 11: ((IDisposable)e).Dispose(); 12: } 13: }
A B
In line 1, you see the first thing we do is cast the collection to the IEnumerable interface. Then in line 2 we get the IEnumerator and in line 4 we start iterating through the Enumerator. Line 6 is where the body of the foreach statement goes. Notice lines 9–12 is where the enumerator is disposed. We put this in a finally block so that it gets executed whether an exception gets thrown or not. This support for disposable enumerators was added relatively late in the design of the language when we discovered some specific cases where developers had to avoid using the foreach statement so they could explicity dispose of the enumerator.
C D E F G H
In retrospect it would have been a good idea to have the IEnumerator implement the IDisposable interface to make lines 10–11 slightly more efficient and more importantly to make this aspect of the language’s foreach support less of a special case and therefore more obvious to developers.
I J K L
Description
M
[Note: System.Collections.IEnumerable contains the System.Collections.IEnumerable.GetEnumerator method. The consumer of an object should call this method to obtain an enumerator for simple iteration over an instance of a collection. Implement this interface to support the foreach semantics of C#.]
N O P Q
Example
R
using System; using System.Collections;
S T
namespace Samples { public class IEnumerableSample { public static void Main() { IEnumerable s = "Hello world"; IEnumerator ie = s.GetEnumerator(); while(ie.MoveNext()) Console.Write(ie.Current); } } }
U V W X Y Z
1955
Contents | Index
IEnumerable Interface
System.Collections
GetEnumerator() Method
The output is Hello world
A B
IEnumerable.GetEnumerator() Method
C [ILASM]
D
.method public hidebysig virtual abstract class System.Collections.IEnumerator GetEnumerator()
E
[C#]
IEnumerator GetEnumerator()
F G
Summary
H
Returns a System.Collections.IEnumerator that can be used for simple iteration over a collection.
I J
Usage
K
For a detailed description regarding the use of an enumerator, see System.Collections.IEnumerator.
L M N O P Q R S T U V W X Y Z
1956
Contents | Index
System.Collections IEnumerator Interface
BCL
IEnumerator
A
CharEnumerator
B
Summary
C
Implemented by classes that support a simple iteration over a collection.
D
Type Summary
E
public interface IEnumerator { // Properties object Current { get; }
F G H
// Methods bool MoveNext (); void Reset ();
I J
}
K
BA During the design of the BCL we debated long and hard about including the
L
Reset method on this interface. On one side, we knew of several kinds of enumerators for which implementing Reset would be impractical. On the other side, we felt it was very important to provide some compatibility with COM’s IEnum interface. So we compromised and included Reset, but took the unusual step of allowing implementers to throw a NotSupportedException if implementing Reset is not appropriate. Usually, having to throw a NotSupportedException from an interface implementation either means that the interface is not well designed, or that this class should not be implementing it.
M N O P Q R S
Description
T
[Note: System.Collections.IEnumerator contains the System.Collections.IEnumerator.MoveNext and System.Collections.IEnumerator.Reset methods and the System.Collections.IEnumerator.Current property. The consumer of an object should call these methods or use this property when iterating over or reading the elements of a collection. When an enumerator is instantiated or a call is made to System.Collections.IEnumerator.Reset, the enumerator is positioned immediately before the first element of the collection and a snapshot of the collection is taken. When the enumerator is in this position, a call to System.Collections.IEnumerator.MoveNext is necessary before reading System.Collections.IEnumerator.Current from the collection. If changes are made to the collection (such as adding, modifying or deleting elements)
U V W X Y Z
1957
Contents | Index
IEnumerator Interface
System.Collections
Current Property
the snapshot may get out of sync, causing the enumerator to throw a System.InvalidOperationException if the System.Collections.IEnumerator.MoveNext or System.Collections.IEnumerator.Reset are invoked. Two enumerators instantiated from the same collection at the same time can have different snapshots of the collection. Enumerators are intended to be used only to read data in the collection. An enumerator does not have exclusive access to the collection for which it was instantiated.]
A B C D
Example
E
using System; using System.Collections;
F namespace Samples { public class IEnumeratorSample { public static void Main() { IEnumerable s = "Hello world"; IEnumerator ie = s.GetEnumerator(); while(ie.MoveNext()) Console.Write(ie.Current); Console.WriteLine(); ie.Reset(); while(ie.MoveNext()) Console.Write(ie.Current); } } }
G H I J K L M N O P Q
The output is
R
Hello world Hello world
S T U
IEnumerator.Current Property
V
[ILASM]
W
.property object Current { public hidebysig virtual abstract specialname object get_Current() }
X
[C#]
Y
object Current { get; }
Z
Summary Gets the element in the collection over which the current instance is positioned. 1958
Contents | Index
System.Collections
IEnumerator Interface Current Property
Description [Note: When the current instance is constructed or after System.Collections.IEnumerator.Reset is called, use System.Collections.IEnumerator.MoveNext to position the current instance over the first element of the collection.]
A B
Behaviors
C
It is required that System.Collections.IEnumerator.Current return the element in the collection over which the current instance is positioned unless it is positioned before the first or after the last element of the collection. If the current instance is positioned before the first element or after the last element of the collection, System.Collections.IEnumerator.Current is required to throw System.InvalidOperationException. If elements were added, removed, or repositioned in the collection after the current instance was instantiated, System.Collections.IEnumerator.Current returns the value it would have returned before the collection was modified. It is also required that System.Collections.IEnumerator.Current not change the position of the current instance: consecutive calls to System.Collections.IEnumerator.Current are required to return the same object until either System.Collections.IEnumerator.MoveNext or System.Collections.IEnumerator.Reset is called.
D E F G H I J K L M
Usage
N
Use System.Collections.IEnumerator.Current to get the element in the collection over which the current instance is positioned, provided that the current instance is not positioned before the first element or after the last element of the collection.
O P Q
Exceptions
R
Exception
Condition
System.InvalidOperationException
The current instance is positioned before the first element or after the last element of the collection.
S T U V W
Example using System; using System.Collections;
X
namespace Samples { public class IEnumeratorCurrent
Z
Y
1959
Contents | Index
IEnumerator Interface
System.Collections
MoveNext() Method
{ public static void Main() { IEnumerable s = "Hello world"; IEnumerator ie = s.GetEnumerator(); while(ie.MoveNext()) Console.Write(ie.Current); }
A B C }
D
}
E
The output is
F
Hello world
G H I
IEnumerator.MoveNext() Method
J
[ILASM]
.method public hidebysig virtual abstract bool MoveNext()
K
[C#]
L
bool MoveNext()
M
Summary
N
Advances the current instance to the next element of the collection.
O P
Return Value
Q
true if the current instance was successfully advanced to the next element; false if the current instance has passed the end of the collection.
R S
Description
T
[Note: When the current instance is constructed or after System.Collections.IEnumerator.Reset is called, the current instance is positioned immediately before the first element of the collection. Use System.Collections.IEnumerator.MoveNext to position it over the first element of the collection.]
U V W
Behaviors
X
A call to System.Collections.IEnumerator.MoveNext is required to position the current instance over the next element in the collection and return true if the current instance was not positioned beyond the last element of the collection when System.Collections.IEnumerator.MoveNext was called. If the current instance is already positioned immediately after the last element of the collection, a call to System.Collections.IEnu-
Y Z
1960
Contents | Index
System.Collections
IEnumerator Interface MoveNext() Method
merator.MoveNext is required to return false, and the current instance is required to remain in the same position. If elements are added, removed, or repositioned in the collection after the current instance was instantiated, it is required that a call to System.Collections.IEnumerator.MoveNext throw System.InvalidOperationException.
A B
Usage
C
Use the System.Collections.IEnumerator.MoveNext method to check if the current instance is positioned immediately after the last element of the collection, and to position it over the next element if it is not already past the last element of the collection. This allows the use of a conditional loop to iterate over the entire collection.
D E F G
Exceptions
H
Exception
Condition
I
The collection was modified after the current instance was instantiated.
J
System.InvalidOperationException
K L
Example
M
using System; using System.Collections;
N O
namespace Samples { public class IEnumeratorMoveNext { public static void Main() { IEnumerable s = "Hello world"; IEnumerator ie = s.GetEnumerator(); while(ie.MoveNext()) Console.Write(ie.Current); } } }
P Q R S T U V W X
The output is
Y
Hello world
Z
1961
Contents | Index
IEnumerator Interface
System.Collections
Reset() Method
IEnumerator.Reset() Method [ILASM]
.method public hidebysig virtual abstract void Reset()
A
[C#]
void Reset()
B C
Summary
D
Positions the enumerator immediately before the first element in the collection.
E
Description
F
[Note: When the current instance is constructed or after System.Collections.IEnumerator.Reset is called, the current instance is positioned immediately before the first element of the collection, use System.Collections.IEnumerator.MoveNext to position the current instance over the first element of the collection.]
G H I J
Behaviors
K
A call to System.Collections.IEnumerator.Reset is required to position the current instance immediately before the first element of the collection. If elements are added, removed, or repositioned in the collection after the current instance was instantiated, it is required that a call to System.Collections.IEnumerator.Reset throw a System.InvalidOperationException.
L M N O
How and When to Override
P
A call to System.Collections.IEnumerator.Reset can involve taking a new snapshot of the collection or simply moving to the beginning of the collection. The preferred implementation is to simply move the current instance to the beginning of the collection, before the first element. This invalidates the current instance if the collection has been modified since the current instance was constructed, which is consistent with System.Collections.IEnumerator.MoveNext and System.Collections.IEnumerator.Current.
Q R S T U
Usage
V
Use the System.Collections.IEnumerator.MoveNext method to check if the current instance is positioned immediately past the last element of the collection, and to position it over the next element if it is not already past the last element of the collection.
W X Y Z
1962
Contents | Index
System.Collections
IEnumerator Interface Reset() Method
Exceptions Exception
Condition
System.InvalidOperationException
The collection was modified after the enumerator was instantiated.
A B C D
Example
E
using System; using System.Collections;
F G
namespace Samples { public class IEnumeratorReset { public static void Main() { IEnumerable s = "Hello world"; IEnumerator ie = s.GetEnumerator(); while(ie.MoveNext()) Console.Write(ie.Current); Console.WriteLine(); ie.Reset(); while(ie.MoveNext()) Console.Write(ie.Current); } } }
H I J K L M N O P Q R
The output is
S Hello world Hello world
T U V W X Y Z
1963
Contents | Index
System IFormatProvider Interface
BCL
IFormatProvider
A
DateTimeFormatInfo
B
NumberFormatInfo
C
Summary
D
Implemented by classes that supply objects that provide formatting services.
E
Type Summary
F
public interface IFormatProvider { // Methods object GetFormat (Type formatType); }
G H I J
Description
K
[Note: When a format specifier includes symbols that vary by culture, such as the currency symbol included by the “C” and “c” formats, a formatting object supplies the actual characters used in a string representation of a numeric value. For example, a formatting object may supply “$” for the currency symbol. The formatting object for system-supplied numeric types is a System.Globalization.NumberFormatInfo instance. For System.DateTime instances, a System.Globalization.DateTimeFormatInfo is used. System.IFormatProvider contains the System.IFormatProvider.GetFormat method. The consumer of an object should call this method to obtain a formatting object.]
L M N O P Q R
Example
S
using System; using System.Globalization;
T
namespace Samples { public class MyFormatProviderSample: IFormatProvider, ICustomFormatter { public object GetFormat(Type t) { if(t == typeof(ICustomFormatter)) return this; return null; } public string Format(string f, object o,
U V W X Y Z
1964
Contents | Index
System
IFormatProvider Interface GetFormat() Method
IFormatProvider p) { if(f == null) return String.Format("{0}", o); if(!f.StartsWith("-")) { if(o is IFormattable) { return ((IFormattable)o).ToString(f, p); } else if(o != null) { return o.ToString(); } } return "Sample Formatted";
A B C D E F G H
} public static void Main() { MyFormatProviderSample m = new MyFormatProviderSample(); Console.WriteLine(String.Format( m, "First (no formatting): {0} \n" + "Second (formatted '-'): {1:-}", new object[] {m, m})); }
I J K L M N O
} }
P Q
The output is
R First (no formatting): Samples.MyFormatProviderSample Second (formatted '-'): Sample Formatted
S T U
IFormatProvider.GetFormat(System.Type) Method
V [ILASM]
W
.method public hidebysig virtual abstract object GetFormat(class System.Type formatType) [C#]
X
object GetFormat(Type formatType)
Y Z
Summary Returns a System.Object that provides formatting services.
1965
Contents | Index
IFormatProvider Interface
System
GetFormat() Method
Parameters Parameter
Description
formatType
The System.Type of the formatting object to be returned.
A B C
Return Value
D
A formatting object of the specified System.Type. If no formatting object of the specified type is available, or formatType is a null reference, returns the formatting object for the current culture.
E F G H
How and When to Override
I
Implement in classes that provide formatting objects for use in methods that generate or parse string representations of objects, such as ToString and Parse.
J K L M N O P Q R S T U V W X Y Z
1966
Contents | Index
System IFormattable Interface
BCL
IFormattable AttributeTargets
A
Byte
B
DateTime
C
DateTimeStyles
D
Decimal
ExtendedNumerics
Double
ExtendedNumerics
E F
Enum
G
EnvironmentPermissionAccess
H
FileAccess
I FileIOPermissionAccess
J FileMode
K FileShare
L
Int16
M
Int32 Int64
N
NumberStyles
O
PermissionState
P
SByte
Q
SecurityActions
R
SecurityPermissionFlag
S
SeekOrigin Single
T ExtendedNumerics
U
ThreadPriority
V
ThreadState
W
UInt16
X
UInt32
Y UInt64
Z UnicodeCategory Version
1967
Contents | Index
IFormattable Interface
System
IFormattable Interface
Summary Implemented by classes that construct customizable string representations of objects. A
Type Summary
B
public interface IFormattable { // Methods string ToString (string format, IFormatProvider formatProvider); }
C D E F
Description
G
[Note: System.IFormattable contains the System.IFormattable.ToString method. The consumer of an object calls this method to obtain a formatted string representation of the value of the object.] A format is a string that describes the appearance of an object when it is converted to a string. Either standard or custom formats can be used. A standard format takes the form Axx, where A is a single alphabetic character called the format specifier, and xx is an integer between 0 and 99 inclusive, called the precision specifier. The format specifier controls the type of formatting applied to the value being represented as a string. The precision specifier controls the number of significant digits or decimal places in the string, if applicable. [Note: For the list of standard format specifiers, see the table below. Note that a given data type, such as System.Int32, might not support one or more of the standard format specifiers.] [Note: When a format includes symbols that vary by culture, such as the currency symbol included by the “C” and “c” formats, a formatting object supplies the actual characters used in the string representation. A method may include a parameter to pass a System.IFormatProvider object that supplies a formatting object, or the method may use the default formatting object, which contains the symbol definitions for the current culture. The current culture typically uses the same set of symbols used system-wide by default. In the Base Class Library, the formatting object for system-supplied numeric types is a System.Globalization.NumberFormatInfo instance. For System.DateTime instances, a System.Globalization.DateTimeFormatInfo is used.] The following table describes the standard format specifiers and associated formatting object members that are used with numeric data types in the Base Class Library.
H I J K L M N O P Q R S T U V W X Y Z
1968
Contents | Index
System
IFormattable Interface IFormattable Interface
Format Specifier
C c
Description A
Currency Format: Used for strings containing a monetary value. The System.Globalization.NumberFormatInfo.CurrencySymbol, System.Globalization.NumberFormatInfo.CurrencyGroupSizes, System.Globalization.NumberFormatInfo.CurrencyGroupSeparator, and System.Globalization.NumberFormatInfo.CurrencyDecimalSeparator members of a System.Globalization.NumberFormatInfo supply the currency symbol, size and separator for digit groupings, and decimal separator, respectively.
B C D E
System.Globalization.NumberFormatInfo.CurrencyNegativePattern and System.Globalization.NumberFormatInfo.CurrencyPositivePattern determine the symbols used to represent negative and positive values. For example, a negative value may be prefixed with a minus sign, or enclosed in parentheses.
F G H
If the precision specifier is omitted, System.Globalization.NumberFormatInfo.CurrencyDecimalDigits determines the number of decimal places in the string. Results are rounded to the nearest representable value when necessary.
I J
D d
Decimal Format: (This format is valid only when specified with integral data types.) Used for strings containing integer values. Negative numbers are prefixed with the negative number symbol specified by the System.Globalization. NumberFormatInfo.NegativeSign property.
K L
The precision specifier determines the minimum number of digits that appear in the string. If the specified precision requires more digits than the value contains, the string is left-padded with zeros. If the precision specifier specifies fewer digits than are in the value, the precision specifier is ignored.
M N O
Scientific (Engineering) Format: Used for strings in one of the following forms:
P Q
[–]m.ddddddE+xxx [–]m.ddddddE-xxx [–]m.dddddde+xxx [–]m.dddddde-xxx
R S
The negative number symbol ('–') appears only if the value is negative, and is supplied by the System.Globalization.NumberFormatInfo.NegativeSign property. E e
T U
Exactly one non-zero decimal digit (m) precedes the decimal separator ('.'), which is supplied by the System.Globalization.NumberFormatInfo.NumberDecimalSeparator property.
V W
The precision specifier determines the number of decimal places (dddddd ) in the string. If the precision specifier is omitted, six decimal places are included in the string.
X
The exponent (+/–xxx) consists of either a positive or negative number symbol followed by a minimum of three digits (xxx). The exponent is left-padded with zeros, if necessary. The case of the format specifier ('E' or 'e') determines the case used for the exponent prefix (E or e) in the string. Results are rounded to the nearest representable value when necessary. The positive number symbol is supplied by the System.Globalization.NumberFormatInfo.PositiveSign property.
Y Z
1969
Contents | Index
IFormattable Interface
System
IFormattable Interface
Format Specifier
Description
A
Fixed-Point Format: Used for strings in the following form:
B
"[–]m.dd...d"
C
At least one non-zero decimal digit (m) precedes the decimal separator ('.'), which is supplied by the System.Globalization.NumberFormatInfo.NumberDecimalSeparator property.
D
F
E
f
F
A negative number symbol sign ('–') precedes m only if the value is negative. This symbol is supplied by the System.Globalization.NumberFormatInfo.NegativeSign property. The precision specifier determines the number of decimal places (dd...d) in the string. If the precision specifier is omitted, System.Globalization.NumberFormatInfo.NumberDecimalDigits determines the number of decimal places in the string. Results are rounded to the nearest representable value when necessary.
G H I J
General Format: The string is formatted in either fixed-point format ('F' or 'f') or scientific format ('E' or 'e').
K
For integral types: Values are formatted using fixed-point format if exponent < precision specifier, where exponent is the exponent of the value in scientific format. For all other values, scientific format is used.
L M
If the precision specifier is omitted, a default precision equal to the field width required to display the maximum value for the data type is used, which results in the value being formatted in fixed-point format. The default precisions for integral types are as follows:
N O
System.Int16, System.UInt16 - 5 System.Int32, System.UInt32 - 10 System.Int64, System.UInt64 - 19
P Q R
G
S
g
For Single, Decimal, and Double types:
T
Values are formatted using fixed-point format if exponent >= –4 and exponent < precision specifier, where exponent is the exponent of the value in scientific format. For all other values, scientific format is used. Results are rounded to the nearest representable value when necessary.
U
If the precision specifier is omitted, the following default precisions are used:
V
System.Single: 7 System.Double: 15 System.Decimal: 29
W
For all types:
X
- The number of digits that appear in the result (not including the exponent) will not exceed the value of the precision specifier; values are rounded as necessary. - The decimal point and any trailing zeros after the decimal point are removed whenever possible. - The case of the format specifier ('G' or 'g') determines whether 'E' or 'e' prefixes the scientific format exponent.
Y Z
1970
Contents | Index
System
IFormattable Interface IFormattable Interface
Format Specifier
N n
Description Number Format: Used for strings in the following form:
A
[–]d,ddd,ddd.dd...d
B
The representation of negative values is determined by the System.Globalization.NumberFormatInfo.NumberNegativePattern property. If the pattern includes a negative number symbol ('–'), this symbol is supplied by the System.Globalization.NumberFormatInfo.NegativeSign property.
C D E
At least one non-zero decimal digit (d) precedes the decimal separator ('.'), which is supplied by the System.Globalization.NumberFormatInfo.NumberDecimalSeparator property. Digits between the decimal point and the most significant digit in the value are grouped using the group size specified by the System.Globalization.NumberFormatInfo.NumberGroupSizes property. The group separator (',') is inserted between each digit group, and is supplied by the System.Globalization.NumberFormatInfo.NumberGroupSeparator property.
F G H I J
The precision specifier determines the number of decimal places (dd...d). If the precision specifier is omitted, System.Globalization.NumberFormatInfo.NumberDecimalDigits determines the number of decimal places in the string. Results are rounded to the nearest representable value when necessary.
P p
K L
Percent Format: Used for strings containing a percentage. The System.Globalization.NumberFormatInfo.PercentSymbol, System.Globalization.NumberFormatInfo.PercentGroupSizes, System.Globalization.NumberFormatInfo.PercentGroupSeparator, and System.Globalization.NumberFormatInfo.PercentDecimalSeparator members of a System.Globalization.NumberFormatInfo supply the percent symbol, size and separator for digit groupings, and decimal separator, respectively.
M
System.Globalization.NumberFormatInfo.PercentNegativePattern and System.Globalization.NumberFormatInfo.PercentPositivePattern determine the symbols used to represent negative and positive values. For example, a negative value may be prefixed with a minus sign, or enclosed in parentheses.
Q
If no precision is specified, the number of decimal places in the result is determined by System.Globalization.NumberFormatInfo.PercentDecimalDigits. Results are rounded to the nearest representable value when necessary.
T U
The result is scaled by 100 (.99 becomes 99%).
V
N O P
R S
W X Y Z
1971
Contents | Index
IFormattable Interface
System
IFormattable Interface
Format Specifier A B R
C
r D E F G
X
H
x
I
Description Round trip Format: (This format is valid only when specified with System.Double or System.Single.) Used to ensure that the precision of the string representation of a floating-point value is such that parsing the string does not result in a loss of precision when compared to the original value. If the maximum precision of the data type (7 for System.Single and 15 for System.Double) would result in a loss of precision, the precision is increased by two decimal places. If a precision specifier is supplied with this format specifier, it is ignored. This format is otherwise identical to the fixed-point format. Hexadecimal Format: (This format is valid only when specified with integral data types.) Used for string representations of numbers in Base 16. The precision determines the minimum number of digits in the string. If the precision specifies more digits than the number contains, the number is left-padded with zeros. The case of the format specifier ('X' or 'x') determines whether uppercase or lowercase letters are used in the hexadecimal representation.
J
If the numerical value is a System.Single or System.Double with a value of NaN, PositiveInfinity, or NegativeInfinity, the format specifier is ignored, and one of the following is returned: System.Globalization.NumberFormatInfo.NaNSymbol, System.Globalization.NumberFormatInfo.PositiveInfinitySymbol, or System.Globalization.NumberFormatInfo.NegativeInfinitySymbol. A custom format is any string specified as a format that is not in the form of a standard format string (Axx) described above. The following table describes the characters that are used in constructing custom formats.
K L M N O P Q R S T U V W X Y Z
1972
Contents | Index
System
IFormattable Interface IFormattable Interface
Format Specifier
0 (zero)
Description A
Zero placeholder: If the value being formatted has a digit in the position where a '0' appears in the custom format, then that digit is copied to the output string; otherwise a zero is stored in that position in the output string. The position of the leftmost '0' before the decimal separator and the rightmost '0' after the decimal separator determines the range of digits that are always present in the output string.
B C D
The number of zero and/or digit placeholders after the decimal separator determines the number of digits that appear after the decimal separator. Values are rounded as necessary.
E F
#
Digit placeholder: If the value being formatted has a digit in the position where a '#' appears in the custom format, then that digit is copied to the output string; otherwise, nothing is stored in that position in the output string. Note that this specifier never stores the '0' character if it is not a significant digit, even if '0' is the only digit in the string. (It does display the '0' character in the output string if it is a significant digit.)
G H I J
The number of zero and/or digit placeholders after the decimal separator determines the number of digits that appear after the decimal separator. Values are rounded as necessary.
. (period)
, (comma)
K L
Decimal separator: The leftmost '.' character in the format string determines the location of the decimal separator in the formatted value; any additional '.' characters are ignored. The System.Globalization.NumberFormatInfo.NumberDecimalSeparator property determines the symbol used as the decimal separator.
M N O
Group separator and number scaling: The ',' character serves two purposes. First, if the custom format contains this character between two zero or digit placeholders (0 or #) and to the left of the decimal separator if one is present, then the output will have group separators inserted between each group of digits to the left of the decimal separator. The System.Globalization.NumberFormatInfo.NumberGroupSeparator and System.Globalization.NumberFormatInfo.NumberGroupSizes properties determine the symbol used as the group separator and the number of digits in each group, respectively.
P Q R S T
If the format string contains one or more ',' characters immediately to the left of the decimal separator, then the number will be scaled. The scale factor is determined by the number of group separator characters immediately to the left of the decimal separator. If there are x characters, then the value is divided by 1000X before it is formatted. For example, the format string '0,,' will divide a value by one million. Note that the presence of the ',' character to indicate scaling does not insert group separators in the output string. Thus, to scale a number by 1 million and insert group separators, use a custom format similar to "#,##0,,".
U V W X Y
% (percent)
Percentage placeholder: The presence of a '%' character in a custom format causes a number to be multiplied by 100 before it is formatted. The percent symbol is inserted in the output string at the location where the '%' appears in the format string. The System.Globalization.NumberFormatInfo.PercentSymbol property determines the percent symbol.
Z
1973
Contents | Index
IFormattable Interface
System
IFormattable Interface
Format Specifier A B
E0
C
E+0 E–0
D
e0 E
e+0
F
e–0
G H I
\ (backslash)
J K L
'ABC'
M
"ABC"
N O
Description Engineering format: If any of the strings 'E', 'E+', 'E–', 'e', 'e+', or 'e–' is present in a custom format and is followed immediately by at least one '0' character, then the value is formatted using scientific notation. The number of '0' characters following the exponent prefix (E or e) determines the minimum number of digits in the exponent. The 'E+' and 'e+' formats indicate that a positive or negative number symbol always precedes the exponent. The 'E', 'E–', 'e', or 'e–' formats indicate that a negative number symbol precedes negative exponents; no symbol precedes positive exponents. The positive number symbol is supplied by the System.Globalization.NumberFormatInfo.PositiveSign property. The negative number symbol is supplied by the System.Globalization.NumberFormatInfo.NegativeSign property. Escape character: In some languages, such as C#, the backslash character causes the next character in the custom format to be interpreted as an escape sequence. It is used with C language formatting sequences, such as "\n" (newline). In some languages, the escape character itself is required to be preceded by an escape character when used as a literal. Otherwise, the compiler interprets the character as an escape sequence. This escape character is not required to be supported in all programming languages. Literal string: Characters enclosed in single or double quotes are copied to the output string literally, and do not affect formatting.
; (semicolon)
Section separator: The ';' character is used to separate sections for positive, negative, and zero numbers in the format string. (This feature is described in detail below.)
Other
All other characters: All other characters are stored in the output string as literals in the position in which they appear.
P Q R S
Note that for fixed-point format strings (strings not containing an ‘E0’, ’E+0’, ’E–0’, ’e0’, ’e+0’, or ’e–0’), numbers are rounded to as many decimal places as there are zero or digit placeholders to the right of the decimal separator. If the custom format does not contain a decimal separator, the number is rounded to the nearest integer. If the number has more digits than there are zero or digit placeholders to the left of the decimal separator, the extra digits are copied to the output string immediately before the first zero or digit placeholder. A custom format can contain up to three sections separated by section separator characters to specify different formatting for positive, negative, and zero values. The sections are interpreted as follows:
T U V W X Y Z
•
One section: The custom format applies to all values (positive, negative, and zero). Negative values include a negative sign.
1974
Contents | Index
System
IFormattable Interface IFormattable Interface
•
•
Two sections: The first section applies to positive values and zeros, and the second section applies to negative values. If the value to be formatted is negative but becomes zero after rounding according to the format in the second section, then the resulting zero is formatted according to the first section. Negative values do not include a negative sign to allow full control over representations of negative values. For example, a negative can be represented in parentheses using a custom format similar to “####.####;(####.####)”. Three sections: The first section applies to positive values, the second section applies to negative values, and the third section applies to zeros. The second section can be empty (nothing appears between the semicolons), in which case the first section applies to all nonzero values, and negative values include a negative sign. If the number to be formatted is nonzero but becomes zero after rounding according to the format in the first or second section, then the resulting zero is formatted according to the third section.
A B C D E F G H I
The System.Enum and System.DateTime types also support using format specifiers to format string representations of values. The meaning of a specific format specifier varies according to the kind of data (numeric, date/time, enumeration) being formatted. See System.Enum and System.Globalization.DateTimeFormatInfo for a comprehensive list of the format specifiers supported by each type.
J K L M
Example
N
using System;
O P
namespace Samples { public class IFormattableSample { public static void Main() { double d = 123.12345678901234; string[] strings = {"C","E","e","F","G","N","P","R"}; foreach(string s in strings) Console.WriteLine("{0:R} as {1}: {2}", d, s, d.ToString(s,null)); strings = new string[]{"D","x","X"}; int i = 255; foreach(string s in strings) Console.WriteLine("{0} as {1}: {2}", i, s, i.ToString(s,null)); } } }
Q R S T U V W X Y Z
1975
Contents | Index
IFormattable Interface
System
ToString() Method
The output is 123.12345678901234 as C: $123.12 123.12345678901234 as c: $123.12 123.12345678901234 as E: 1.231235E+002 123.12345678901234 as e: 1.231235e+002 123.12345678901234 as F: 123.12 123.12345678901234 as G: 123.123456789012 123.12345678901234 as g: 123.123456789012 123.12345678901234 as N: 123.12 123.12345678901234 as n: 123.12 123.12345678901234 as P: 12,312.35 % 123.12345678901234 as p: 12,312.35 % 123.12345678901234 as R: 123.12345678901234 123.12345678901234 as r: 123.12345678901234 2147483647 as D: 2147483647 2147483647 as d: 2147483647 2147483647 as x: 7fffffff 2147483647 as X: 7FFFFFFF 2147483647 as D42: 000000000000000000000000000000002147483647 2147483647 as d42: 000000000000000000000000000000002147483647 2147483647 as x42: 00000000000000000000000000000000007fffffff 2147483647 as X42: 00000000000000000000000000000000007FFFFFFF 2147483647 as "C": $2,147,483,647.00 2147483647 as "C": R$ 2.147.483.647,00 2147483647 as "C": 2ÿ147ÿ483ÿ647,00 Sk 2147483647 as "C": HK$2,147,483,647.00
A B C D E F G H I J K L M N O P Q
IFormattable.ToString(System.String, System.IFormatProvider) Method
R
[ILASM]
S
.method public hidebysig virtual abstract string ToString(string format, class System.IFormatProvider formatProvider)
T
[C#]
string ToString(string format, IFormatProvider formatProvider)
U V
Summary
W
Returns a System.String representation of the value of the current instance.
X Y Z
1976
Contents | Index
System
IFormattable Interface ToString() Method
Parameters Parameter
Description
format
A System.String that specifies the format of the returned string. If format is a null reference or the empty string, the default format defined for the type of the current instance is used.
A
formatProvider
B C D
A System.IFormatProvider that supplies a formatting object containing culture-specific formatting information, or null.
E F
Return Value
G
A System.String containing the value of the current instance formatted in accordance with format and formatProvider.
H I
Behaviors
J
Conforming implementations do not throw an exception when format and/or formatProvider are null references. If formatProvider is a null reference, the string is constructed using a system-supplied formatting object containing information for the current system culture. If format is null, the string is constructed using a system-supplied default format appropriate for the type of the current instance. If the object returned by formatProvider supplies a culture-specific representation of symbols or patterns included in format, the returned string is required to use the information supplied by formatProvider.
K L M N O P Q
How and When to Override
R
Implement to allow consumers of a class to use format strings and formatting objects to control the way in which the class is represented as a string.
S T
Exceptions
U
Exception
Condition
System.FormatException
The specified format is invalid or cannot be used with the type of the current instance.
V W X Y Z
1977
Contents | Index
System.Collections IHashCodeProvider Interface
BCL
IHashCodeProvider
A
Summary
B
Implemented by classes that support custom hash functions for instances of the class.
C D
Type Summary
E
public interface IHashCodeProvider { // Methods int GetHashCode (object obj); }
F G H I
BG Note that the IHashCodeProvider interface allows you to define your own
J
hash function for a given object. This allows users to either override it for special comparisons such as case-insensitive string lookup, or to replace a poorly written hash function on a third party data type. Combined with IComparer, you can use types as keys in a Hashtable even if the original author neglected to override Equals and GetHashCode on their type.
K L M N
One note on IHashCodeProvider—many of our users either don’t get the type or don’t understand when they need to do it. We’ve found instances where people want to use a case-insensitive Hashtable, yet they remember to specify the IComparer but not the IHashCodeProvider, giving them incorrect results.
O P Q R
We are considering replacing IHashCodeProvider and unifying it with IComparer in a new IKeyComparer interface that would define CompareTo, Equals, and GetHashCode methods. It turns out that Hashtable only needs to compare whether two keys are equal, not establish an ordering over two particular keys. For certain data types, doing an equality check can be done more quickly than a comparison. Strings in the Microsoft CLR implementation fall into this bucket, since we internally store the length of the String. Equals on strings is defined as a bit-wise equality check (which isn’t linguistically correct, of course).
S T U V W X Y Z
1978
Contents | Index
System.Collections
IHashCodeProvider Interface IHashCodeProvider Interface
Description [Note: System.Collections.IHashCodeProvider contains the System.Collections.IHashCodeProvider.GetHashCode method. The consumer of an object should call this method to obtain a hash code for the object using a custom hash function.]
A B
Example
C
using System; using System.Collections;
D E
namespace Samples { public class IHashCodeProviderSample { public class MyComparer: IComparer { public int Compare(Object a, Object b) { return ((IComparable)a).CompareTo(b); } } public class MyHashCodeProvider: IHashCodeProvider { public int GetHashCode(Object o) { return o.GetHashCode(); } }
F G H I J K L M N O P Q
public static void Main() { Hashtable ht1 = new Hashtable( CaseInsensitiveHashCodeProvider.Default, new MyComparer()); Hashtable ht2 = new Hashtable(new MyHashCodeProvider(), new MyComparer()); AddEntires(ht1); AddEntires(ht2); DisplayEntires(ht1); DisplayEntires(ht2); } public static void AddEntires(Hashtable ht) { ht.Add("One","damien"); ht.Add("two", "brad"); ht.Add("Three", "mark"); ht.Add("four", "Maire");
R S T U V W X Y Z
1979
Contents | Index
IHashCodeProvider Interface
System.Collections
GetHashCode() Method
ht.Add("Five", "sacha"); ht.Add("six", "Sarah"); } public static void DisplayEntires(Hashtable ht) { Console.WriteLine("Count: {0}", ht.Count ); IDictionaryEnumerator de = ht.GetEnumerator(); while(de.MoveNext()) Console.WriteLine("Key: {0} \tValue: {1}", de.Key, de.Value); }
A B C D E F
} }
G
The output is
H I
Count: 6 Key: One Key: Three Key: four Key: Five Key: two Key: six Count: 6 Key: six Key: One Key: four Key: two Key: Three Key: Five
J K L M N O P Q
Value: damien Value: mark Value: Maire Value: sacha Value: brad Value: Sarah Value: Sarah Value: damien Value: Maire Value: brad Value: mark Value: sacha
R S
IHashCodeProvider.GetHashCode(System.Object) Method
T [ILASM]
U
.method public hidebysig virtual abstract int32 GetHashCode(object obj)
V
[C#]
int GetHashCode(object obj)
W X
Summary
Y
Generates a hash code for the specified System.Object.
Z
1980
Contents | Index
System.Collections
IHashCodeProvider Interface GetHashCode() Method
Parameters Parameter
Description
obj
The System.Object for which a hash code is to be generated.
A B C
Behaviors
D
If obj is null, it is required that a call to System.Collections.IHashCodeProvider.GetHashCode throw System.ArgumentNullException.
E
How and When to Override
G
Implement this method to generate a better hash table distribution than the default method provided by the type of the System.Object for which the hash code is being generated.
H
F
I J
Usage
K
The value returned by this method should not be persisted past the lifetime of the application that created the value. The first reason is that the hash function of a class may be altered to generate a better distribution, rendering any values from the old hash function useless. The second reason is that the default implementation of this class does not guarantee that the same value will be returned by different instances.
L M N O P
Exceptions
Q
Exception
Condition
R
System.ArgumentNullException
obj is null.
S T U V W X Y Z
1981
Contents | Index
System.Collections IList Interface
BCL
ICollection IList
A
IEnumerable Array
B ArrayList
C D
Summary
E
Implemented by classes that support a collection of objects that can be individually indexed.
F G
Type Summary
H
public interface IList : ICollection, IEnumerable { // Properties bool IsFixedSize { get; } bool IsReadOnly { get; } object this[int index] { set; get; }
I J K L
// Methods int Add (object value); void Clear (); bool Contains (object value); int IndexOf (object value); void Insert (int index, object value); void Remove (object value); void RemoveAt (int index);
M N O P Q
}
R S
X
BA IList and IDictionary are examples of interfaces that are slightly more complex and central to the design than I would have liked. Ordinarily I would have liked to make these abstract base classes in order to share some implementation and to version more easily. One of the compelling reasons that made us decide to make this an interface is to support strongly typed collections. We use strongly typed collections heavily in Windows Forms and ASP.NET to enable an easier programming model. Tools and compilers can help developers catch errors at design time rather than runtime.
Y
continued
T U V W
Z
1982
Contents | Index
System.Collections
IList Interface IList Interface
To define a collection of MenuItems you would want the indexer to be strongly typed to return MenuItems as: A public MenuItems this [int index] {get; set;}
B
In most cases we also wanted this collection of MenuItems to be an IList as well such that we could build services that work against all lists (such as databinding). In such a case you would want the indexer to be typed loosely so that it can handle any kind of elements:
C D E F
public object this [int index] {get; set;}
G
You will notice that a class cannot have both of these methods as they differ only in return type (MenuItem vs. Object). However, if we define the loosely typed methods to be part of an interface we are able to use explicit member implementation to get around this limitation.
H I J
public MenuItems this [int index] {get; set;} public object IList.this [int index] {get; set;}
K L
Now when the MenuItemColleciton is used directly the indexer returns a menu item, and when it is cast to IList the indexer returns Object.
M N O
Description
P
[Note: System.Collections.IList implementations fall into three categories: readonly, fixed-size, and variable-size. A read-only list cannot be modified. A fixed-size list allows the modification of existing elements, but does not allow the addition or removal of elements. A variable-size list allows the modification, addition, and removal of elements.]
Q R S
Example
T
using System; using System.Collections;
U V
namespace Samples { public class MySimpleList: IList { private object[] objects; private int counter = 0; private int modifications = 0; public MySimpleList(int i) {
W X Y Z
1983
Contents | Index
IList Interface
System.Collections
IList Interface
if(i <= 0) throw new ArgumentOutOfRangeException(); objects = new object[i]; } public IEnumerator GetEnumerator() {return new Enumerator(this);} public int Count {get {return counter - 1;}} public bool IsSynchronized {get {return false;}} public object SyncRoot {get {return this;}} public void CopyTo(System.Array array, int index) { objects.CopyTo(array, index); } public bool IsFixedSize {get {return false;}} public bool IsReadOnly {get {return false;}} public Object this[int index] { get { if(index < 0 || index >= counter) throw new ArgumentOutOfRangeException(); return objects[index]; } set { if(index < 0 || index >= counter) throw new ArgumentOutOfRangeException(); objects[index] = value; modifications++; } } public int Add(Object item) { if(counter == objects.Length) Resize(); objects[counter++] = item; modifications++; return counter - 1; } public void Clear() { if(counter > 0) { Array.Clear(objects, 0, counter); counter = 0; } modifications++; }
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1984
Contents | Index
System.Collections
IList Interface IList Interface
public bool Contains(Object value) { return IndexOf(value) >= 0; } public int IndexOf(Object value) { return ((IList)objects).IndexOf(value); } public void Insert(int index, Object value) { if(index < 0 || index > counter) throw new ArgumentOutOfRangeException(); if(counter == objects.Length) Resize(); if(index < counter) Array.Copy(objects, index, objects, index + 1, counter - index); objects[index] = value; counter++; modifications++; } public void Remove(Object item) { int index = IndexOf(item); if(index >= 0) RemoveAt(index); modifications++; } public void RemoveAt(int index) { if(index < 0 || index >= counter) throw new ArgumentOutOfRangeException(); counter--; if(index < counter) { Array.Copy(objects, index + 1, objects, index, counter - index); } objects[counter] = null; modifications++; } private void Resize() { if(objects.Length == counter) { object[] tmp = new object[counter * 2]; objects.CopyTo(tmp, 0); objects = tmp; } } public struct Enumerator: IEnumerator
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1985
Contents | Index
IList Interface
System.Collections
IList Interface
{ private MySimpleList list; private object[] objects; private int maxIndex; private int counter; private int modifications; internal Enumerator(MySimpleList list) { this.list = list; objects = list.objects; counter = -1; maxIndex = list.counter; modifications = list.modifications; } public Object Current {get {return objects[counter];}} public bool MoveNext() { Valid(); if(counter == maxIndex) return false; counter++; return true; } void IEnumerator.Reset() { Valid(); counter = -1; } private void Valid() { if(modifications != list.modifications) throw new InvalidOperationException(); }
A B C D E F G H I J K L M N O P Q R S
} } public class IListSample { public static void Main() { IList il = new MySimpleList(1); Console.WriteLine("Is fixed size: {0}", il.IsFixedSize); Console.WriteLine("Is read only: {0}", il.IsReadOnly); string name = "TAMARA"; string[] strings = {"damien", "mark", "brad", "maire", "sacha", name}; foreach(string s in strings) il.Add(s); DisplayList(il);
T U V W X Y Z
1986
Contents | Index
System.Collections
IList Interface IsFixedSize Property
il.Insert(il.IndexOf(name), name.ToLower()); il.Remove(name.ToUpper()); DisplayList(il); foreach(string s in strings) il.Add(s.ToUpper()); DisplayList(il); il.RemoveAt(il.Count); DisplayList(il); il.Clear(); DisplayList(il);
A B C D
} public static void DisplayList(IList il) { Console.WriteLine("The values in the list are:"); foreach(object o in il) Console.Write("{0} ", o); Console.WriteLine(); }
E F G H I
}
J
}
K
The output is Is fixed size: False Is read only: False The values in the list damien mark brad maire The values in the list damien mark brad maire The values in the list damien mark brad maire The values in the list damien mark brad maire The values in the list
L M are: sacha are: sacha are: sacha are: sacha are:
N TAMARA
O
tamara
P
tamara DAMIEN MARK BRAD MAIRE SACHA TAMARA
Q R
tamara DAMIEN MARK BRAD MAIRE SACHA
S T U
IList.IsFixedSize Property
V [ILASM]
W
.property bool IsFixedSize { public hidebysig virtual abstract specialname bool get_IsFixedSize() } [C#]
X
bool IsFixedSize { get; }
Y Z
Summary Gets a System.Boolean value indicating whether the current instance has a fixed size.
1987
Contents | Index
IList Interface
System.Collections
IsFixedSize Property
Property Value true if the current instance has a fixed size; otherwise, false. A
Description
B
[Note: A collection with a fixed size does not allow the addition or removal of elements, but it allows the modification of existing elements.]
C D
Behaviors
E
Any method that adds or removes an element of a collection is required to check the value of this property for the particular collection before adding or removing elements. If the value of this property is false, any attempt to add or remove an element of the current instance is required to throw a System.NotSupportedException.
F G H I
Default
J
The default of this property is false.
K
How and When to Override
L
Override this property, setting the value to true, in order to prevent the addition or removal of elements in the current instance.
M N
Usage
O
Use System.Collections.IList.IsFixedSize to secure the current instance from modification from methods, such as System.Collections.IList.Add and System.Collections.IList.Remove, which add or remove elements from a list.
P Q R
Example
S
using System; using System.Collections;
T U
namespace Samples { public class IListIsFixedSize { public static void Main() { ArrayList al = new ArrayList(); IList il = al; Console.WriteLine("Is fixed size: {0}", il.IsFixedSize); Console.WriteLine("Is read only: {0}",
V W X Y Z
1988
Contents | Index
System.Collections
IList Interface IsReadOnly Property
il.IsReadOnly); il = ArrayList.ReadOnly(al); Console.WriteLine("Is fixed size: {0}", il.IsFixedSize); Console.WriteLine("Is read only: {0}", il.IsReadOnly); il = Array.CreateInstance(typeof(string), 5); Console.WriteLine("Is fixed size: {0}", il.IsFixedSize); Console.WriteLine("Is read only: {0}", il.IsReadOnly);
A B C D E
}
F
} }
G
The output is Is Is Is Is Is Is
H I
fixed size: False read only: False fixed size: True read only: True fixed size: True read only: False
J K L M N
IList.IsReadOnly Property
O
[ILASM]
P
.property bool IsReadOnly { public hidebysig virtual abstract specialname bool get_IsReadOnly() }
Q
[C#]
R
bool IsReadOnly { get; }
S
Summary
T
Gets a value indicating whether the current instance is read-only.
U
Property Value
V
true if the current instance is read-only; otherwise, false.
W X
Description
Y
[Note: A collection that is read-only does not allow the modification, addition, or removal of elements.]
Z
1989
Contents | Index
IList Interface
System.Collections
IsReadOnly Property
Behaviors Any method that modifies, adds, or removes an element of a collection is required to check the value of this property for the particular collection before executing. If the value of this property is false, any attempt to modify, add, or remove an element of the current instance is required to throw a System.NotSupportedException.
A B C
Default
D
The default of this property is false.
E F
How and When to Override
G
Override this property, setting the value to true, in order to prevent the modification, addition, or removal of elements in the current instance.
H
Usage
I
Use System.Collections.IList.IsReadOnly to secure the current instance from modification from methods, such as System.Collections.IList.Add and System.Collections.IList.Remove, which modify, add, or remove elements from a list.
J K L M
Example
N
using System; using System.Collections;
O
namespace Samples { public class IListIsReadOnly { public static void Main() { ArrayList al = new ArrayList(); IList il = al; Console.WriteLine("Is fixed size: {0}", il.IsFixedSize); Console.WriteLine("Is read only: {0}", il.IsReadOnly); il = ArrayList.ReadOnly(al); Console.WriteLine("Is fixed size: {0}", il.IsFixedSize); Console.WriteLine("Is read only: {0}", il.IsReadOnly); il = Array.CreateInstance(typeof(string), 5);
P Q R S T U V W X Y Z
1990
Contents | Index
System.Collections
IList Interface Item Property
Console.WriteLine("Is fixed size: {0}", il.IsFixedSize); Console.WriteLine("Is read only: {0}", il.IsReadOnly);
A
} }
B
}
C
The output is Is Is Is Is Is Is
D
fixed size: False read only: False fixed size: True read only: True fixed size: True read only: False
E F G H I
IList.Item Property
J
[ILASM]
K
.property bool IsReadOnly { public hidebysig virtual abstract specialname bool get_IsReadOnly() }
L
[C#]
M
bool IsReadOnly { get; }
N
Summary
O
Gets or sets the element at the specified index in the current instance.
P Q
Parameters
R
Parameter
Description
index
A System.Int32 that specifies the zero-based index of the element to get or set.
S T U V
Usage
W
Use this property for subscript indexing for the current instance in the following form: myCollection[index].
X Y Z
1991
Contents | Index
IList Interface
System.Collections
Item Property
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
index is not a valid index in the current instance.
System.NotSupportedException
The property is being set and the current instance is read-only.
A B C D E F
Example
G
using System; using System.Collections;
H
namespace Samples { public class IListItem { public static void Main() { IList il = new ArrayList(); string[] strings = {"damien", "MARK", "brad"}; foreach(string s in strings) Console.WriteLine("{0} added at {1}", s, il.Add(s)); il[il.IndexOf("MARK")] = "mark"; for(int i = 0; i < strings.Length; i++) Console.WriteLine("{0} ", il[i]); } } }
I J K L M N O P Q R S
The output is
T U
damien added at 0 MARK added at 1 brad added at 2 damien mark brad
V W X Y Z
1992
Contents | Index
System.Collections
IList Interface Add() Method
IList.Add(System.Object) Method [ILASM]
.method public hidebysig virtual abstract int32 Add(object value) [C#]
A
int Add(object value)
B C
Summary
D
Adds an item to the current instance.
E
Parameters
F G
Parameter
Description
value
The System.Object to add to the current instance.
H I J
Usage
K
Use the System.Collections.IList.Add method to add another element to the current instance. The index into which that element is added is implementation-dependent.
L M N
Exceptions
O
Exception
Condition
System.NotSupportedException
The current instance is read-only or has a fixed size.
P Q R
Example
S
using System; using System.Collections;
T U
namespace Samples { public class IListAdd { public static void Main() { try { IList il = new ArrayList(); Console.WriteLine("Is fixed size: {0}",
V W X Y Z
1993
Contents | Index
IList Interface
System.Collections
Clear() Method
il.IsFixedSize); string[] strings = {"damien", "mark", "brad"}; foreach(string s in strings) Console.WriteLine("{0} added at {1}", s, il.Add(s)); il = Array.CreateInstance(typeof(string), 5); Console.WriteLine("Is fixed size: {0}", il.IsFixedSize); foreach(string s in strings) Console.WriteLine("{0} added at {1}", s, il.Add(s));
A B C D E
} catch(Exception e) { Console.WriteLine("Exception: {0}", e); }
F G H }
I
} }
J K
The output is
L
Is fixed size: False damien added at 0 mark added at 1 brad added at 2 Is fixed size: True Exception: System.NotSupportedException: Collection was of a fixed size. at System.Array.System.Collections.IList.Add(Object value) at Samples.IListAdd.Main() in C:\Books\BCL\Samples\System.Collections\IList\ Add(System.Object)\IList.cs:line 23
M N O P Q R S
IList.Clear() Method
T [ILASM]
U
.method public hidebysig virtual abstract void Clear()
V
[C#]
void Clear()
W X
Summary
Y
Removes all items from the current instance.
Z
1994
Contents | Index
System.Collections
IList Interface Clear() Method
How and When to Override Implementations of this method can vary in how a call to this method affects the capacity of a list. Typically, the count is set to zero. The capacity can be set to zero, some default, or remain unchanged.
A B
Exceptions
C
Exception
Condition
System.NotSupportedException
The current instance is read-only.
D E F G
Example
H
using System; using System.Collections;
I J
namespace Samples { public class IListClear { public static void Main() { IList il = new ArrayList(); Console.WriteLine("Is fixed size: {0}", il.IsFixedSize); string[] strings = {"damien", "mark", "brad"}; foreach(string s in strings) Console.WriteLine("{0} added at {1}", s, il.Add(s)); il.Clear(); foreach(string s in il) Console.WriteLine("Value: {0}", s); } } }
K L M N O P Q R S T U V
The output is
W X
Is fixed size: False damien added at 0 mark added at 1 brad added at 2
Y Z
1995
Contents | Index
IList Interface
System.Collections
Contains() Method
IList.Contains(System.Object) Method [ILASM]
.method public hidebysig virtual abstract bool Contains(object value)
A
[C#]
bool Contains(object value)
B C
Summary
D
Determines whether the current instance contains a specific value.
E
Parameters
F G H
Parameter
Description
value
The System.Object to locate in the current instance.
I J
Return Value
K
true if the System.Object is found in the current instance; otherwise, false.
L
Usage
M
Use the System.Collections.IList.Contains method to determine if a particular System.Object is an element of the current instance.
N O P
Example
Q
using System; using System.Collections;
R
namespace Samples { public class IListContains { public static void Main() { IList il = new ArrayList(); string[] strings = {"damien", "mark", "brad"}; foreach(string s in strings) Console.WriteLine("{0} added at {1}", s, il.Add(s)); strings[1] = "maire"; foreach(string s in strings) Console.WriteLine("Is {0} contained in list {1}", s, il.Contains(s)); } } }
S T U V W X Y Z
1996
Contents | Index
System.Collections
IList Interface IndexOf() Method
The output is damien added at 0 mark added at 1 brad added at 2 Is damien contained in list True Is maire contained in list False Is brad contained in list True
A B C D E
IList.IndexOf(System.Object) Method
F [ILASM]
.method public hidebysig virtual abstract int32 IndexOf(object value)
G
[C#]
H
int IndexOf(object value)
I
Summary
J
Determines the index of a specific item in the current instance.
K L
Parameters
M
Parameter
Description
value
The System.Object to locate in the current instance.
N O P Q
Return Value
R
The index of value if found in the current instance; otherwise, –1.
S
How and When to Override
T
The default implementations of this method use System.Object.Equals to search for value in the current instance.
U V
Usage
W
Use System.Collections.IList.IndexOf to determine if a System.Object is contained in the current instance and, if it is contained, its index in the current instance.
X Y Z
1997
Contents | Index
IList Interface
System.Collections
Insert() Method
Example using System; using System.Collections;
A namespace Samples { public class IListIndexOf { public static void Main() { IList il = new ArrayList(); string[] strings = {"damien", "mark", "brad"}; foreach(string s in strings) Console.WriteLine("{0} added at {1}", s, il.Add(s)); strings[1] = "maire"; foreach(string s in strings) Console.WriteLine("Index of {0} is {1}", s, il.IndexOf(s)); } } }
B C D E F G H I J K L M
The output is
N damien added at 0 mark added at 1 brad added at 2 Index of damien is 0 Index of maire is -1 Index of brad is 2
O P Q R S
IList.Insert(System.Int32, System.Object) Method
T
[ILASM]
U
.method public hidebysig virtual abstract void Insert(int32 index, object value)
V
[C#]
void Insert(int index, object value)
W X
Summary
Y
Inserts an item to the current instance at the specified position.
Z
1998
Contents | Index
System.Collections
IList Interface Insert() Method
Parameters Parameter
Description
index
A System.Int32 that specifies the zero-based index at which value is inserted.
value
The System.Object to insert into the current instance.
A B C D E
Behaviors
F
If index equals the number of items in the System.Collections.IList, then value is required to be appended to the end of the current instance.
G H
Usage
I
Use System.Collections.IList.Insert to place a new element into a specific position in the current instance.
J K
Exceptions
L M
Exception
Condition
System.ArgumentOutOfRangeException
index is not a valid index in the current instance (i.e., is greater than the number of elements in the current instance).
System.NotSupportedException
The current instance is read-only or has a fixed size.
N O P Q R S
Example
T
using System; using System.Collections;
U V
namespace Samples { public class IListInsert { public static void Main() { try { IList il = new ArrayList(); Console.WriteLine("Is fixed size: {0}",
W X Y Z
1999
Contents | Index
IList Interface
System.Collections
Remove() Method
il.IsFixedSize); string[] strings = {"damien", "mark", "brad"}; foreach(string s in strings) il.Insert(0, s); foreach(string s in il) Console.WriteLine("{0} ", s); il = Array.CreateInstance(typeof(string), 5); Console.WriteLine("Is fixed size: {0}", il.IsFixedSize); foreach(string s in strings) il.Insert(0, s);
A B C D E
} catch(Exception e) { Console.WriteLine("Exception: {0}", e); }
F G H }
I
} }
J K
The output is
L
Is fixed size: False brad mark damien Is fixed size: True Exception: System.NotSupportedException: Collection was of a fixed size. at System.Array.System.Collections.IList.Insert(Int32 index, Object value) at Samples.IListInsert.Main() in C:\Books\BCL\Samples\System.Collections\IList\ Insert(System.Int32,System.Object)\IList.cs:line 24
M N O P Q R S
IList.Remove(System.Object) Method
T [ILASM]
U
.method public hidebysig virtual abstract void Remove(object value)
V
[C#]
void Remove(object value)
W X
Summary
Y
Removes the first occurrence of a specified System.Object from the current instance.
Z
2000
Contents | Index
System.Collections
IList Interface Remove() Method
Parameters Parameter
Description
value
The System.Object to remove from the current instance.
A B C
Behaviors
D
In addition, if value is null or is not found in the current instance, it is required that no exception be thrown and the current instance remain unchanged.
E
How and When to Override
G
The default implementations of this method use System.Object.Equals to search for value in the current instance.
H
Usage
J
Use System.Collections.IList.Remove to delete a specified System.Object from the current instance.
K
F
I
L M
Exceptions
N
Exception
Condition
System.NotSupportedException
The current instance is read-only or has a fixed size.
O P Q R
Example
S
using System; using System.Collections;
T U
namespace Samples { public class IListRemove { public static void Main() { IList il = new ArrayList(); string[] strings = {"damien", "mark", "brad"}; foreach(string s in strings) Console.WriteLine("{0} added at {1}", s, il.Add(s));
V W X Y Z
2001
Contents | Index
IList Interface
System.Collections
RemoveAt() Method
strings[1] = "maire"; foreach(string s in strings) il.Remove(s); foreach(string s in il) Console.WriteLine("{0} ",s);
A }
B }
C
}
D
The output is
E damien added at 0 mark added at 1 brad added at 2 mark
F G H I
IList.RemoveAt(System.Int32) Method
J
[ILASM]
K
.method public hidebysig virtual abstract void RemoveAt(int32 index)
L
[C#]
void RemoveAt(int index)
M N
Summary
O
Removes the item at the specified index of the current instance.
P
Parameters
Q R
Parameter
Description
index
A System.Int32 that specifies the zero-based index of the item to remove.
S T U
Exceptions
V W
Exception
Condition
System.ArgumentOutOfRangeException
index is not a valid index in current instance.
System.NotSupportedException
The current instance is read-only or has a fixed size.
X Y Z
2002
Contents | Index
System.Collections
IList Interface RemoveAt() Method
Example using System; using System.Collections;
A namespace Samples { public class IListRemoveAt { public static void Main() { IList il = new ArrayList(); string[] strings = {"damien", "mark", "brad"}; foreach(string s in strings) Console.WriteLine("{0} added at {1}", s, il.Add(s)); il.RemoveAt(0); foreach(string s in il) Console.WriteLine("{0} ", s); } } }
B C D E F G H I J K L
The output is
M
damien added at 0 mark added at 1 brad added at 2 mark brad
N O P Q R S T U V W X Y Z
2003
Contents | Index
System IndexOutOfRangeException
BCL
Object
A
Exception
B
ISerializable
NotStandardized
SystemException IndexOutOfRangeException
C D
Summary
E
Represents the error that occurs when an attempt is made to access an element of an array with an index that is outside the bounds of the array.
F G
Type Summary
H
public sealed class IndexOutOfRangeException : SystemException { // Constructors public IndexOutOfRangeException (); public IndexOutOfRangeException (string message); public IndexOutOfRangeException (string message, Exception innerException); }
I J K L M N
Example
O
using System;
P
namespace Samples { public class IndexOutOfRangeExceptionSample { public static void Main() { try { string[] strings = {"zero", "one", "two"}; strings[3] = "three"; } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
Q R S T U V W X Y Z
2004
Contents | Index
System
IndexOutOfRangeException IndexOutOfRangeException() Constructor
The output is Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array. at Samples.IndexOutOfRangeExceptionSample.Main() in C:\Books\BCL\Samples\ System\IndexOutOfRangeException\IndexOutOfRangeException.cs:line 12
A B C D
IndexOutOfRangeException() Constructor
E
[ILASM]
public rtspecialname specialname instance void .ctor()
F
[C#]
G
public IndexOutOfRangeException()
H
Summary
I
Constructs and initializes a new instance of the System.IndexOutOfRangeException class.
J K
Description
L
This constructor initializes the System.IndexOutOfRangeException.Message property of the new instance to a system-supplied message that describes the error, such as “An array index is out of range.” This message takes into account the current system culture. The System.IndexOutOfRangeException.InnerException property is initialized to null.
M N O P Q
IndexOutOfRangeException(System.String) Constructor
R
[ILASM]
S
public rtspecialname specialname instance void .ctor(string message)
T
[C#]
public IndexOutOfRangeException(string message)
U V
Summary
W
Constructs and initializes a new instance of the System.IndexOutOfRangeException class.
X Y Z
2005
Contents | Index
IndexOutOfRangeException
System
IndexOutOfRangeException() Constructor
Parameters Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
A B C D E
Description
F
This constructor initializes the System.IndexOutOfRangeException.Message property of the new instance using message. If message is null, the System.IndexOutOfRangeException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.IndexOutOfRangeException.InnerException property is initialized to null.
G H I J K
IndexOutOfRangeException(System.String, System.Exception) Constructor
L
[ILASM]
M
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
N
[C#]
public IndexOutOfRangeException(string message, Exception innerException)
O P
Summary
Q
Constructs and initializes a new instance of the System.IndexOutOfRangeException class.
R S
Parameters
T U
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
V W X Y Z
2006
Contents | Index
System
IndexOutOfRangeException IndexOutOfRangeException() Constructor
Description This constructor initializes the System.IndexOutOfRangeException.Message property of the new instance using message, and the System.IndexOutOfRangeException.InnerException property using innerException. If message is null, the System.IndexOutOfRangeException.Message property is initialized to the systemsupplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
2007
Contents | Index
System Int16 Structure
BCL
Object
A
ValueType
B
Int16
C
IComparable IFormattable IConvertible
NotStandardized
D
Summary
E
Represents a 16-bit signed integer.
F G
Type Summary public struct Int16 : IComparable, IFormattable, IConvertible { // Fields public const short MaxValue = 32767; public const short MinValue = -32768;
H I J K L
// Methods public int CompareTo (object value); public override bool Equals (object obj); public override int GetHashCode (); MS public TypeCode GetTypeCode (); public static short Parse (string s); public static short Parse (string s, NumberStyles style); public static short Parse (string s, NumberStyles style, IFormatProvider provider); CF public static short Parse (string s, IFormatProvider provider); public override string ToString (); public string ToString (string format); public string ToString (string format, IFormatProvider provider); public string ToString (IFormatProvider provider);
M N O P Q R S T U
// MS MS MS MS MS MS MS MS MS MS
V W X Y Z
Explicit Interface Members bool IConvertible.ToBoolean(IFormatProvider provider); byte IConvertible.ToByte(IFormatProvider provider); char IConvertible.ToChar(IFormatProvider provider); DateTime IConvertible.ToDateTime(IFormatProvider provider); decimal IConvertible.ToDecimal(IFormatProvider provider); double IConvertible.ToDouble(IFormatProvider provider); short IConvertible.ToInt16(IFormatProvider provider); int IConvertible.ToInt32(IFormatProvider provider); long IConvertible.ToInt64(IFormatProvider provider); sbyte IConvertible.ToSByte(IFormatProvider provider);
2008
Contents | Index
System
Int16 Structure Int16 Structure
MS MS MS MS MS
float IConvertible.ToSingle(IFormatProvider provider); object IConvertible.ToType(Type type,IFormatProvider provider); ushort IConvertible.ToUInt16(IFormatProvider provider); uint IConvertible.ToUInt32(IFormatProvider provider); ulong IConvertible.ToUInt64(IFormatProvider provider);
A
}
B C
Description
D
The System.Int16 data type represents integer values ranging from negative 32,768 to positive 32,767; that is, hexadecimal: 0x8000 to 0x7FFF.
E F
Example
G
using System;
H namespace Samples { public class Int16Sample { public static void Main() { short max = short.MaxValue, min = short.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); Console.WriteLine("Is {0} equal to {1}: {2}", max, max, max.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", max, min, max.Equals(min)); Console.WriteLine("{0} has hashcode of: {1}", max, max.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", min, min.GetHashCode()); string s = max.ToString(); Console.WriteLine("\"{0}\" parsed from string yields: {1}", s, Int16.Parse(s)); s = min.ToString(); Console.WriteLine("\"{0}\" parsed from string yields: {1}", s, Int16.Parse(s)); string[] formats = {"c", "d", "e", "f", "g", "n", "p", "x" }; foreach(string f in formats) Console.WriteLine("{0}: {1}", max, max.ToString(f)); } } }
I J K L M N O P Q R S T U V W X Y Z
2009
Contents | Index
Int16 Structure
System
MaxValue Field
The output is MaxValue: 32767 MinValue: -32768 Is 32767 equal to 32767: True Is 32767 equal to -32768: False 32767 has hashcode of: 2147450879 -32768 has hashcode of: -2147450880 "32767" parsed from string yields: 32767 "-32768" parsed from string yields: -32768 32767: $32,767.00 32767: 32767 32767: 3.276700e+004 32767: 32767.00 32767: 32767 32767: 32,767.00 32767: 3,276,700.00 % 32767: 7fff
A B C D E F G H I J K
Int16.MaxValue Field
L
[ILASM]
M
.field public static literal int16 MaxValue [C#]
N
public const short MaxValue = 32767
O P
Summary
Q
Contains the maximum value for the System.Int16 type.
R
Description
S
The value of this constant is 32,767 (hexadecimal 0x7FFF).
T
Example
U
using System;
V
namespace Samples { public class Int16MaxValue { public static void Main() { short max = short.MaxValue, min = short.MinValue; Console.WriteLine("MaxValue: {0}", max);
W X Y Z
2010
Contents | Index
System
Int16 Structure MinValue Field
Console.WriteLine("MinValue: {0}", min); } } }
A
The output is
B
MaxValue: 32767 MinValue: -32768
C D E
Int16.MinValue Field
F
[ILASM]
G
.field public static literal int16 MinValue
H
[C#]
public const short MinValue = -32768
I
Summary
J
Contains the minimum value for the System.Int16 type.
K L
Description
M
The value of this constant is –32,768 (hexadecimal 0x8000).
N
Example
O
using System;
P
namespace Samples { public class Int16MinValue { public static void Main() { short max = short.MaxValue, min = short.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); } } }
Q R S T U V W X Y
The output is
Z
MaxValue: 32767 MinValue: -32768
2011
Contents | Index
Int16 Structure
System
CompareTo() Method
Int16.CompareTo(System.Object) Method [ILASM]
.method public final hidebysig virtual int32 CompareTo(object value)
A
[C#]
public int CompareTo(object value)
B C
Summary
D
Returns the sort order of the current instance compared to the specified System.Object.
E
Parameters
F G
Parameter
Description
value
The System.Object to compare to the current instance.
H I J
Return Value
K
A System.Int32 containing a value that reflects the sort order of the current instance as compared to value. The following table defines the conditions under which the return value is a negative number, zero, or a positive number.
L M N O
Return Value
Description
Q
any negative number
Current instance < value.
R
zero
Current instance == value.
any positive number
Current instance > value, or value is a null reference.
P
S T U
Description
V
[Note: This method is implemented to support the System.IComparable interface.]
W
Exceptions
X Y Z
Exception
Condition
System.ArgumentException
value is not a System.Int16 and is not a null reference.
2012
Contents | Index
System
Int16 Structure Equals() Method
Example using System; namespace Samples { public class Int16CompareTo { private static string CompareInt16s(short s1, short s2) { int i = s1.CompareTo(s2); if(0 == i) return String.Format("{0} is equal to {1}", s1, s2); if(i > 0) return String.Format("{0} is greater than {1}", s1, s2); else return String.Format("{0} is less than {1}", s1, s2); } public static void Main() { short max = short.MaxValue, min = short.MinValue; Console.WriteLine(CompareInt16s(max, max)); Console.WriteLine(CompareInt16s(max, min)); Console.WriteLine(CompareInt16s(min, max)); } } }
A B C D E F G H I J K L M N O P
The output is
Q R
32767 is equal to 32767 32767 is greater than -32768 -32768 is less than 32767
S T U
Int16.Equals(System.Object) Method
V
[ILASM]
.method public hidebysig virtual bool Equals(object obj)
W
[C#]
X
public override bool Equals(object obj)
Y
Summary
Z
Determines whether the current instance and the specified System.Object represent the same type and value. 2013
Contents | Index
Int16 Structure
System
Equals() Method
Parameters Parameter
Description
obj
The System.Object to compare to the current instance.
A B C D
Return Value
E
true if obj represents the same type and value as the current instance. If obj is a null reference or is not an instance of System.Int16, returns false.
F G
Description
H
[Note: This method overrides System.Object.Equals.]
I
Example
J
using System;
K namespace Samples { public class Int16Equals { public static void Main() { short max = short.MaxValue, min = short.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); Console.WriteLine("Is {0} equal to {1}: {2}", max, max, max.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", max, min, max.Equals(min)); Console.WriteLine("Is {0} equal to {1}: {2}", min, max, min.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", min, min, min.Equals(min)); } } }
L M N O P Q R S T U V W X Y
The output is
Z
MaxValue: 32767 MinValue: -32768 Is 32767 equal to 32767: True
2014
Contents | Index
System
Int16 Structure GetHashCode() Method
Is 32767 equal to -32768: False Is -32768 equal to 32767: False Is -32768 equal to -32768: True
A
Int16.GetHashCode() Method
B
[ILASM]
C
.method public hidebysig virtual int32 GetHashCode()
D
[C#]
E
public override int GetHashCode()
F
Summary
G
Generates a hash code for the current instance.
H
Description
I
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
J K
Example
L
using System;
M
namespace Samples { public class Int16GetHashCode { public static void Main() { short max = short.MaxValue, zero = 0, min = short.MinValue; Console.WriteLine("{0} has hashcode of: {1}", max, max.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", zero, zero.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", min, min.GetHashCode()); } } }
N O P Q R S T U V W X Y
The output is
Z
32767 has hashcode of: 2147450879 0 has hashcode of: 0 -32768 has hashcode of: -2147450880
2015
Contents | Index
Int16 Structure
System
GetTypeCode() Method
Int16.GetTypeCode() Method [ILASM]
.method public final hidebysig virtual valuetype System.TypeCode GetTypeCode()
A
[C#]
public TypeCode GetTypeCode()
B C
Summary
D
Returns the System.TypeCode for value type System.Int16.
E F
Int16.Parse(System.String) Method
G
[ILASM]
H
.method public hidebysig static int16 Parse(string s) [C#]
I
public static short Parse(string s)
J K
Summary
L
Returns the specified System.String converted to a System.Int16 value.
M
Parameters
N O
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Integer style.
P Q R S
Description
T
This version of System.Int16.Parse is equivalent to System.Int16.Parse(s, System.Globalization.NumberStyles.Integer, null). The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.]
U V W X Y Z
2016
Contents | Index
System
Int16 Structure Parse() Method
Exceptions Exception
Condition A
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.Int16.MaxValue or less than System.Int16.MinValue.
B C D E F G
Example
H
using System;
I namespace Samples { public class Int16Parse { public static void Main() { string s; try { s = Int16.MaxValue.ToString(); Console.WriteLine("From String {0} yields s, Int16.Parse(s)); s = "0"; Console.WriteLine("From String {0} yields s, Int16.Parse(s)); s = Int16.MinValue.ToString(); Console.WriteLine("From String {0} yields s, Int16.Parse(s)); s = String.Empty; Console.WriteLine("From String {0} yields s, Int16.Parse(s)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = (Int16.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields s, Int16.Parse(s));
J K L M N O {1}",
P Q
{1}",
R S
{1}",
T U
{1}",
V W X Y Z {1}",
2017
Contents | Index
Int16 Structure
System
Parse() Method
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A }
B }
C
}
D
The output is
E From String 32767 yields 32767 From String 0 yields 0 From String -32768 yields -32768 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int16.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Int16.Parse(String s) at Samples.Int16Parse.Main() in C:\Books\BCL\Samples\System\Int16\ Parse(System.String)\Int16.cs:line 22 Exception: System.OverflowException: Value was either too large or too small for an Int16. at System.Int16.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Int16.Parse(String s) at Samples.Int16Parse.Main() in C:\Books\BCL\Samples\System\Int16\ Parse(System.String)\Int16.cs:line 32
F G H I J K L M N O P
Int16.Parse(System.String, System.Globalization.NumberStyles) Method
Q [ILASM]
R
.method public hidebysig static int16 Parse(string s, valuetype System.Globalization.NumberStyles style)
S
[C#]
T
public static short Parse(string s, NumberStyles style)
U
Summary
V
Returns the specified System.String converted to a System.Int16 value.
W X Y Z
2018
Contents | Index
System
Int16 Structure Parse() Method
Parameters Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Integer style.
A B C D E F G
Description
H
This version of System.Int16.Parse is equivalent to System.Int16.Parse(s, style, null). The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.]
I J K L
Exceptions
M N
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
Q
s represents a number greater than System.Int16.MaxValue or less than System.Int16.MinValue.
R
System.OverflowException
O P
S T U
Example
V
using System; using System.Globalization;
W
namespace Samples { public class Int16Parse { public static void Main() { string s;
X Y Z
2019
Contents | Index
Int16 Structure
System
Parse() Method
try { s = "$0"; Console.WriteLine("From String {0} yields {1}", s, Int16.Parse(s, NumberStyles.AllowCurrencySymbol)); s = String.Format("${0}", (Int16.MaxValue).ToString()); Console.WriteLine("From String {0} yields {1}", s, Int16.Parse(s, NumberStyles.AllowCurrencySymbol)); s = String.Format("({0})", (Int16.MaxValue).ToString()); Console.WriteLine("From String {0} yields {1}", s, Int16.Parse(s, NumberStyles.AllowParentheses)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Int16.Parse(s, NumberStyles.Any)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = (Int16.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Int16.Parse(s, NumberStyles.Any)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E F G H I J K L M N O P Q R S T }
U }
V
The output is
W
From String $0 yields 0 From String $32767 yields 32767 From String (32767) yields -32767 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int16.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Int16.Parse(String s, NumberStyles style)
X Y Z
2020
Contents | Index
System
Int16 Structure Parse() Method
at Samples.Int16Parse.Main() in C:\Books\BCL\Samples\System\Int16\ Parse(System.String,System.Globalization.NumberStyles)\Int16.cs:line 29 Exception: System.OverflowException: Value was either too large or too small for an Int16. at System.Int16.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Int16.Parse(String s, NumberStyles style) at Samples.Int16Parse.Main() in C:\Books\BCL\Samples\System\Int16\ Parse(System.String,System.Globalization.NumberStyles)\Int16.cs:line 41
A B C D
Int16.Parse(System.String, System.Globalization.NumberStyles, System.IFormatProvider) Method
E F
[ILASM]
G
.method public hidebysig static int16 Parse(string s, valuetype System.Globalization.NumberStyles style, class System.IFormatProvider provider)
H
[C#]
public static short Parse(string s, NumberStyles style, IFormatProvider provider)
I
Summary
J
Returns the specified System.String converted to a System.Int16 value.
K L
Parameters
M
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Integer style.
N O
provider
P Q R S T
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
U V
Description
W
The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used.
X Y Z
2021
Contents | Index
Int16 Structure
System
Parse() Method
Exceptions Exception
Condition
B
System.ArgumentNullException
s is a null reference.
C
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.Int16.MaxValue or less than System.Int16.MinValue.
A
D E F G
Example
H
using System; using System.Globalization;
I namespace Samples { public class Int16Parse { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; string s = " ~0"; Console.WriteLine("From String {0} yields {1}", s, Int16.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowLeadingSign, c)); s = "(1)"; Console.WriteLine("From String {0} yields {1}", s, Int16.Parse(s, NumberStyles.AllowParentheses, c)); s = "!1"; Console.WriteLine("From String {0} yields {1}", s, Int16.Parse(s, NumberStyles.Any, c)); } } }
J K L M N O P Q R S T U V W X Y Z
2022
Contents | Index
System
Int16 Structure Parse() Method
The output is From String ~0 yields 0 From String (1) yields -1 From String !1 yields -1
A B C
Int16.Parse(System.String, System.IFormatProvider) Method
D
[ILASM]
E
.method public hidebysig static int16 Parse(string s, class System.IFormatProvider provider)
F
[C#]
G
public static short Parse(string s, IFormatProvider provider)
H
Summary
I
Returns the specified System.String converted to a System.Int16 value.
J K
Parameters
L
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Integer style.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
M N O P Q R
Description
S
This version of System.Int16.Parse is equivalent to System.Int16.Parse(s, System.Globalization.NumberStyles.Integer, provider). The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used.
T U V W X Y Z
2023
Contents | Index
Int16 Structure
System
Parse() Method
Exceptions Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.Int16.MaxValue or less than System.Int16.MinValue.
A B C D E F G
Example
H
using System; using System.Globalization;
I J
namespace Samples { public class Int16Parse { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; try { s = "~0"; Console.WriteLine("From String {0} yields s, Int16.Parse(s, c)); s = Int16.MaxValue.ToString(); Console.WriteLine("From String {0} yields s, Int16.Parse(s, c)); s = "!1"; Console.WriteLine("From String {0} yields s, Int16.Parse(s, c)); s = String.Empty; Console.WriteLine("From String {0} yields s, Int16.Parse(s, c)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e);
K L M N O P Q R S T U V W X Y Z
{1}",
{1}",
{1}",
{1}",
2024
Contents | Index
System
Int16 Structure ToString() Method
} try { s = (Int16.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Int16.Parse(s, c)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E
}
F
} }
G
The output is
H I
From String ~0 yields 0 From String 32767 yields 32767 From String !1 yields -1 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int16.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Int16.Parse(String s, IFormatProvider provider) at Samples.Int16Parse.Main() in C:\Books\BCL\Samples\System\Int16\ Parse(System.String,System.IFormatProvider)\Int16.cs:line 27 Exception: System.OverflowException: Value was either too large or too small for an Int16. at System.Int16.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Int16.Parse(String s, IFormatProvider provider) at Samples.Int16Parse.Main() in C:\Books\BCL\Samples\System\Int16\ Parse(System.String,System.IFormatProvider)\Int16.cs:line 37
J K L M N O P Q R S
Int16.ToString() Method
T
[ILASM]
U
.method public hidebysig virtual string ToString()
V
[C#]
W
public override string ToString()
X
Summary
Y
Returns a System.String representation of the value of the current instance.
Z
2025
Contents | Index
Int16 Structure
System
ToString() Method
Return Value A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the current system culture. A B
Description
C
This version of System.Int16.ToString is equivalent to System.Int16.ToString(null, null). [Note: This method overrides System.Object.ToString.]
D E
Example
F
using System;
G
namespace Samples { public class ToString { public static void Main() { short max = short.MaxValue, min = short.MinValue; Console.WriteLine("{0}.ToString() yields {1}", max, max.ToString()); Console.WriteLine("{0}.ToString() yields {1}", min, min.ToString()); } } }
H I J K L M N O P Q
The output is
R S
32767.ToString() yields 32767 -32768.ToString() yields -32768
T U V
Int16.ToString(System.String) Method
W
[ILASM]
.method public hidebysig instance string ToString(string format)
X
[C#]
public string ToString(string format)
Y Z
Summary Returns a System.String representation of the value of the current instance.
2026
Contents | Index
System
Int16 Structure ToString() Method
Parameters Parameter
Description
format
A System.String that specifies the format of the returned string. [Note: For a list of valid values, see System.Int16.ToString(System.String, System.IFormatProvider).]
A B C D
Return Value
E
A System.String representation of the current instance formatted as specified by format. The string takes into account the current system culture.
F G
Description
H
This version of System.Int16.ToString is equivalent to System.Int16.ToString(format, null). If format is a null reference, the general format specifier “G” is used.
I J K L
Exceptions
M
Exception
Condition
System.FormatException
format is invalid.
N O P
Example
Q
using System;
R S
namespace Samples { public class Int16ToString { public static void Main() { short max = short.MaxValue, min = short.MinValue; string[] formats = {"C", "c", "D", "d", "E", "e", "F", "f", "G", "g", "N", "n", "P", "p", "X", "x"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\") yields {2}", max, f, max.ToString(f)); foreach(string f in formats)
T U V W X Y Z
2027
Contents | Index
Int16 Structure
System
ToString() Method
Console.WriteLine("{0}.ToString(\"{1}\") yields {2}", min, f, min.ToString(f)); } }
A
}
B
The output is
C 32767.ToString("C") yields $32,767.00 32767.ToString("c") yields $32,767.00 32767.ToString("D") yields 32767 32767.ToString("d") yields 32767 32767.ToString("E") yields 3.276700E+004 32767.ToString("e") yields 3.276700e+004 32767.ToString("F") yields 32767.00 32767.ToString("f") yields 32767.00 32767.ToString("G") yields 32767 32767.ToString("g") yields 32767 32767.ToString("N") yields 32,767.00 32767.ToString("n") yields 32,767.00 32767.ToString("P") yields 3,276,700.00 % 32767.ToString("p") yields 3,276,700.00 % 32767.ToString("X") yields 7FFF 32767.ToString("x") yields 7fff -32768.ToString("C") yields -$32,768.00 -32768.ToString("c") yields -$32,768.00 -32768.ToString("D") yields -32768 -32768.ToString("d") yields -32768 -32768.ToString("E") yields -3.276800E+004 -32768.ToString("e") yields -3.276800e+004 -32768.ToString("F") yields -32768.00 -32768.ToString("f") yields -32768.00 -32768.ToString("G") yields -32768 -32768.ToString("g") yields -32768 -32768.ToString("N") yields -32,768.00 -32768.ToString("n") yields -32,768.00 -32768.ToString("P") yields -3,276,800.00 % -32768.ToString("p") yields -3,276,800.00 % -32768.ToString("X") yields 8000 -32768.ToString("x") yields 8000
D E F G H I J K L M N O P Q R S T U V W X
Int16.ToString(System.String, System.IFormatProvider) Method
Y
[ILASM]
Z
.method public final hidebysig virtual string ToString(string format, class System.IFormatProvider provider) [C#]
public string ToString(string format, IFormatProvider provider)
2028
Contents | Index
System
Int16 Structure ToString() Method
Summary Returns a System.String representation of the value of the current instance. A
Parameters
B
Parameter
Description
C
A System.String containing a character that specifies the format of the returned string.
D
format
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo instance containing culture-specific formatting information.
F
provider
E
G H
Return Value
I
A System.String representation of the current instance formatted as specified by format. The string takes into account the formatting information in the System.Globalization.NumberFormatInfo instance supplied by provider.
J K
Description
M
If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. If format is a null reference, the general format specifier “G” is used. [Note: For a detailed description of formatting, see the System.IFormattable interface. This method is implemented to support the System.IFormattable interface.] The following table lists the characters that are valid for the System.Int16 type.
N
L
O P Q R S
Format Characters
Description
"C", "c"
Currency format.
"D", "d"
Decimal format.
"E", "e"
Exponential notation format.
X
"F", "f"
Fixed-point format.
Y
"G", "g"
General format.
Z
T U V W
2029
Contents | Index
Int16 Structure
System
ToString() Method
Format Characters
Description
A
"N", "n"
Number format.
B
"P", "p"
Percent format.
"X", "x"
Hexadecimal format.
C D E
Exceptions
F G H
Exception
Condition
System.FormatException
format is invalid.
I J
Example
K
using System; using System.Globalization;
L M
namespace Samples { public class Int16ToString { public static void Main() { short max = short.MaxValue, min = short.MinValue; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; n.CurrencySymbol = "#"; string[] formats = {"C", "c", "D", "d", "E", "e", "F", "f", "G", "g", "N", "n", "P", "p", "X", "x"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\", c) yields {2}", max, f, max.ToString(f, c)); foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\",n) yields {2}", min, f, min.ToString(f, c)); } } }
N O P Q R S T U V W X Y Z
2030
Contents | Index
System
Int16 Structure ToString() Method
The output is 32767.ToString("C", c) 32767.ToString("c", c) 32767.ToString("D", c) 32767.ToString("d", c) 32767.ToString("E", c) 32767.ToString("e", c) 32767.ToString("F", c) 32767.ToString("f", c) 32767.ToString("G", c) 32767.ToString("g", c) 32767.ToString("N", c) 32767.ToString("n", c) 32767.ToString("P", c) 32767.ToString("p", c) 32767.ToString("X", c) 32767.ToString("x", c) -32768.ToString("C",n) -32768.ToString("c",n) -32768.ToString("D",n) -32768.ToString("d",n) -32768.ToString("E",n) -32768.ToString("e",n) -32768.ToString("F",n) -32768.ToString("f",n) -32768.ToString("G",n) -32768.ToString("g",n) -32768.ToString("N",n) -32768.ToString("n",n) -32768.ToString("P",n) -32768.ToString("p",n) -32768.ToString("X",n) -32768.ToString("x",n)
yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields
#32,767.00 #32,767.00 32767 32767 3.276700E~004 3.276700e~004 32767.00 32767.00 32767 32767 32,767.00 32,767.00 3,276,700.00 % 3,276,700.00 % 7FFF 7fff !#32,768.00 !#32,768.00 !32768 !32768 !3.276800E~004 !3.276800e~004 !32768.00 !32768.00 !32768 !32768 !32,768.00 !32,768.00 !3,276,800.00 % !3,276,800.00 % 8000 8000
A B C D E F G H I J K L M N O P Q R S T U
Int16.ToString(System.IFormatProvider) Method
V [ILASM]
W
.method public final hidebysig virtual string ToString(class System.IFormatProvider provider) [C#]
X
public string ToString(IFormatProvider provider)
Y Z
Summary Returns a System.String representation of the value of the current instance.
2031
Contents | Index
Int16 Structure
System
ToString() Method
Parameters Parameter
Description
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
A B C D
Return Value
E
A System.String representation of the current instance formatted using the general format specifier, “G”. The string takes into account the formatting information in the System.Globalization.NumberFormatInfo instance supplied by provider.
F G H
Description
I
This version of System.Int16.ToString is equivalent to System.Int16.ToString(“G”, provider). If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used.
J K L M
Example
N
using System; using System.Globalization;
O namespace Samples { public class Int16ToString { public static void Main() { short max = short.MaxValue, min = short.MinValue; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; Console.WriteLine("{0}.ToString yields {1}", max, max.ToString(c)); Console.WriteLine("{0}.ToString yields {1}", min, min.ToString(c)); } } }
P Q R S T U V W X Y Z
2032
Contents | Index
System
Int16 Structure ToChar() Method
The output is 32767.ToString yields 32767 -32768.ToString yields !32768
A B
IConvertible.ToBoolean(System.IFormatProvider) Method
C
[ILASM]
D
.method private final hidebysig virtual bool System.IConvertible.ToBoolean(class System.IFormatProvider provider)
E
[C#]
F
bool IConvertible.ToBoolean(IFormatProvider provider)
G
Summary
H
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToBoolean.]
I J K
IConvertible.ToByte(System.IFormatProvider) Method
L
[ILASM]
M
.method private final hidebysig virtual unsigned int8 System.IConvertible.ToByte(class System.IFormatProvider provider)
N
[C#]
O
byte IConvertible.ToByte(IFormatProvider provider)
P
Summary
Q
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToByte.]
R S T
IConvertible.ToChar(System.IFormatProvider) Method
U
[ILASM]
V
.method private final hidebysig virtual valuetype System.Char System.IConvertible.ToChar(class System.IFormatProvider provider)
W
[C#]
X
char IConvertible.ToChar(IFormatProvider provider)
Y
Summary
Z
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToChar.] 2033
Contents | Index
Int16 Structure
System
ToDateTime() Method
IConvertible.ToDateTime(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual valuetype System.DateTime System.IConvertible.ToDateTime(class System.IFormatProvider provider)
B
[C#]
DateTime IConvertible.ToDateTime(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDateTime.]
F G H
IConvertible.ToDecimal(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual decimal System.IConvertible.ToDecimal(class System.IFormatProvider provider)
K
[C#]
decimal IConvertible.ToDecimal(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDecimal.]
O P Q
IConvertible.ToDouble(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual float64 System.IConvertible.ToDouble(class System.IFormatProvider provider)
T
[C#]
double IConvertible.ToDouble(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDouble.]
X Y Z
2034
Contents | Index
System
Int16 Structure ToInt64() Method
IConvertible.ToInt16(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual int16 System.IConvertible.ToInt16(class System.IFormatProvider provider)
A
[C#]
B
short IConvertible.ToInt16(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt16.]
E F G
IConvertible.ToInt32(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual int32 System.IConvertible.ToInt32(class System.IFormatProvider provider)
J
[C#]
K
int IConvertible.ToInt32(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt32.]
N O P
IConvertible.ToInt64(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual int64 System.IConvertible.ToInt64(class System.IFormatProvider provider)
S
[C#]
T
long IConvertible.ToInt64(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt64.]
W X Y Z
2035
Contents | Index
Int16 Structure
System
ToSByte() Method
IConvertible.ToSByte(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual int8 System.IConvertible.ToSByte(class System.IFormatProvider provider)
B
[C#]
sbyte IConvertible.ToSByte(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSByte.]
F G H
IConvertible.ToSingle(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual float32 System.IConvertible.ToSingle(class System.IFormatProvider provider)
K
[C#]
float IConvertible.ToSingle(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSingle.]
O P Q
IConvertible.ToType(System.Type, System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual object System.IConvertible.ToType(class System.Type type, class System.IFormatProvider provider)
T
[C#]
object IConvertible.ToType(Type type, IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToType.]
X Y Z
2036
Contents | Index
System
Int16 Structure ToUInt64() Method
IConvertible.ToUInt16(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual unsigned int16 System.IConvertible.ToUInt16(class System.IFormatProvider provider)
A
[C#]
B
ushort IConvertible.ToUInt16(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt16.] This member is not CLS-compliant.
E F G
IConvertible.ToUInt32(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual unsigned int32 System.IConvertible.ToUInt32(class System.IFormatProvider provider)
J
[C#]
K
uint IConvertible.ToUInt32(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt32.] This member is not CLS-compliant.
N O P
IConvertible.ToUInt64(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual unsigned int64 System.IConvertible.ToUInt64(class System.IFormatProvider provider)
S
[C#]
T
ulong IConvertible.ToUInt64(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt64.] This member is not CLS-compliant.
W X Y Z
2037
Contents | Index
System Int32 Structure
BCL
Object
A
ValueType
B
Int32
C
IComparable IFormattable IConvertible
NotStandardized
D
Summary
E
Represents a 32-bit signed integer.
F
Type Summary
G
public struct Int32 : IComparable, IFormattable, IConvertible { // Fields public const int MaxValue = 2147483647; public const int MinValue = -2147483648;
H I J K
// Methods public int CompareTo (object value); public override bool Equals (object obj); public override int GetHashCode (); MS public TypeCode GetTypeCode (); public static int Parse (string s); public static int Parse (string s, NumberStyles style); public static int Parse (string s, NumberStyles style, IFormatProvider provider); public static int Parse (string s, IFormatProvider provider); public override string ToString (); public string ToString (string format); public string ToString (string format, IFormatProvider provider); public string ToString (IFormatProvider provider);
L M N O P Q R S T
// MS MS MS MS MS MS MS MS MS MS MS MS MS
U V W X Y Z
Explicit Interface Members bool IConvertible.ToBoolean(IFormatProvider provider); byte IConvertible.ToByte(IFormatProvider provider); char IConvertible.ToChar(IFormatProvider provider); DateTime IConvertible.ToDateTime(IFormatProvider provider); decimal IConvertible.ToDecimal(IFormatProvider provider); double IConvertible.ToDouble(IFormatProvider provider); short IConvertible.ToInt16(IFormatProvider provider); int IConvertible.ToInt32(IFormatProvider provider); long IConvertible.ToInt64(IFormatProvider provider); sbyte IConvertible.ToSByte(IFormatProvider provider); float IConvertible.ToSingle(IFormatProvider provider); object IConvertible.ToType(Type type,IFormatProvider provider); ushort IConvertible.ToUInt16(IFormatProvider provider);
2038
Contents | Index
System
Int32 Structure Int32 Structure
MS uint IConvertible.ToUInt32(IFormatProvider provider); MS ulong IConvertible.ToUInt64(IFormatProvider provider); }
A
BA We had lots of debate about the naming of the base types. Because of the multi-
B
ple programming language aspects of the platform many of the obvious names were ruled out as the languages differ in their meaning for names such as Integer (for example, 16 bits in VB, 32 bits in Java). So we decided to use names that are technically accurate and encourage language vendors to alias the names to their language’s types. For example, in C#, the keyword int is simply an alias for System.Int32. If you spend much time looking at raw IL you will recognize that the IL language designers decided to use byte count rather than bit count to represent the same values. So in IL the Int32 value is encoded as I4. This is an example of different parts of the system optimizing for their own customers. Luckily few folks using the library are forced to understand the IL representation, and vice versa.
C D E F G H I J
One of our guidelines for value types (structs) is that they be immutable so that they behave more like the built-in primitive types (Int32, Double, etc.). An object is immutable if it has no methods or properties that change the state of the object. Although it may be counterintuitive, integers are immutable. For example, consider an instance of the Int32 structure with the value five. That instance is always five and can not be changed. You can add one to it and you get a new instance, namely six, but the five-ness of the five remains. A given location in memory can be assigned one instance or another, but the value of those instances can never change.
K L M N O P Q
BG Note that the Parse method throws a FormatException when parsing a
R
string that is not a number. There is no predicate to determine whether a string can be parsed. In this particular case, checking to see whether a string can be parsed is a somewhat common operation and particularly expensive. Since there isn’t a significant additional cost to parsing a data type vs. telling whether a string iscan be parsed, and since most often when checking whether a data type can be parsed, you then want to parse the data type, we opted to not add a method like IsParsible(String). We added a TryParse method to Double for this purpose in the Microsoft CLR implementation and we intend to add TryParse to all the base data types in a future version.
S T U V W X
JR I have run into some developers who like the fact that on some C systems, int is
Y
a 32-bit value and on some other systems, int may be represented by a different number of bits. Personally, I don’t like this, and I think that this makes programming much
Z
continued
2039
Contents | Index
Int32 Structure
System
Int32 Structure
more difficult. Recompiling some C code for a different platform could give wildly different results. I applaud the BCL for giving the numeric types names indicating their bit width. There is no doubt that an Int32 will be a 32-bit integer on any and all CLI-compliant systems, giving me the confidence to know that my existing code should perform just fine when recompiled or re-JIT compiled.
A B C D
Description
E
The System.Int32 data type represents integer values ranging from negative 2,147,483,648 to positive 2,147,483,647; that is, hexadecimal 0x80000000 to 0x7FFFFFFF.
F G
Example
H
using System;
I namespace Samples { public class Int32Sample { public static void Main() { int max = int.MaxValue, min = int.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); Console.WriteLine("Is {0} equal to {1}: {2}", max, max, max.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", max, min, max.Equals(min)); Console.WriteLine("{0} has hashcode of: {1}", max, max.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", min, min.GetHashCode()); string s = max.ToString(); Console.WriteLine("\"{0}\" parsed from string yields: {1}", s, Int32.Parse(s)); s = min.ToString(); Console.WriteLine("\"{0}\" parsed from string yields: {1}", s, Int32.Parse(s)); string[] formats = {"c", "d", "e", "f", "g", "n", "p", "x" }; foreach(string f in formats) Console.WriteLine("{0}: {1}", max, max.ToString(f)); } } }
J K L M N O P Q R S T U V W X Y Z
2040
Contents | Index
System
Int32 Structure MaxValue Field
The output is MaxValue: 2147483647 MinValue: -2147483648 Is 2147483647 equal to 2147483647: True Is 2147483647 equal to -2147483648: False 2147483647 has hashcode of: 2147483647 -2147483648 has hashcode of: -2147483648 "2147483647" parsed from string yields: 2147483647 "-2147483648" parsed from string yields: -2147483648 2147483647: $2,147,483,647.00 2147483647: 2147483647 2147483647: 2.147484e+009 2147483647: 2147483647.00 2147483647: 2147483647 2147483647: 2,147,483,647.00 2147483647: 214,748,364,700.00 % 2147483647: 7fffffff
A B C D E F G H I J K
Int32.MaxValue Field
L
[ILASM]
.field public static literal int32 MaxValue
M
[C#]
N
public const int MaxValue = 2147483647
O
Summary
P
Contains the maximum value for the System.Int32 type.
Q R
Description
S
The value of this constant is 2,147,483,647 (hexadecimal 0x7FFFFFFF).
T
Example
U
using System;
V
namespace Samples { public class Int32MaxValue { public static void Main() { int max = int.MaxValue, min = int.MinValue;
W X Y Z
2041
Contents | Index
Int32 Structure
System
MinValue Field
Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); } }
A
}
B
The output is
C MaxValue: 2147483647 MinValue: -2147483648
D E F
Int32.MinValue Field
G [ILASM]
H
.field public static literal int32 MinValue [C#]
I
public const int MinValue = -2147483648
J
Summary
K
Contains the minimum value for the System.Int32 type.
L M
Description
N
The value of this constant is –2,147,483,648 (hexadecimal 0x80000000).
O
Example
P
using System;
Q
namespace Samples { public class Int32MinValue { public static void Main() { int max = int.MaxValue, min = int.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); } } }
R S T U V W X Y
The output is
Z
MaxValue: 2147483647 MinValue: -2147483648
2042
Contents | Index
System
Int32 Structure CompareTo() Method
Int32.CompareTo(System.Object) Method [ILASM]
.method public final hidebysig virtual int32 CompareTo(object value) [C#]
A
public int CompareTo(object value)
B C
Summary
D
Returns the sort order of the current instance compared to the specified System.Object.
E
Parameters
F G
Parameter
Description
value
The System.Object to compare to the current instance.
H I J
Return Value
K
A System.Int32 containing a value that reflects the sort order of the current instance as compared to value. The following table defines the conditions under which the return value is a negative number, zero, or a positive number.
L M N O
Return Value
Description
any negative number
Current instance < value.
Q
zero
Current instance == value.
R
any positive number
Current instance > value, or value is a null reference.
P
S T U
Description
V
[Note: This method is implemented to support the System.IComparable interface.]
W
Exceptions
X Y
Exception
Condition
System.ArgumentException
value is not a System.Int32 and is not a null reference.
Z
2043
Contents | Index
Int32 Structure
System
Equals() Method
Example using System; namespace Samples { public class Int32CompareTo { private static string CompareInt32s(int i1, int i2) { int i = i1.CompareTo(i2); if(0 == i) return String.Format("{0} is equal to {1}", i1, i2); if(i > 0) return String.Format("{0} is greater than {1}", i1, i2); else return String.Format("{0} is less than {1}", i1, i2); } public static void Main() { int max = int.MaxValue, min = int.MinValue; Console.WriteLine(CompareInt32s(min, min)); Console.WriteLine(CompareInt32s(max, min)); Console.WriteLine(CompareInt32s(min, max)); } } }
A B C D E F G H I J K L M N O P
The output is
Q -2147483648 is equal to -2147483648 2147483647 is greater than -2147483648 -2147483648 is less than 2147483647
R S T U
Int32.Equals(System.Object) Method
V
[ILASM]
.method public hidebysig virtual bool Equals(object obj)
W
[C#]
public override bool Equals(object obj)
X Y
Summary
Z
Determines whether the current instance and the specified System.Object represent the same type and value.
2044
Contents | Index
System
Int32 Structure Equals() Method
Parameters Parameter
Description
obj
The System.Object to compare to the current instance.
A B C
Return Value
D
true if obj represents the same type and value as the current instance. If obj is a null reference or is not an instance of System.Int32, returns false.
E F
Description
G
[Note: This method overrides System.Object.Equals.]
H I
Example
J
using System;
K namespace Samples { public class Int32Equals { public static void Main() { int max = int.MaxValue, min = int.MinValue; Console.WriteLine("Is {0} equal to {1}: {2}", max, max, max.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", max, min, max.Equals(min)); Console.WriteLine("Is {0} equal to {1}: {2}", min, max, min.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", min, min, min.Equals(min)); } } }
L M N O P Q R S T U V W
The output is Is Is Is Is
X Y
2147483647 equal to 2147483647: True 2147483647 equal to -2147483648: False -2147483648 equal to 2147483647: False -2147483648 equal to -2147483648: True
Z
2045
Contents | Index
Int32 Structure
System
GetHashCode() Method
Int32.GetHashCode() Method [ILASM]
.method public hidebysig virtual int32 GetHashCode()
A
[C#]
public override int GetHashCode()
B C
Summary
D
Generates a hash code for the current instance.
E F
Description
G
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
H I
Example
J
using System;
K
namespace Samples { public class Int32GetHashCode { public static void Main() { int max = int.MaxValue, zero = 0, min = int.MinValue; Console.WriteLine("{0} has hashcode of: {1}", max, max.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", zero, zero.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", min, min.GetHashCode()); } } }
L M N O P Q R S T U V
The output is
W X
2147483647 has hashcode of: 2147483647 0 has hashcode of: 0 -2147483648 has hashcode of: -2147483648
Y Z
2046
Contents | Index
System
Int32 Structure Parse() Method
Int32.GetTypeCode() Method [ILASM]
.method public final hidebysig virtual valuetype System.TypeCode GetTypeCode() [C#]
A
public TypeCode GetTypeCode()
B C
Summary
D
Returns the System.TypeCode for value type System.Int32.
E F
Int32.Parse(System.String) Method
G
[ILASM]
H
.method public hidebysig static int32 Parse(string s) [C#]
I
public static int Parse(string s)
J
Summary
K
Returns the specified System.String converted to a System.Int32 value.
L M
Parameters
N
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Integer style.
O P Q R
Description
S
This version of System.Int32.Parse is equivalent to System.Int32.Parse(s, System.Globalization.NumberStyles.Integer, null). The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.]
T U V W X Y Z
2047
Contents | Index
Int32 Structure
System
Parse() Method
Exceptions Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.Int32.MaxValue or less than System.Int32.MinValue.
A B C D E F G
Example
H
using System;
I namespace Samples { public class Int32Parse { public static void Main() { string s; try { s = Int32.MaxValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Int32.Parse(s)); s = "0"; Console.WriteLine("From String {0} yields {1}", s, Int32.Parse(s)); s = Int32.MinValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Int32.Parse(s)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Int32.Parse(s)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = ((Int64)Int32.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Int32.Parse(s));
J K L M N O P Q R S T U V W X Y Z
2048
Contents | Index
System
Int32 Structure Parse() Method
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A
}
B
}
C
}
D
The output is
E From String 2147483647 yields 2147483647 From String 0 yields 0 From String -2147483648 yields -2147483648 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s) at Samples.Int32Parse.Main() in C:\Books\BCL\Samples\System\Int32\ Parse(System.String)\Int32.cs:line 22 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s) at Samples.Int32Parse.Main() in C:\Books\BCL\Samples\System\Int32\ Parse(System.String)\Int32.cs:line 32
F G H I J K L M N O
Int32.Parse(System.String, System.Globalization.NumberStyles) Method
P
[ILASM]
Q
.method public hidebysig static int32 Parse(string s, valuetype System.Globalization.NumberStyles style)
R
[C#]
S
public static int Parse(string s, NumberStyles style)
T
Summary
U
Returns the specified System.String converted to a System.Int32 value.
V W X Y Z
2049
Contents | Index
Int32 Structure
System
Parse() Method
Parameters Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Integer style.
A B C D E F G
Description
H
This version of System.Int32.Parse is equivalent to System.Int32.Parse(s, style, null). The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.]
I J K L
Exceptions
M N O P Q R
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.Int32.MaxValue or less than System.Int32.MinValue.
S T
Example
U
using System; using System.Globalization;
V W
namespace Samples { public class Int32Parse { public static void Main() { string s; try
X Y Z
2050
Contents | Index
System
Int32 Structure Parse() Method
{ s = "$0"; Console.WriteLine("From String {0} yields {1}", s, Int32.Parse(s, NumberStyles.AllowCurrencySymbol)); s = String.Format("${0}", Int32.MaxValue.ToString()); Console.WriteLine("From String {0} yields {1}", s, Int32.Parse(s, NumberStyles.AllowCurrencySymbol)); s = String.Format("({0})", (Int32.MaxValue).ToString()); Console.WriteLine("From String {0} yields {1}", s, Int32.Parse(s, NumberStyles.AllowParentheses)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Int32.Parse(s, NumberStyles.Any));
A B C D E F G H I J K
} catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = ((Int64) Int32.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Int32.Parse(s, NumberStyles.Any)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
L M N O P Q R S T U V
} }
W
}
X
The output is
Y
From String $0 yields 0 From String $2147483647 yields 2147483647 From String (2147483647) yields -2147483647 Exception: System.FormatException: Input string was not in a correct format.
Z
2051
Contents | Index
Int32 Structure
System
Parse() Method
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s, NumberStyles style) at Samples.Int32Parse.Main() in C:\Books\BCL\Samples\System\Int32\ Parse(System.String,System.Globalization.NumberStyles)\Int32.cs:line 29 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s, NumberStyles style) at Samples.Int32Parse.Main() in C:\Books\BCL\Samples\System\Int32\ Parse(System.String,System.Globalization.NumberStyles)\Int32.cs:line 41
A B C D E F
Int32.Parse(System.String, System.Globalization.NumberStyles, System.IFormatProvider) Method
G H
[ILASM]
I
.method public hidebysig static int32 Parse(string s, valuetype System.Globalization.NumberStyles style, class System.IFormatProvider provider)
J
[C#]
public static int Parse(string s, NumberStyles style, IFormatProvider provider)
K L
Summary
M
Returns the specified System.String converted to a System.Int32 value.
N
Parameters
O P
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Integer style.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
Q R S T U V W X Y
Description
Z
The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If pro-
2052
Contents | Index
System
Int32 Structure Parse() Method
vider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. A
Exceptions
B
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.Int32.MaxValue or less than System.Int32.MinValue.
C D E F G H I
Example
J
using System; using System.Globalization;
K L
namespace Samples { public class Int32Parse { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; string s = " ~0"; Console.WriteLine("From String {0} yields {1}", s, Int32.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowLeadingSign, c)); s = "(1)"; Console.WriteLine("From String {0} yields {1}", s, Int32.Parse(s, NumberStyles.AllowParentheses, c)); s = " !1 "; Console.WriteLine("From String {0} yields {1}", s,
M N O P Q R S T U V W X Y Z
2053
Contents | Index
Int32 Structure
System
Parse() Method
Int32.Parse(s, NumberStyles.Any, c)); }
A
} }
B C
The output is
D From String ~0 yields 0 From String (1) yields -1 From String !1 yields -1
E F G H
Int32.Parse(System.String, System.IFormatProvider) Method
I
[ILASM]
J
.method public hidebysig static int32 Parse(string s, class System.IFormatProvider provider)
K
[C#]
public static int Parse(string s, IFormatProvider provider)
L M
Summary
N
Returns the specified System.String converted to a System.Int32 value.
O
Parameters
P Q R
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Integer style.
provider
A System.IFormatProvider that supplies a System.Globalization. NumberFormatInfo containing culture-specific formatting information about s.
S T U V
Description
W
This version of System.Int32.Parse is equivalent to System.Int32.Parse(s, System.Globalization.NumberStyles.Integer, provider). The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used.
X Y Z
2054
Contents | Index
System
Int32 Structure Parse() Method
Exceptions Exception
Condition A
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.Int32.MaxValue or less than System.Int32.MinValue.
B C D E F G
Example
H
using System; using System.Globalization; namespace Samples { public class Int32Parse { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; try { s = "~0"; Console.WriteLine("From String {0} yields s, Int32.Parse(s, c)); s = (Int32.MaxValue).ToString(); Console.WriteLine("From String {0} yields s, Int32.Parse(s, c)); s = "!1"; Console.WriteLine("From String {0} yields s, Int32.Parse(s, c)); s = String.Empty; Console.WriteLine("From String {0} yields s, Int32.Parse(s, c)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e);
I J K L M N O P Q R {1}",
S T
{1}",
U V
{1}",
W X
{1}",
Y Z
2055
Contents | Index
Int32 Structure
System
ToString() Method
} try { s = ((Int64)Int32.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, Int32.Parse(s, c)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E }
F
} }
G
The output is
H I
From String ~0 yields 0 From String 2147483647 yields 2147483647 From String !1 yields -1 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s, IFormatProvider provider) at Samples.Int32Parse.Main() in C:\Books\BCL\Samples\System\Int32\ Parse(System.String,System.IFormatProvider)\Int32.cs:line 27 Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s, IFormatProvider provider) at Samples.Int32Parse.Main() in C:\Books\BCL\Samples\System\Int32\ Parse(System.String,System.IFormatProvider)\Int32.cs:line 37
J K L M N O P Q R S
Int32.ToString() Method
T [ILASM]
U
.method public hidebysig virtual string ToString()
V
[C#]
public override string ToString()
W X
Summary
Y
Returns a System.String representation of the value of the current instance.
Z
2056
Contents | Index
System
Int32 Structure ToString() Method
Return Value A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the current system culture. A
Description
B
This version of System.Int32.ToString is equivalent to System.Int32.ToString (null, null). [Note: This method overrides System.Object.ToString.]
C D E
Example
F
using System;
G
namespace Samples { public class Int32ToString { public static void Main() { int max = int.MaxValue, min = int.MinValue; Console.WriteLine("{0}.ToString() yields {1}", max, max.ToString()); Console.WriteLine("{0}.ToString() yields {1}", min, min.ToString()); } } }
H I J K L M N O P Q
The output is
R S
2147483647.ToString() yields 2147483647 -2147483648.ToString() yields -2147483648
T U
Int32.ToString(System.String) Method
V
[ILASM]
W
.method public hidebysig instance string ToString(string format)
X
[C#]
public string ToString(string format)
Y
Summary
Z
Returns a System.String representation of the value of the current instance.
2057
Contents | Index
Int32 Structure
System
ToString() Method
Parameters Parameter
Description
format
A System.String that specifies the format of the returned string. [Note: For a list of valid values, see System.Int32.ToString(System.String, System.IFormatProvider).]
A B C D E
Return Value
F
A System.String representation of the current instance formatted as specified by format. The string takes into account the current system culture.
G H
Description
I
This method is equivalent to System.Int32.ToString(format, null). If format is a null reference, the general format specifier “G” is used.
J K
Exceptions
L M N
Exception
Condition
System.FormatException
format is invalid.
O P
Example
Q
using System;
R
namespace Samples { public class Int32ToString { public static void Main() { int max = int.MaxValue, min = int.MinValue; string[] formats = {"C", "c", "D", "d", "E", "e", "F", "f", "G", "g", "N", "n", "P", "p", "X", "x"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\") yields {2}", max, f, max.ToString(f)); foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\") yields {2}",
S T U V W X Y Z
2058
Contents | Index
System
Int32 Structure ToString() Method
min, f, min.ToString(f)); } } }
A
The output is
B C
2147483647.ToString("C") yields $2,147,483,647.00 2147483647.ToString("c") yields $2,147,483,647.00 2147483647.ToString("D") yields 2147483647 2147483647.ToString("d") yields 2147483647 2147483647.ToString("E") yields 2.147484E+009 2147483647.ToString("e") yields 2.147484e+009 2147483647.ToString("F") yields 2147483647.00 2147483647.ToString("f") yields 2147483647.00 2147483647.ToString("G") yields 2147483647 2147483647.ToString("g") yields 2147483647 2147483647.ToString("N") yields 2,147,483,647.00 2147483647.ToString("n") yields 2,147,483,647.00 2147483647.ToString("P") yields 214,748,364,700.00 % 2147483647.ToString("p") yields 214,748,364,700.00 % 2147483647.ToString("X") yields 7FFFFFFF 2147483647.ToString("x") yields 7fffffff -2147483648.ToString("C") yields -$2,147,483,648.00 -2147483648.ToString("c") yields -$2,147,483,648.00 -2147483648.ToString("D") yields -2147483648 -2147483648.ToString("d") yields -2147483648 -2147483648.ToString("E") yields -2.147484E+009 -2147483648.ToString("e") yields -2.147484e+009 -2147483648.ToString("F") yields -2147483648.00 -2147483648.ToString("f") yields -2147483648.00 -2147483648.ToString("G") yields -2147483648 -2147483648.ToString("g") yields -2147483648 -2147483648.ToString("N") yields -2,147,483,648.00 -2147483648.ToString("n") yields -2,147,483,648.00 -2147483648.ToString("P") yields -214,748,364,800.00 % -2147483648.ToString("p") yields -214,748,364,800.00 % -2147483648.ToString("X") yields 80000000 -2147483648.ToString("x") yields 80000000
D E F G H I J K L M N O P Q R S T U V W
Int32.ToString(System.String, System.IFormatProvider) Method
X
[ILASM]
Y
.method public final hidebysig virtual string ToString(string format, class System.IFormatProvider provider)
Z
[C#]
public string ToString(string format, IFormatProvider provider)
2059
Contents | Index
Int32 Structure
System
ToString() Method
Summary Returns a System.String representation of the value of the current instance. A
Parameters
B C D
Parameter
Description
format
A System.String containing a character that specifies the format of the returned string.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo instance containing culture-specific formatting information.
E F G H I
Return Value
J
A System.String representation of the current instance formatted as specified by format. The string takes into account the formatting information in the System.Globalization.NumberFormatInfo instance supplied by provider.
K L M
Description
N
If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. If format is a null reference, the general format specifier “G” is used. [Note: For a detailed description of formatting, see the System.IFormattable interface. This method is implemented to support the System.IFormattable interface.] The following table lists the characters that are valid for the System.Int32 type.
O P Q R S T U V
Item
Description
"C", "c"
Currency format.
"D", "d"
Decimal format.
"E", "e"
Exponential notation format.
"F", "f"
Fixed-point format.
"G", "g"
General format.
"N", "n"
Number format.
W X Y Z
2060
Contents | Index
System
Int32 Structure ToString() Method
Item
Description
"P", "p"
Percent format.
A
"X", "x"
Hexadecimal format.
B C D
Exceptions
E
Exception
Condition
System.FormatException
format is invalid.
F G H
Example
I
using System; using System.Globalization;
J K
namespace Samples { public class Int32ToString { public static void Main() { int max = int.MaxValue, min = int.MinValue; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; n.CurrencySymbol = "#"; string[] formats = {"C", "c", "D", "d", "E", "e", "F", "f", "G", "g", "N", "n", "P", "p", "X", "x"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\",n) yields {2}", max, f, max.ToString(f, n)); foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\",n) yields {2}", min, f, min.ToString(f, n)); } } }
L M N O P Q R S T U V W X Y Z
2061
Contents | Index
Int32 Structure
System
ToString() Method
The output is 2147483647.ToString("C",n) yields #2,147,483,647.00 2147483647.ToString("c",n) yields #2,147,483,647.00 2147483647.ToString("D",n) yields 2147483647 2147483647.ToString("d",n) yields 2147483647 2147483647.ToString("E",n) yields 2.147484E~009 2147483647.ToString("e",n) yields 2.147484e~009 2147483647.ToString("F",n) yields 2147483647.00 2147483647.ToString("f",n) yields 2147483647.00 2147483647.ToString("G",n) yields 2147483647 2147483647.ToString("g",n) yields 2147483647 2147483647.ToString("N",n) yields 2,147,483,647.00 2147483647.ToString("n",n) yields 2,147,483,647.00 2147483647.ToString("P",n) yields 214,748,364,700.00 % 2147483647.ToString("p",n) yields 214,748,364,700.00 % 2147483647.ToString("X",n) yields 7FFFFFFF 2147483647.ToString("x",n) yields 7fffffff -2147483648.ToString("C",n) yields !#2,147,483,648.00 -2147483648.ToString("c",n) yields !#2,147,483,648.00 -2147483648.ToString("D",n) yields !2147483648 -2147483648.ToString("d",n) yields !2147483648 -2147483648.ToString("E",n) yields !2.147484E~009 -2147483648.ToString("e",n) yields !2.147484e~009 -2147483648.ToString("F",n) yields !2147483648.00 -2147483648.ToString("f",n) yields !2147483648.00 -2147483648.ToString("G",n) yields !2147483648 -2147483648.ToString("g",n) yields !2147483648 -2147483648.ToString("N",n) yields !2,147,483,648.00 -2147483648.ToString("n",n) yields !2,147,483,648.00 -2147483648.ToString("P",n) yields !214,748,364,800.00 % -2147483648.ToString("p",n) yields !214,748,364,800.00 % -2147483648.ToString("X",n) yields 80000000 -2147483648.ToString("x",n) yields 80000000
A B C D E F G H I J K L M N O P Q R S T U
Int32.ToString(System.IFormatProvider) Method
V [ILASM]
W
.method public final hidebysig virtual string ToString(class System.IFormatProvider provider)
X
[C#]
public string ToString(IFormatProvider provider)
Y Z
Summary Returns a System.String representation of the value of the current instance.
2062
Contents | Index
System
Int32 Structure ToString() Method
Parameters Parameter
Description
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
A B C D
Return Value
E
A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the formatting information in the System.Globalization.NumberFormatInfo instance supplied by provider.
F G H
Description
I
This version of System.Int32.ToString is equivalent to System.Int32.ToString(“G”, provider). If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used.
J K L
Example
M
using System; using System.Globalization;
N O
namespace Samples { public class Int32ToString { public static void Main() { int max = int.MaxValue, min = int.MinValue; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; Console.WriteLine("{0}.ToString yields {1}", max, max.ToString(n)); Console.WriteLine("{0}.ToString yields {1}", min, min.ToString(n)); } } }
P Q R S T U V W X Y Z
2063
Contents | Index
Int32 Structure
System
ToBoolean() Method
The output is 2147483647.ToString yields 2147483647 -2147483648.ToString yields !2147483648
A B C
IConvertible.ToBoolean(System.IFormatProvider) Method
D
[ILASM]
E
.method private final hidebysig virtual bool System.IConvertible.ToBoolean(class System.IFormatProvider provider)
F
[C#]
bool IConvertible.ToBoolean(IFormatProvider provider)
G H
Summary
I
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToBoolean.]
J K L
IConvertible.ToByte(System.IFormatProvider) Method
M
[ILASM]
N
.method private final hidebysig virtual unsigned int8 System.IConvertible.ToByte(class System.IFormatProvider provider)
O
[C#]
byte IConvertible.ToByte(IFormatProvider provider)
P Q
Summary
R
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToByte.]
S T U
IConvertible.ToChar(System.IFormatProvider) Method
V
[ILASM]
W
.method private final hidebysig virtual valuetype System.Char System.IConvertible.ToChar(class System.IFormatProvider provider)
X
[C#]
char IConvertible.ToChar(IFormatProvider provider)
Y
Summary
Z
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToChar.] 2064
Contents | Index
System
Int32 Structure ToDouble() Method
IConvertible.ToDateTime(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual valuetype System.DateTime System.IConvertible.ToDateTime(class System.IFormatProvider provider)
A
[C#]
B
DateTime IConvertible.ToDateTime(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDateTime.]
E F G
IConvertible.ToDecimal(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual decimal System.IConvertible.ToDecimal(class System.IFormatProvider provider)
J
[C#]
K
decimal IConvertible.ToDecimal(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDecimal.]
N O P
IConvertible.ToDouble(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual float64 System.IConvertible.ToDouble(class System.IFormatProvider provider)
S
[C#]
T
double IConvertible.ToDouble(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDouble.]
W X Y Z
2065
Contents | Index
Int32 Structure
System
ToInt16() Method
IConvertible.ToInt16(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual int16 System.IConvertible.ToInt16(class System.IFormatProvider provider)
B
[C#]
short IConvertible.ToInt16(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt16.]
F G H
IConvertible.ToInt32(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual int32 System.IConvertible.ToInt32(class System.IFormatProvider provider)
K
[C#]
int IConvertible.ToInt32(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt32.]
O P Q
IConvertible.ToInt64(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual int64 System.IConvertible.ToInt64(class System.IFormatProvider provider)
T
[C#]
long IConvertible.ToInt64(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt64.]
X Y Z
2066
Contents | Index
System
Int32 Structure ToType() Method
IConvertible.ToSByte(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual int8 System.IConvertible.ToSByte(class System.IFormatProvider provider)
A
[C#]
B
sbyte IConvertible.ToSByte(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSByte.]
E F G
IConvertible.ToSingle(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual float32 System.IConvertible.ToSingle(class System.IFormatProvider provider)
J
[C#]
K
float IConvertible.ToSingle(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSingle.]
N O P
IConvertible.ToType(System.Type, System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual object System.IConvertible.ToType(class System.Type type, class System.IFormatProvider provider)
S
[C#]
T
object IConvertible.ToType(Type type, IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToType.]
W X Y Z
2067
Contents | Index
Int32 Structure
System
ToUInt16() Method
IConvertible.ToUInt16(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual unsigned int16 System.IConvertible.ToUInt16(class System.IFormatProvider provider)
B
[C#]
ushort IConvertible.ToUInt16(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt16.] This member is not CLS-compliant.
F G H
IConvertible.ToUInt32(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual unsigned int32 System.IConvertible.ToUInt32(class System.IFormatProvider provider)
K
[C#]
uint IConvertible.ToUInt32(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt32.] This member is not CLS-compliant.
O P Q
IConvertible.ToUInt64(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual unsigned int64 System.IConvertible.ToUInt64(class System.IFormatProvider provider)
T
[C#]
ulong IConvertible.ToUInt64(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt64.] This member is not CLS-compliant.
X Y Z
2068
Contents | Index
System Int64 Structure
BCL
Object ValueType Int64
A
IComparable
B
IFormattable IConvertible
NotStandardized
C D
Summary
E
Represents a 64-bit signed integer.
F G
Type Summary public struct Int64 : IComparable, IFormattable, IConvertible { // Fields public const long MaxValue = 9223372036854775807; public const long MinValue = -9223372036854775808;
H I J K L
// Methods public int CompareTo (object value); public override bool Equals (object obj); public override int GetHashCode (); MS public TypeCode GetTypeCode (); public static long Parse (string s); public static long Parse (string s, NumberStyles style); public static long Parse (string s, NumberStyles style, IFormatProvider provider); CF public static long Parse (string s, IFormatProvider provider); public override string ToString (); public string ToString (string format); public string ToString (string format, IFormatProvider provider); public string ToString (IFormatProvider provider); // MS MS MS MS MS MS MS MS MS MS MS
M N O P Q R S T U
Explicit Interface Members bool IConvertible.ToBoolean(IFormatProvider provider); byte IConvertible.ToByte(IFormatProvider provider); char IConvertible.ToChar(IFormatProvider provider); DateTime IConvertible.ToDateTime(IFormatProvider provider); decimal IConvertible.ToDecimal(IFormatProvider provider); double IConvertible.ToDouble(IFormatProvider provider); short IConvertible.ToInt16(IFormatProvider provider); int IConvertible.ToInt32(IFormatProvider provider); long IConvertible.ToInt64(IFormatProvider provider); sbyte IConvertible.ToSByte(IFormatProvider provider); float IConvertible.ToSingle(IFormatProvider provider);
V W X Y Z
2069
Contents | Index
Int64 Structure
System
Int64 Structure
MS MS MS MS
A
object IConvertible.ToType(Type type,IFormatProvider provider); ushort IConvertible.ToUInt16(IFormatProvider provider); uint IConvertible.ToUInt32(IFormatProvider provider); ulong IConvertible.ToUInt64(IFormatProvider provider);
}
B
Description
C
The System.Int64 data type represents integer values ranging from negative 9,223,372,036,854,775,808 to positive 9,223,372,036,854,775,807; that is, hexadecimal 0x8000000000000000 to 0x7FFFFFFFFFFFFFFF.
D E F
Example
G
using System;
H namespace Samples { public class Int64Sample { public static void Main() { long max = long.MaxValue, min = long.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); Console.WriteLine("Is {0} equal to {1}: {2}", max, max, max.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", max, min, max.Equals(min)); Console.WriteLine("{0} has hashcode of: {1}", max, max.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", min, min.GetHashCode()); string s = max.ToString(); Console.WriteLine("\"{0}\" parsed from string yields: {1}", s, Int64.Parse(s)); s = min.ToString(); Console.WriteLine("\"{0}\" parsed from string yields: {1}", s, Int64.Parse(s)); string[] formats = {"c", "d", "e", "f", "g", "n", "p", "x" }; foreach(string f in formats) Console.WriteLine("{0}: {1}", max, max.ToString(f)); } } }
I J K L M N O P Q R S T U V W X Y Z
2070
Contents | Index
System
Int64 Structure MaxValue Field
The output is MaxValue: 9223372036854775807 MinValue: -9223372036854775808 Is 9223372036854775807 equal to 9223372036854775807: True Is 9223372036854775807 equal to -9223372036854775808: False 9223372036854775807 has hashcode of: -2147483648 -9223372036854775808 has hashcode of: -2147483648 "9223372036854775807" parsed from string yields: 9223372036854775807 "-9223372036854775808" parsed from string yields: -9223372036854775808 9223372036854775807: $9,223,372,036,854,775,807.00 9223372036854775807: 9223372036854775807 9223372036854775807: 9.223372e+018 9223372036854775807: 9223372036854775807.00 9223372036854775807: 9223372036854775807 9223372036854775807: 9,223,372,036,854,775,807.00 9223372036854775807: 922,337,203,685,477,580,700.00 % 9223372036854775807: 7fffffffffffffff
A B C D E F G H I J K
Int64.MaxValue Field
L
[ILASM]
.field public static literal int64 MaxValue
M
[C#]
N
public const long MaxValue = 9223372036854775807
O
Summary
P
Contains the maximum value for the System.Int64 type.
Q R
Description
S
The value of this constant is 9,223,372,036,854,775,807 (hexadecimal 0x7FFFFFFFFFFFFFFF).
T
Example
U
using System;
V
namespace Samples { public class Int64MaxValue { public static void Main() { long max = long.MaxValue, min = long.MinValue;
W X Y Z
2071
Contents | Index
Int64 Structure
System
MinValue Field
Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); } }
A
}
B
The output is
C
MaxValue: 9223372036854775807 MinValue: -9223372036854775808
D E F
Int64.MinValue Field
G H
[ILASM]
I
[C#]
.field public static literal int64 MinValue public const long MinValue = -9223372036854775808
J K
Summary
L
Contains the minimum value for the System.Int64 type.
M
Description
N
The value of this constant is –9,223,372,036,854,775,808 (hexadecimal 0x8000000000000000).
O P
Example
Q
using System;
R
namespace Samples { public class Int64MinValue { public static void Main() { long max = long.MaxValue, min = long.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); } } }
S T U V W X Y Z
2072
Contents | Index
System
Int64 Structure CompareTo() Method
The output is MaxValue: 9223372036854775807 MinValue: -9223372036854775808
A B
Int64.CompareTo(System.Object) Method
C
[ILASM]
D
.method public final hidebysig virtual int32 CompareTo(object value)
E
[C#]
public int CompareTo(object value)
F G
Summary
H
Returns the sort order of the current instance compared to the specified System.Object.
I
Parameters Parameter
J K
Description
L
value
The System.Object to compare to the current instance.
M N
Return Value
O
A System.Int32 containing a value that reflects the sort order of the current instance as compared to value. The following table defines the conditions under which the return value is a negative number, zero, or a positive number.
P Q R S
Return Value
Description
any negative number
Current instance < value.
U
zero
Current instance == value.
V
any positive number
Current instance > value, or value is a null reference.
T
W X Y
Description
Z
[Note: This method is implemented to support the System.IComparable interface.]
2073
Contents | Index
Int64 Structure
System
Equals() Method
Exceptions Exception
Condition
System.ArgumentException
value is not a System.Int64 and is not a null reference.
A B C
Example
D
using System;
E namespace Samples { public class Int64CompareTo { private static string CompareInt64s(long l1, long l2) { int i = l1.CompareTo(l2); if(0 == i) return String.Format("{0} is equal to {1}", l1, l2); if(i > 0) return String.Format("{0} is greater than {1}", l1, l2); else return String.Format("{0} is less than {1}", l1, l2); } public static void Main() { long max = long.MaxValue, min = long.MinValue; Console.WriteLine(CompareInt64s(min, min)); Console.WriteLine(CompareInt64s(max, min)); Console.WriteLine(CompareInt64s(min, max)); } } }
F G H I J K L M N O P Q R S T
The output is
U -9223372036854775808 is equal to -9223372036854775808 9223372036854775807 is greater than -9223372036854775808 -9223372036854775808 is less than 9223372036854775807
V W X
Int64.Equals(System.Object) Method
Y
[ILASM]
Z
.method public hidebysig virtual bool Equals(object obj) [C#]
public override bool Equals(object obj)
2074
Contents | Index
System
Int64 Structure Equals() Method
Summary Determines whether the current instance and the specified System.Object represent the same type and value. A
Parameters
B C
Parameter
Description
obj
The System.Object to compare to the current instance.
D E F
Return Value
G
true if obj represents the same type and value as the current instance. If obj is a null reference or is not an instance of System.Int64, returns false.
H
Description
J
[Note: This method overrides System.Object.Equals.]
K
I
L
Example
M
using System;
N namespace Samples { public class Int64Equals { public static void Main() { long max = long.MaxValue, min = long.MinValue; Console.WriteLine("Is {0} equal to {1}: {2}", max, max, max.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", max, min, max.Equals(min)); Console.WriteLine("Is {0} equal to {1}: {2}", min, max, min.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", min, min, min.Equals(min)); } } }
O P Q R S T U V W X Y Z
2075
Contents | Index
Int64 Structure
System
GetHashCode() Method
The output is Is Is Is Is
A B
9223372036854775807 equal to 9223372036854775807: True 9223372036854775807 equal to -9223372036854775808: False -9223372036854775808 equal to 9223372036854775807: False -9223372036854775808 equal to -9223372036854775808: True
C D
Int64.GetHashCode() Method
E
[ILASM]
.method public hidebysig virtual int32 GetHashCode()
F
[C#]
G
public override int GetHashCode()
H
Summary
I
Generates a hash code for the current instance.
J K
Description
L
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
M N
Example
O
using System;
P
namespace Samples { public class Int64GetHashCode { public static void Main() { long max = long.MaxValue, zero = 0, min = long.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); Console.WriteLine("{0} has hashcode of: {1}", max, max.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", zero, zero.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", min, min.GetHashCode()); } } }
Q R S T U V W X Y Z
2076
Contents | Index
System
Int64 Structure Parse() Method
The output is MaxValue: 9223372036854775807 MinValue: -9223372036854775808 9223372036854775807 has hashcode of: -2147483648 0 has hashcode of: 0 -9223372036854775808 has hashcode of: -2147483648
A B C D
Int64.GetTypeCode() Method
E
[ILASM]
.method public final hidebysig virtual valuetype System.TypeCode GetTypeCode()
F
[C#]
G
public TypeCode GetTypeCode()
H
Summary
I
Returns the System.TypeCode for value type System.Int64.
J K
Int64.Parse(System.String) Method
L
[ILASM]
M
.method public hidebysig static int64 Parse(string s)
N
[C#]
public static long Parse(string s)
O P
Summary
Q
Returns the specified System.String converted to a System.Int64 value.
R
Parameters
S
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Integer style.
T U V W X
Description
Y
This version of System.Int64.Parse is equivalent to System.Int64.Parse(s, System.Globalization.NumberStyles.Integer, null).
Z
2077
Contents | Index
Int64 Structure
System
Parse() Method
The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.] A
Exceptions
B C
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.Int64.MaxValue or less than System.Int64.MinValue.
D E F G H I J
Example
K
using System;
L namespace Samples { public class Int64Parse { public static void Main() { string s; try { s = Int64.MaxValue.ToString(); Console.WriteLine("From String {0} yields s, Int64.Parse(s)); s = "0"; Console.WriteLine("From String {0} yields s, Int64.Parse(s)); s = (Int64.MinValue).ToString(); Console.WriteLine("From String {0} yields s, Int64.Parse(s)); s = String.Empty; Console.WriteLine("From String {0} yields s, Int64.Parse(s)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e);
M N O P Q R S T U V W X Y Z
{1}",
{1}",
{1}",
{1}",
2078
Contents | Index
System
Int64 Structure Parse() Method
} try { s = String.Format("{0}1", Int64.MaxValue); Console.WriteLine("From String {0} yields {1}", s, Int64.Parse(s)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E
}
F
} }
G
The output is
H I
From String 9223372036854775807 yields 9223372036854775807 From String 0 yields 0 From String -9223372036854775808 yields -9223372036854775808 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt64(String s, NumberStyles style, NumberFormatInfo info) at System.Int64.Parse(String s) at Samples.Int64Parse.Main() in C:\Books\BCL\Samples\System\Int64\ Parse(System.String)\Int64.cs:line 22 Exception: System.OverflowException: Value was either too large or too small for an Int64. at System.Number.ParseInt64(String s, NumberStyles style, NumberFormatInfo info) at System.Int64.Parse(String s) at Samples.Int64Parse.Main() in C:\Books\BCL\Samples\System\Int64\ Parse(System.String)\Int64.cs:line 32
J K L M N O P Q R S
Int64.Parse(System.String, System.Globalization.NumberStyles) Method
T [ILASM]
U
.method public hidebysig static int64 Parse(string s, valuetype System.Globalization.NumberStyles style)
V
[C#]
W
public static long Parse(string s, NumberStyles style)
X
Summary
Y
Returns the specified System.String converted to a System.Int64 value.
Z
2079
Contents | Index
Int64 Structure
System
Parse() Method
Parameters Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Integer style.
A B C D E F G
Description
H
This version of System.Int64.Parse is equivalent to System.Int64.Parse(s, style, null). The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.]
I J K L
Exceptions
M N
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.Int64.MaxValue or less than System.Int64.MinValue.
O P Q R S T U
Example
V
using System; using System.Globalization;
W X
namespace Samples { public class Int64Parse { public static void Main() { string s;
Y Z
2080
Contents | Index
System
Int64 Structure Parse() Method
try { s = "$0"; Console.WriteLine("From String {0} yields {1}", s, Int64.Parse(s, NumberStyles.AllowCurrencySymbol)); s = String.Format("${0}", Int64.MaxValue.ToString()); Console.WriteLine("From String {0} yields {1}", s, Int64.Parse(s, NumberStyles.AllowCurrencySymbol)); s = String.Format("({0})", Int64.MaxValue.ToString()); Console.WriteLine("From String {0} yields {1}", s, Int64.Parse(s, NumberStyles.AllowParentheses)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Int64.Parse(s, NumberStyles.Any)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = String.Format("{0}1", Int64.MaxValue); Console.WriteLine("From String {0} yields {1}", s, Int64.Parse(s, NumberStyles.Any)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E F G H I J K L M N O P Q R S T U V
}
W
} }
X Y
The output is
Z From String $0 yields 0 From String $9223372036854775807 yields 9223372036854775807 From String (9223372036854775807) yields -9223372036854775807
2081
Contents | Index
Int64 Structure
System
Parse() Method
Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt64(String s, NumberStyles style, NumberFormatInfo info) at System.Int64.Parse(String s, NumberStyles style) at Samples.Int64Parse.Main() in C:\Books\BCL\Samples\System\Int64\ Parse(System.String,System.Globalization.NumberStyles)\Int64.cs:line 29 Exception: System.OverflowException: Value was either too large or too small for an Int64. at System.Number.ParseInt64(String s, NumberStyles style, NumberFormatInfo info) at System.Int64.Parse(String s, NumberStyles style) at Samples.Int64Parse.Main() in C:\Books\BCL\Samples\System\Int64\ Parse(System.String,System.Globalization.NumberStyles)\Int64.cs:line 41
A B C D E F G H
Int64.Parse(System.String, System.Globalization.NumberStyles, System.IFormatProvider) Method
I
[ILASM]
J
.method public hidebysig static int64 Parse(string s, valuetype System.Globalization.NumberStyles style, class System.IFormatProvider provider)
K
[C#]
public static long Parse(string s, NumberStyles style, IFormatProvider provider)
L M
Summary
N
Returns the specified System.String converted to a System.Int64 value.
O
Parameters
P Q
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Integer style.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
R S T U V W X Y Z
2082
Contents | Index
System
Int64 Structure Parse() Method
Description The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used.
A B C
Exceptions
D
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.Int64.MaxValue or less than System.Int64.MinValue.
E F G H I J K
Example
L
using System; using System.Globalization;
M N
namespace Samples { public class Int64Parse { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; string s = " ~0"; Console.WriteLine("From String {0} yields {1}", s, Int64.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowLeadingSign, c)); s = "(1)"; Console.WriteLine("From String {0} yields {1}", s, Int64.Parse(s, NumberStyles.AllowParentheses, c));
O P Q R S T U V W X Y Z
2083
Contents | Index
Int64 Structure
System
Parse() Method
s = " !1 "; Console.WriteLine("From String {0} yields {1}", s, Int64.Parse(s, NumberStyles.Any, c));
A B }
C
} }
D
The output is
E F
From String ~0 yields 0 From String (1) yields -1 From String !1 yields -1
G H I
Int64.Parse(System.String, System.IFormatProvider) Method
J
[ILASM]
K
.method public hidebysig static int64 Parse(string s, class System.IFormatProvider provider)
L
[C#]
M
public static long Parse(string s, IFormatProvider provider)
N
Summary
O
Returns the specified System.String converted to a System.Int64 value.
P Q
Parameters
R S T
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Integer style.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
U V W X Y
Description
Z
This version of System.Int64.Parse is equivalent to System.Int64.Parse(s, System.Globalization.NumberStyles.Integer, provider).
2084
Contents | Index
System
Int64 Structure Parse() Method
The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used.
A B
Exceptions
C
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.Int64.MaxValue or less than System.Int64.MinValue.
D E F G H I J
Example
K
using System; using System.Globalization;
L M
namespace Samples { public class Int64Parse { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; try { s = "~0"; Console.WriteLine("From String {0} yields {1}", s, Int64.Parse(s, c)); s = (Int64.MaxValue).ToString(); Console.WriteLine("From String {0} yields {1}", s, Int64.Parse(s, c)); s = "!1"; Console.WriteLine("From String {0} yields {1}", s, Int64.Parse(s, c)); s = String.Empty;
N O P Q R S T U V W X Y Z
2085
Contents | Index
Int64 Structure
System
ToString() Method
Console.WriteLine("From String {0} yields {1}", s, Int64.Parse(s, c)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = String.Format("{0}1", Int64.MaxValue); Console.WriteLine("From String {0} yields {1}", s, Int64.Parse(s, c)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E F G H I
} }
J }
K
The output is
L M
From String ~0 yields 0 From String 9223372036854775807 yields 9223372036854775807 From String !1 yields -1 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt64(String s, NumberStyles style, NumberFormatInfo info) at System.Int64.Parse(String s, IFormatProvider provider) at Samples.Int64Parse.Main() in C:\Books\BCL\Samples\System\Int64\ Parse(System.String,System.IFormatProvider)\Int64.cs:line 27 Exception: System.OverflowException: Value was either too large or too small for an Int64. at System.Number.ParseInt64(String s, NumberStyles style, NumberFormatInfo info) at System.Int64.Parse(String s, IFormatProvider provider) at Samples.Int64Parse.Main() in C:\Books\BCL\Samples\System\Int64\ Parse(System.String,System.IFormatProvider)\Int64.cs:line 37
N O P Q R S T U V W
Int64.ToString() Method
X
[ILASM]
Y
.method public hidebysig virtual string ToString() [C#]
Z
public override string ToString()
2086
Contents | Index
System
Int64 Structure ToString() Method
Summary Returns a System.String representation of the value of the current instance.
Return Value
A
A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the current system culture.
B C D
Description
E
This version of System.Int64.ToString is equivalent to System.Int64.ToString(null, null). [Note: This method overrides System.Object.ToString.]
F G H
Example
I
using System;
J
namespace Samples { public class Int64ToString { public static void Main() { long max = long.MaxValue, min = long.MinValue; Console.WriteLine("{0}.ToString() yields {1}", max, max.ToString()); Console.WriteLine("{0}.ToString() yields {1}", min, min.ToString()); } } }
K L M N O P Q R S T
The output is
U 9223372036854775807.ToString() yields 9223372036854775807 -9223372036854775808.ToString() yields -9223372036854775808
V W X
Int64.ToString(System.String) Method
Y [ILASM]
Z
.method public hidebysig instance string ToString(string format) [C#]
public string ToString(string format)
2087
Contents | Index
Int64 Structure
System
ToString() Method
Summary Returns a System.String representation of the value of the current instance. A
Parameters
B C
Parameter
Description
format
A System.String that specifies the format of the returned string. [Note: For a list of valid values, see System.Int64.ToString(System.String, System.IFormatProvider).]
D E F G
Return Value
H
A System.String representation of the current instance formatted as specified by format. The string takes into account the current system culture.
I J
Description
K
This method is equivalent to System.Int64.ToString(format, null). If format is a null reference, the general format specifier “G” is used.
L M
Exceptions
N O P
Exception
Condition
System.FormatException
format is invalid.
Q R
Example
S
using System;
T namespace Samples { public class Int64ToString { public static void Main() { long max = long.MaxValue, min = long.MinValue; string[] formats = {"C", "c", "D", "d", "E", "e", "F", "f", "G", "g", "N", "n", "P", "p", "X", "x"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\") yields {2}",
U V W X Y Z
2088
Contents | Index
System
Int64 Structure ToString() Method
max, f, max.ToString(f)); foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\") yields {2}", min, f, min.ToString(f));
A
} }
B
}
C
The output is
D E
9223372036854775807.ToString("C") yields $9,223,372,036,854,775,807.00 9223372036854775807.ToString("c") yields $9,223,372,036,854,775,807.00 9223372036854775807.ToString("D") yields 9223372036854775807 9223372036854775807.ToString("d") yields 9223372036854775807 9223372036854775807.ToString("E") yields 9.223372E+018 9223372036854775807.ToString("e") yields 9.223372e+018 9223372036854775807.ToString("F") yields 9223372036854775807.00 9223372036854775807.ToString("f") yields 9223372036854775807.00 9223372036854775807.ToString("G") yields 9223372036854775807 9223372036854775807.ToString("g") yields 9223372036854775807 9223372036854775807.ToString("N") yields 9,223,372,036,854,775,807.00 9223372036854775807.ToString("n") yields 9,223,372,036,854,775,807.00 9223372036854775807.ToString("P") yields 922,337,203,685,477,580,700.00 % 9223372036854775807.ToString("p") yields 922,337,203,685,477,580,700.00 % 9223372036854775807.ToString("X") yields 7FFFFFFFFFFFFFFF 9223372036854775807.ToString("x") yields 7fffffffffffffff -9223372036854775808.ToString("C") yields -$9,223,372,036,854,775,808.00 -9223372036854775808.ToString("c") yields -$9,223,372,036,854,775,808.00 -9223372036854775808.ToString("D") yields -9223372036854775808 -9223372036854775808.ToString("d") yields -9223372036854775808 -9223372036854775808.ToString("E") yields -9.223372E+018 -9223372036854775808.ToString("e") yields -9.223372e+018 -9223372036854775808.ToString("F") yields -9223372036854775808.00 -9223372036854775808.ToString("f") yields -9223372036854775808.00 -9223372036854775808.ToString("G") yields -9223372036854775808 -9223372036854775808.ToString("g") yields -9223372036854775808 -9223372036854775808.ToString("N") yields -9,223,372,036,854,775,808.00 -9223372036854775808.ToString("n") yields -9,223,372,036,854,775,808.00 -9223372036854775808.ToString("P") yields -922,337,203,685,477,580,800.00 % -9223372036854775808.ToString("p") yields -922,337,203,685,477,580,800.00 % -9223372036854775808.ToString("X") yields 8000000000000000 -9223372036854775808.ToString("x") yields 8000000000000000
F G H I J K L M N O P Q R S T U V W X Y Z
2089
Contents | Index
Int64 Structure
System
ToString() Method
Int64.ToString(System.String, System.IFormatProvider) Method [ILASM]
A
.method public final hidebysig virtual string ToString(string format, class System.IFormatProvider provider)
B
[C#]
public string ToString(string format, IFormatProvider provider)
C D
Summary
E
Returns a System.String representation of the value of the current instance.
F
Parameters
G H
Parameter
Description
format
A System.String containing a character that specifies the format of the returned string.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo instance containing culture-specific formatting information.
I J K L M N
Return Value
O
A System.String representation of the current instance formatted as specified by format. The string takes into account the formatting information in the System.Globalization.NumberFormatInfo instance supplied by provider.
P Q R
Description
S
If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. If format is a null reference, the general format specifier “G” is used. [Note: For a detailed description of formatting, see the System.IFormattable interface. This method is implemented to support the System.IFormattable interface.] The following table lists the characters that are valid for the System.Int64 type.
T U V W X Y Z
2090
Contents | Index
System
Int64 Structure ToString() Method
Format Characters
Description
"C", "c"
Currency format.
A
"D", "d"
Decimal format.
B
"E", "e"
Exponential notation format.
"F", "f"
Fixed-point format.
"G", "g"
General format.
F
"N", "n"
Number format.
G
"P", "p"
Percent format.
"X", "x"
Hexadecimal format.
C D E
H I J K
Exceptions
L
Exception
Condition
System.FormatException
format is invalid.
M N O P
Example
Q
using System; using System.Globalization;
R S
namespace Samples { public class Int64ToString { public static void Main() { long max = long.MaxValue, min = long.MinValue; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; n.CurrencySymbol = "#"; string[] formats = {"C", "c", "D", "d", "E", "e",
T U V W X Y Z
2091
Contents | Index
Int64 Structure
System
ToString() Method
"F", "f", "G", "g", "N", "n", "P", "p", "X", "x"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\",n) yields {2}", max, f, max.ToString(f, c)); foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\",n) yields {2}", min, f, min.ToString(f, c));
A B C }
D
} }
E F
The output is
G 9223372036854775807.ToString("C",n) yields #9,223,372,036,854,775,807.00 9223372036854775807.ToString("c",n) yields #9,223,372,036,854,775,807.00 9223372036854775807.ToString("D",n) yields 9223372036854775807 9223372036854775807.ToString("d",n) yields 9223372036854775807 9223372036854775807.ToString("E",n) yields 9.223372E~018 9223372036854775807.ToString("e",n) yields 9.223372e~018 9223372036854775807.ToString("F",n) yields 9223372036854775807.00 9223372036854775807.ToString("f",n) yields 9223372036854775807.00 9223372036854775807.ToString("G",n) yields 9223372036854775807 9223372036854775807.ToString("g",n) yields 9223372036854775807 9223372036854775807.ToString("N",n) yields 9,223,372,036,854,775,807.00 9223372036854775807.ToString("n",n) yields 9,223,372,036,854,775,807.00 9223372036854775807.ToString("P",n) yields 922,337,203,685,477,580,700.00 % 9223372036854775807.ToString("p",n) yields 922,337,203,685,477,580,700.00 % 9223372036854775807.ToString("X",n) yields 7FFFFFFFFFFFFFFF 9223372036854775807.ToString("x",n) yields 7fffffffffffffff -9223372036854775808.ToString("C",n) yields !#9,223,372,036,854,775,808.00 -9223372036854775808.ToString("c",n) yields !#9,223,372,036,854,775,808.00 -9223372036854775808.ToString("D",n) yields !9223372036854775808 -9223372036854775808.ToString("d",n) yields !9223372036854775808 -9223372036854775808.ToString("E",n) yields !9.223372E~018 -9223372036854775808.ToString("e",n) yields !9.223372e~018 -9223372036854775808.ToString("F",n) yields !9223372036854775808.00 -9223372036854775808.ToString("f",n) yields !9223372036854775808.00 -9223372036854775808.ToString("G",n) yields !9223372036854775808 -9223372036854775808.ToString("g",n) yields !9223372036854775808 -9223372036854775808.ToString("N",n) yields !9,223,372,036,854,775,808.00 -9223372036854775808.ToString("n",n) yields !9,223,372,036,854,775,808.00 -9223372036854775808.ToString("P",n) yields !922,337,203,685,477,580,800.00 % -9223372036854775808.ToString("p",n) yields !922,337,203,685,477,580,800.00 % -9223372036854775808.ToString("X",n) yields 8000000000000000 -9223372036854775808.ToString("x",n) yields 8000000000000000
H I J K L M N O P Q R S T U V W X Y Z
2092
Contents | Index
System
Int64 Structure ToString() Method
Int64.ToString(System.IFormatProvider) Method [ILASM]
.method public final hidebysig virtual string ToString(class System.IFormatProvider provider)
A
[C#]
B
public string ToString(IFormatProvider provider)
C
Summary
D
Returns a System.String representation of the value of the current instance.
E F
Parameters
G
Parameter
Description
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
H I J K
Return Value
L
A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the formatting information in the System.Globalization.NumberFormatInfo instance supplied by provider.
M N O
Description
P
This version of System.Int64.ToString is equivalent to System.Int64.ToString(“G”, provider). If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used.
Q R S T
Example
U
using System; using System.Globalization;
V W
namespace Samples { public class Int64ToString { public static void Main() { long max = long.MaxValue, min = long.MinValue;
X Y Z
2093
Contents | Index
Int64 Structure
System
ToBoolean() Method
CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; Console.WriteLine("{0}.ToString yields {1}", max, max.ToString(c)); Console.WriteLine("{0}.ToString yields {1}", min, min.ToString(c));
A B C }
D
} }
E F
The output is
G 9223372036854775807.ToString yields 9223372036854775807 -9223372036854775808.ToString yields !9223372036854775808
H I J
IConvertible.ToBoolean(System.IFormatProvider) Method
K [ILASM]
L
.method private final hidebysig virtual bool System.IConvertible.ToBoolean(class System.IFormatProvider provider)
M
[C#]
bool IConvertible.ToBoolean(IFormatProvider provider)
N O
Summary
P
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToBoolean.]
Q R S
IConvertible.ToByte(System.IFormatProvider) Method
T
[ILASM]
U
.method private final hidebysig virtual unsigned int8 System.IConvertible.ToByte(class System.IFormatProvider provider)
V
[C#]
byte IConvertible.ToByte(IFormatProvider provider)
W X
Summary
Y
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToByte.]
Z
2094
Contents | Index
System
Int64 Structure ToDecimal() Method
IConvertible.ToChar(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual valuetype System.Char System.IConvertible.ToChar(class System.IFormatProvider provider)
A
[C#]
B
char IConvertible.ToChar(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToChar.]
E F G
IConvertible.ToDateTime(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual valuetype System.DateTime System.IConvertible.ToDateTime(class System.IFormatProvider provider)
J
[C#]
K
DateTime IConvertible.ToDateTime(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDateTime.]
N O P
IConvertible.ToDecimal(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual decimal System.IConvertible.ToDecimal(class System.IFormatProvider provider)
S
[C#]
T
decimal IConvertible.ToDecimal(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDecimal.]
W X Y Z
2095
Contents | Index
Int64 Structure
System
ToDouble() Method
IConvertible.ToDouble(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual float64 System.IConvertible.ToDouble(class System.IFormatProvider provider)
B
[C#]
double IConvertible.ToDouble(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDouble.]
F G H
IConvertible.ToInt16(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual int16 System.IConvertible.ToInt16(class System.IFormatProvider provider)
K
[C#]
short IConvertible.ToInt16(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt16.]
O P Q
IConvertible.ToInt32(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual int32 System.IConvertible.ToInt32(class System.IFormatProvider provider)
T
[C#]
int IConvertible.ToInt32(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt32.]
X Y Z
2096
Contents | Index
System
Int64 Structure ToSingle() Method
IConvertible.ToInt64(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual int64 System.IConvertible.ToInt64(class System.IFormatProvider provider)
A
[C#]
B
long IConvertible.ToInt64(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt64.]
E F G
IConvertible.ToSByte(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual int8 System.IConvertible.ToSByte(class System.IFormatProvider provider)
J
[C#]
K
sbyte IConvertible.ToSByte(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSByte.]
N O P
IConvertible.ToSingle(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual float32 System.IConvertible.ToSingle(class System.IFormatProvider provider)
S
[C#]
T
float IConvertible.ToSingle(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSingle.]
W X Y Z
2097
Contents | Index
Int64 Structure
System
ToType() Method
IConvertible.ToType(System.Type, System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual object System.IConvertible.ToType(class System.Type type, class System.IFormatProvider provider)
B
[C#]
object IConvertible.ToType(Type type, IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToType.]
F G H
IConvertible.ToUInt16(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual unsigned int16 System.IConvertible.ToUInt16(class System.IFormatProvider provider)
K
[C#]
ushort IConvertible.ToUInt16(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt16.] This member is not CLS-compliant.
O P Q
IConvertible.ToUInt32(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual unsigned int32 System.IConvertible.ToUInt32(class System.IFormatProvider provider)
T
[C#]
uint IConvertible.ToUInt32(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt32.] This member is not CLS-compliant.
X Y Z
2098
Contents | Index
System
Int64 Structure ToUInt64() Method
IConvertible.ToUInt64(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual unsigned int64 System.IConvertible.ToUInt64(class System.IFormatProvider provider)
A
[C#]
B
ulong IConvertible.ToUInt64(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt64.] This member is not CLS-compliant.
E F G H I J K L M N O P Q R S T U V W X Y Z
2099
Contents | Index
System.Threading Interlocked
BCL
Object
A
Interlocked
B
Summary
C
The System.Threading.Interlocked class provides atomic operations for variables that are shared by multiple threads.
D E
Type Summary
F
public sealed class Interlocked { // Methods CF public static float CompareExchange (ref float location1, float value, float comparand); public static int CompareExchange (ref int location1, int value, int comparand); public static object CompareExchange (ref object location1, object value, object comparand); public static int Decrement (ref int location); CF public static long Decrement (ref long location); CF public static float Exchange (ref float location1, float value); public static int Exchange (ref int location1, int value); public static object Exchange (ref object location1, object value); public static int Increment (ref int location); CF public static long Increment (ref long location); }
G H I J K L M N O P Q R S T U
BA This is one of the very few examples of places in the library where usage of byreference parameters is warranted, and it is this exact example that pushed us to include them in the CLS. In general by reference parameters make the APIs much harder to use and should be avoided in good library design.
V W X
JR Methods that take an Object by reference are not that useful, because the only thing you can pass is a reference to a System.Object object; it is not legal to pass a reference to an object whose type is derived from Object.
Y Z
2100
Contents | Index
System.Threading
Interlocked Interlocked Class
Description The System.Threading.Interlocked methods protect against errors that can occur when the scheduler switches contexts while a thread is updating a variable that can be accessed by other threads. The members of this class do not throw exceptions. [Note: The System.Threading.Interlocked.Increment method and its counterpart, System.Threading.Interlocked.Decrement, increment or decrement a variable and store the resulting value as an atomic operation. The System.Threading.Interlocked.Exchange method atomically exchanges the values of the specified variables. The System.Threading.Interlocked.CompareExchange method provides an atomic operation that compares two values and stores a third value in one of the variables, based on the outcome of the comparison.]
A B C D E F G
Example
H
using System; using System.Threading; using System.Collections;
I J K
namespace Samples { public class InterlockedSample { private static Hashtable ht = new Hashtable(); public static void Add(object key, object value) { Monitor.Enter(ht); ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); } public static void Display() { Monitor.Enter(ht); IDictionaryEnumerator ide = ht.GetEnumerator(); while(ide.MoveNext()) Console.WriteLine("Key: {0}, Value: {1}", ide.Key, ide.Value); Monitor.Exit(ht); } public static void StartHere(Object o) { Add(Interlocked.Increment(ref number), o); if(Interlocked.Decrement(ref threads) == 0) threadsDone.Set(); }
L M N O P Q R S T U V W X Y Z
2101
Contents | Index
Interlocked
System.Threading
CompareExchange() Method
static int number = 0; static int threads = 5; static AutoResetEvent threadsDone = new AutoResetEvent(false); public static void Main() { for(int i = 0; i < threads; i++) { ThreadPool.QueueUserWorkItem( new WaitCallback(StartHere), "Add"); } threadsDone.WaitOne(); Display(); }
A B C D E F G H
} }
I
The output is
J K
Key: Key: Key: Key: Key:
L M
5, 4, 3, 2, 1,
Value: Value: Value: Value: Value:
Add Add Add Add Add
N O
Interlocked.CompareExchange(System.Single&, System.Single, System.Single) Method
P Q
[ILASM]
R
.method public hidebysig static float32 CompareExchange(class System.Single& location1, float32 value, float32 comparand)
S
[C#]
T
public static float CompareExchange(ref float location1, float value, float comparand)
U V
Summary
W
Compares two System.Single values for equality and stores a specified value if they are equal.
X Y Z
2102
Contents | Index
System.Threading
Interlocked CompareExchange() Method
Parameters Parameter
Description
location1
A System.Single whose value is updated with value if its original value is equal to comparand.
value
The System.Single value that will replace the value of location1 if location1 and comparand are equal.
comparand
A System.Single to be compared to location1.
A B C D E F G
Return Value
H
A System.Single containing the original value of location1.
I
Description
J
The compare and store operations are performed as an atomic operation. This member must be implemented if the Extended Numerics Library is present in the implementation.
K
Exceptions
M
L
N
Exception
Condition
System.ArgumentNullException
The address of location1 is null.
O P Q R
Interlocked.CompareExchange(System.Int32&, System.Int32, System.Int32) Method
S T
[ILASM]
U
.method public hidebysig static int32 CompareExchange(class System.Int32& location1, int32 value, int32 comparand)
V
[C#]
W
public static int CompareExchange(ref int location1, int value, int comparand)
X
Summary
Y
Compares two System.Int32 values for equality and stores a specified value if they are equal.
Z
2103
Contents | Index
Interlocked
System.Threading
CompareExchange() Method
Parameters Parameter
Description
location1
A System.Int32 reference whose value is updated with value if the original value of location1 is equal to comparand.
value
A System.Int32 whose value will replace the value of location1 if location1 and comparand are equal.
comparand
A System.Int32 to be compared to location1.
A B C D E F G
Return Value
H
The original value of location1.
I J
Description
K
The compare and store operations are performed as an atomic operation.
L
Example
M
using System; using System.Threading; using System.Collections;
N O
namespace Samples { public class InterlockedCompareExchange { public static int threads = 10; public static int anInteger = threads; static AutoResetEvent threadsDone = new AutoResetEvent(false); public static void StartHere(Object o) { int i = (int) o; while(i != Interlocked.CompareExchange(ref anInteger, i - 1, i)) Thread.Sleep(1000); Console.WriteLine("anInteger set to {0}", --i); if(Interlocked.Decrement(ref threads) == 0) threadsDone.Set(); } public static void Main() {
P Q R S T U V W X Y Z
2104
Contents | Index
System.Threading
Interlocked CompareExchange() Method
for(int i = 1; i <= threads; i++) { ThreadPool.QueueUserWorkItem( new WaitCallback(StartHere), i); } threadsDone.WaitOne(); Console.WriteLine("Done");
A B C
}
D
} }
E F
The output is
G anInteger anInteger anInteger anInteger anInteger anInteger anInteger anInteger anInteger anInteger Done
set set set set set set set set set set
to to to to to to to to to to
9 8 7 6 5 4 3 2 1 0
H I J K L M N O
Interlocked.CompareExchange(System.Object&, System.Object, System.Object) Method
P Q
[ILASM]
R
.method public hidebysig static object CompareExchange(class System.Object& location1, object value, object comparand)
S
[C#]
T
public static object CompareExchange(ref object location1, object value, object comparand)
U
Summary
V
Compares two System.Object variables for equality and stores a specified object if they are equal.
W X Y Z
2105
Contents | Index
Interlocked
System.Threading
Decrement() Method
Parameters Parameter
Description
location1
A System.Object reference that is set to value if the object to which it refers is equal to comparand.
value
The reference that will replace the value of location1 if location1 and comparand are equal.
comparand
An object to be compared to that referred to by location1.
A B C D E F G
Return Value
H
A System.Object containing the original value of location1.
I
Description
J
The compare and store operations are performed as an atomic operation.
K
Exceptions
L M
Exception
Condition
System.ArgumentNullException
The address of location1 is null.
N O P Q
Interlocked.Decrement(System.Int32&) Method
R [ILASM]
S
.method public hidebysig static int32 Decrement(class System.Int32& location)
T
[C#]
public static int Decrement(ref int location)
U V
Summary
W
Decrements the specified variable and stores the result as an atomic operation.
X
Parameters
Y Z
Parameter
Description
location
A System.Int32 containing the variable whose value is to be decremented.
2106
Contents | Index
System.Threading
Interlocked Decrement() Method
Return Value A System.Int32 containing the decremented value.
Description
A
This method handles an overflow condition by wrapping: if location = System.Int32.MinValue, location–1=System.Int32.MaxValue. No exception is thrown.
B C D
Example
E
using System; using System.Threading; using System.Collections;
F G
namespace Samples { public class InterlockedDecrement { private static Hashtable ht = new Hashtable(); public static void Add(object key, object value) { Monitor.Enter(ht); ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); } public static bool AddNoWait(object key, object value) { if(Monitor.TryEnter(ht)) { ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); return true; } return false; } public static bool AddWithWaitTime(object key, object value, int waitTime) { if(Monitor.TryEnter(ht, waitTime)) { ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); return true; }
H I J K L M N O P Q R S T U V W X Y Z
2107
Contents | Index
Interlocked
System.Threading
Decrement() Method
return true; } public static void Display() { Monitor.Enter(ht); IDictionaryEnumerator ide = ht.GetEnumerator(); while(ide.MoveNext()) Console.WriteLine("Key: {0}, Value: {1}", ide.Key, ide.Value); Monitor.Exit(ht); } public static void StartHere(Object o) { int i = (int) o; Add(i, "Add"); i += 10; Console.WriteLine( "AddNoWait for thread {0} succeeded: {1}", o, AddNoWait(i, "AddNoWait")); i += 10; Console.WriteLine( "AddNoWait for thread {0} succeeded: {1}", o, AddNoWait(i, "AddNoWait")); i += 10; Console.WriteLine( "AddWithWaitTime for thread {0} succeeded: {1}", o, AddWithWaitTime(i, "AddWithWaitTime", 100)); if(Interlocked.Decrement(ref threads) == 0) threadsDone.Set(); } static int threads = 5; static AutoResetEvent threadsDone = new AutoResetEvent(false); public static void Main() { for(int i = 0; i < threads; i++) { ThreadPool.QueueUserWorkItem( new WaitCallback(StartHere), i); } threadsDone.WaitOne(); Display(); }
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
} }
2108
Contents | Index
System.Threading
Interlocked Decrement() Method
The output is AddNoWait for thread 0 succeeded: False AddNoWait for thread 0 succeeded: False AddWithWaitTime for thread 0 succeeded: AddNoWait for thread 1 succeeded: False AddNoWait for thread 1 succeeded: False AddWithWaitTime for thread 1 succeeded: AddNoWait for thread 2 succeeded: False AddNoWait for thread 2 succeeded: False AddWithWaitTime for thread 2 succeeded: AddNoWait for thread 3 succeeded: False AddNoWait for thread 3 succeeded: False AddWithWaitTime for thread 3 succeeded: AddNoWait for thread 4 succeeded: True AddNoWait for thread 4 succeeded: True AddWithWaitTime for thread 4 succeeded: Key: 14, Value: AddNoWait Key: 34, Value: AddWithWaitTime Key: 31, Value: AddWithWaitTime Key: 24, Value: AddNoWait Key: 4, Value: Add Key: 3, Value: Add Key: 2, Value: Add Key: 1, Value: Add Key: 0, Value: Add
A
True
B C
True
D E
True
F True
G H
True
I J K L M N O P
Interlocked.Decrement(System.Int64&) Method
Q [ILASM]
.method public hidebysig static int64 Decrement(class System.Int64& location)
R
[C#]
S
public static long Decrement(ref long location)
T
Summary
U
Decrements the specified variable and stores the result as an atomic operation.
V W
Parameters
X
Parameter
Description
location
A System.Int64 containing the variable whose value is to be decremented.
Y Z
2109
Contents | Index
Interlocked
System.Threading
Exchange() Method
Return Value A System.Int64 containing the decremented value. A
Description
B
This method handles an overflow condition by wrapping: if location = System.Int64.MinValue, location–1=System.Int64.MaxValue. No exception is thrown. The 64-bit versions of System.Threading.Interlocked.Increment and System.Threading.Interlocked.Decrement are truly atomic only on systems where a System.IntPtr is 64-bits long. On other systems, these methods are atomic with respect to each other, but not with respect to other means of accessing the data.
C D E F G H
Interlocked.Exchange(System.Single&, System.Single) Method
I
[ILASM]
J
.method public hidebysig static float32 Exchange(class System.Single& location1, float32 value)
K
[C#]
public static float Exchange(ref float location1, float value)
L M
Summary
N
Sets a System.Single variable to a specified value as an atomic operation and returns the original value.
O P
Parameters
Q R
Parameter
Description
S
location1
A System.Single variable to set to the supplied value as an atomic operation.
value
The System.Single value to which location1 is set.
T U V
Return Value
W
A System.Single containing the value of location1 before the exchange.
X Y
Description
Z
This member must be implemented if the Extended Numerics Library is present in the implementation.
2110
Contents | Index
System.Threading
Interlocked Exchange() Method
Interlocked.Exchange(System.Int32&, System.Int32) Method [ILASM]
.method public hidebysig static int32 Exchange(class System.Int32& location1, int32 value)
A
[C#]
B
public static int Exchange(ref int location1, int value)
C
Summary
D
Sets a System.Int32 variable to a specified value as an atomic operation and returns the original value.
E
Parameters
G
F
H
Parameter
Description
location1
A System.Int32 variable to set to the supplied value as an atomic operation.
value
The System.Int32 value to which location1 is set.
I J K L M
Return Value
N
A System.Int32 containing the value of location1 before the exchange.
O
Example
P
using System; using System.Threading; using System.Collections;
Q R S
namespace Samples { public class InterlockedExchange { public static int threads = 10; public static int anInteger = threads; static AutoResetEvent threadsDone = new AutoResetEvent(false); public static void StartHere(Object o) { int i = (int) o; int j = Interlocked.Exchange(ref anInteger, i); Console.WriteLine("From {0} to {1}", j, i); if(Interlocked.Decrement(ref threads) == 0) threadsDone.Set();
T U V W X Y Z
2111
Contents | Index
Interlocked
System.Threading
Exchange() Method
} public static void Main() { for(int i = 1; i <= threads; i++) { ThreadPool.QueueUserWorkItem( new WaitCallback(StartHere), i); } threadsDone.WaitOne(); Console.WriteLine("Done"); }
A B C D E F
} }
G
The output is
H I
From From From From From From From From From From Done
J K L M N O
10 to 1 1 to 2 2 to 3 3 to 4 4 to 5 5 to 6 6 to 7 7 to 8 8 to 9 9 to 10
P Q
Interlocked.Exchange(System.Object&, System.Object) Method
R
[ILASM]
S
.method public hidebysig static object Exchange(class System.Object& location1, object value)
T
[C#]
U
public static object Exchange(ref object location1, object value)
V W
Summary
X
Sets a System.Object reference to refer to a specified object as an atomic operation and returns a reference to the original object.
Y Z
2112
Contents | Index
System.Threading
Interlocked Increment() Method
Parameters Parameter
Description
location1
The variable to set.
value
The reference to which location1 is set.
A B C D
Return Value
E
The original value of location1.
F G
Exceptions
H
Exception
Condition
System.ArgumentNullException
The address of location1 is null.
I J K L M
Interlocked.Increment(System.Int32&) Method
N
[ILASM]
O
.method public hidebysig static int32 Increment(class System.Int32& location) [C#]
P
public static int Increment(ref int location)
Q
Summary
R
Increments the specified variable and stores the result as an atomic operation.
S T
Parameters
U
Parameter
Description
V
location
A System.Int32 containing the variable whose value is to be incremented.
W X
Return Value
Y
A System.Int32 containing the incremented value.
Z
2113
Contents | Index
Interlocked
System.Threading
Increment() Method
Description This method handles an overflow condition by wrapping: if location = System.Int32.MaxValue, location+1=System.Int32.MinValue. No exception is thrown. A B
Example
C
using System; using System.Threading; using System.Collections;
D E
namespace Samples { public class InterlockedIncrement { private static Hashtable ht = new Hashtable(); public static void Add(object key, object value) { Monitor.Enter(ht); ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); } public static void Display() { Monitor.Enter(ht); IDictionaryEnumerator ide = ht.GetEnumerator(); while(ide.MoveNext()) Console.WriteLine("Key: {0}, Value: {1}", ide.Key, ide.Value); Monitor.Exit(ht); } public static void StartHere(Object o) { Add(Interlocked.Increment(ref number), o); if(Interlocked.Decrement(ref threads) == 0) threadsDone.Set(); } static int number = 0; static int threads = 5; static AutoResetEvent threadsDone = new AutoResetEvent(false); public static void Main() { for(int i = 0; i < threads; i++) { ThreadPool.QueueUserWorkItem( new WaitCallback(StartHere), "Add");
F G H I J K L M N O P Q R S T U V W X Y Z
2114
Contents | Index
System.Threading
Interlocked Increment() Method
} threadsDone.WaitOne(); Display(); }
A
} }
B
The output is Key: Key: Key: Key: Key:
5, 4, 3, 2, 1,
Value: Value: Value: Value: Value:
C D
Add Add Add Add Add
E F G H
Interlocked.Increment(System.Int64&) Method
I
[ILASM]
J
.method public hidebysig static int64 Increment(class System.Int64& location)
K
[C#]
public static long Increment(ref long location)
L
Summary
M
Increments the specified variable and stores the result as an atomic operation.
N O
Parameters
P
Parameter
Description
location
A System.Int64 containing the variable whose value is to be incremented.
Q R S T
Return Value
U
A System.Int64 containing the incremented value.
V
Description
W
This method handles an overflow condition by wrapping: if location = System.Int64.MaxValue, location+1=System.Int64.MinValue. No exception is thrown. The 64-bit versions of System.Threading.Interlocked.Increment and System.Threading.Interlocked.Decrement are truly atomic only on systems where a System.IntPtr is 64 bits long. On other systems, these methods are atomic with respect to each other, but not with respect to other means of accessing the data.
X Y Z
2115
Contents | Index
System InvalidCastException
BCL
Object
A
Exception
B
ISerializable
NotStandardized
SystemException InvalidCastException
C D
Summary
E
Represents the error that occurs when an explicit conversion (casting operation) fails because the source type cannot be converted to the destination type.
F G
Type Summary
H
public class InvalidCastException : SystemException { // Constructors public InvalidCastException (); public InvalidCastException (string message); public InvalidCastException (string message, Exception innerException); MS CF protected InvalidCastException (SerializationInfo info, StreamingContext context); }
I J K L M N O
Description
P
[Note: For information on conversions supported by the system, see the System.Convert class. For errors that occur when the destination type can store source type values, but is not large enough to store a specific source value, see System.OverflowException exception.]
Q R S T
Example
U
using System;
V
namespace s { public class InvalidCastExceptionSample { public static void Main() { try { Object o = new Object(); string s = (string) o;
W X Y Z
2116
Contents | Index
System
InvalidCastException InvalidCastException() Constructor
} catch(InvalidCastException e) { Console.WriteLine("Exception: {0}", e); }
A
}
B
}
C
}
D
The output is
E Exception: System.InvalidCastException: Specified cast is not valid. at s.InvalidCastExceptionSample.Main() in C:\Books\BCL\Samples\System\ InvalidCastException\InvalidCastException.cs:line 12
F G H
InvalidCastException() Constructor
I
[ILASM]
J
public rtspecialname specialname instance void .ctor()
K
[C#]
L
public InvalidCastException()
M
Summary
N
Constructs and initializes a new instance of the System.InvalidCastException class.
O
Description
P
This constructor initializes the System.InvalidCastException.Message property of the new instance to a system-supplied message that describes the error, such as “Cannot cast from source type to destination type.” This message takes into account the current system culture. The System.InvalidCastException.InnerException property is initialized to null.
Q R S T U V
InvalidCastException(System.String) Constructor
W
[ILASM]
X
public rtspecialname specialname instance void .ctor(string message)
Y
[C#]
public InvalidCastException(string message)
Z
2117
Contents | Index
InvalidCastException
System
InvalidCastException() Constructor
Summary Constructs and initializes a new instance of the System.InvalidCastException class. A
Parameters
B C
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
D E F G
Description
H
This constructor initializes the System.InvalidCastException.Message property of the new instance using message. If message is null, the System.InvalidCastException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.InvalidCastException.InnerException property is initialized to null.
I J K L M
InvalidCastException(System.String, System.Exception) Constructor
N [ILASM]
O
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
P
[C#]
public InvalidCastException(string message, Exception innerException)
Q R
Summary
S
Constructs and initializes a new instance of the System.InvalidCastException class.
T
Parameters
U V
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
W X Y Z
2118
Contents | Index
System
InvalidCastException InvalidCastException() Constructor
Description This constructor initializes the System.InvalidCastException.Message property of the new instance using message, and the System.InvalidCastException.InnerException property using innerException. If message is null, the System.InvalidCastException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
A B C D E F
InvalidCastException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
G
[ILASM]
H
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
I J
[C#]
K
protected InvalidCastException(SerializationInfo info, StreamingContext context)
L
Summary
M
Initializes a new instance of the System.InvalidCastException class with serialized data.
N O
Parameters
P Q
Parameter
Description R
info
The object that holds the serialized object data.
S
context
The contextual information about the source or destination.
T U
Description
V
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
W X Y Z
2119
Contents | Index
System InvalidOperationException
BCL
Object
A
Exception
B
ISerializable
NotStandardized
SystemException InvalidOperationException
C
ObjectDisposedException
D E
Summary
F
Represents the error that occurs when an operation cannot be performed.
G
Type Summary
H
public class InvalidOperationException : SystemException { // Constructors public InvalidOperationException (); public InvalidOperationException (string message); public InvalidOperationException (string message, Exception innerException); MS CF protected InvalidOperationException (SerializationInfo info, StreamingContext context); }
I J K L M N O
Description
P
[Note: System.InvalidOperationException is typically thrown when the state of one or more objects determines whether an operation can be performed. For example, when initially enumerating over a set of objects, if the enumerator has not been positioned over the first element via a call to System.Collections.IEnumerator.MoveNext, the system throws a System.InvalidOperationException exception when System.Collections.IEnumerator.Current is accessed. The System.InvalidOperationException exception should not be thrown for errors caused by invalid arguments. For invalid argument errors, throw System.ArgumentException or one of its derived types, such as System.ArgumentNullException or System.ArgumentOutOfRangeException. The ldflda IL instruction throws System.InvalidOperationException.]
Q R S T U V W X Y Z
2120
Contents | Index
System
InvalidOperationException InvalidOperationException() Constructor
Example using System; using System.Collections;
A namespace Samples { public class InvalidOperationExceptionSample { public static void Main() { try { string[] strings = {"zero", "one", "two"}; IEnumerator ie = strings.GetEnumerator(); Console.Write("{0}", ie.Current); } catch(InvalidOperationException e) { Console.WriteLine("Exception: {0}", e); } } } }
B C D E F G H I J K L M
The output is
N O
Exception: System.InvalidOperationException: Enumeration has not started. Call MoveNext. at System.SZArrayEnumerator.get_Current() at Samples.InvalidOperationExceptionSample.Main() in C:\Books\BCL\Samples\ System\InvalidOperationException\InvalidOperationException.cs:line 14
P Q R S
InvalidOperationException() Constructor
T
[ILASM]
U
public rtspecialname specialname instance void .ctor()
V
[C#]
public InvalidOperationException()
W
Summary
X
Constructs and initializes a new instance of the System.InvalidOperationException class.
Y Z
2121
Contents | Index
InvalidOperationException
System
InvalidOperationException() Constructor
Description This constructor initializes the System.InvalidOperationException.Message property of the new instance to a system-supplied message that describes the error, such as “The requested operation cannot be performed.” This message takes into account the current system culture. The System.InvalidOperationException.InnerException property is initialized to null.
A B C D E
InvalidOperationException(System.String) Constructor
F
[ILASM]
G
public rtspecialname specialname instance void .ctor(string message)
H
[C#]
public InvalidOperationException(string message)
I J
Summary
K
Constructs and initializes a new instance of the System.InvalidOperationException class.
L M
Parameters
N O
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
P Q R S
Description
T
This constructor initializes the System.InvalidOperationException.Message property of the new instance using message. If message is null, the System.InvalidOperationException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.InvalidOperationException.InnerException property is initialized to null.
U V W X Y Z
2122
Contents | Index
System
InvalidOperationException InvalidOperationException() Constructor
InvalidOperationException(System.String, System.Exception) Constructor [ILASM]
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
A
[C#]
B
public InvalidOperationException(string message, Exception innerException)
C
Summary
D
Constructs and initializes a new instance of the System.InvalidOperationException class.
E
Parameters
G
F
H
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
I J K L
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
M N O
Description
P
This constructor initializes the System.InvalidOperationException.Message property of the new instance using message, and the System.InvalidOperationException.InnerException property using innerException. If message is null, the System.InvalidOperationException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
Q R S T U V
InvalidOperationException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
W X
[ILASM]
Y
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
Z
[C#]
protected InvalidOperationException(SerializationInfo info, StreamingContext context)
2123
Contents | Index
InvalidOperationException
System
InvalidOperationException() Constructor
Summary Initializes a new instance of the System.InvalidOperationException class with serialized data. A
Parameters
B C
Parameter
Description
E
info
The object that holds the serialized object data.
F
context
The contextual information about the source or destination.
D
G H
Description
I
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
J K L M N O P Q R S T U V W X Y Z
2124
Contents | Index
System InvalidProgramException
BCL
Object Exception
ISerializable
NotStandardized
A B
SystemException InvalidProgramException
C D
Summary
E
Represents the error that occurs when a program contains invalid IL instructions or metadata.
F G
Type Summary
H
public sealed class InvalidProgramException : SystemException { // Constructors public InvalidProgramException (); public InvalidProgramException (string message); public InvalidProgramException (string message, Exception inner); }
I J K L M N O
KG This class contains one of those silly mistakes that pop their heads up too often. The innerException parameter in 95% of the framework is called innerException; here it is just called inner. Another learning exercise is to get checking and consistency tools in place sooner rather than later.
P Q R S
Description
T
[Note: This exception is thrown by the system when a compiler emits incorrect IL or metadata.]
U V W
InvalidProgramException() Constructor
X [ILASM]
Y
public rtspecialname specialname instance void .ctor() [C#]
Z
public InvalidProgramException()
2125
Contents | Index
InvalidProgramException
System
InvalidProgramException() Constructor
Summary Constructs and initializes a new instance of the System.InvalidProgramException class. A B
Description
C
This constructor initializes the System.InvalidProgramException.Message property of the new instance to a system-supplied message that describes the error, such as “Metadata is incorrect.” This message takes into account the current system culture. The System.InvalidProgramException.InnerException property is initialized to null.
D E F G H
InvalidProgramException(System.String) Constructor
I
[ILASM]
J
public rtspecialname specialname instance void .ctor(string message)
K
public InvalidProgramException(string message)
[C#]
L
Summary
M
Constructs and initializes a new instance of the System.InvalidProgramException class.
N O
Parameters
P Q
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
R S T U
Description
V
This constructor initializes the System.InvalidProgramException.Message property of the new instance using message. If message is null, the System.InvalidProgramException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.InvalidProgramException.InnerException property is initialized to null.
W X Y Z
2126
Contents | Index
System
InvalidProgramException InvalidProgramException() Constructor
InvalidProgramException(System.String, System.Exception) Constructor [ILASM]
public rtspecialname specialname instance void .ctor(string message, class System.Exception inner)
A
[C#]
B
public InvalidProgramException(string message, Exception inner)
C
Summary
D
Constructs and initializes a new instance of the System.InvalidProgramException class.
E
Parameters
G
F
H
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
inner
An instance of System.Exception that is the cause of the current exception. If inner is non-null, then the current exception was raised in a catch block handling inner.
I J K L M N O
Description
P
This constructor initializes the System.InvalidProgramException.Message property of the new instance using message, and the System.InvalidProgramException.InnerException property using inner. If message is null, the System.InvalidProgramException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
Q R S T U V W X Y Z
2127
Contents | Index
System.IO IOException
BCL
Object
A
Exception
B
ISerializable
NotStandardized
SystemException IOException
C D
DirectoryNotFoundException
E
EndOfStreamException FileLoadException
F
FileNotFoundException
G
PathTooLongException
H I
Summary
J
Represents the error that occurs when an I/O operation fails.
K
Type Summary
L
public class IOException : SystemException { // Constructors public IOException (); public IOException (string message); MS CF public IOException (string message, int hresult); public IOException (string message, Exception innerException); MS CF protected IOException (SerializationInfo info, StreamingContext context); }
M N O P Q R S
Description
T
System.IO.IOException is the base class for exceptions thrown while accessing information using streams, files, and directories. [Note: The Base Class Library includes the following types, each of which is derived from System.IO.IOException: Where appropriate, use these types instead of System.IO.IOException.]
U V W X Y Z
2128
Contents | Index
System.IO
IOException IOException() Constructor
Example using System; using System.IO;
A namespace Samples { public class IOExceptionSample { public static void Main() { try { string n = @"C:\foo\bar"; string[] s = Directory.GetFiles(n); } catch(IOException e) { Console.WriteLine("Exception: {0}", e); } } } }
B C D E F G H I J K L M
The output is
N Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path "C:\foo\bar". at System.IO.__Error.WinIOError(Int32 errorCode, String str) at System.IO.Directory.InternalGetFileDirectoryNames(String fullPath, Boolean file) at System.IO.Directory.InternalGetFiles(String path, String searchPattern) at System.IO.Directory.GetFiles(String path, String searchPattern) at System.IO.Directory.GetFiles(String path) at Samples.IOExceptionSample.Main() in C:\Books\BCL\Samples\System.IO\ IOException\IOException.cs:line 13
O P Q R S T U
IOException() Constructor
V
[ILASM]
W
public rtspecialname specialname instance void .ctor()
X
[C#]
public IOException()
Y Z
Summary Constructs and initializes a new instance of the System.IO.IOException class.
2129
Contents | Index
IOException
System.IO
IOException() Constructor
Description The constructor initializes the System.IO.IOException.Message property of the new instance to a system-supplied message that describes the error, such as “An I/O error occurred while performing the requested operation.” This message takes into account the current system culture. The System.IO.IOException.InnerException property of the new instance is initialized to null.
A B C D E
IOException(System.String) Constructor
F [ILASM]
G
public rtspecialname specialname instance void .ctor(string message) [C#]
H
public IOException(string message)
I
Summary
J
Constructs and initializes a new instance of the System.IO.IOException class.
K
Parameters
L M N
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
O P Q R
Description
S
The constructor initializes the System.IO.IOException.Message property of the new instance using message. If message is null, the System.IO.IOException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.IO.IOException.InnerException property of the new instance is initialized to null.
T U V W X
IOException(System.String, System.Int32) Constructor
Y
[ILASM]
Z
public rtspecialname specialname instance void .ctor(string message, int32 hresult) [C#]
public IOException(string message, int hresult)
2130
Contents | Index
System.IO
IOException IOException() Constructor
Summary Initializes a new instance of the System.IO.IOException class with its message string set to message and its HRESULT user-defined. A
Parameters
B C
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
hresult
D E F G
An integer identifying the error that has occurred.
H I
IOException(System.String, System.Exception) Constructor
J
[ILASM]
K
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
L
[C#]
M
public IOException(string message, Exception innerException)
N
Summary
O
Constructs and initializes a new instance of the System.IO.IOException class.
P Q
Parameters
R
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
S T U V
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
W X Y Z
2131
Contents | Index
IOException
System.IO
IOException() Constructor
Description The constructor initializes the System.IO.IOException.Message property of the new instance using message and the System.IO.IOException.InnerException property using innerException. If message is null, the System.IO.IOException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For more information on inner exceptions, see System.Exception.InnerException.]
A B C D E F G
IOException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
H
[ILASM]
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
I J
[C#]
K
protected IOException(SerializationInfo info, StreamingContext context)
L M
Summary
N
Initializes a new instance of the System.IO.IOException class with the specified serialization and context information.
O
Parameters
P Q
Parameter
Description
S
info
The data for serializing or deserializing the object.
T
context
The source and destination for the object.
R
U V W X Y Z
2132
Contents | Index
System.Security IPermission Interface
BCL
IPermission
ISecurityEncodable
NotStandardized
CodeAccessPermission
A
EnvironmentPermission
B
FileIOPermission
C
SecurityPermission
D E
Summary
F
Defines methods implemented by permission types.
G
Type Summary
H
CF public interface IPermission : ISecurityEncodable { // Methods CF IPermission Copy (); CF void Demand (); CF IPermission Intersect (IPermission target); CF bool IsSubsetOf (IPermission target); CF IPermission Union (IPermission target); }
I J K L M N
Description
O
[Note: Permission types describe a level of access to secured operations or resources, such as files or environment variables. Permission instances do not confer the right to access a resource or perform an operation; the security system determines whether or not requested permissions are granted. Permissions are used by both application code and the security system in the following ways.]
P Q R S T
Example
U
using System; using System.Security; using System.Security.Permissions;
V W
namespace Samples { public class IPermissionSample { public static void Main() { EnvironmentPermission ep1 =
X Y Z
2133
Contents | Index
IPermission Interface
System.Security
IPermission Interface
new EnvironmentPermission( EnvironmentPermissionAccess.Read, "COMPUTERNAME"); IPermission ip1 = ep1; IPermission ip2 = ep1.Copy(); ep1.AddPathList(EnvironmentPermissionAccess.Read, "USERNAME"); Console.WriteLine("ip1 is: {0}", ip1); Console.WriteLine("ip2 is: {0}", ip2); Console.WriteLine("Is ip2 a subset of ip1: {0}", ip2.IsSubsetOf(ip1)); Console.WriteLine("Is ip1 a subset of ip2: {0}", ip1.IsSubsetOf(ip2)); Console.WriteLine("Is ip1 a subset of ip1: {0}", ip1.IsSubsetOf(ip1)); Console.WriteLine("ip1.Intersect(ip2): {0}", ip1.Intersect(ip2)); Console.WriteLine("ip1.Union(ip2): {0}", ip1.Union(ip2));
A B C D E F G H I J
} }
K
}
L
The output is
M
ip1 is:
N O P
ip2 is:
Q R S
Is ip2 a subset of ip1: True Is ip1 a subset of ip2: False Is ip1 a subset of ip1: True ip1.Intersect(ip2):
T U V W X
ip1.Union(ip2):
Y Z
2134
Contents | Index
System.Security
IPermission Interface Copy() Method
IPermission.Copy() Method [ILASM]
.method public hidebysig virtual abstract class System.Security.IPermission Copy() [C#]
A
IPermission Copy()
B
Summary
C
Returns a System.Security.IPermission object of the same type and containing the same values as the current instance.
D E F
Behaviors
G
The object returned by this method is required to be a deep copy of the current instance; any objects referenced by the current instance are duplicated in the copy.
H I
Example
J
using System; using System.Security; using System.Security.Permissions;
K L
namespace Samples { public class IPermissionCopy { public static void Main() { EnvironmentPermission ep1 = new EnvironmentPermission( EnvironmentPermissionAccess.Read, "COMPUTERNAME"); IPermission ip1 = ep1; IPermission ip2 = ep1.Copy(); ep1.AddPathList(EnvironmentPermissionAccess.Read, "USERNAME"); Console.WriteLine("ip1 is: {0}", ip1); Console.WriteLine("ip2 is: {0}", ip2); } } }
M N O P Q R S T U V W X
The output is
Y
ip1 is:
Z
2135
Contents | Index
IPermission Interface
System.Security
Demand() Method
ip2 is:
A B
IPermission.Demand() Method
C D
[ILASM]
E
[C#]
.method public hidebysig virtual abstract void Demand() void Demand()
F G
Summary
H
Forces a System.Security.SecurityException if all callers do not have the permission specified by the current instance.
I J
Description
K
The permission check for System.Security.IPermission.Demand begins with the immediate caller of the code that calls this method and continues until all callers have been checked or a caller has been found that is not granted the demanded permission, in which case a System.Security.SecurityException exception is thrown.
L M N
Behaviors
O
Notifies the system that a security check is required for all callers of the method that invokes System.Security.IPermission.Demand. All callers are required to have the permissions described by the current instance. If one of the callers asserts the permissions and that caller has the permissions, the system is required to allow all callers that have not been checked to bypass the security check. If the security check fails, a System.Security.SecurityException is thrown by the system.
P Q R S T
Usage
U
Use this method to ensure that callers that call the method containing a System.Security.IPermission.Demand call have the permissions described by the current instance.
V W
Exceptions
X Y
Exception
Condition
System.Security.SecurityException
A caller does not have the permission specified by the current instance.
Z
2136
Contents | Index
System.Security
IPermission Interface Demand() Method
Example using System; using System.Security; using System.Security.Permissions;
A B
namespace Samples { public class IPermissionDemand { public static void Main() { EnvironmentPermission p = new EnvironmentPermission( EnvironmentPermissionAccess.Read, "COMPUTERNAME"); IPermission ip = p; p.Assert(); DemandPermission(ip); CodeAccessPermission.RevertAssert(); p.Deny(); DemandPermission(ip); CodeAccessPermission.RevertDeny(); } public static void DemandPermission(IPermission ip) { try { ip.Demand(); Console.WriteLine("Demand succeeded"); } catch(SecurityException) { Console.WriteLine("Demand failed"); } } } }
C D E F G H I J K L M N O P Q R S T U V
The output is
W Demand succeeded Demand failed
X Y Z
2137
Contents | Index
IPermission Interface
System.Security
Intersect() Method
IPermission.Intersect(System.Security.IPermission) Method [ILASM]
A
.method public hidebysig virtual abstract class System.Security.IPermission Intersect(class System.Security.IPermission target)
B
[C#]
IPermission Intersect(IPermission target)
C D
Summary
E
Returns an object that is the intersection of the current instance and the specified System.Security.IPermission object.
F
Parameters
G H
Parameter
Description
target
An object of the same type as the current instance to intersect with the current instance.
I J K L
Return Value
M
A new System.Security.IPermission object that is the same type as the current instance and represents the intersection of the current instance and target. If the intersection is empty, or target is null, returns null. If the current instance is unrestricted, returns a copy of target. If target is unrestricted, returns a copy of the current instance.
N O P Q
Description
R
The object returned by System.Security.IPermission.Intersect is a permission that secures the resources and operations secured by two System.Security.IPermission objects: a demand passes the intersection of two objects only if it passes both of the objects.
S T
Behaviors
U
If target is not null and is not of the same type as the current instance, a System.ArgumentException exception is required to be thrown. The following statements are required to be true for all implementations of the System.Security.IPermission.Intersect method. X and Y represent non-null System.Security.IPermission object references:
V W X Y
• • •
Z
X.Intersect(X) returns a value equal to X. X.Intersect(Y) returns the same value as Y.Intersect(X). X.Intersect(null) returns null.
2138
Contents | Index
System.Security
IPermission Interface Intersect() Method
Usage Use this method to obtain the set of permissions that are described both by the current instance and the specified object. A
Exceptions
B
Exception
Condition
System.ArgumentException
target is not null and is not of the same type as the current instance.
C D E F
Example
G
using System; using System.Security; using System.Security.Permissions;
H I J
namespace Samples { public class IPermissionIntersect { public static void Main() { EnvironmentPermission ep1 = new EnvironmentPermission( EnvironmentPermissionAccess.Read, "COMPUTERNAME"); IPermission ip1 = ep1; IPermission ip2 = ep1.Copy(); ep1.AddPathList(EnvironmentPermissionAccess.Read, "USERNAME"); EnvironmentPermission ep2 = (EnvironmentPermission) ip2; ep2.AddPathList(EnvironmentPermissionAccess.Read, "DOMAINNAME"); Console.WriteLine("ip1.Intersect(ip2) is: {0}", ip1.Intersect(ip2)); } } }
K L M N O P Q R S T U V W X
The output is
Y
ip1.Intersect(ip2) is:
Z
2139
Contents | Index
IPermission Interface
System.Security
IsSubsetOf() Method
IPermission.IsSubsetOf(System.Security.IPermission) Method [ILASM]
A
.method public hidebysig virtual abstract bool IsSubsetOf(class System.Security.IPermission target)
B
[C#]
bool IsSubsetOf(IPermission target)
C D
Summary
E
Determines whether the current instance is a subset of the specified object.
F
Parameters
G H
Parameter
Description
target
A System.Security.IPermission object of the same type as the current instance that is to be tested for the subset relationship.
I J K L
Return Value
M
true if the current instance is a subset of target; otherwise, false. If the current instance is unrestricted, and target is not, returns false. If target is unrestricted, returns true. If target is null and the current instance does not secure any resources or operations, returns true. If target is null and the current instance secures one or more resources or operations, returns false.
N O P Q
Description
R
The current instance is a subset of target if the current instance specifies a set of accesses to resources or operations that is wholly contained by target. For example, a permission that represents read access to a file is a subset of a permission that represents read and write access to the file.
S T U V
Behaviors
W
If target is not null and is not of the same type as the current instance, a System.ArgumentException exception is required to be thrown. The following statements are required to be true for all implementations of the System.Security.IPermission.IsSubsetOf method. X, Y, and Z represent nonnull System.Security.IPermission objects:
X Y Z
2140
Contents | Index
System.Security
IPermission Interface IsSubsetOf() Method
• • •
X.IsSubsetOf(X) returns true. X.IsSubsetOf(Y) returns the same value as Y.IsSubsetOf(X) if and only if X and Y represent the same set of permissions. if X.IsSubsetOf(Y) and Y.IsSubsetOf(Z) both return true, X.IsSubsetOf(Z) returns true.
A B C
Usage
D
Use this method to determine if the permissions described by the current instance are also described by the specified object.
E F
Exceptions
G
Exception
Condition
System.ArgumentException
target is not null and is not of the same type as the current instance.
H I J K L
Example
M
using System; using System.Security; using System.Security.Permissions;
N O
namespace Samples { public class IPermissionIsSubsetOf { public static void Main() { EnvironmentPermission ep1 = new EnvironmentPermission( EnvironmentPermissionAccess.Read, "COMPUTERNAME"); IPermission ip1 = ep1; IPermission ip2 = ep1.Copy(); ep1.AddPathList(EnvironmentPermissionAccess.Read, "USERNAME"); Console.WriteLine("ip1 is: {0}", ip1); Console.WriteLine("ip2 is: {0}", ip2); Console.WriteLine("Is ip2 a subset of ip1: {0}", ip2.IsSubsetOf(ip1)); Console.WriteLine("Is ip1 a subset of ip2: {0}", ip1.IsSubsetOf(ip2));
P Q R S T U V W X Y Z
2141
Contents | Index
IPermission Interface
System.Security
Union() Method
Console.WriteLine("Is ip1 a subset of ip1: {0}", ip1.IsSubsetOf(ip1)); } }
A
}
B
The output is
C ip1 is:
D E F
ip2 is:
G H I
Is ip2 a subset of ip1: True Is ip1 a subset of ip2: False Is ip1 a subset of ip1: True
J K L M
IPermission.Union(System.Security.IPermission) Method
N
[ILASM]
O
.method public hidebysig virtual abstract class System.Security.IPermission Union(class System.Security.IPermission target)
P
[C#]
IPermission Union(IPermission target)
Q R
Summary
S
Returns an object that is the union of the current instance and the specified object.
T
Parameters
U V
Parameter
Description
target
A System.Security.IPermission object of the same type as the current instance to combine with the current instance.
W X Y Z
Return Value A new System.Security.IPermission object of the same type as the current instance that represents the union of the current instance and target. 2142
Contents | Index
System.Security
IPermission Interface Union() Method
Description The object returned by System.Security.IPermission.Union is a permission that represents the permissions described by the current instance and those described by target. Any demand that passes either the current instance or target is required to pass the union of the two.
A B C
Behaviors
D
If target is not null and is not of the same type as the current instance, a System.ArgumentException exception is required to be thrown. The following statements are required to be true for all implementations of the System.Security.IPermission.Union method. X and Y represent non-null System.Security.IPermission objects.
E F G H
• • •
X.Union(X) returns an object that is value-equal to X. X.Union(Y) returns an object that is value-equal to the object returned by Y.Union(X). X.Union(null) returns an object that is value-equal to X.
I J K
Usage
L
Use this method to obtain a System.Security.IPermission object of the same type as the current instance and target that describes the permissions described by the current instance and those described by target.
M N O
Exceptions
P
Exception
Condition
System.ArgumentException
target is not null and is not of the same type as the current instance.
Q R S T U
Example
V
using System; using System.Security; using System.Security.Permissions;
W X
namespace Samples { public class IPermissionUnion { public static void Main() {
Y Z
2143
Contents | Index
IPermission Interface
System.Security
Union() Method
EnvironmentPermission ep1 = new EnvironmentPermission( EnvironmentPermissionAccess.Read, "COMPUTERNAME"); IPermission ip1 = ep1; IPermission ip2 = ep1.Copy(); ep1.AddPathList(EnvironmentPermissionAccess.Read, "USERNAME"); EnvironmentPermission ep2 = (EnvironmentPermission) ip2; ep2.AddPathList(EnvironmentPermissionAccess.Read, "DOMAINNAME"); Console.WriteLine("ip1.Union(ip2) is: {0}", ip1.Union(ip2));
A B C D E F G
}
H
} }
I
The output is
J K
ip1.Union(ip2) is:
L M N O P Q R S T U V W X Y Z
2144
Contents | Index
System MarshalByRefObject
BCL
Object
A
MarshalByRefObject Stream
B
IDisposable
FileStream
C
MemoryStream TextReader
D IDisposable
E
StreamReader
F
StringReader TextWriter
G IDisposable
H StreamWriter
I StringWriter
J Timer
IDisposable
WaitHandle
IDisposable
K L
Summary
M
Enables access to objects across application domain boundaries in implementations that support remoting.
N O P
Type Summary public abstract class MarshalByRefObject { // Constructors MS protected MarshalByRefObject ();
Q
// Methods MS CF public virtual ObjRef CreateObjRef (Type requestedType); MS CF public object GetLifetimeService (); MS CF public virtual object InitializeLifetimeService (); }
T
R S
U V W X
BA The meaning of this class is only interesting when you consider cross-process or
Y
cross-machine remoting. That functionality was not included as part of the CLI standard. However, we needed to keep this placeholder type in the standard, as many of the types in the standard extend from it.
Z
2145
Contents | Index
MarshalByRefObject
System
MarshalByRefObject() Constructor
Description [Note: An application domain is a partition in an OS process where one or more applications reside. Objects in the same application domain communicate directly. Objects that reside in different application domains communicate either by transporting copies of objects across application domain boundaries, or by exchanging messages via proxy.] System.MarshalByRefObject is the base class for objects that communicate across application domain boundaries by exchanging messages via a proxy. Objects that do not inherit from System.MarshalByRefObject are implicitly marshal by value. When a remote application references a marshal by value object, a copy of the object is passed across application domain boundaries.
A B C D E F G
MarshalByRefObject() Constructor
H I
[ILASM] family rtspecialname specialname instance void .ctor()
J
[C#]
protected MarshalByRefObject ();
K L
Summary
M
Initializes a new instance of the MarshalByRefObject class.
N O
MarshalByRefObject.CreateObjRef(System.Type) Method
P [ILASM]
Q
.method public hidebysig virtual class System.Runtime.Remoting.ObjRef CreateObjRef(class System.Type requestedType)
R
[C#]
public virtual ObjRef CreateObjRef(Type requestedType)
S T
Summary
U
Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
V W
Parameters
X Y
Parameter
Description
requestedType
The System.Type of the object that the new System.Runtime.Remoting.ObjRef will reference.
Z
2146
Contents | Index
System
MarshalByRefObject GetLifetimeService() Method
Exceptions Exception
Condition A
System.Runtime.Remoting.RemotingException
This instance is not a valid remoting object.
System.Security.SecurityException
The immediate caller does not have infrastructure permission.
B C D E F
Permissions
G
Permission
Description
System.Security.Permissions.SecurityPermission
For operating with infrastructure code. Associated enumeration: System.Security.Permissions.Security-PermissionFlag.Infrastructure.
H I J K L
MarshalByRefObject.GetLifetimeService() Method
M
[ILASM]
N
.method public final hidebysig virtual object GetLifetimeService()
O
[C#]
public object GetLifetimeService()
P Q
Summary
R
Retrieves the current lifetime service object that controls the lifetime policy for this instance.
S T
Description
U
For more information about lifetime services, see the System.Runtime.Remoting.Lifetime.LifetimeServices class.
V W
Exceptions
X
Exception
Condition
System.Security.SecurityException
The immediate caller does not have infrastructure permission.
Y Z
2147
Contents | Index
MarshalByRefObject
System
InitializeLifetimeService() Method
Permissions Permission
Description
System.Security.Permissions.SecurityPermission
For operating with infrastructure code. Associated enumeration: System.Security.Permissions.SecurityPermissionFlag.Infrastructure.
A B C D E
MarshalByRefObject.InitializeLifetimeService() Method
F G
[ILASM]
H
[C#]
.method public hidebysig virtual object InitializeLifetimeService() public virtual object InitializeLifetimeService()
I J
Summary
K
Obtains a lifetime service object to control the lifetime policy for this instance.
L
Return Value
M
An object of type System.Runtime.Remoting.Lifetime.ILease used to control the lifetime policy for this instance. This is the current lifetime service object for this instance if one exists; otherwise, a new lifetime service object initialized to the value of the System.Runtime.Remoting.Lifetime.LifetimeServices.LeaseManagerPollTime property.
N O P Q R
Description
S
For more information about lifetime services, see the System.Runtime.Remoting.Lifetime.LifetimeServices class.
T
Exceptions
U V W X
Exception
Condition
System.Security.SecurityException
The immediate caller does not have infrastructure permission.
Y Z
2148
Contents | Index
System
MarshalByRefObject InitializeLifetimeService() Method
Permissions Permission
Description
System.Security.Permissions.SecurityPermission
For operating with infrastructure code. Associated enumeration: System.Security.Permissions.SecurityPermissionFlag.Infrastructure.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
2149
Contents | Index
System Math
Extended Numerics
Object
A
Math
ExtendedNumerics
B
Summary
C
Provides constants and static methods for trigonometric, logarithmic, and other common mathematical functions.
D E
Type Summary
F
public sealed class Math { // Fields public const double E = 2.7182818284590452354; public const double PI = 3.14159265358979323846;
G H I J
// Methods public static decimal Abs (decimal value); public static double Abs (double a); public static float Abs (float a); public static int Abs (int value); public static long Abs (long value); public static sbyte Abs (sbyte value); public static short Abs (short value); public static double Acos (double d); public static double Asin (double d); public static double Atan (double d); public static double Atan2(double y, double x); CF 1.1 public static long BigMul (int a, int b); public static double Ceiling (double a); public static double Cos (double d); public static double Cosh (double value); CF 1.1 public static int DivRem (int a, int b, out int result); CF 1.1 public static long DivRem (long a, long b, out long result); public static double Exp (double a); public static double Floor (double a); public static double IEEERemainder (double x, double y); public static double Log (double a); CF public static double Log (double a, double newBase); public static double Log10(double a); public static byte Max (byte val1, byte val2);
K L M N O P Q R S T U V W X Y Z
2150
Contents | Index
System
Math Math Class
public static decimal Max (decimal val1, decimal val2); public static double Max (double val1, double val2); public static float Max (float val1, float val2); public static int Max (int val1, int val2); public static long Max (long val1, long val2); public static sbyte Max (sbyte val1, sbyte val2); public static short Max (short val1, short val2); public static uint Max (uint val1, uint val2); public static ulong Max (ulong val1, ulong val2); public static ushort Max (ushort val1, ushort val2); public static byte Min (byte val1, byte val2); public static decimal Min (decimal val1, decimal val2); public static double Min (double val1, double val2); public static float Min (float val1, float val2); public static int Min (int val1, int val2); public static long Min (long val1, long val2); public static sbyte Min (sbyte val1, sbyte val2); public static short Min (short val1, short val2); public static uint Min (uint val1, uint val2); public static ulong Min (ulong val1, ulong val2); public static ushort Min (ushort val1, ushort val2); public static double Pow (double x, double y); public static decimal Round (decimal d); MS public static decimal Round (decimal d, int decimals); public static double Round (double a); public static double Round (double value, int digits); public static int Sign (decimal value); public static int Sign (double value); public static int Sign (float value); public static int Sign (int value); public static int Sign (long value); public static int Sign (sbyte value); public static int Sign (short value); public static double Sin (double a); public static double Sinh (double value); public static double Sqrt (double a); public static double Tan (double a); public static double Tanh (double value);
A B C D E F G H I J K L M N O P Q R S T U V W X
}
Y Z
2151
Contents | Index
Math
System
E Field
BA The decision to include Decimal in many of the overloads in this class was not obvious in the original design because the Decimal class does not have native support in the runtime. That is, none of the IL instructions operate directly on Decimals in the same way they do on doubles, ints, etc.
A B C D
Math.E Field
E [ILASM]
F
.field public static literal float64 E [C#]
G
public const double E = 2.71828182845905
H
Summary
I
A constant, e, which specifies the natural logarithmic base rounded to double precision.
J K
Description
L
The value of this constant is 2.7182818284590452354 converted to System.Double.
M
Example
N
using System;
O namespace Samples { public class MathE { public static void Main() { Console.WriteLine("E: {0}", Math.E); Console.WriteLine("Pi: {0}", Math.PI); } } }
P Q R S T U V W
The output is
X
E: 2.71828182845905 Pi: 3.14159265358979
Y Z
2152
Contents | Index
System
Math Abs() Method
Math.PI Field [ILASM]
.field public static literal float64 PI [C#]
A
public const double PI = 3.14159265358979
B C
Summary
D
A constant, π, which specifies the ratio of the circumference of a circle to its diameter rounded to double precision.
E F
Description
G
The value of this constant is 3.14159265358979323846 converted to System.Double.
H
Example
I
using System;
J
namespace Samples { public class MathPI { public static void Main() { Console.WriteLine("E: {0}", Math.E); Console.WriteLine("Pi: {0}", Math.PI); } } }
K L M N O P Q R
The output is
S E: 2.71828182845905 Pi: 3.14159265358979
T U V
Math.Abs(System.Decimal) Method
W [ILASM]
X
.method public hidebysig static decimal Abs(decimal value) [C#]
Y
public static decimal Abs(decimal value)
Z
Summary Returns the absolute value of the specified System.Decimal. 2153
Contents | Index
Math
System
Abs() Method
Parameters Parameter
Description
value
A System.Decimal.
A B C D
Return Value
E
A System.Decimal containing the absolute value of value.
F
Example
G
using System;
H
namespace Samples { public class MathAbs { public static void Main() { Decimal max = Decimal.MaxValue, one = Decimal.One, zero = Decimal.Zero, minusOne = Decimal.MinusOne, min = Decimal.MinValue; Console.WriteLine("Abs({0}): {1}", max, Math.Abs(max)); Console.WriteLine("Abs({0}): {1}", one, Math.Abs(one)); Console.WriteLine("Abs({0}): {1}", zero, Math.Abs(zero)); Console.WriteLine("Abs({0}): {1}", minusOne, Math.Abs(minusOne)); Console.WriteLine("Abs({0}): {1}", min, Math.Abs(min)); } } }
I J K L M N O P Q R S T U
The output is
V Abs(79228162514264337593543950335): 79228162514264337593543950335 Abs(1): 1 Abs(0): 0 Abs(-1): 1 Abs(-79228162514264337593543950335): 79228162514264337593543950335
W X Y Z
2154
Contents | Index
System
Math Abs() Method
Math.Abs(System.Double) Method [ILASM]
.method public hidebysig static float64 Abs(float64 value) [C#]
A
public static double Abs(double value)
B C
Summary
D
Returns the absolute value of the specified System.Double.
E
Parameters
F
Parameter
Description
value
A System.Double.
G H I J
Return Value
K
A System.Double containing the absolute value of value. If value is equal to System.Double.NegativeInfinity or System.Double.PositiveInfinity, returns System.Double.PositiveInfinity. If value is equal to System.Double.NaN, returns System.Double.NaN.
L M N O
Example
P
using System;
Q namespace Samples { public class MathAbs { public static void Main() { Double max = Double.MaxValue, nan = Double.NaN, positiveInfinity = Double.PositiveInfinity, negativeInfinity = Double.NegativeInfinity, min = Double.MinValue; Console.WriteLine("Abs({0}): {1}", max, Math.Abs(max)); Console.WriteLine("Abs({0}): {1}", nan, Math.Abs(nan)); Console.WriteLine("Abs({0}): {1}", positiveInfinity, Math.Abs(positiveInfinity));
R S T U V W X Y Z
2155
Contents | Index
Math
System
Abs() Method
Console.WriteLine("Abs({0}): {1}", negativeInfinity, Math.Abs(negativeInfinity)); Console.WriteLine("Abs({0}): {1}", min, Math.Abs(min)); }
A
} }
B C
The output is
D Abs(1.79769313486232E+308): 1.79769313486232E+308 Abs(NaN): NaN Abs(Infinity): Infinity Abs(-Infinity): Infinity Abs(-1.79769313486232E+308): 1.79769313486232E+308
E F G H I
Math.Abs(System.Single) Method
J
[ILASM]
.method public hidebysig static float32 Abs(float32 value)
K
[C#]
L
public static float Abs(float value)
M
Summary
N
Returns the absolute value of the specified System.Single.
O
Parameters
P Q R S
Parameter
Description
value
A System.Single.
T U
Return Value
V
A System.Single containing the absolute value of value. If value is equal to System.Single.NegativeInfinity or System.Single.PositiveInfinity, returns System.Single.PositiveInfinity. If value is equal to System.Single.NaN, returns System.Single.NaN.
W X Y Z
2156
Contents | Index
System
Math Abs() Method
Example using System; namespace Samples { public class MathAbs { public static void Main() { float max = float.MaxValue, nan = float.NaN, positiveInfinity = float.PositiveInfinity, negativeInfinity = float.NegativeInfinity, min = float.MinValue; Console.WriteLine("Abs({0}): {1}", max, Math.Abs(max)); Console.WriteLine("Abs({0}): {1}", nan, Math.Abs(nan)); Console.WriteLine("Abs({0}): {1}", positiveInfinity, Math.Abs(positiveInfinity)); Console.WriteLine("Abs({0}): {1}", negativeInfinity, Math.Abs(negativeInfinity)); Console.WriteLine("Abs({0}): {1}", min, Math.Abs(min)); } } }
A B C D E F G H I J K L M N
The output is
O Abs(3.402823E+38): 3.402823E+38 Abs(NaN): NaN Abs(Infinity): Infinity Abs(-Infinity): Infinity Abs(-3.402823E+38): 3.402823E+38
P Q R S T
Math.Abs(System.Int32) Method
U [ILASM]
V
.method public hidebysig static int32 Abs(int32 value) [C#]
W
public static int Abs(int value)
X
Summary
Y
Returns the absolute value of the specified System.Int32.
Z
2157
Contents | Index
Math
System
Abs() Method
Parameters Parameter
Description
value
A System.Int32.
A B C D
Return Value
E
A System.Int32 containing the absolute value of value.
F
Exceptions
G H I
Exception
Condition
System.OverflowException
value equals System.Int32.MinValue.
J K
Example
L
using System;
M namespace Samples { public class MathAbs { public static void Main() { try { int max = int.MaxValue, min = int.MinValue; Console.WriteLine("Abs({0}): {1}", max, Math.Abs(max)); Console.WriteLine("Abs({0}): {1}", min + 1, Math.Abs(min + 1)); Console.WriteLine("Abs({0}): {1}", min, Math.Abs(min)); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
N O P Q R S T U V W X Y Z
2158
Contents | Index
System
Math Abs() Method
The output is Abs(2147483647): 2147483647 Abs(-2147483647): 2147483647 Exception: System.OverflowException: Negating the minimum value of a twos complement number is invalid. at System.Math.AbsHelper(Int32 value) at System.Math.Abs(Int32 value) at Samples.MathAbs.Main() in C:\Books\BCL\Samples\System\Math\ Abs(System.Int32)\Math.cs:line 16
A B C D E F
Math.Abs(System.Int64) Method
G
[ILASM]
H
.method public hidebysig static int64 Abs(int64 value)
I
[C#]
public static long Abs(long value)
J
Summary
K
Returns the absolute value of the specified System.Int64.
L M
Parameters
N O
Parameter
Description
value
A System.Int64.
P Q R
Exceptions
S
Exception
Condition
System.OverflowException
value equals System.Int64.MinValue.
T U V W X Y Z
2159
Contents | Index
Math
System
Abs() Method
Example using System; namespace Samples { public class MathAbs { public static void Main() { try { long max = long.MaxValue, min = long.MinValue; Console.WriteLine("Abs({0}): {1}", max, Math.Abs(max)); Console.WriteLine("Abs({0}): {1}", min + 1, Math.Abs(min + 1)); Console.WriteLine("Abs({0}): {1}", min, Math.Abs(min)); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N
The output is
O P
Abs(9223372036854775807): 9223372036854775807 Abs(-9223372036854775807): 9223372036854775807 Exception: System.OverflowException: Negating the minimum value of a twos complement number is invalid. at System.Math.AbsHelper(Int64 value) at System.Math.Abs(Int64 value) at Samples.MathAbs.Main() in C:\Books\BCL\Samples\System\Math\ Abs(System.Int64)\Math.cs:line 16
Q R S T U V W
Math.Abs(System.SByte) Method
X
[ILASM]
.method public hidebysig static int8 Abs(int8 value)
Y
[C#]
public static sbyte Abs(sbyte value)
Z
2160
Contents | Index
System
Math Abs() Method
Summary Returns the absolute value of the specified System.SByte. A
Parameters
B
Parameter
Description
C
value
A System.SByte.
D E F
Return Value
G
A System.SByte containing the absolute value of value.
H
Description
I
This method is not CLS-compliant. For a CLS-compliant alternative, use System.Math.Abs(System.Int16).
J K
Exceptions
L M
Exception
Condition N
System.OverflowException
value equals System.SByte.MinValue.
O P
Example
Q
using System;
R
namespace Samples { public class MathAbs { public static void Main() { try { sbyte max = sbyte.MaxValue, min = sbyte.MinValue; Console.WriteLine("Abs({0}): {1}", max, Math.Abs(max)); Console.WriteLine("Abs({0}): {1}", min + 1, Math.Abs(min + 1)); Console.WriteLine("Abs({0}): {1}", min, Math.Abs(min)); }
S T U V W X Y Z
2161
Contents | Index
Math
System
Abs() Method
catch(Exception e) { Console.WriteLine("Exception: {0}", e); }
A
} }
B }
C
The output is
D E
Abs(127): 127 Abs(-127): 127 Exception: System.OverflowException: Negating the minimum value of a twos complement number is invalid. at System.Math.AbsHelper(SByte value) at System.Math.Abs(SByte value) at Samples.MathAbs.Main() in C:\Books\BCL\Samples\System\Math\ Abs(System.SByte)\Math.cs:line 16
F G H I J K
Math.Abs(System.Int16) Method
L
[ILASM]
M
.method public hidebysig static int16 Abs(int16 value) [C#]
N
public static short Abs(short value)
O P
Summary
Q
Returns the absolute value of the specified System.Int16.
R
Parameters
S T U
Parameter
Description
value
A System.Int16.
V W
Exceptions
X Y
Exception
Condition
System.OverflowException
value equals System.Int16.MinValue.
Z
2162
Contents | Index
System
Math Acos() Method
Example using System; namespace Samples { public class MathAbs { public static void Main() { try { short max = short.MaxValue, min = short.MinValue; Console.WriteLine("Abs({0}): {1}", max, Math.Abs(max)); Console.WriteLine("Abs({0}): {1}", min + 1, Math.Abs(min + 1)); Console.WriteLine("Abs({0}): {1}", min, Math.Abs(min)); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N
The output is
O P
Abs(32767): 32767 Abs(-32767): 32767 Exception: System.OverflowException: Negating the minimum value of a twos complement number is invalid. at System.Math.AbsHelper(Int16 value) at System.Math.Abs(Int16 value) at Samples.MathAbs.Main() in C:\Books\BCL\Samples\System\Math\ Abs(System.Int16)\Math.cs:line 16
Q R S T U V
Math.Acos(System.Double) Method
W
[ILASM]
X
.method public hidebysig static float64 Acos(float64 d)
Y
[C#]
public static double Acos(double d)
Z
2163
Contents | Index
Math
System
Acos() Method
Summary Returns the angle whose cosine is the specified System.Double. A
Parameters
B C
Parameter
Description
D
d
A System.Double representing a cosine, where –1 <= d <= 1.
E F
Return Value A System.Double containing the value of an angle, θ, measured in radians, for which d is the cosine, such that 0 <= θ <= π. If d < –1, d> 1, or d = System.Double.NaN, returns System.Double.NaN.
G H I J
Description
K
[Note: Multiply the return value by 180/θ to convert from radians to degrees.]
L
Example
M
using System;
N namespace Samples { public class MathAcos { public static void Main() { Double[] doubles = {-1, -0.5, 0, 0.5, 1}; foreach(Double d in doubles) Console.WriteLine("Acos({0}): {1}", d, Math.Acos(d)); } } }
O P Q R S T U V
The output is
W
Acos(-1): 3.14159265358979 Acos(-0.5): 2.0943951023932 Acos(0): 1.5707963267949 Acos(0.5): 1.0471975511966 Acos(1): 0
X Y Z
2164
Contents | Index
System
Math Asin() Method
Math.Asin(System.Double) Method [ILASM]
.method public hidebysig static float64 Asin(float64 d) [C#]
A
public static double Asin(double d)
B C
Summary
D
Returns the angle whose sine is the specified System.Double.
E
Parameters
F
Parameter
Description
d
A System.Double representing a sine, where –1 <= d <= 1.
G H I J
Return Value
K
A System.Double containing the value of an angle, θ, measured in radians, for which d is the sine, such that –θ/2 <= θ <= θ/2. If d < –1, d > 1, or d = System.Double.NaN, returns System.Double.NaN.
L M N
Description
O
[Note: A positive return value represents a counterclockwise angle from the positive x-axis; a negative return value represents a clockwise angle. Multiply the return value by 180/θ to convert from radians to degrees.]
P Q R
Example
S
using System;
T namespace Samples { public class MathAsin { public static void Main() { Double[] doubles = {-1, -0.5, 0, 0.5, 1}; foreach(Double d in doubles) Console.WriteLine("Asin({0}): {1}", d, Math.Asin(d)); } } }
U V W X Y Z
2165
Contents | Index
Math
System
Atan() Method
The output is Asin(-1): -1.5707963267949 Asin(-0.5): -0.523598775598299 Asin(0): 0 Asin(0.5): 0.523598775598299 Asin(1): 1.5707963267949
A B C D E
Math.Atan(System.Double) Method
F
[ILASM]
.method public hidebysig static float64 Atan(float64 d)
G
[C#]
public static double Atan(double d)
H I
Summary
J
Returns the angle whose tangent is the specified System.Double.
K
Parameters
L M
Parameter
Description
d
A System.Double that represents a tangent.
N O P
Return Value
Q
A System.Double containing the value of the angle, θ, measured in radians, for which d is the tangent, such that –θ/2 <= θ <= θ/2. The following table specifies the return value if d is equal to System.Double.NaN, System.Double.NegativeInfinity, or System.Double.PositiveInfinity.
R S T U V
Return Value
Condition
System.Double.NaN
d is equal to System.Double.NaN.
–θ/2 rounded to double precision (–1.5707963267949)
d is equal to System.Double.NegativeInfinity.
θ/2 rounded to double precision (1.5707963267949)
d is equal to System.Double.PositiveInfinity.
W X Y Z
2166
Contents | Index
System
Math Atan2() Method
Description [Note: A positive return value represents a counterclockwise angle from the positive x-axis; a negative return value represents a clockwise angle. Multiply the return value by 180/θ to convert from radians to degrees.]
A B
Example
C
using System;
D namespace Samples { public class MathAtan { public static void Main() { Double[] doubles = {-1, -0.5, 0, 0.5, 1}; foreach(Double d in doubles) Console.WriteLine("Atan({0}): {1}", d, Math.Atan(d)); } } }
E F G H I J K L
The output is
M N
Atan(-1): -0.785398163397448 Atan(-0.5): -0.463647609000806 Atan(0): 0 Atan(0.5): 0.463647609000806 Atan(1): 0.785398163397448
O P Q R
Math.Atan2(System.Double, System.Double) Method
S
[ILASM]
T
.method public hidebysig static float64 Atan2(float64 y, float64 x)
U
[C#]
public static double Atan2(double y, double x)
V
Summary
W
Returns the angle whose tangent is the quotient of two specified System.Double values.
X Y Z
2167
Contents | Index
Math
System
Atan2() Method
Parameters Parameter
Description
y
A System.Double representing the y coordinate of a point.
x
A System.Double representing the x coordinate of a point.
A B C D
Return Value
E
A System.Double containing the value of an angle, θ, measured in radians, such that - θ<= θ <= θ and tanθ = y/x, where (x, y) is a point in the Cartesian plane. If both x and y are any combination of System.Double.NegativeInfinity and System.Double.PositiveInfinity, System.Double.NaN is returned. If either x or y is equal to System.Double.NaN, System.Double.NaN is returned. The following table specifies the return value if x or y is equal to System.Double.NegativeInfinity or System.Double.PositiveInfinity.
F G H I J K L
Condition
Return Value
M N
y is equal to System.Double.PositiveInfinity or System.Double.NegativeInfinity, and
O
x is equal to System.Double.PositiveInfinity or System.Double.NegativeInfinity
System.Double.NaN
P
y is equal to System.Double.NegativeInfinity, and
Q R
x is not equal to System.Double.PositiveInfinity or System.Double.NegativeInfinity
S
y is equal to System.Double.PositiveInfinity, and
T
x is not equal to System.Double.PositiveInfinity or System.Double.NegativeInfinity
U
–System.Math.PI/2
System.Math.PI/2
x is equal to System.Double.PositiveInfinity, and
V W
y is not equal to System.Double.PositiveInfinity or System.Double.NegativeInfinity
X
x is equal to System.Double.NegativeInfinity, and
Y
y >= 0 and not equal to System.Double.PositiveInfinity
Z
x is equal to System.Double.NegativeInfinity, and y < 0 and not equal to System.Double.NegativeInfinity
0
System.Math.PI
–System.Math.PI
2168
Contents | Index
System
Math BigMul() Method
Description The return value is the angle in the Cartesian plane formed by the x-axis, and a vector starting from the origin, (0,0), and terminating at the point, (x,y). [Note: For For For For
(x, (x, (x, (x,
y) y) y) y)
in in in in
quadrant quadrant quadrant quadrant
1, 2, 3, 4,
A
0 < θ < /2. θ/2 < θ < θ. -θ < θ < -θ/2. -θ/2 < θ < 0.]
B C D
Example
E
using System;
F G
namespace Samples { public class MathAtan2 { public static void Main() { Double[] doubles = {-1, -0.5, 0, 0.5, 1}; foreach(Double d in doubles) Console.WriteLine("Atan2({0}, 0): {1}", d, Math.Atan2(d, 0)); } } }
H I J K L M N O
The output is
P Atan2(-1, 0): -1.5707963267949 Atan2(-0.5, 0): -1.5707963267949 Atan2(0, 0): 0 Atan2(0.5, 0): 1.5707963267949 Atan2(1, 0): 1.5707963267949
Q R S T
Math.BigMul(System.Int32, System.Int32) Method
U
[ILASM]
V
.method public hidebysig static int64 BigMul(int32 a,int32 b)
W
[C#]
X
public static long BigMul(int a, int b)
Y
Summary
Z
Produces the full product of two 32-bit numbers.
2169
Contents | Index
Math
System
Ceiling() Method
Parameters Parameter
Description
a
The first System.Int32 to multiply.
b
The second System.Int32 to multiply.
A B C D E
Return Value
F
A System.Int64 containing the product of the specified numbers.
G H
Math.Ceiling(System.Double) Method
I [ILASM]
J
.method public hidebysig static float64 Ceiling(float64 a) [C#]
K
public static double Ceiling(double a)
L
Summary
M
Returns the smallest integer greater than or equal to the specified System.Double.
N O
Parameters
P Q
Parameter
Description
R
a
A System.Double.
S T
Return Value
U
A System.Double containing the value of the smallest integer greater than or equal to a. If a is equal to System.Double.NaN, System.Double.NegativeInfinity, or System.Double.PositiveInfinity, that value is returned.
V W X Y Z
2170
Contents | Index
System
Math Cos() Method
Example using System; namespace Samples { public class MathCeiling { public static void Main() { Double[] doubles = {-1, -0.5, 0, 0.5, 1}; foreach(Double d in doubles) Console.WriteLine("Ceiling({0}): {1}", d, Math.Ceiling(d)); } } }
A B C D E F G H
The output is
I
Ceiling(-1): -1 Ceiling(-0.5): 0 Ceiling(0): 0 Ceiling(0.5): 1 Ceiling(1): 1
J K L M N
Math.Cos(System.Double) Method
O
[ILASM]
P
.method public hidebysig static float64 Cos(float64 d)
Q
[C#]
public static double Cos(double d)
R
Summary
S
Returns the cosine of the specified System.Double that represents an angle.
T U
Parameters
V
Parameter
Description
d
A System.Double that represents an angle measured in radians.
W X Y Z
2171
Contents | Index
Math
System
Cosh() Method
Return Value A System.Double containing the value of the cosine of d. If d is equal to System.Double.NaN, System.Double.NegativeInfinity, or System.Double.PositiveInfinity, returns System.Double.NaN.
A B
Description
C
[Note: Multiply by θ/180 to convert degrees to radians.]
D E
Example
F
using System;
G
namespace Samples { public class MathCos { public static void Main() { Double[] doubles = {-1, -0.5, 0, 0.5, 1}; foreach(Double d in doubles) Console.WriteLine("Cos({0}): {1}", d, Math.Cos(d)); } } }
H I J K L M N O
The output is
P Cos(-1): 0.54030230586814 Cos(-0.5): 0.877582561890373 Cos(0): 1 Cos(0.5): 0.877582561890373 Cos(1): 0.54030230586814
Q R S T U
Math.Cosh(System.Double) Method
V
[ILASM]
W
.method public hidebysig static float64 Cosh(float64 value) [C#]
X
public static double Cosh(double value)
Y
Summary
Z
Returns the hyperbolic cosine of the specified System.Double that represents an angle.
2172
Contents | Index
System
Math Cosh() Method
Parameters Parameter
Description
value
A System.Double that represents an angle measured in radians.
A B C
Return Value
D
The hyperbolic cosine of value. If value is equal to System.Double.NegativeInfinity or System.Double.PositiveInfinity, returns System.Double.PositiveInfinity. If value is equal to System.Double.NaN, returns System.Double.NaN.
E F G
Description
H
[Note: Multiply by θ/180 to convert degrees to radians.]
I
Example
J
using System;
K L
namespace Samples { public class MathCosh { public static void Main() { Double[] doubles = {-1, -0.5, 0, 0.5, 1}; foreach(Double d in doubles) Console.WriteLine("Cosh({0}): {1}", d, Math.Cosh(d)); } } }
M N O P Q R S T
The output is
U Cosh(-1): 1.54308063481524 Cosh(-0.5): 1.12762596520638 Cosh(0): 1 Cosh(0.5): 1.12762596520638 Cosh(1): 1.54308063481524
V W X Y Z
2173
Contents | Index
Math
System
DivRem() Method
Math.DivRem(System.Int32, System.Int32, System.Int32) Method [ILASM]
.method public hidebysig static int32 DivRem(int32 a,int32 b, [out] int32 &result)
A
[C#]
public static int DivRem(int a, int b, out int result)
B C
Summary
D
Returns the quotient of two numbers, also passing the remainder as an output parameter.
E
Parameters
F G
Parameter
Description
I
a
A System.Int32 that contains the dividend.
J
b
A System.Int32 that contains the divisor.
K
result
A System.Int32 that receives the remainder.
H
L M N
Math.DivRem(System.Int64, System.Int64, System.Int64) Method
O
[ILASM]
.method public hidebysig static int64 DivRem(int64 a,int64 b,[out] int64 &result)
P
[C#]
public static long DivRem(long a, long b, out long result)
Q R
Summary
S
Returns the quotient of two numbers, also passing the remainder as an output parameter.
T
Parameters
U V
Parameter
Description
X
a
A System.Int64 that contains the dividend.
Y
b
A System.Int64 that contains the divisor.
result
A System.Int64 that receives the remainder.
W
Z
2174
Contents | Index
System
Math Exp() Method
Math.Exp(System.Double) Method [ILASM]
.method public hidebysig static float64 Exp(float64 d) [C#]
A
public static double Exp(double d)
B C
Summary
D
Returns e raised to the specified System.Double that represents an exponent.
E
Parameters
F
Parameter
Description
d
A System.Double that represents an exponent.
G H I J
Return Value
K
A System.Double equal to the number e raised to the power of d. If d equals System.Double.NaN or System.Double.PositiveInfinity, returns that value. If d equals System.Double.NegativeInfinity, returns 0.
L M N
Description
O
[Note: Use the System.Math.Pow method to calculate powers of other bases. System.Math.Exp is the inverse of System.Math.Log.]
P Q
Example
R
using System;
S
namespace Samples { public class MathExp { public static void Main() { Double[] doubles = {-1, -0.5, 0, 0.5, 1}; foreach(Double d in doubles) Console.WriteLine("Exp({0}): {1}", d, Math.Exp(d)); } } }
T U V W X Y Z
2175
Contents | Index
Math
System
Floor() Method
The output is Exp(-1): 0.367879441171442 Exp(-0.5): 0.606530659712633 Exp(0): 1 Exp(0.5): 1.64872127070013 Exp(1): 2.71828182845905
A B C D E
Math.Floor(System.Double) Method
F
[ILASM]
.method public hidebysig static float64 Floor(float64 d)
G
[C#]
public static double Floor(double d)
H I
Summary
J
Returns the largest integer less than or equal to the specified System.Double.
K
Parameters
L M
Parameter
Description
d
A System.Double.
N O P
Return Value
Q
A System.Double containing the value of the largest integer less than or equal to d. If d is equal to System.Double.NaN, System.Double.NegativeInfinity, or System.Double.PositiveInfinity, that value is returned.
R S T
Description
U
The behavior of this method follows IEEE Standard 754, section 4.
V W
Example
X
using System;
Y
namespace Samples { public class MathFloor { public static void Main()
Z
2176
Contents | Index
System
Math IEEERemainder() Method
{ Double[] doubles = {-1, -0.5, 0, 0.5, 1}; foreach(Double d in doubles) Console.WriteLine("Floor({0}): {1}", d, Math.Floor(d));
A
} }
B
}
C
The output is
D E
Floor(-1): -1 Floor(-0.5): -1 Floor(0): 0 Floor(0.5): 0 Floor(1): 1
F G H I
Math.IEEERemainder(System.Double, System.Double) Method
J
[ILASM]
K
.method public hidebysig static float64 IEEERemainder(float64 x, float64 y)
L
[C#]
public static double IEEERemainder(double x, double y)
M
Summary
N
Returns the remainder resulting from the division of one specified System.Double by another specified System.Double.
O P Q
Parameters
R
Parameter
Description
x
A System.Double that represents a dividend.
y
A System.Double that represents a divisor.
S T U V W
Return Value
X
A System.Double whose value is as follows:
Y Z
2177
Contents | Index
Math
System
IEEERemainder() Method
A
Value
Description
x – (y Q),
Q is the quotient of x/ y rounded to the nearest integer (if x/ y is exactly halfway between two integers, the even integer is returned).
+0
Q is the quotient of x/ y rounded to the nearest integer (if x/ y is exactly halfway between two integers, the even integer is returned). x – (y Q) is zero, and x is positive.
–0
Q is the quotient of x/ y rounded to the nearest integer (if x/ y is exactly halfway between two integers, the even integer is returned). x – (y Q) is zero, and x is negative.
System.Double.NaN
y = 0.
B C D E F G H
Description
I
This operation complies with the remainder operation defined in Section 5.1 of ANSI/IEEE Std 754-1985; IEEE Standard for Binary Floating-Point Arithmetic; Institute of Electrical and Electronics Engineers, Inc; 1985. [Note: For more information regarding the use of +0 and –0, see Section 3.1 of ANSI/ IEEE Std 754-1985; IEEE Standard for Binary Floating-Point Arithmetic; Institute of Electrical and Electronics Engineers, Inc; 1985.]
J K L M N
Example
O
using System;
P namespace Samples { public class MathIEEERemainder { public static void Main() { Double[] doubles = {21.5, 20.5, 9, 0.8, 0, -0.8, -9, -20.5, -21.5}; foreach(Double d in doubles) Console.WriteLine("IEEERemainder(42d, {0}): {1}", d, Math.IEEERemainder(42d, d)); } } }
Q R S T U V W X Y
The output is
Z IEEERemainder(42d, 21.5): -1 IEEERemainder(42d, 20.5): 1 IEEERemainder(42d, 9): -3
2178
Contents | Index
System
Math Log() Method
IEEERemainder(42d, IEEERemainder(42d, IEEERemainder(42d, IEEERemainder(42d, IEEERemainder(42d, IEEERemainder(42d,
0.8): 0.399999999999999 0): NaN -0.8): 0.399999999999999 -9): -3 -20.5): 1 -21.5): -1
A B C
Math.Log(System.Double) Method
D
[ILASM]
E
.method public hidebysig static float64 Log(float64 d)
F
[C#]
public static double Log(double d)
G
Summary
H
Returns the natural logarithm of the specified System.Double.
I J
Parameters
K
Parameter
Description
L
d
A System.Double whose natural logarithm is to be found.
M N O
Return Value
P
Returns a System.Double whose value is as follows.
Q R
Condition
Returns
d > 0.
The value of the natural logarithm of d.
d == 0.
System.Double.NegativeInfinity.
S
d < 0. -ord is equal to System.Double.NegativeInfinity. -ord is equal to System.Double.NaN.
T U V W
System.Double.NaN.
X Y Z
d is equal to System.Double.PositiveInfinity.
System.Double.PositiveInfinity.
2179
Contents | Index
Math
System
Log() Method
Description d is specified as a base 10 number. A
Example
B
using System;
C
namespace Samples { public class MathLog { public static void Main() { Double[] doubles = {-1, -0.5, 0, 0.5, 1}; foreach(Double d in doubles) Console.WriteLine("Log({0}): {1}", d, Math.Log(d)); } } }
D E F G H I J
The output is
K
Log(-1): NaN Log(-0.5): NaN Log(0): -Infinity Log(0.5): -0.693147180559945 Log(1): 0
L M N O P
Math.Log(System.Double, System.Double) Method
Q [ILASM]
R
.method public hidebysig static float64 Log(float64 a, float64 newBase) [C#]
S
public static double Log(double a, double newBase)
T
Summary
U
Returns the logarithm of the specified System.Double in the specified base.
V W
Parameters
X Y Z
Parameter
Description
a
A System.Double whose logarithm is to be found.
newBase
A System.Double containing the value of the base of the logarithm.
2180
Contents | Index
System
Math Log() Method
Return Value Returns a System.Double whose value is as follows: A
Condition
Returns
a > 0.
The value of LognewBasea, if and only if newBase is greater than or equal to 0; otherwise, System.Double.NaN.
D
a == 0.
System.Double.NegativeInfinity.
E
a < 0.
System.Double.NaN.
B C
F G H
If a is equal to System.Double.PositiveInfinity and newBase is not equal to System.Double.PositiveInfinity, System.Double.NegativeInfinity, or System.Double.NaN, returns System.Double.PositiveInfinity. If newBase is equal to System.Double.PositiveInfinity and a is not equal to System.Double.PositiveInfinity, System.Double.NegativeInfinity, or System.Double.NaN, returns 0. If both a and newBase are equal to System.Double.PositiveInfinity, or a or newBase is equal to System.Double.NaN or System.Double.NegativeInfinity, returns System.Double.NaN.
I J K L M N O
Example
P
using System;
Q
namespace Samples { public class MathLog { public static void Main() { Double[] doubles = {10, Math.E}; foreach(Double d in doubles) Console.WriteLine("Log(0.5, {0}): {1}", d, Math.Log(0.5, d)); } } }
R S T U V W X Y
The output is
Z Log(0.5, 10): -0.301029995663981 Log(0.5, 2.71828182845905): -0.693147180559945
2181
Contents | Index
Math
System
Log10() Method
Math.Log10(System.Double) Method [ILASM]
.method public hidebysig static float64 Log10(float64 d)
A
[C#]
public static double Log10(double d)
B C
Summary
D
Returns log10 of the specified System.Double.
E
Parameters
F G
Parameter
Description
d
A System.Double whose logarithm is to be found.
H I J K
Return Value
L
Returns a System.Double as indicated by the following table.
M N O P Q
Condition
Returns
d > 0.
A System.Double containing the value of log10d.
d == 0.
System.Double.NegativeInfinity.
R
d < 0.
S
-or-
T
d is equal to System.Double.NegativeInfinity.
U
-or-
V
d is equal to System.Double.NaN.
W
d is equal to System.Double.PositiveInfinity.
X
System.Double.NaN.
System.Double.PositiveInfinity.
Y Z
2182
Contents | Index
System
Math Max() Method
Example using System; namespace Samples { public class MathLog10 { public static void Main() { Double[] doubles = {-1, -0.5, 0, 0.5, 1}; foreach(Double d in doubles) Console.WriteLine("Log10({0}): {1}", d, Math.Log10(d)); } } }
A B C D E F G H
The output is
I J
Log10(-1): NaN Log10(-0.5): NaN Log10(0): -Infinity Log10(0.5): -0.301029995663981 Log10(1): 0
K L M N
Math.Max(System.Byte, System.Byte) Method
O
[ILASM]
P
.method public hidebysig static unsigned int8 Max(unsigned int8 val1, unsigned int8 val2)
Q
[C#]
R
public static byte Max(byte val1, byte val2)
S
Summary
T
Returns the greater of two specified System.Byte values.
U V
Parameters
W
Parameter
Description
val1
The first of two specified System.Byte values to compare.
val2
The second of two specified System.Byte values to compare.
X Y Z
2183
Contents | Index
Math
System
Max() Method
Return Value A System.Byte that is equal to val1 if val1 is greater than or equal to val2; otherwise, the return value is equal to val2. A B
Example
C
using System;
D
namespace Samples { public class MathMax { public static void Main() { byte[] bytes = {byte.MaxValue, 42, byte.MinValue}; for(int i = 0; i < bytes.Length; i++) Console.WriteLine("Max({0}, {1}): {2}", bytes[i], bytes[bytes.Length - (i + 1)], Math.Max(bytes[i], bytes[bytes.Length - (i + 1)])); } } }
E F G H I J K L M N
The output is
O
Max(255, 0): 255 Max(42, 42): 42 Max(0, 255): 255
P Q R
Math.Max(System.Decimal, System.Decimal) Method
S
[ILASM]
T
.method public hidebysig static decimal Max(decimal val1, decimal val2)
U
[C#]
public static decimal Max(decimal val1, decimal val2)
V W
Summary
X
Returns the greater of two specified System.Decimal values.
Y Z
2184
Contents | Index
System
Math Max() Method
Parameters Parameter
Description
val1
The first of two specified System.Decimal values to compare.
val2
The second of two specified System.Decimal values to compare.
A B C D
Return Value
E
A System.Decimal that is equal to val1 if val1 is greater than or equal to val2; otherwise, the return value is equal to val2.
F G H
Example
I
using System;
J
namespace Samples { public class MathMax { public static void Main() { Decimal[] decimals = {Decimal.MaxValue, 1, 0, -1, Decimal.MinValue}; for(int i = 0; i < decimals.Length; i++) Console.WriteLine("Max({0}, {1}): {2}", decimals[i], decimals[decimals.Length - (i + 1)], Math.Max(decimals[i], decimals[decimals.Length - (i + 1)])); } } }
K L M N O P Q R S T
The output is
U V
Max(79228162514264337593543950335, -79228162514264337593543950335): 79228162514264337593543950335 Max(1, -1): 1 Max(0, 0): 0 Max(-1, 1): 1 Max(-79228162514264337593543950335, 79228162514264337593543950335): 79228162514264337593543950335
W X Y Z
2185
Contents | Index
Math
System
Max() Method
Math.Max(System.Double, System.Double) Method [ILASM]
.method public hidebysig static float64 Max(float64 val1, float64 val2)
A
[C#]
public static double Max(double val1, double val2)
B C
Summary
D
Returns the greater of two specified System.Double values.
E
Parameters
F G
Parameter
Description
I
val1
The first of two specified System.Double values to compare.
J
val2
The second of two specified System.Double values to compare.
H
K L
Return Value
M
A System.Double equal to val1 if val1 is greater than or equal to val2; otherwise, the return value is equal to val2. If val1, val2, or both are equal to System.Double.NaN, System.Double.NaN is returned.
N O P
Example
Q
using System;
R
namespace Samples { public class MathMax { public static void Main() { double[] doubles = {double.MaxValue, 1, 0, -1, double.MinValue}; for(int i = 0; i < doubles.Length; i++) Console.WriteLine("Max({0}, {1}): {2}", doubles[i], doubles[doubles.Length - (i + 1)], Math.Max(doubles[i], doubles[doubles.Length - (i + 1)])); } } }
S T U V W X Y Z
2186
Contents | Index
System
Math Max() Method
The output is Max(1.79769313486232E+308, -1.79769313486232E+308): 1.79769313486232E+308 Max(1, -1): 1 Max(0, 0): 0 Max(-1, 1): 1 Max(-1.79769313486232E+308, 1.79769313486232E+308): 1.79769313486232E+308
A B C D
Math.Max(System.Single, System.Single) Method
E
[ILASM]
F
.method public hidebysig static float32 Max(float32 val1, float32 val2)
G
[C#]
public static float Max(float val1, float val2)
H
Summary
I
Returns the greater of two specified System.Single values.
J K
Parameters
L M
Parameter
Description
val1
The first of two specified System.Single values to compare.
val2
The second of two specified System.Single values to compare.
N O P Q
Return Value
R
A System.Single equal to val1 if val1 is greater than or equal to val2; otherwise, the return value is equal to val2. If val1, val2, or both are equal to System.Single.NaN, System.Single.NaN is returned.
S T U
Example
V
using System;
W
namespace Samples { public class MathMax { public static void Main() { float[] floats = {float.MaxValue, 1,
X Y Z 0, -1, float.MinValue};
2187
Contents | Index
Math
System
Max() Method
for(int i = 0; i < floats.Length; i++) Console.WriteLine("Max({0}, {1}): {2}", floats[i], floats[floats.Length - (i + 1)], Math.Max(floats[i], floats[floats.Length - (i + 1)]));
A }
B }
C
}
D
The output is
E Max(3.402823E+38, -3.402823E+38): 3.402823E+38 Max(1, -1): 1 Max(0, 0): 0 Max(-1, 1): 1 Max(-3.402823E+38, 3.402823E+38): 3.402823E+38
F G H I J
Math.Max(System.Int32, System.Int32) Method
K [ILASM]
L
.method public hidebysig static int32 Max(int32 val1, int32 val2) [C#]
M
public static int Max(int val1, int val2)
N
Summary
O
Returns the greater of two specified System.Int32 values.
P Q
Parameters
R S
Parameter
Description
T
val1
The first of two specified System.Int32 values to compare.
val2
The second of two specified System.Int32 values to compare.
U V W
Return Value
X
A System.Int32 that is equal to val1 if val1 is greater than or equal to val2; otherwise, the return value is equal to val2.
Y Z
2188
Contents | Index
System
Math Max() Method
Example using System; namespace Samples { public class MathMax { public static void Main() { int[] ints = {int.MaxValue, 1, 0, -1, int.MinValue}; for(int i = 0; i < ints.Length; i++) Console.WriteLine("Max({0}, {1}): {2}", ints[i], ints[ints.Length - (i + 1)], Math.Max(ints[i], ints[ints.Length - (i + 1)])); } } }
A B C D E F G H I J
The output is
K
Max(2147483647, -2147483648): 2147483647 Max(1, -1): 1 Max(0, 0): 0 Max(-1, 1): 1 Max(-2147483648, 2147483647): 2147483647
L M N O
Math.Max(System.Int64, System.Int64) Method
P
[ILASM]
Q
.method public hidebysig static int64 Max(int64 val1, int64 val2)
R
[C#]
S
public static long Max(long val1, long val2)
T
Summary
U
Returns the greater of two specified System.Int64 values.
V
Parameters
W X
Parameter
Description
val1
The first of two specified System.Int64 values to compare.
val2
The second of two specified System.Int64 values to compare.
Y Z
2189
Contents | Index
Math
System
Max() Method
Return Value A System.Int64 that is equal to val1 if val1 is greater than or equal to val2; otherwise, the return value is equal to val2. A B
Example
C
using System;
D
namespace Samples { public class MathMax { public static void Main() { long[] longs = {long.MaxValue, 1, 0, -1, long.MinValue}; for(long i = 0; i < longs.Length; i++) Console.WriteLine("Max({0}, {1}): {2}", longs[i], longs[longs.Length - (i + 1)], Math.Max(longs[i], longs[longs.Length - (i + 1)])); } } }
E F G H I J K L M
The output is
N
Max(2147483647, -2147483648): 2147483647 Max(1, -1): 1 Max(0, 0): 0 Max(-1, 1): 1 Max(-2147483648, 2147483647): 2147483647
O P Q R S
Math.Max(System.SByte, System.SByte) Method
T [ILASM]
U
.method public hidebysig static int8 Max(int8 val1, int8 val2)
V
[C#]
public static sbyte Max(sbyte val1, sbyte val2)
W X
Summary
Y
Returns the greater of two specified System.SByte values.
Z
2190
Contents | Index
System
Math Max() Method
Parameters Parameter
Description
val1
The first of two specified System.Byte values to compare.
val2
The second of two specified System.Byte values to compare.
A B C D
Return Value
E
A System.SByte that is equal to val1 if val1 is greater than or equal to val2; otherwise, the return value is equal to val2.
F G H
Description
I
This method is not CLS-compliant. For a CLS-compliant alternative, use System.Math.Max(System.Int16, System.Int16).
J K
Example
L
using System;
M namespace Samples { public class MathMax { public static void Main() { sbyte[] sbytes = {sbyte.MaxValue, 1, 0, -1, sbyte.MinValue}; for(int i = 0; i < sbytes.Length; i++) Console.WriteLine("Max({0}, {1}): {2}", sbytes[i], sbytes[sbytes.Length - (i + 1)], Math.Max(sbytes[i], sbytes[sbytes.Length - (i + 1)])); } } }
N O P Q R S T U V W
The output is
X Max(127, -128): 127 Max(1, -1): 1 Max(0, 0): 0 Max(-1, 1): 1 Max(-128, 127): 127
Y Z
2191
Contents | Index
Math
System
Max() Method
Math.Max(System.Int16, System.Int16) Method [ILASM]
.method public hidebysig static int16 Max(int16 val1, int16 val2)
A
[C#]
public static short Max(short val1, short val2)
B C
Summary
D
Returns the greater of two specified System.Int16 values.
E
Parameters
F G
Parameter
Description
I
val1
The first of two specified System.Int16 values to compare.
J
val2
The second of two specified System.Int16 values to compare.
H
K L
Return Value
M
A System.Int16 that is equal to val1 if val1 is greater than or equal to val2; otherwise, the return value is equal to val2.
N O
Example
P
using System;
Q
namespace Samples { public class MathMax { public static void Main() { short[] shorts = {short.MaxValue, 1, 0, -1, short.MinValue}; for(int i = 0; i < shorts.Length; i++) Console.WriteLine("Max({0}, {1}): {2}", shorts[i], shorts[shorts.Length - (i + 1)], Math.Max(shorts[i], shorts[shorts.Length - (i + 1)])); } } }
R S T U V W X Y Z
2192
Contents | Index
System
Math Max() Method
The output is Max(32767, -32768): 32767 Max(1, -1): 1 Max(0, 0): 0 Max(-1, 1): 1 Max(-32768, 32767): 32767
A B C D
Math.Max(System.UInt32, System.UInt32) Method
E
[ILASM]
F
.method public hidebysig static unsigned int32 Max(unsigned int32 val1, unsigned int32 val2)
G
[C#]
H
public static uint Max(uint val1, uint val2)
I
Summary
J
Returns the greater of two specified System.UInt32 values.
K
Parameters
L M
Parameter
Description
val1
The first of two specified System.UInt32 values to compare.
val2
The second of two specified System.UInt32 values to compare.
N O P Q
Return Value
R
A System.UInt32 that is equal to val1 if val1 is greater than or equal to val2; otherwise, the return value is equal to val2.
S T
Description
U
This method is not CLS-compliant. For a CLS-compliant alternative, use System.Math.Max(System.Int64, System.Int64).
V W
Example
X
using System;
Y
namespace Samples { public class MathMax {
Z
2193
Contents | Index
Math
System
Max() Method
public static void Main() { uint[] uints = {uint.MaxValue, 42, uint.MinValue}; for(int i = 0; i < uints.Length; i++) Console.WriteLine("Max({0}, {1}): {2}", uints[i], uints[uints.Length - (i + 1)], Math.Max(uints[i], uints[uints.Length - (i + 1)])); }
A B C }
D
}
E
The output is
F
Max(4294967295, 0): 4294967295 Max(42, 42): 42 Max(0, 4294967295): 4294967295
G H I J
Math.Max(System.UInt64, System.UInt64) Method
K [ILASM]
L
.method public hidebysig static unsigned int64 Max(unsigned int64 val1, unsigned int64 val2)
M
[C#]
public static ulong Max(ulong val1, ulong val2)
N O
Summary
P
Returns the greater of two specified System.UInt64 values.
Q
Parameters
R S
Parameter
Description
U
val1
The first of two specified System.UInt64 values to compare.
V
val2
The second of two specified System.UInt64 values to compare.
T
W X
Return Value
Y
A System.UInt64 equal to val1 if val1 is greater than or equal to val2; otherwise, the return value is equal to val2.
Z
2194
Contents | Index
System
Math Max() Method
Description This method is not CLS-compliant. For a CLS-compliant alternative, use System.Math.Max(System.Decimal, System.Decimal). A
Example
B
using System;
C
namespace Samples { public class MathMax { public static void Main() { ulong[] ulongs = {ulong.MaxValue, 42, ulong.MinValue}; for(int i = 0; i < ulongs.Length; i++) Console.WriteLine("Max({0}, {1}): {2}", ulongs[i], ulongs[ulongs.Length - (i + 1)], Math.Max(ulongs[i], ulongs[ulongs.Length - (i + 1)])); } } }
D E F G H I J K L M
The output is
N O
Max(18446744073709551615, 0): 18446744073709551615 Max(42, 42): 42 Max(0, 18446744073709551615): 18446744073709551615
P Q R
Math.Max(System.UInt16, System.UInt16) Method
S
[ILASM]
T
.method public hidebysig static unsigned int16 Max(unsigned int16 val1, unsigned int16 val2)
U
[C#]
V
public static ushort Max(ushort val1, ushort val2)
W
Summary
X
Returns the greater of two specified System.UInt16 values.
Y Z
2195
Contents | Index
Math
System
Max() Method
Parameters Parameter
Description
val1
The first of two specified System.UInt16 values to compare.
val2
The second of two specified System.UInt16 values to compare.
A B C D E
Return Value
F
A System.UInt16 that is equal to val1 if val1 is greater than or equal to val2; otherwise, the return value is equal to val2.
G H
Description
I
This method is not CLS-compliant. For a CLS-compliant alternative, use System.Math.Max(System.Int32, System.Int32).
J K
Example
L
using System;
M namespace Samples { public class MathMax { public static void Main() { ushort[] ushorts = {ushort.MaxValue, 42, ushort.MinValue}; for(int i = 0; i < ushorts.Length; i++) Console.WriteLine("Max({0}, {1}): {2}", ushorts[i], ushorts[ushorts.Length - (i + 1)], Math.Max(ushorts[i], ushorts[ushorts.Length - (i + 1)])); } } }
N O P Q R S T U V W
The output is
X Max(65535, 0): 65535 Max(42, 42): 42 Max(0, 65535): 65535
Y Z
2196
Contents | Index
System
Math Min() Method
Math.Min(System.Byte, System.Byte) Method [ILASM]
.method public hidebysig static unsigned int8 Min(unsigned int8 val1, unsigned int8 val2)
A
[C#]
B
public static byte Min(byte val1, byte val2)
C
Summary
D
Returns the lesser of two specified System.Byte values.
E F
Parameters
G
Parameter
Description
val1
The first of two specified System.Byte values to compare.
val2
The second of two specified System.Byte values to compare.
H I J K L
Return Value
M
A System.Byte equal to val1 if val1 is less than or equal to val2; otherwise, the return value is equal to val2.
N O
Example
P
using System;
Q
namespace Samples { public class MathMin { public static void Main() { byte[] bytes = {byte.MaxValue, 42, byte.MinValue}; for(int i = 0; i < bytes.Length; i++) Console.WriteLine("Min({0}, {1}): {2}", bytes[i], bytes[bytes.Length - (i + 1)], Math.Min(bytes[i], bytes[bytes.Length - (i + 1)])); } } }
R S T U V W X Y Z
2197
Contents | Index
Math
System
Min() Method
The output is Min(255, 0): 0 Min(42, 42): 42 Min(0, 255): 0
A B C
Math.Min(System.Decimal, System.Decimal) Method
D
[ILASM]
E
.method public hidebysig static decimal Min(decimal val1, decimal val2) [C#]
F
public static decimal Min(decimal val1, decimal val2)
G H
Summary
I
Returns the lesser of two specified System.Decimal values.
J
Parameters
K L M
Parameter
Description
val1
The first of two specified System.Decimal values to compare.
val2
The second of two specified System.Decimal values to compare.
N O P Q
Return Value
R
A System.Decimal equal to val1 if val1 is less than or equal to val2; otherwise, the return value is equal to val2.
S T
Example
U
using System;
V
namespace Samples { public class MathMin { public static void Main() { double[] doubles = {double.MaxValue, 1, 0, -1, double.MinValue}; for(int i = 0; i < doubles.Length; i++) Console.WriteLine("Min({0}, {1}): {2}",
W X Y Z
2198
Contents | Index
System
Math Min() Method
doubles[i], doubles[doubles.Length - (i + 1)], Math.Min(doubles[i], doubles[doubles.Length - (i + 1)])); }
A
} }
B C
The output is
D Min(79228162514264337593543950335, -79228162514264337593543950335): -79228162514264337593543950335 Min(1, -1): -1 Min(0, 0): 0 Min(-1, 1): -1 Min(-79228162514264337593543950335, 79228162514264337593543950335): -79228162514264337593543950335
E F G H I J
Math.Min(System.Double, System.Double) Method
K [ILASM]
L
.method public hidebysig static float64 Min(float64 val1, float64 val2) [C#]
M
public static double Min(double val1, double val2)
N
Summary
O
Returns the lesser of two specified System.Double values.
P Q
Parameters
R
Parameter
Description
S
val1
The first of two specified System.Double values to compare.
T
val2
The second of two specified System.Double values to compare.
U V W
Return Value
X
A System.Double equal to val1 if val1 is less than or equal to val2; otherwise, the return value is equal to val2. If val1, val2, or both are equal to System.Double.NaN, System.Double.NaN is returned.
Y Z
2199
Contents | Index
Math
System
Min() Method
Example using System; namespace Samples { public class MathMin { public static void Main() { double[] doubles = {double.MaxValue, 1, 0, -1, double.MinValue}; for(int i = 0; i < doubles.Length; i++) Console.WriteLine("Min({0}, {1}): {2}", doubles[i], doubles[doubles.Length - (i + 1)], Math.Min(doubles[i], doubles[doubles.Length - (i + 1)])); } } }
A B C D E F G H I J
The output is
K
Min(1.79769313486232E+308, -1.79769313486232E+308): -1.79769313486232E+308 Min(1, -1): -1 Min(0, 0): 0 Min(-1, 1): -1 Min(-1.79769313486232E+308, 1.79769313486232E+308): -1.79769313486232E+308
L M N O P
Math.Min(System.Single, System.Single) Method
Q
[ILASM]
R
.method public hidebysig static float32 Min(float32 val1, float32 val2)
S
public static float Min(float val1, float val2)
[C#]
T
Summary
U
Returns the lesser of two specified System.Single values.
V
Parameters
W X
Parameter
Description
val1
The first of two specified System.Single values to compare.
val2
The second of two specified System.Single values to compare.
Y Z
2200
Contents | Index
System
Math Min() Method
Return Value A System.Single equal to val1 if val1 is less than or equal to val2; otherwise, the return value is equal to val2. If val1, val2, or both are equal to System.Single.NaN, System.Single.NaN is returned.
A B
Example
C
using System;
D namespace Samples { public class MathMin { public static void Main() { float[] floats = {float.MaxValue, 1, 0, -1, float.MinValue}; for(int i = 0; i < floats.Length; i++) Console.WriteLine("Min({0}, {1}): {2}", floats[i], floats[floats.Length - (i + 1)], Math.Min(floats[i], floats[floats.Length - (i + 1)])); } } }
E F G H I J K L M N
The output is
O
Min(3.402823E+38, -3.402823E+38): -3.402823E+38 Min(1, -1): -1 Min(0, 0): 0 Min(-1, 1): -1 Min(-3.402823E+38, 3.402823E+38): -3.402823E+38
P Q R S T
Math.Min(System.Int32, System.Int32) Method
U
[ILASM]
.method public hidebysig static int32 Min(int32 val1, int32 val2)
V
[C#]
W
public static int Min(int val1, int val2)
X
Summary
Y
Returns the lesser of two specified System.Int32 values.
Z
2201
Contents | Index
Math
System
Min() Method
Parameters Parameter
Description
val1
The first of two specified System.Int32 values to compare.
val2
The second of two specified System.Int32 values to compare.
A B C D E
Return Value
F
A System.Int32 equal to val1 if val1 is less than or equal to val2; otherwise, the return value is equal to val2.
G H
Example
I
using System;
J
namespace Samples { public class MathMin { public static void Main() { int[] ints = {int.MaxValue, 1, 0, -1, int.MinValue}; for(int i = 0; i < ints.Length; i++) Console.WriteLine("Min({0}, {1}): {2}", ints[i], ints[ints.Length - (i + 1)], Math.Min(ints[i], ints[ints.Length - (i + 1)])); } } }
K L M N O P Q R S T
The output is
U
Min(2147483647, -2147483648): -2147483648 Min(1, -1): -1 Min(0, 0): 0 Min(-1, 1): -1 Min(-2147483648, 2147483647): -2147483648
V W X Y Z
2202
Contents | Index
System
Math Min() Method
Math.Min(System.Int64, System.Int64) Method [ILASM]
.method public hidebysig static int64 Min(int64 val1, int64 val2) [C#]
A
public static long Min(long val1, long val2)
B
Summary
C
Returns the lesser of two specified System.Int64 values.
D E
Parameters
F
Parameter
Description
val1
The first of two specified System.Int64 values to compare.
val2
The second of two specified System.Int64 values to compare.
G H I J K
Return Value
L
A System.Int64 equal to val1 if val1 is less than or equal to val2; otherwise, the return value is equal to val2.
M
Example
O
using System;
P
namespace Samples { public class MathMin { public static void Main() { long[] longs = {long.MaxValue, 1, 0, -1, long.MinValue}; for(long i = 0; i < longs.Length; i++) Console.WriteLine("Min({0}, {1}): {2}", longs[i], longs[longs.Length - (i + 1)], Math.Min(longs[i], longs[longs.Length - (i + 1)])); } } }
Q
N
R S T U V W X Y Z
2203
Contents | Index
Math
System
Min() Method
The output is Min(9223372036854775807, -9223372036854775808): -9223372036854775808 Min(1, -1): -1 Min(0, 0): 0 Min(-1, 1): -1 Min(-9223372036854775808, 9223372036854775807): -9223372036854775808
A B C D E
Math.Min(System.SByte, System.SByte) Method
F
[ILASM]
.method public hidebysig static int8 Min(int8 val1, int8 val2)
G
[C#]
public static sbyte Min(sbyte val1, sbyte val2)
H I
Summary
J
Returns the lesser of two specified System.SByte values.
K
Parameters
L M
Parameter
Description
val1
The first of two specified System.SByte values to compare.
val2
The second of two specified System.SByte values to compare.
N O P Q R
Return Value
S
A System.SByte equal to val1 if val1 is less than or equal to val2; otherwise, the return value is equal to val2.
T U
Description
V
This method is not CLS-compliant. For a CLS-compliant alternative, use System.Math.Min(System.Int16, System.Int16).
W X Y Z
2204
Contents | Index
System
Math Min() Method
Example using System; namespace Samples { public class MathMin { public static void Main() { sbyte[] sbytes = {sbyte.MaxValue, 1, 0, -1, sbyte.MinValue}; for(int i = 0; i < sbytes.Length; i++) Console.WriteLine("Min({0}, {1}): {2}", sbytes[i], sbytes[sbytes.Length - (i + 1)], Math.Min(sbytes[i], sbytes[sbytes.Length - (i + 1)])); } } }
A B C D E F G H I J
The output is
K
Min(127, -128): -128 Min(1, -1): -1 Min(0, 0): 0 Min(-1, 1): -1 Min(-128, 127): -128
L M N O
Math.Min(System.Int16, System.Int16) Method
P
[ILASM]
Q
.method public hidebysig static int16 Min(int16 val1, int16 val2)
R
[C#]
S
public static short Min(short val1, short val2)
T
Summary
U
Returns the lesser of two specified System.Int16 values.
V
Parameters
W X
Parameter
Description
val1
The first of two specified System.Int16 values to compare.
val2
The second of two specified System.Int16 values to compare.
Y Z
2205
Contents | Index
Math
System
Min() Method
Return Value A System.Int16 that is equal to val1 if val1 is less than or equal to val2; otherwise, the return value is equal to val2. A B
Example
C
using System;
D
namespace Samples { public class MathMin { public static void Main() { short[] shorts = {short.MaxValue, 1, 0, -1, short.MinValue}; for(int i = 0; i < shorts.Length; i++) Console.WriteLine("Min({0}, {1}): {2}", shorts[i], shorts[shorts.Length - (i + 1)], Math.Min(shorts[i], shorts[shorts.Length - (i + 1)])); } } }
E F G H I J K L M
The output is
N O
Min(32767, -32768): -32768 Min(1, -1): -1 Min(0, 0): 0 Min(-1, 1): -1 Min(-32768, 32767): -32768
P Q R S T
Math.Min(System.UInt32, System.UInt32) Method
U
[ILASM]
V
.method public hidebysig static unsigned int32 Min(unsigned int32 val1, unsigned int32 val2) [C#]
W
public static uint Min(uint val1, uint val2)
X Y
Summary
Z
Returns the lesser of two specified System.UInt32 values.
2206
Contents | Index
System
Math Min() Method
Parameters Parameter
Description
val1
The first of two specified System.UInt32 values to compare.
val2
The second of two specified System.UInt32 values to compare.
A B C D
Return Value
E
A System.UInt32 equal to val1 if val1 is less than or equal to val2; otherwise, the return value is equal to val2.
F G H
Description
I
This method is not CLS-compliant. For a CLS-compliant alternative, use System.Math.Min(System.Int64, System.Int64).
J K
Example
L
using System;
M namespace Samples { public class MathMin { public static void Main() { uint[] uints = {uint.MaxValue, 42, uint.MinValue}; for(int i = 0; i < uints.Length; i++) Console.WriteLine("Min({0}, {1}): {2}", uints[i], uints[uints.Length - (i + 1)], Math.Min(uints[i], uints[uints.Length - (i + 1)])); } } }
N O P Q R S T U V W
The output is
X Min(4294967295, 0): 0 Min(42, 42): 42 Min(0, 4294967295): 0
Y Z
2207
Contents | Index
Math
System
Min() Method
Math.Min(System.UInt64, System.UInt64) Method [ILASM]
A
.method public hidebysig static unsigned int64 Min(unsigned int64 val1, unsigned int64 val2)
B
[C#]
public static ulong Min(ulong val1, ulong val2)
C D
Summary
E
Returns the lesser of two specified System.UInt64 values.
F
Parameters
G H I
Parameter
Description
val1
The first of two specified System.UInt64 values to compare.
val2
The second of two specified System.UInt64 values to compare.
J K L M
Return Value
N
A System.UInt64 equal to val1 if val1 is less than or equal to val2; otherwise, the return value is equal to val2.
O P
Description
Q
This method is not CLS-compliant. For a CLS-compliant alternative, use System.Math.Min(System.Decimal, System.Decimal).
R S
Example
T
using System;
U
namespace Samples { public class MathMin { public static void Main() { ulong[] ulongs = {ulong.MaxValue, 42, ulong.MinValue}; for(int i = 0; i < ulongs.Length; i++) Console.WriteLine("Min({0}, {1}): {2}", ulongs[i], ulongs[ulongs.Length - (i + 1)],
V W X Y Z
2208
Contents | Index
System
Math Min() Method
Math.Min(ulongs[i], ulongs[ulongs.Length - (i + 1)])); } }
A
}
B
The output is
C
Min(18446744073709551615, 0): 0 Min(42, 42): 42 Min(0, 18446744073709551615): 0
D E F G
Math.Min(System.UInt16, System.UInt16) Method
H
[ILASM]
I
.method public hidebysig static unsigned int16 Min(unsigned int16 val1, unsigned int16 val2)
J
[C#]
public static ushort Min(ushort val1, ushort val2)
K L
Summary
M
Returns the lesser of two specified System.UInt16 values.
N
Parameters
O
Parameter
Description
val1
The first of two specified System.UInt16 values to compare.
val2
The second of two specified System.UInt16 values to compare.
P Q R S T
Return Value
U
A System.UInt16 equal to val1 if val1 is less than or equal to val2; otherwise, the return value is equal to val2.
V W
Description
X
This method is not CLS-compliant. For a CLS-compliant alternative, use System.Math.Min(System.Int32, System.Int32).
Y Z
2209
Contents | Index
Math
System
Pow() Method
Example using System; namespace Samples { public class MathMin { public static void Main() { ushort[] ushorts = {ushort.MaxValue, 42, ushort.MinValue}; for(int i = 0; i < ushorts.Length; i++) Console.WriteLine("Min({0}, {1}): {2}", ushorts[i], ushorts[ushorts.Length - (i + 1)], Math.Min(ushorts[i], ushorts[ushorts.Length - (i + 1)])); } } }
A B C D E F G H I J
The output is
K L
Min(65535, 0): 0 Min(42, 42): 42 Min(0, 65535): 0
M N O
Math.Pow(System.Double, System.Double) Method
P [ILASM]
Q
.method public hidebysig static float64 Pow(float64 x, float64 y)
R
[C#]
public static double Pow(double x, double y)
S T
Summary
U
Returns the specified System.Double raised to the specified power.
V
Parameters
W X Y
Parameter
Description
x
A System.Double to be raised to a power.
y
A System.Double that specifies that power.
Z
2210
Contents | Index
System
Math Pow() Method
Return Value A System.Double equal to x raised to the power y. The following table specifies the results if x or y is equal to System.Double.NaN, System.Double.NegativeInfinity, or System.Double.PositiveInfinity.
A B
Parameter Values
C
Returns
D
x or y is equal to System.Double.NaN
System.Double.NaN.
E
x is equal to System.Double.NegativeInfinity
System.Double.NegativeInfinity if y is an odd integer; otherwise, System.Double.PositiveInfinity.
F
y is equal to System.Double.NegativeInfinity
0
I
x is equal to System.Double.PositiveInfinity
0 if y is equal to System.Double.NegativeInfinity; otherwise, System.Double.PositiveInfinity.
J
G H
K L
y is equal to System.Double.PositiveInfinity
System.Double.PositiveInfinity.
M N O
Example
P
using System;
Q
namespace Samples { public class MathPow { public static void Main() { double[] doubles = {-1, 0, 1, double.MinValue, double.MaxValue}; foreach(double d in doubles) Console.WriteLine("Pow(10, {0}): {1}", d, Math.Pow(10, d)); } } }
R S T U V W X Y Z
2211
Contents | Index
Math
System
Round() Method
The output is Pow(10, Pow(10, Pow(10, Pow(10, Pow(10,
A B
-1): 0.1 0): 1 1): 10 -1.79769313486232E+308): 0 1.79769313486232E+308): Infinity
C D E
Math.Round(System.Decimal) Method
F
[ILASM]
.method public hidebysig static decimal Round(decimal d)
G
[C#]
public static decimal Round(decimal d)
H I
Summary
J
Returns the integer nearest the specified System.Decimal.
K
Parameters
L M
Parameter
Description
d
A System.Decimal to be rounded.
N O P
Return Value
Q
A System.Decimal containing the value of the integer nearest d. If d is exactly halfway between two integers, one of which is even and the other odd, then the even integer is returned.
R S T
Description
U
The behavior of this method follows IEEE Standard 754, section 4.1.
V W
Example
X
using System;
Y
namespace Samples { public class MathRound { public static void Main()
Z
2212
Contents | Index
System
Math Round() Method
{ Decimal[] decimals = {-0.5m, 0.5m, 0.51m}; foreach(Decimal d in decimals) Console.WriteLine("Round({0}): {1}", d, Math.Round(d));
A
} }
B
}
C
The output is
D E
Round(-0.5): 0 Round(0.5): 0 Round(0.51): 1 Round(0.500001): 1
F G H
Math.Round(System.Decimal, System.Int32) Method
I
[ILASM]
J
.method public hidebysig static decimal Round(decimal d, int32 decimals)
K
[C#]
L
public static decimal Round(decimal d, int decimals)
M
Summary
N
Returns the number with the specified precision nearest the specified value.
O
Parameters
P Q
Parameter
Description
d
A System.Decimal number to be rounded.
S
decimals
The number of significant fractional digits (precision) in the return value.
T
R
U V
Return Value
W
The number nearest d with precision equal to decimals. If d is halfway between two numbers, one of which is even and the other odd, then the even number is returned. If the precision of d is less than decimals, then d is returned unchanged.
X Y Z
2213
Contents | Index
Math
System
Round() Method
Description The decimals parameter specifies the number of significant fractional digits in the return value and ranges from 0 to 28. If decimals is zero, then a whole number is returned. The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker’s rounding. If decimals is zero, this kind of rounding is sometimes called rounding toward zero.
A B C D E
Math.Round(System.Double) Method
F
[ILASM]
.method public hidebysig static float64 Round(float64 a)
G
[C#]
public static double Round(double a)
H I
Summary
J
Returns the integer nearest the specified System.Double.
K
Parameters
L M
Parameter
Description
a
A System.Double to be rounded.
N O P
Return Value
Q
A System.Double containing the value of the integer nearest a. If a is exactly halfway between two integers, one of which is even and the other odd, then the even integer is returned.
R S T
Description
U
The behavior of this method follows IEEE Standard 754, section 4.1.
V W
Example
X
using System;
Y
namespace Samples { public class MathRound { public static void Main()
Z
2214
Contents | Index
System
Math Round() Method
{ double[] doubles = {-0.5, 0.5, 0.51}; foreach(double d in doubles) Console.WriteLine("Round({0}): {1}", d, Math.Round(d));
A
} }
B
}
C
The output is
D
Round(-0.5): 0 Round(0.5): 0 Round(0.51): 1
E F G
Math.Round(System.Double, System.Int32) Method
H
[ILASM]
I
.method public hidebysig static float64 Round(float64 value, int32 digits)
J
[C#]
K
public static double Round(double value, int digits)
L
Summary
M
Returns the number nearest the specified System.Double within the specified precision.
N O
Parameters
P
Parameter
Description
value
A System.Double to be rounded.
R
A System.Int32 containing the value of the number of significant fractional digits (precision) in the return value. This number is required to be greater than or equal to 0 and less than or equal to 15.
S
digits
Q
T U V
Return Value
W
A System.Double containing the value of the number nearest value with a precision equal to digits. If the digit in value that is in the 10–(digits + 1) place is equal to 5 and there are no non-zero numbers in any less significant place, then the digit in the 10–digits place will be unchanged if it is even, else it will be set to the closest even integer value in the direction of the digit in the 10–(digits + 1) place. If the precision of value is less than digits, then value is returned unchanged. If digits is zero, this method behaves in the same manner as System.Math.Round(value).
X Y Z
2215
Contents | Index
Math
System
Round() Method
Description The behavior of this method follows IEEE Standard 754, section 4.1. A
Exceptions
B
Exception
C
Condition
D System.ArgumentOutOfRangeException
E
digits < 0. digits > 15.
F G
Example
H
using System;
I
namespace Samples { public class MathRound { public static void Main() { double d = 0.5456456456456; for(int i = 0; i < 10; i++) Console.WriteLine("Round({0}, {1}): {2}", d, i, Math.Round(d, i)); } } }
J K L M N O P Q
The output is
R S
Round(0.5456456456456, Round(0.5456456456456, Round(0.5456456456456, Round(0.5456456456456, Round(0.5456456456456, Round(0.5456456456456, Round(0.5456456456456, Round(0.5456456456456, Round(0.5456456456456, Round(0.5456456456456,
T U V W X Y
0): 1): 2): 3): 4): 5): 6): 7): 8): 9):
1 0.5 0.55 0.546 0.5456 0.54565 0.545646 0.5456456 0.54564565 0.545645646
Z
2216
Contents | Index
System
Math Sign() Method
Math.Sign(System.Decimal) Method [ILASM]
.method public hidebysig static int32 Sign(decimal value) [C#]
A
public static int Sign(decimal value)
B C
Summary
D
Returns a value indicating the sign of the specified System.Decimal.
E
Parameters
F G
Parameter
Description
value
A System.Decimal number whose sign is to be determined.
H I J
Return Value
K
A System.Int32 indicating the sign of value.
L M
Number
Description
–1
value < 0.
O
0
value == 0.
P
1
value > 0.
Q
N
R
Example
S
using System;
T U
namespace Samples { public class MathSign { public static void Main() { Decimal[] decimals = {Decimal.MaxValue, Decimal.One, Decimal.Zero, Decimal.MinusOne, Decimal.MinValue};
V W X Y Z
2217
Contents | Index
Math
System
Sign() Method
foreach(Decimal d in decimals) Console.WriteLine("Sign({0}): {1}", d, Math.Sign(d)); } }
A
}
B
The output is
C
Sign(79228162514264337593543950335): 1 Sign(1): 1 Sign(0): 0 Sign(-1): -1 Sign(-79228162514264337593543950335): -1
D E F G H
Math.Sign(System.Double) Method
I [ILASM]
J
.method public hidebysig static int32 Sign(float64 value)
K
[C#]
public static int Sign(double value)
L M
Summary
N
Returns a value indicating the sign of the specified System.Double.
O
Parameters
P Q R
Parameter
Description
value
A System.Double whose sign is to be determined.
S T
Return Value
U
A System.Int32 indicating the sign of value.
V W
Number
Description
Y
–1
value < 0.
Z
0
value == 0.
1
value > 0.
X
2218
Contents | Index
System
Math Sign() Method
Exceptions Exception
Condition
System.ArithmeticException
value is equal to System.Double.NaN.
A B C
Example
D
using System;
E
namespace Samples { public class MathSign { public static void Main() { Double[] doubles = {Double.MaxValue, Double.Epsilon, Double.NegativeInfinity, Double.PositiveInfinity, Double.MinValue}; foreach(Double d in doubles) Console.WriteLine("Sign({0}): {1}", d, Math.Sign(d)); } } }
F G H I J K L M N O P
The output is
Q Sign(1.79769313486232E+308): 1 Sign(4.94065645841247E-324): 1 Sign(-Infinity): -1 Sign(Infinity): 1 Sign(-1.79769313486232E+308): -1
R S T U V
Math.Sign(System.Single) Method
W [ILASM]
X
.method public hidebysig static int32 Sign(float32 value) [C#]
Y
public static int Sign(float value)
Z
Summary Returns a value indicating the sign of the specified System.Single. 2219
Contents | Index
Math
System
Sign() Method
Parameters Parameter
Description
value
A System.Single whose sign is to be determined.
A B C D
Return Value
E
A System.Int32 indicating the sign of value.
F G
Number
Description
–1
value < 0.
J
0
value == 0.
K
1
value > 0.
H I
L M
Exceptions
N O P
Exception
Condition
System.ArithmeticException
value is equal to System.Single.NaN.
Q R
Example
S
using System;
T
namespace Samples { public class MathSign { public static void Main() { float[] floats = {float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.MinValue};
U V W X Y Z
2220
Contents | Index
System
Math Sign() Method
foreach(float f in floats) Console.WriteLine("Sign({0}): {1}", f, Math.Sign(f)); } }
A
}
B
The output is
C
Sign(3.402823E+38): 1 Sign(1.401298E-45): 1 Sign(-Infinity): -1 Sign(Infinity): 1 Sign(-3.402823E+38): -1
D E F G H
Math.Sign(System.Int32) Method
I [ILASM]
.method public hidebysig static int32 Sign(int32 value)
J
[C#]
K
public static int Sign(int value)
L
Summary
M
Returns a value indicating the sign of the specified System.Int32.
N O
Parameters
P
Parameter
Description
value
A System.Int32 whose sign is to be determined.
Q R S
Return Value
T
A System.Int32 indicating the sign of value.
U V
Number
Description
–1
value < 0.
X
0
value == 0.
Y
1
value > 0.
Z
W
2221
Contents | Index
Math
System
Sign() Method
Example using System; namespace Samples { public class MathSign { public static void Main() { int[] ints = {int.MaxValue, -42, 0, 42, int.MinValue}; foreach(int i in ints) Console.WriteLine("Sign({0}): {1}", i, Math.Sign(i)); } } }
A B C D E F G H I
The output is
J Sign(2147483647): 1 Sign(-42): -1 Sign(0): 0 Sign(42): 1 Sign(-2147483648): -1
K L M N O
Math.Sign(System.Int64) Method
P
[ILASM]
.method public hidebysig static int32 Sign(int64 value)
Q
[C#]
R
public static int Sign(long value)
S
Summary
T
Returns a value indicating the sign of the specified System.Int64.
U V
Parameters
W X Y
Parameter
Description
value
A System.Int64 whose sign is to be determined.
Z
2222
Contents | Index
System
Math Sign() Method
Return Value A System.Int32 indicating the sign of value. A
Number
Description
B
–1
value < 0.
C
0
value == 0.
1
value > 0.
D E F G
Example
H
using System;
I namespace Samples { public class MathSign { public static void Main() { long[] longs = {long.MaxValue, -42, 0, 42, long.MinValue}; foreach(long l in longs) Console.WriteLine("Sign({0}): {1}", l, Math.Sign(l)); } } }
J K L M N O P Q R
The output is
S T
Sign(9223372036854775807): 1 Sign(-42): -1 Sign(0): 0 Sign(42): 1 Sign(-9223372036854775808): -1
U V W X
Math.Sign(System.SByte) Method
Y
[ILASM]
Z
.method public hidebysig static int32 Sign(int8 value) [C#]
public static int Sign(sbyte value)
2223
Contents | Index
Math
System
Sign() Method
Summary Returns a value indicating the sign of the specified System.SByte. A
Parameters
B C
Parameter
Description
D
value
A System.SByte whose sign is to be determined.
E F
Return Value
G
A System.Int32 indicating the sign of value.
H I J
Number
Description
–1
value < 0.
0
value == 0.
1
value > 0.
K L M N
Description
O
This method is not CLS-compliant. For a CLS-compliant alternative, use System.Math.Sign(System.Int16).
P Q
Example
R
using System;
S
namespace Samples { public class MathSign { public static void Main() { sbyte[] shorts = {sbyte.MaxValue, -42, 0, 42, sbyte.MinValue}; foreach(sbyte s in sbytes) Console.WriteLine("Sign({0}): {1}", s, Math.Sign(s)); } } }
T U V W X Y Z
2224
Contents | Index
System
Math Sign() Method
The output is Sign(32767): 1 Sign(-42): -1 Sign(0): 0 Sign(42): 1 Sign(-32768): -1
A B C D
Math.Sign(System.Int16) Method
E
[ILASM]
F
.method public hidebysig static int32 Sign(int16 value)
G
[C#]
public static int Sign(short value)
H
Summary
I
Returns a value indicating the sign of the specified System.Int16.
J K
Parameters
L
Parameter
Description
value
A System.Int16 whose sign is to be determined.
M N O P
Return Value
Q
A System.Int32 indicating the sign of value.
R S
Number
Description
T
–1
value < 0.
U
0
value == 0.
1
value > 0.
V W X Y Z
2225
Contents | Index
Math
System
Sin() Method
Example using System; namespace Samples { public class MathSign { public static void Main() { short[] shorts = {short.MaxValue, -42, 0, 42, short.MinValue}; foreach(short s in shorts) Console.WriteLine("Sign({0}): {1}", s, Math.Sign(s)); } } }
A B C D E F G H I J
The output is
K
Sign(32767): 1 Sign(-42): -1 Sign(0): 0 Sign(42): 1 Sign(-32768): -1
L M N O P
Math.Sin(System.Double) Method
Q
[ILASM]
R
.method public hidebysig static float64 Sin(float64 a)
S
public static double Sin(double a)
[C#]
T
Summary
U
Returns the sine of the specified System.Double that represents an angle.
V
Parameters
W X
Parameter
Description
a
A System.Double containing the value of an angle measured in radians.
Y Z
2226
Contents | Index
System
Math Sinh() Method
Return Value A System.Double containing the value of the sine of a. If a is equal to System.Double.NaN, System.Double.NegativeInfinity, or System.Double.PositiveInfinity, returns System.Double.NaN.
A B
Description
C
[Note: Multiply by θ/180 to convert degrees to radians.]
D
Example
E
using System;
F G
namespace Samples { public class MathSin { public static void Main() { Double[] doubles = {-1, -0.5, 0, 0.5, 1}; foreach(Double d in doubles) Console.WriteLine("Sin({0}): {1}", d, Math.Sin(d)); } } }
H I J K L M N O
The output is
P Sin(-1): -0.841470984807897 Sin(-0.5): -0.479425538604203 Sin(0): 0 Sin(0.5): 0.479425538604203 Sin(1): 0.841470984807897
Q R S T
Math.Sinh(System.Double) Method
U
[ILASM]
V
.method public hidebysig static float64 Sinh(float64 value)
W
[C#]
X
public static double Sinh(double value)
Y
Summary
Z
Returns the hyperbolic sine of the specified System.Double that represents an angle.
2227
Contents | Index
Math
System
Sinh() Method
Parameters Parameter
Description
value
A System.Double containing the value of an angle measured in radians.
A B C
Return Value
D
A System.Double containing the value of the hyperbolic sine of value. If value is equal to System.Double.NegativeInfinity, System.Double.PositiveInfinity, or System.Double.NaN, returns a System.Double equal to value.
E F G
Description
H
[Note: Multiply by θ/180 to convert degrees to radians.]
I J
Example
K
using System;
L
namespace Samples { public class MathSinh { public static void Main() { Double[] doubles = {-1, -0.5, 0, 0.5, 1}; foreach(Double d in doubles) Console.WriteLine("Sinh({0}): {1}", d, Math.Sinh(d)); } } }
M N O P Q R S T
The output is
U Sinh(-1): -1.1752011936438 Sinh(-0.5): -0.521095305493747 Sinh(0): 0 Sinh(0.5): 0.521095305493747 Sinh(1): 1.1752011936438
V W X Y Z
2228
Contents | Index
System
Math Sqrt() Method
Math.Sqrt(System.Double) Method [ILASM]
.method public hidebysig static float64 Sqrt(float64 d) [C#]
A
public static double Sqrt(double d)
B C
Summary
D
Returns the square root of the specified System.Double.
E
Parameters
F
Parameter
Description
d
A System.Double.
G H I J
Return Value
K
A System.Double whose value is indicated as follows:
L M
Condition
Returns
d >= 0
A System.Double containing the positive square root of d.
N O P Q
d<0 d is equal to System.Double.NegativeInfinity
R
System.Double.NaN.
S
d is equal to System.Double.NaN
T
d is equal to System.Double.PositiveInfinity
System.Double.PositiveInfinity.
U V W X Y Z
2229
Contents | Index
Math
System
Tan() Method
Example using System; namespace Samples { public class MathSqrt { public static void Main() { Double[] doubles = {Double.MaxValue, 42, 1, 0.5, 0, Double.MinValue}; foreach(Double d in doubles) Console.WriteLine("Sqrt({0}): {1}", d, Math.Sqrt(d)); } } }
A B C D E F G H I J
The output is
K
Sqrt(1.79769313486232E+308): 1.34078079299426E+154 Sqrt(42): 6.48074069840786 Sqrt(1): 1 Sqrt(0.5): 0.707106781186548 Sqrt(0): 0 Sqrt(-1.79769313486232E+308): NaN
L M N O P
Math.Tan(System.Double) Method
Q R
[ILASM]
S
[C#]
.method public hidebysig static float64 Tan(float64 a) public static double Tan(double a)
T U
Summary
V
Returns the tangent of the specified System.Double that represents an angle.
W
Parameters
X Y
Parameter
Description
a
A System.Double that represents an angle measured in radians.
Z
2230
Contents | Index
System
Math Tanh() Method
Return Value A System.Double containing the value of the tangent of a. If a is equal to System.Double.NaN, System.Double.NegativeInfinity, or System.Double.PositiveInfinity, returns System.Double.NaN.
A B
Description
C
[Note: Multiply by θ/180 to convert degrees to radians.]
D
Example
E
using System;
F G
namespace Samples { public class MathTan { public static void Main() { Double[] doubles = {-1, -0.5, 0, 0.5, 1}; foreach(Double d in doubles) Console.WriteLine("Tan({0}): {1}", d, Math.Tan(d)); } } }
H I J K L M N O
The output is
P Tan(-1): -1.5574077246549 Tan(-0.5): -0.54630248984379 Tan(0): 0 Tan(0.5): 0.54630248984379 Tan(1): 1.5574077246549
Q R S T
Math.Tanh(System.Double) Method
U
[ILASM]
V
.method public hidebysig static float64 Tanh(float64 value)
W
[C#]
X
public static double Tanh(double value)
Y
Summary
Z
Returns the hyperbolic tangent of the specified System.Double that represents an angle.
2231
Contents | Index
Math
System
Tanh() Method
Parameters Parameter
Description
value
A System.Double that represents an angle measured in radians.
A B C
Return Value
D
A System.Double containing the value of the hyperbolic tangent of value. If value is equal to System.Double.NegativeInfinity, returns –1. If value is equal to System.Double.PositiveInfinity, returns 1. If value is equal to System.Double.NaN, returns System.Double.NaN.
E F G H
Description
I
[Note: Multiply by θ/180 to convert degrees to radians.]
J K
Example
L
using System;
M
namespace Samples { public class MathTanh { public static void Main() { Double[] doubles = {-1, -0.5, 0, 0.5, 1}; foreach(Double d in doubles) Console.WriteLine("Tanh({0}): {1}", d, Math.Tanh(d)); } } }
N O P Q R S T
The output is
U V
Tanh(-1): -0.761594155955765 Tanh(-0.5): -0.46211715726001 Tanh(0): 0 Tanh(0.5): 0.46211715726001 Tanh(1): 0.761594155955765
W X Y Z
2232
Contents | Index
System.IO MemoryStream
BCL
Object
A
MarshalByRefObject Stream
B
IDisposable
MemoryStream
C D
Summary
E
Provides support for creating and using a stream whose backing store is memory.
F
Type Summary
G
public class MemoryStream : Stream { // Constructors public MemoryStream (); public MemoryStream (byte[] buffer); public MemoryStream (byte[] buffer, bool writable); public MemoryStream (byte[] buffer, int index, int count); public MemoryStream (byte[] buffer, int index, int count, bool writable); public MemoryStream (byte[] buffer, int index, int count, bool writable, bool publiclyVisible); public MemoryStream (int capacity);
H I J K L M N O P
// Properties public override bool CanRead { get; } public override bool CanSeek { get; } public override bool CanWrite { get; } public virtual int Capacity { set; get; } public override long Length { get; } public override long Position { set; get; }
Q R S T U
// Methods public override void Close (); public override void Flush (); public virtual byte[] GetBuffer (); public override int Read (byte[] buffer, int offset, int count); public override int ReadByte (); public override long Seek (long offset, SeekOrigin loc); public override void SetLength (long value);
V W X Y Z
2233
Contents | Index
MemoryStream
System.IO
MemoryStream Class
public virtual byte[] ToArray (); public override void Write (byte[] buffer, int offset, int count); public override void WriteByte (byte value); public virtual void WriteTo (Stream stream);
A B }
C D
Description
E
The System.IO.MemoryStream class creates streams that have memory as a backing store instead of a disk or a network connection. System.IO.MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application. The current position of a stream is the position at which the next read or write operation takes place. The current position can be retrieved or set through the System.IO.MemoryStream.Seek method. When a new instance of System.IO.MemoryStream is created, the current position is set to zero. [Note: Memory streams created with an unsigned byte array provide a non-resizable stream view of the data. When using a byte array, you can neither append to nor shrink the stream, although you might be able to modify the existing contents depending on the parameters passed into the constructor.]
F G H I J K L M N
Example
O
using System; using System.IO;
P Q
namespace Samples { public class MemoryStreamSample { public static void Main() { byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; using(MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length)) { DisplayInformationAboutStream(ms); bytes = new Byte[5]; ms.Read(bytes, 0, bytes.Length); foreach(Byte b in bytes) Console.WriteLine(b); } using(MemoryStream ms = new MemoryStream(256))
R S T U V W X Y Z
2234
Contents | Index
System.IO
MemoryStream MemoryStream Class
{ ms.SetLength(10); DisplayInformationAboutStream(ms); byte[] bytes1 = ms.GetBuffer(); ms.SetLength(1024); DisplayInformationAboutStream(ms); Byte[] bytes2 = ms.GetBuffer(); Console.WriteLine("Are the buffers the same: {0}", Object.ReferenceEquals(bytes1, bytes2));
A B C D
} } public static void DisplayInformationAboutStream( MemoryStream ms) { Console.WriteLine("Can read from stream: {0}", ms.CanRead); Console.WriteLine("Can write to stream: {0}", ms.CanWrite); Console.WriteLine("Can seek in stream: {0}", ms.CanSeek); Console.WriteLine("Capacity of stream: {0}", ms.Capacity); Console.WriteLine("Length of stream: {0}", ms.Length); Console.WriteLine("Position in stream: {0}", ms.Position); }
E F G H I J K L M N O
} }
P Q
The output is
R Can read from stream: True Can write to stream: True Can seek in stream: True Capacity of stream: 10 Length of stream: 10 Position in stream: 0 0 1 2 3 4 Can read from stream: True Can write to stream: True Can seek in stream: True Capacity of stream: 256 Length of stream: 10
S T U V W X Y Z
2235
Contents | Index
MemoryStream
System.IO
MemoryStream() Constructor
Position in stream: 0 Can read from stream: True Can write to stream: True Can seek in stream: True Capacity of stream: 1024 Length of stream: 1024 Position in stream: 0 Are the buffers the same: False
A B C D E
MemoryStream() Constructor
F [ILASM]
G
public rtspecialname specialname instance void .ctor() [C#]
H
public MemoryStream()
I J
Summary
K
Constructs and initializes a new resizable instance of the System.IO.MemoryStream class.
L M
Description
N
The System.IO.Stream.CanRead, System.IO.Stream.CanSeek, and System.IO.Stream.CanWrite properties of the new instance of the System.IO.MemoryStream class are set to true. The capacity of the new stream instance can be increased by using the System.IO.MemoryStream.SetLength method or by setting the System.IO.MemoryStream.Capacity property. The new stream exposes the underlying byte buffer, which can be accessed through the System.IO.MemoryStream.GetBuffer method.
O P Q R S T
Example
U
using System; using System.IO;
V W
namespace Samples { public class MemoryStreamConstructor { public static void Main() { using(MemoryStream ms = new MemoryStream()) {
X Y Z
2236
Contents | Index
System.IO
MemoryStream MemoryStream() Constructor
DisplayInformationAboutStream(ms); ms.SetLength(10); DisplayInformationAboutStream(ms); } } public static void DisplayInformationAboutStream( MemoryStream ms) { Console.WriteLine("Can read from stream: {0}", ms.CanRead); Console.WriteLine("Can write to stream: {0}", ms.CanWrite); Console.WriteLine("Can seek in stream: {0}", ms.CanSeek); Console.WriteLine("Capacity of stream: {0}", ms.Capacity); Console.WriteLine("Length of stream: {0}", ms.Length); Console.WriteLine("Position in stream: {0}", ms.Position); }
A B C D E F G H I J K
}
L
}
M
The output is
N
Can read from stream: True Can write to stream: True Can seek in stream: True Capacity of stream: 0 Length of stream: 0 Position in stream: 0 Can read from stream: True Can write to stream: True Can seek in stream: True Capacity of stream: 256 Length of stream: 10 Position in stream: 0
O P Q R S T U V W
MemoryStream(System.Byte[]) Constructor
X
[ILASM]
Y
public rtspecialname specialname instance void .ctor(class System.Byte[] buffer)
Z
[C#]
public MemoryStream(byte[] buffer)
2237
Contents | Index
MemoryStream
System.IO
MemoryStream() Constructor
Summary Constructs and initializes a new non-resizable instance of the System.IO.MemoryStream class. A
Parameters
B C D E
Parameter
Description
buffer
The System.Byte array from which to create the new stream.
F G
Description
H
The System.IO.Stream.CanRead, System.IO.Stream.CanSeek, and System.IO.Stream.CanWrite properties of the new instance of the System.IO.MemoryStream class are set to true. System.IO.MemoryStream.Capacity is set to the length of the specified System.Byte array. [Note: The new stream instance can be written to, but the System.IO.MemoryStream.Capacity of the underlying System.Byte array cannot be changed. The length of the stream cannot be set to a value greater than System.IO.MemoryStream.Capacity, but the stream can be truncated (see System.IO.MemoryStream.SetLength).] The new stream does not expose the underlying byte buffer, and calls to the System.IO.MemoryStream.GetBuffer method throw System.UnauthorizedAccessException.
I J K L M N O P Q
Exceptions
R S T
Exception
Condition
System.ArgumentNullException
The buffer parameter is null.
U V
Example
W
using System; using System.IO;
X Y
namespace Samples { public class MemoryStreamConstructor { public static void Main()
Z
2238
Contents | Index
System.IO
MemoryStream MemoryStream() Constructor
{ Byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; using(MemoryStream ms = new MemoryStream(bytes)) { DisplayInformationAboutStream(ms); }
A B
} public static void DisplayInformationAboutStream( MemoryStream ms) { Console.WriteLine("Can read from stream: {0}", ms.CanRead); Console.WriteLine("Can write to stream: {0}", ms.CanWrite); Console.WriteLine("Can seek in stream: {0}", ms.CanSeek); Console.WriteLine("Capacity of stream: {0}", ms.Capacity); Console.WriteLine("Length of stream: {0}", ms.Length); Console.WriteLine("Position in stream: {0}", ms.Position); }
C D E F G H I J K L
}
M
}
N
The output is
O
Can read from stream: True Can write to stream: True Can seek in stream: True Capacity of stream: 10 Length of stream: 10 Position in stream: 0
P Q R S T
MemoryStream(System.Byte[], System.Boolean) Constructor
U
[ILASM]
V
public rtspecialname specialname instance void .ctor(class System.Byte[] buffer, bool writable)
W
[C#]
X
public MemoryStream(byte[] buffer, bool writable)
Y
Summary
Z
Constructs and initializes a new non-resizable instance of the System.IO.MemoryStream class. 2239
Contents | Index
MemoryStream
System.IO
MemoryStream() Constructor
Parameters Parameter
Description
buffer
The System.Byte array from which to create the new stream.
writable
A System.Boolean that specifies whether the new stream instance supports writing.
A B C D E
Description
F
The System.IO.Stream.CanRead and System.IO.Stream.CanSeek properties of the new instance of the System.IO.MemoryStream class are set to true. The System.IO.MemoryStream.Capacity property is set to the length of the specified System.Byte array. The System.IO.Stream.CanWrite property is set to writable. [Note: The new stream instance can be written to, but the System.IO.MemoryStream.Capacity of the underlying System.Byte array cannot be changed. The length of the stream cannot be set to a value larger than System.IO.MemoryStream.Capacity, but the stream can be truncated (see System.IO.MemoryStream.SetLength).] The new stream does not expose the underlying System.Byte buffer, and calls to the System.IO.MemoryStream.GetBuffer method throw System.UnauthorizedAccessException.
G H I J K L M N O P
Exceptions
Q R S
Exception
Condition
System.ArgumentNullException
buffer is null.
T U
Example
V
using System; using System.IO;
W
namespace Samples { public class MemoryStreamConstructor { public static void Main() { Byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
X Y Z
2240
Contents | Index
System.IO
MemoryStream MemoryStream() Constructor
using(MemoryStream ms = new MemoryStream(bytes, true)) { DisplayInformationAboutStream(ms); }
A
} public static void DisplayInformationAboutStream( MemoryStream ms) { Console.WriteLine("Can read from stream: {0}", ms.CanRead); Console.WriteLine("Can write to stream: {0}", ms.CanWrite); Console.WriteLine("Can seek in stream: {0}", ms.CanSeek); Console.WriteLine("Capacity of stream: {0}", ms.Capacity); Console.WriteLine("Length of stream: {0}", ms.Length); Console.WriteLine("Position in stream: {0}", ms.Position); }
B C D E F G H I J K
}
L
}
M
The output is
N
Can read from stream: True Can write to stream: True Can seek in stream: True Capacity of stream: 10 Length of stream: 10 Position in stream: 0
O P Q R S
MemoryStream(System.Byte[], System.Int32, System.Int32) Constructor
T
[ILASM]
U
public rtspecialname specialname instance void .ctor(class System.Byte[] buffer, int32 index, int32 count)
V
[C#]
W
public MemoryStream(byte[] buffer, int index, int count)
X
Summary
Y
Constructs and initializes a new non-resizable instance of the System.IO.MemoryStream class.
Z
2241
Contents | Index
MemoryStream
System.IO
MemoryStream() Constructor
Parameters Parameter
Description
buffer
The System.Byte array from which to create the new stream.
C
index
A System.Int32 that specifies the index into buffer at which the stream begins.
D
count
A System.Int32 that specifies the length of the stream in bytes.
A B
E F
Description
G
The System.IO.Stream.CanRead, System.IO.Stream.CanSeek, and System.IO.Stream.CanWrite properties of the new System.IO.MemoryStream instance are set to true. The System.IO.MemoryStream.Capacity property is set to count. [Note: The new stream instance can be written to, but the System.IO.MemoryStream.Capacity of the underlying System.Byte array cannot be changed. The length of the stream cannot be set to a value larger than System.IO.MemoryStream.Capacity, but the stream can be truncated (see System.IO.MemoryStream.SetLength).] The new stream does not expose the underlying System.Byte buffer, and calls to the System.IO.MemoryStream.GetBuffer method throw System.UnauthorizedAccessException.
H I J K L M N O P
Exceptions
Q R
Exception
Condition
System.ArgumentNullException
buffer is null.
System.ArgumentOutOfRangeException
index or count is less than zero.
System.ArgumentException
(index + count ) is greater than the length of buffer.
S T U V W X Y Z
2242
Contents | Index
System.IO
MemoryStream MemoryStream() Constructor
Example using System; using System.IO;
A namespace Samples { public class MemoryStreamConstructor { public static void Main() { Byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; using(MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length)) { DisplayInformationAboutStream(ms); } } public static void DisplayInformationAboutStream( MemoryStream ms) { Console.WriteLine("Can read from stream: {0}", ms.CanRead); Console.WriteLine("Can write to stream: {0}", ms.CanWrite); Console.WriteLine("Can seek in stream: {0}", ms.CanSeek); Console.WriteLine("Capacity of stream: {0}", ms.Capacity); Console.WriteLine("Length of stream: {0}", ms.Length); Console.WriteLine("Position in stream: {0}", ms.Position); } } }
B C D E F G H I J K L M N O P Q R S T U
The output is
V W
Can read from stream: True Can write to stream: True Can seek in stream: True Capacity of stream: 10 Length of stream: 10 Position in stream: 0
X Y Z
2243
Contents | Index
MemoryStream
System.IO
MemoryStream() Constructor
MemoryStream(System.Byte[], System.Int32, System.Int32, System.Boolean) Constructor [ILASM]
A
public rtspecialname specialname instance void .ctor(class System.Byte[] buffer, int32 index, int32 count, bool writable)
B
[C#]
C
public MemoryStream(byte[] buffer, int index, int count, bool writable)
D E
Summary
F
Constructs and initializes a new non-resizable instance of the System.IO.MemoryStream class.
G
Parameters
H I
Parameter
Description
K
buffer
The System.Byte array from which to create the new stream.
L
index
A System.Int32 that specifies the index in buffer at which the stream begins.
count
A System.Int32 that specifies the length of the stream in bytes.
writable
A System.Boolean that specifies whether the new stream instance supports writing.
J
M N O P Q
Description
R
The System.IO.MemoryStream.CanRead and System.IO.MemoryStream.CanSeek properties of the new System.IO.MemoryStream are set to true. The System.IO.MemoryStream.Capacity property is set to count. The Sytem.IO.Stream.CanWrite property is set to writable. [Note: The new stream instance can be written to, but the System.IO.MemoryStream.Capacity of the underlying byte array cannot be changed. The length of the stream cannot be set to a value larger than System.IO.MemoryStream.Capacity, but the stream can be truncated (see System.IO.MemoryStream.SetLength).] The new stream does not expose the underlying byte buffer, and calls to the System.IO.MemoryStream.GetBuffer method throw System.UnauthorizedAccessException.
S T U V W X Y Z
2244
Contents | Index
System.IO
MemoryStream MemoryStream() Constructor
Exceptions Exception
Condition
System.ArgumentNullException
buffer is null.
System.ArgumentOutOfRangeException
index or count is negative.
System.ArgumentException
(index + count ) is greater than the length of buffer.
A B C D E F
Example
G
using System; using System.IO;
H I
namespace Samples { public class MemoryStreamConstructor { public static void Main() { byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; using(MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length, true)) { DisplayInformationAboutStream(ms); } } public static void DisplayInformationAboutStream( MemoryStream ms) { Console.WriteLine("Can read from stream: {0}", ms.CanRead); Console.WriteLine("Can write to stream: {0}", ms.CanWrite); Console.WriteLine("Can seek in stream: {0}", ms.CanSeek); Console.WriteLine("Capacity of stream: {0}", ms.Capacity); Console.WriteLine("Length of stream: {0}", ms.Length); Console.WriteLine("Position in stream: {0}", ms.Position); } } }
J K L M N O P Q R S T U V W X Y Z
2245
Contents | Index
MemoryStream
System.IO
MemoryStream() Constructor
The output is Can read from stream: True Can write to stream: True Can seek in stream: True Capacity of stream: 10 Length of stream: 10 Position in stream: 0
A B C D E
MemoryStream(System.Byte[], System.Int32, System.Int32, System.Boolean, System.Boolean) Constructor
F G
[ILASM]
public rtspecialname specialname instance void .ctor(class System.Byte[] buffer, int32 index, int32 count, bool writable, bool publiclyVisible)
H I
[C#]
J
public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible)
K L
Summary
M
Constructs and initializes a new instance of the System.IO.MemoryStream class.
N
Parameters
O P Q
Parameter
Description
buffer
The System.Byte array from which to create the new stream.
index
A System.Int32 that specifies the index into buffer at which the stream begins.
count
A System.Int32 that specifies the length of the stream in bytes.
writable
A System.Boolean that specifies whether the new stream instance supports writing.
publiclyVisible
A System.Boolean that specifies whether buffer is exposed via the System.IO.MemoryStream.GetBuffer, which returns the System.Byte array from which the stream was created. Specify true to expose buffer; otherwise, specify false.
R S T U V W X Y Z
2246
Contents | Index
System.IO
MemoryStream MemoryStream() Constructor
Description The System.IO.MemoryStream.CanRead and System.IO.MemoryStream.CanSeek properties of the new System.IO.MemoryStream instance are set to true. The System.IO.MemoryStream.Capacity property is set to count. The System.IO.Stream.CanWrite property is set to writable. [Note: The new stream instance can be written to, but the System.IO.MemoryStream.Capacity of the underlying System.Byte array cannot be changed. The length of the stream cannot be set to a value larger than System.IO.MemoryStream.Capacity, but the stream can be truncated (see System.IO.MemoryStream.SetLength).]
A B C D E F G
Exceptions
H
Exception
Condition
System.ArgumentNullException
buffer is null.
J
System.ArgumentOutOfRangeException
index or count is negative.
K
System.ArgumentException
(index + count ) is greater than the length of buffer.
I
L M N
Example
O
using System; using System.IO;
P Q
namespace Samples { public class MemoryStreamConstructor { public static void Main() { byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; using(MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length, true, true)) { DisplayInformationAboutStream(ms); } } public static void DisplayInformationAboutStream( MemoryStream ms)
R S T U V W X Y Z
2247
Contents | Index
MemoryStream
System.IO
MemoryStream() Constructor
{ Console.WriteLine("Can read from stream: {0}", ms.CanRead); Console.WriteLine("Can write to stream: {0}", ms.CanWrite); Console.WriteLine("Can seek in stream: {0}", ms.CanSeek); Console.WriteLine("Capacity of stream: {0}", ms.Capacity); Console.WriteLine("Length of stream: {0}", ms.Length); Console.WriteLine("Position in stream: {0}", ms.Position);
A B C D E F }
G
}
H
}
I
The output is
J Can read from stream: True Can write to stream: True Can seek in stream: True Capacity of stream: 10 Length of stream: 10 Position in stream: 0
K L M N O P
MemoryStream(System.Int32) Constructor
Q
[ILASM]
public rtspecialname specialname instance void .ctor(int32 capacity)
R
[C#]
public MemoryStream(int capacity)
S T
Summary
U
Constructs and initializes a new resizable instance of the System.IO.MemoryStream class.
V W
Parameters
X Y
Parameter
Description
capacity
A System.Int32 that specifies the initial size of the internal System.Byte array.
Z
2248
Contents | Index
System.IO
MemoryStream MemoryStream() Constructor
Description The System.IO.Stream.CanRead, System.IO.Stream.CanSeek, and System.IO.Stream.CanWrite properties of the new instance of the System.IO.MemoryStream class are set to true. The System.IO.MemoryStream.Capacity of the new stream instance is set to capacity and can be increased by using the System.IO.MemoryStream.SetLength method or by setting the System.IO.MemoryStream.Capacity property. Write operations at the end of the new instance of the System.IO.MemoryStream class expand the System.IO.MemoryStream. The new stream exposes the underlying byte buffer, which can be accessed through the System.IO.MemoryStream.GetBuffer method.
A B C D E F G
Exceptions
H
Exception
Condition
System.ArgumentOutOfRangeException
capacity is negative.
I J K L
Example
M
using System; using System.IO;
N O
namespace Samples { public class MemoryStreamConstructor { public static void Main() { using(MemoryStream ms = new MemoryStream(256)) { DisplayInformationAboutStream(ms); } } public static void DisplayInformationAboutStream( MemoryStream ms) { Console.WriteLine("Can read from stream: {0}", ms.CanRead); Console.WriteLine("Can write to stream: {0}", ms.CanWrite); Console.WriteLine("Can seek in stream: {0}", ms.CanSeek);
P Q R S T U V W X Y Z
2249
Contents | Index
MemoryStream
System.IO
CanRead Property
Console.WriteLine("Capacity of stream: {0}", ms.Capacity); Console.WriteLine("Length of stream: {0}", ms.Length); Console.WriteLine("Position in stream: {0}", ms.Position);
A B }
C
} }
D
The output is
E F
Can read from stream: True Can write to stream: True Can seek in stream: True Capacity of stream: 256 Length of stream: 0 Position in stream: 0
G H I J K
MemoryStream.CanRead Property
L [ILASM]
M
.property bool CanRead { public hidebysig virtual specialname bool get_CanRead() }
N
[C#]
public override bool CanRead { get; }
O P
Summary
Q
Gets a System.Boolean value indicating whether the current stream supports reading.
R
Property Value
S
true if the current stream supports reading; otherwise false.
T U
Example
V
using System; using System.IO;
W namespace Samples { public class MemoryStreamCanRead { public static void Main() { byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
X Y Z
2250
Contents | Index
System.IO
MemoryStream CanSeek Property
using(MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length, false, false)) { DisplayInformationAboutStream(ms); Console.WriteLine(); } using(MemoryStream ms = new MemoryStream()) { DisplayInformationAboutStream(ms); Console.WriteLine(); }
A B C D E F G
} public static void DisplayInformationAboutStream( MemoryStream ms) { Console.WriteLine("Can read from stream: {0}", ms.CanRead); Console.WriteLine("Can write to stream: {0}", ms.CanWrite); Console.WriteLine("Can seek in stream: {0}", ms.CanSeek); }
H I J K L M N
} }
O
The output is
P Q
Can read from stream: True Can write to stream: False Can seek in stream: True
R S
Can read from stream: True Can write to stream: True Can seek in stream: True
T U V
MemoryStream.CanSeek Property
W
[ILASM]
X
.property bool CanSeek { public hidebysig virtual specialname bool get_CanSeek() }
Y
[C#]
Z
public override bool CanSeek { get; }
2251
Contents | Index
MemoryStream
System.IO
CanSeek Property
Summary Gets a System.Boolean value indicating whether the current stream supports seeking. A
Property Value
B
true if the stream supports seeking; otherwise false.
C
Example
D
using System; using System.IO;
E F
namespace Samples { public class MemoryStreamCanSeek { public static void Main() { byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; using(MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length, false, false)) { DisplayInformationAboutStream(ms); Console.WriteLine(); } using(MemoryStream ms = new MemoryStream()) { DisplayInformationAboutStream(ms); Console.WriteLine(); } } public static void DisplayInformationAboutStream( MemoryStream ms) { Console.WriteLine("Can read from stream: {0}", ms.CanRead); Console.WriteLine("Can write to stream: {0}", ms.CanWrite); Console.WriteLine("Can seek in stream: {0}", ms.CanSeek); } } }
G H I J K L M N O P Q R S T U V W X Y Z
2252
Contents | Index
System.IO
MemoryStream CanWrite Property
The output is Can read from stream: True Can write to stream: False Can seek in stream: True
A B
Can read from stream: True Can write to stream: True Can seek in stream: True
C D E
MemoryStream.CanWrite Property
F
[ILASM]
G
.property bool CanWrite { public hidebysig virtual specialname bool get_CanWrite() }
H
[C#]
I
public override bool CanWrite { get; }
J
Summary
K
Gets a System.Boolean value indicating whether the current stream supports writing.
L M
Property Value
N
true if the stream supports writing; otherwise, false.
O
Example
P
using System; using System.IO;
Q R
namespace Samples { public class MemoryStreamCanWrite { public static void Main() { byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; using(MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length, false, false)) { DisplayInformationAboutStream(ms); Console.WriteLine(); }
S T U V W X Y Z
2253
Contents | Index
MemoryStream
System.IO
Capacity Property
using(MemoryStream ms = new MemoryStream()) { DisplayInformationAboutStream(ms); Console.WriteLine(); }
A
} public static void DisplayInformationAboutStream( MemoryStream ms) { Console.WriteLine("Can read from stream: {0}", ms.CanRead); Console.WriteLine("Can write to stream: {0}", ms.CanWrite); Console.WriteLine("Can seek in stream: {0}", ms.CanSeek); }
B C D E F G H }
I
}
J
The output is
K Can read from stream: True Can write to stream: False Can seek in stream: True
L M N
Can read from stream: True Can write to stream: True Can seek in stream: True
O P Q
MemoryStream.Capacity Property
R
[ILASM]
S
.property int32 Capacity { public hidebysig virtual specialname int32 get_Capacity() public hidebysig virtual specialname void set_Capacity(int32 value) }
T U
[C#]
public virtual int Capacity { get; set; }
V W
Summary
X
Gets or sets the number of bytes allocated for the current stream.
Y
Description
Z
System.IO.MemoryStream.Capacity is the buffer length for system-provided byte arrays. If the current stream is created with a specified System.Byte array,
2254
Contents | Index
System.IO
MemoryStream Capacity Property
System.IO.MemoryStream.Capacity indicates the length of the portion of the provided array to which the current stream has access. [Note: For additional information, see the System.IO.MemoryStream(System.Byte[], System.Int32, System.Int32) constructor.] System.IO.MemoryStream.Capacity cannot be set to a value less than the current length of the stream, but can be set to less than the current capacity. If the capacity specified is less than the current capacity, the size of the buffer used to hold the stream may be reduced, but need not be. [Note: If the value specified for a set operation is less than the default value, for performance reasons the property is set to the default. The default value of the System.IO.MemoryStream.Capacity property is unspecified.]
A B C D E F G
Exceptions
H
Exception
Condition
System.ArgumentOutOfRangeException
The value specified for a set operation is negative or less than the current length of the stream.
System.NotSupportedException
A set operation was attempted on a stream whose capacity cannot be modified.
System.ObjectDisposedException
A set operation was attempted on a stream that is closed.
I J K L M N O P
Example
Q
using System; using System.IO;
R S
namespace Samples { public class MemoryStreamCapacity { public static void Main() { byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; using(MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length, false, false)) { DisplayInformationAboutStream(ms);
T U V W X Y Z
2255
Contents | Index
MemoryStream
System.IO
Capacity Property
try { ms.Capacity = 5; } catch(NotSupportedException e) { Console.WriteLine("Exception: {0}", e); } Console.WriteLine();
A B C D
} using(MemoryStream ms = new MemoryStream()) { DisplayInformationAboutStream(ms); ms.SetLength(10); ms.Capacity = 512; DisplayInformationAboutStream(ms); }
E F G H I
} public static void DisplayInformationAboutStream( MemoryStream ms) { Console.WriteLine("Capacity of stream: {0}", ms.Capacity); Console.WriteLine("Length of stream: {0}", ms.Length); }
J K L M N }
O
}
P
The output is
Q
Capacity of stream: 10 Length of stream: 10 Exception: System.NotSupportedException: Memory stream is not expandable. at System.IO.__Error.MemoryStreamNotExpandable() at System.IO.MemoryStream.set_Capacity(Int32 value) at Samples.MemoryStreamCapacity.Main() in C:\Books\BCL\Samples\System.IO\ MemoryStream\Capacity\MemoryStream.cs:line 20
R S T U V
Capacity of stream: 0 Length of stream: 0 Capacity of stream: 512 Length of stream: 10
W X Y Z
2256
Contents | Index
System.IO
MemoryStream Length Property
MemoryStream.Length Property [ILASM]
.property int64 Length { public hidebysig virtual specialname int64 get_Length() } [C#]
A
public override long Length { get; }
B C
Summary
D
Gets the length of the stream in bytes.
E
Description
F
[Note: This property overrides System.IO.Stream.Length.]
G H
Exceptions
I
Exception
Condition
J
System.ObjectDisposedException
The current stream is closed.
K L M
Example
N
using System; using System.IO;
O P
namespace Samples { public class MemoryStreamLength { public static void Main() { byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; using(MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length, false, false)) { DisplayInformationAboutStream(ms); Console.WriteLine(); } using(MemoryStream ms = new MemoryStream()) { DisplayInformationAboutStream(ms); Console.WriteLine(); ms.SetLength(200);
Q R S T U V W X Y Z
2257
Contents | Index
MemoryStream
System.IO
Position Property
DisplayInformationAboutStream(ms); } } public static void DisplayInformationAboutStream( MemoryStream ms) { Console.WriteLine("Capacity of stream: {0}", ms.Capacity); Console.WriteLine("Length of stream: {0}", ms.Length); }
A B C D E
} }
F G
The output is
H
Capacity of stream: 10 Length of stream: 10
I J
Capacity of stream: 0 Length of stream: 0
K
Capacity of stream: 256 Length of stream: 200
L M N
MemoryStream.Position Property
O
[ILASM]
P
.property int64 Position { public hidebysig virtual specialname int64 get_Position() public hidebysig virtual specialname void set_Position(int64 value) }
Q
[C#]
R
public override long Position { get; set; }
S
Summary
T
Gets or sets the current position within the stream.
U V
Description
W
The position cannot be set more than one byte beyond the end of the stream. [Note: This property overrides System.IO.Stream.Position.]
X Y Z
2258
Contents | Index
System.IO
MemoryStream Position Property
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
The value specified for a set operation is negative or greater than one byte beyond the length of the current stream.
A
System.ObjectDisposedException
B C D
The current stream is closed.
E
Example
F
using System; using System.IO;
G H
namespace Samples { public class MemoryStreamPosition { public static void Main() { byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; using(MemoryStream ms = new MemoryStream(bytes)) { ms.Seek(0, SeekOrigin.Begin); DisplayInformationAboutStream(ms); ms.Seek(0, SeekOrigin.End); DisplayInformationAboutStream(ms); ms.Position = 1; DisplayInformationAboutStream(ms); } } public static void DisplayInformationAboutStream( MemoryStream ms) { Console.WriteLine("Length of stream: {0}", ms.Length); Console.WriteLine("Position in stream: {0}", ms.Position); } } }
I J K L M N O P Q R S T U V W X Y Z
2259
Contents | Index
MemoryStream
System.IO
Close() Method
The output is Length of stream: 10 Position in stream: 0 Length of stream: 10 Position in stream: 10 Length of stream: 10 Position in stream: 1
A B C D E
MemoryStream.Close() Method
F [ILASM]
G
.method public hidebysig virtual void Close() [C#]
H
public override void Close()
I J
Summary
K
Closes the current System.IO.MemoryStream instance.
L
Description
M
The stream will not support reading or writing after this method is invoked. Following a call to System.IO.MemoryStream.Close, operations on the stream can raise an exception. The buffer of a closed System.IO.MemoryStream is still available, and the System.IO.MemoryStream.ToArray and System.IO.MemoryStream.GetBuffer methods can be called successfully. [Note: This method overrides System.IO.Stream.Close.]
N O P Q R
Example
S
using System; using System.IO;
T U
namespace Samples { public class MemoryStreamClose { public static void Main() { byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; MemoryStream ms = new MemoryStream(bytes); DisplayInformationAboutStream(ms); ms.Close(); try {
V W X Y Z
2260
Contents | Index
System.IO
MemoryStream Flush() Method
DisplayInformationAboutStream(ms); } catch(ObjectDisposedException e) { Console.WriteLine("Exception: {0}", e); }
A B
} public static void DisplayInformationAboutStream( MemoryStream ms) { Console.WriteLine("Can read from stream: {0}", ms.CanRead); Console.WriteLine("Can write to stream: {0}", ms.CanWrite); Console.WriteLine("Can seek in stream: {0}", ms.CanSeek); }
C D E F G H I
} }
J K
The output is Can Can Can Can Can Can
L
read from stream: True write to stream: True seek in stream: True read from stream: False write to stream: False seek in stream: False
M N O P Q
MemoryStream.Flush() Method
R
[ILASM]
S
.method public hidebysig virtual void Flush()
T
[C#]
public override void Flush()
U
Summary
V
Overrides System.IO.Stream.Flush so that no action is performed.
W X
Description
Y
Since any data written to a System.IO.MemoryStream is written into RAM, this method is redundant. [Note: This method overrides System.IO.Stream.Flush.]
Z
2261
Contents | Index
MemoryStream
System.IO
GetBuffer() Method
MemoryStream.GetBuffer() Method [ILASM]
.method public hidebysig virtual class System.Byte[] GetBuffer()
A
[C#]
public virtual byte[] GetBuffer()
B C
Summary
D
Returns the array of unsigned bytes from which this stream was created.
E
Return Value
F
The System.Byte array from which the current stream was created, or the underlying array if a System.Byte array was not provided to the System.IO.MemoryStream constructor during construction of the current instance.
G H I
Description
J
To create a System.IO.MemoryStream instance with a publicly visible buffer use the default constructor, or System.IO.MemoryStream(System.Byte [], System.Int32, System.Int32, System.Boolean, System.Boolean) or System.IO.MemoryStream(System.Int32) constructor. If the current stream is resizable, multiple calls to this method do not return the same array if the underlying System.Byte array is resized between calls. For additional information, see System.IO.MemoryStream.Capacity. [Note: This method works when the System.IO.MemoryStream is closed.]
K L M N O P Q
Exceptions
R S
Exception
Condition
System.UnauthorizedAccessException
The current instance was not created with a publicly visible buffer.
T U V W
Example
X
using System; using System.IO;
Y namespace Samples { public class MemoryStreamGetBuffer {
Z
2262
Contents | Index
System.IO
MemoryStream Read() Method
public static void Main() { using(MemoryStream ms = new MemoryStream(256)) { DisplayInformationAboutStream(ms); Console.WriteLine("Length of buffer is: {0}", ms.GetBuffer().Length); if(ms.CanWrite) { ms.SetLength(10); DisplayInformationAboutStream(ms); } Console.WriteLine("Length of buffer is: {0}", ms.GetBuffer().Length); } } public static void DisplayInformationAboutStream( MemoryStream ms) { Console.WriteLine("Capacity of stream: {0}", ms.Capacity); Console.WriteLine("Length of stream: {0}", ms.Length); Console.WriteLine("Position in stream: {0}", ms.Position); }
A B C D E F G H I J K L M N
}
O
}
P
The output is
Q Capacity of stream: 256 Length of stream: 0 Position in stream: 0 Length of buffer is: 256 Capacity of stream: 256 Length of stream: 10 Position in stream: 0 Length of buffer is: 256
R S T U V W
MemoryStream.Read(System.Byte[], System.Int32, System.Int32) Method
X
[ILASM]
Y
.method public hidebysig virtual int32 Read(class System.Byte[] buffer, int32 offset, int32 count)
Z
[C#]
public override int Read(byte[] buffer, int offset, int count)
2263
Contents | Index
MemoryStream
System.IO
Read() Method
Summary Reads a block of bytes from the current stream at the current position, and writes the data to the specified byte array. A
Parameters
B C
Parameter
Description
buffer
A System.Byte array. When this method returns, contains the specified byte array with the values between offset and (offset + count – 1) replaced by the characters read from the current stream.
offset
A System.Int32 that specifies the byte offset in buffer at which to begin writing.
count
A System.Int32 that specifies the maximum number of bytes to read.
D E F G H I J K
Return Value
L
A System.Int32 that specifies the total number of bytes read into the buffer, or zero if the end of the stream is reached before any bytes are read.
M N
Description
O
If the read operation is successful, the current position within the stream advances by the number of bytes read. If an exception occurs, the current position within the stream remains unchanged. [Note: If the byte array specified in the buffer parameter is the underlying buffer returned by the System.IO.MemoryStream.GetBuffer method, the array contents are overwritten, and no exception is thrown. This method overrides System.IO.Stream.Read.]
P Q R S T
Exceptions
U
Exception
Condition
W
System.ArgumentNullException
buffer is null.
X
System.ArgumentOutOfRangeException
offset or count is negative.
System.ArgumentException
(offset + count) is larger than the length of buffer.
System.ObjectDisposedException
The current stream is closed.
V
Y Z
2264
Contents | Index
System.IO
MemoryStream ReadByte() Method
Example using System; using System.IO;
A namespace Samples { public class MemoryStreamRead { public static void Main() { byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; using(MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length)) { bytes = new Byte[5]; ms.Read(bytes, 0, bytes.Length); foreach(Byte b in bytes) Console.WriteLine(b); } } } }
B C D E F G H I J K L M
The output is
N 0 1 2 3 4
O P Q R S
MemoryStream.ReadByte() Method
T [ILASM]
U
.method public hidebysig virtual int32 ReadByte() [C#]
V
public override int ReadByte()
W
Summary
X
Reads a byte from the current stream at the current position.
Y Z
Return Value The byte cast to a System.Int32, or –1 if the end of the stream has been reached.
2265
Contents | Index
MemoryStream
System.IO
ReadByte() Method
Description If the read operation is successful, the current position within the stream is advanced by one byte. If an exception occurs, the current position within the stream is unchanged. [Note: This method overrides System.IO.Stream.ReadByte.]
A B
Exceptions
C D
Exception
Condition
System.ObjectDisposedException
The current stream is closed.
E F G H
Example
I
using System; using System.IO;
J
namespace Samples { public class MemoryStreamReadByte { public static void Main() { byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; using(MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length)) { for(int i = 0; i < ms.Length; i++) Console.WriteLine("{0}: {1}", i, ms.ReadByte()); } } } }
K L M N O P Q R S T U
The output is
V
0: 1: 2: 3: 4: 5: 6: 7: 8: 9:
W X Y Z
0 1 2 3 4 5 6 7 8 9
2266
Contents | Index
System.IO
MemoryStream Seek() Method
MemoryStream.Seek(System.Int64, System.IO.SeekOrigin) Method [ILASM]
.method public hidebysig virtual int64 Seek(int64 offset, valuetype System.IO.SeekOrigin loc)
A
[C#]
B
public override long Seek(long offset, SeekOrigin loc)
C
Summary
D
Sets the current position within the current stream to the specified value.
E F
Parameters
G
Parameter
Description
offset
A System.Int64 that specifies the new position within the stream. This is relative to the loc parameter, and may be positive or negative.
loc
A System.IO.SeekOrigin value that specifies the seek reference point.
H I J K L
Return Value
M
A System.Int64 containing the new position within the stream, calculated by combining the seek reference point and the offset.
N O P
Description
Q
The position cannot be set to more than one byte beyond the end of the stream. [Note: This method overrides System.IO.Stream.Seek.]
R S
Exceptions
T U
Exception
Condition
System.IO.IOException
Seeking is attempted before the beginning or more than one byte beyond the end of the stream.
System.ArgumentOutOfRangeException
offset is greater than the maximum length of the System.IO.MemoryStream.
X
System.ArgumentException
loc is not a valid System.IO.SeekOrigin value.
Z
System.ObjectDisposedException
The current stream is closed.
V W
Y
2267
Contents | Index
MemoryStream
System.IO
SetLength() Method
Example using System; using System.IO;
A namespace Samples { public class MemoryStreamSeek { public static void Main() { byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; using(MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length)) { ms.Seek(0, SeekOrigin.Begin); Console.WriteLine(ms.ReadByte()); ms.Seek(1, SeekOrigin.Current); Console.WriteLine(ms.ReadByte()); ms.Seek(0, SeekOrigin.End); ms.Seek(-1, SeekOrigin.Current); Console.WriteLine(ms.ReadByte()); } } } }
B C D E F G H I J K L M N O
The output is
P 0 2 9
Q R S T
MemoryStream.SetLength(System.Int64) Method
U [ILASM]
V
.method public hidebysig virtual void SetLength(int64 value) [C#]
W
public override void SetLength(long value)
X
Summary
Y
Sets the length of the current stream to the specified value.
Z
2268
Contents | Index
System.IO
MemoryStream SetLength() Method
Parameters Parameter
Description
value
A System.Int64 that specifies the value at which to set the length.
A B C
Description
D
If the specified value is less than the current length of the stream, the stream is truncated. If after the truncation the current position within the stream is past the end of the stream, the System.IO.MemoryStream.ReadByte method returns –1, the System.IO.MemoryStream.Read method reads zero bytes into the provided byte array, and the System.IO.MemoryStream.Write and System.IO.MemoryStream.WriteByte methods append specified bytes at the end of the stream, increasing its length. If the specified value is larger than the current capacity and the stream is resizable, the capacity is increased, and the current position within the stream is unchanged. If the length is increased, the contents of the stream between the old and the new length are initialized to zeros. [Note: A System.IO.MemoryStream instance must support writing for this method to work. Use the System.IO.MemoryStream.CanWrite property to determine whether the current instance supports writing. For additional information, see System.IO.Stream.CanWrite. This method overrides System.IO.Stream.SetLength.]
E F G H I J K L M N O P
Exceptions Exception
System.NotSupportedException
Q R
Condition
S
The current stream is not resizable and value is greater than the current System.IO.MemoryStream.Capacity.
T U
-or-
V
The current stream does not support writing.
System.ArgumentOutOfRangeException
W
value is negative or is greater than the maximum length of the System.IO.MemoryStream, where the maximum length is (System.Int32.MaxValue – origin), and origin is the index into the underlying buffer at which the stream starts.
X Y Z
2269
Contents | Index
MemoryStream
System.IO
SetLength() Method
Example using System; using System.IO;
A namespace Samples { public class MemoryStreamSetLength { public static void Main() { using(MemoryStream ms = new MemoryStream()) { DisplayInformationAboutStream(ms); ms.SetLength(10); DisplayInformationAboutStream(ms); ms.SetLength(512); DisplayInformationAboutStream(ms); } } public static void DisplayInformationAboutStream( MemoryStream ms) { Console.WriteLine("Capacity of stream: {0}", ms.Capacity); Console.WriteLine("Length of stream: {0}", ms.Length); Console.WriteLine("Position in stream: {0}", ms.Position); } } }
B C D E F G H I J K L M N O P Q R
The output is
S
Capacity of stream: 0 Length of stream: 0 Position in stream: 0 Capacity of stream: 256 Length of stream: 10 Position in stream: 0 Capacity of stream: 512 Length of stream: 512 Position in stream: 0
T U V W X Y Z
2270
Contents | Index
System.IO
MemoryStream ToArray() Method
MemoryStream.ToArray() Method [ILASM]
.method public hidebysig virtual class System.Byte[] ToArray() [C#]
A
public virtual byte[] ToArray()
B C
Summary
D
Writes the entire stream contents to a System.Byte array, regardless of the current position within the stream.
E F
Description
G
This method returns a copy of the contents of the System.IO.MemoryStream as a byte array. If the current instance was constructed on a provided byte array, a copy of the section of the array to which the current instance has access is returned. [Note: For additional information, see the System.IO.MemoryStream(System.Byte[], System.Int32, System.Int32) constructor.] [Note: This method works when the System.IO.MemoryStream is closed.]
H I J K L
Example
M
using System; using System.IO;
N O
namespace Samples { public class MemoryStreamToArray { public static void Main() { byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; using(MemoryStream ms = new MemoryStream(bytes)) { byte[] bytes1 = ms.ToArray(); foreach(byte b in bytes1) Console.WriteLine(b); } } } }
P Q R S T U V W X Y Z
2271
Contents | Index
MemoryStream
System.IO
Write() Method
The output is 0 1 2 3 4 5 6 7 8 9
A B C D E F G H
MemoryStream.Write(System.Byte[], System.Int32, System.Int32) Method
I
[ILASM]
J
.method public hidebysig virtual void Write(class System.Byte[] buffer, int32 offset, int32 count)
K
[C#]
public override void Write(byte[] buffer, int offset, int count)
L M
Summary
N
Writes a block of bytes to the current stream at the current position using data read from buffer.
O P
Parameters
Q R S
Parameter
Description
buffer
The System.Byte array to write data from.
offset
A System.Int32 that specifies the zero-based byte offset into buffer at which to begin writing from.
count
A System.Int32 that specifies the maximum number of bytes to write from buffer.
T U V W X
Description
Y
If the write operation is successful, the current position within the stream is advanced by the number of bytes written. If an exception occurs, the current position within the stream is unchanged.
Z
2272
Contents | Index
System.IO
MemoryStream Write() Method
Write operations at the end of a resizable System.IO.MemoryStream expand the System.IO.MemoryStream. [Note: Use the System.IO.MemoryStream.CanWrite method to determine whether the current stream supports writing.] [Note: This method overrides System.IO.Stream.Write.]
A B C
Exceptions
D
Exception
Condition
E
System.ArgumentNullException
buffer is null.
F
The current stream does not support writing.
G
-or-
H
The current position is closer than count bytes to the end of the stream, and the capacity cannot be modified.
I
System.ArgumentException
(offset + count ) is greater than the length of buffer.
K
System.ArgumentOutOfRangeException
offset or count are negative.
System.IO.IOException
An I/O error occurred.
System.ObjectDisposedException
The current stream is closed.
System.NotSupportedException
J
L M N O P
Example
Q
using System; using System.IO;
R S
namespace Samples { public class MemoryStreamWrite { public static void Main() { byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; using(MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length)) { bytes = new byte[]{10, 11, 12, 13, 14, 15, 16, 17, 18, 19}; ms.Write(bytes, 0, bytes.Length); bytes = new byte[10];
T U V W X Y Z
2273
Contents | Index
MemoryStream
System.IO
WriteByte() Method
ms.Seek(0, SeekOrigin.Begin); ms.Read(bytes, 0, bytes.Length); foreach(byte b in bytes) Console.WriteLine(b);
A
} }
B
} }
C D
The output is
E 10 11 12 13 14 15 16 17 18 19
F G H I J K L M
MemoryStream.WriteByte(System.Byte) Method
N
[ILASM]
O
.method public hidebysig virtual void WriteByte(unsigned int8 value) [C#]
P
public override void WriteByte(byte value)
Q
Summary
R
Writes a System.Byte to the current stream at the current position.
S T
Parameters
U V W
Parameter
Description
value
The System.Byte to write.
X Y
Description
Z
Write operations at the end of a resizable System.IO.MemoryStream expand the System.IO.MemoryStream. If the write operation is successful, the current position within the stream is advanced by one byte. If an exception occurs, the position is unchanged. 2274
Contents | Index
System.IO
MemoryStream WriteByte() Method
[Note: Use the System.IO.MemoryStream.CanWrite method to determine whether the current stream supports writing.] [Note: This method overrides System.IO.Stream.WriteByte.] A
Exceptions Exception
B C
Condition
D System.ObjectDisposedException
System.NotSupportedException
The current stream is closed.
E
The current stream does not support writing.
F
-or-
G
The current position is at the end of the stream, and the stream’s capacity cannot be modified.
H I J
Example
K
using System; using System.IO;
L M
namespace Samples { public class MemoryStreamWriteByte { public static void Main() { byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; using(MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length)) { bytes = new byte[]{10, 11, 12, 13, 14, 15, 16, 17, 18, 19}; foreach(byte b in bytes) ms.Writebyte(b); ms.Seek(0, SeekOrigin.Begin); for(int i = 0; i < ms.Length; i++) Console.WriteLine(ms.ReadByte()); } } } }
N O P Q R S T U V W X Y Z
2275
Contents | Index
MemoryStream
System.IO
WriteTo() Method
The output is 10 11 12 13 14 15 16 17 18 19
A B C D E F G
MemoryStream.WriteTo(System.IO.Stream) Method
H [ILASM]
I
.method public hidebysig virtual void WriteTo(class System.IO.Stream stream) [C#]
J
public virtual void WriteTo(Stream stream)
K L
Summary
M
Writes the entire contents of the current System.IO.MemoryStream instance to a specified stream.
N
Parameters
O P
Parameter
Description
stream
The System.IO.Stream to write the current memory stream to.
Q R S T
Description
U
[Note: When the current stream is open, this method is equivalent to calling System.IO.Stream.Write and passing in the underlying buffer of the current instance.]
V
Exceptions
W X Y Z
Exception
Condition
System.ArgumentNullException
stream is null.
System.ObjectDisposedException
The current or target stream is closed.
2276
Contents | Index
System.IO
MemoryStream WriteTo() Method
Example using System; using System.IO;
A namespace Samples { public class MemoryStreamWriteTo { public static void Main() { byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; using(MemoryStream ms1 = new MemoryStream(bytes, 0, bytes.Length)) { using(MemoryStream ms2 = new MemoryStream()) { ms1.WriteTo(ms2); ms2.Seek(0, SeekOrigin.Begin); for(int i = 0; i < ms2.Length; i++) Console.WriteLine("{0}: {1}", i, ms2.ReadByte()); } } } } }
B C D E F G H I J K L M N O
The output is 0: 1: 2: 3: 4: 5: 6: 7: 8: 9:
P
0 1 2 3 4 5 6 7 8 9
Q R S T U V W X Y Z
2277
Contents | Index
System.Threading Monitor
BCL
Object
A
Monitor
B
Summary
C
Provides a mechanism that synchronizes access to objects.
D
Type Summary
E
public sealed class Monitor { // Methods public static void Enter (object obj); public static void Exit (object obj); CF public static void Pulse (object obj); CF public static void PulseAll (object obj); CF public static bool TryEnter (object obj); CF public static bool TryEnter (object obj, int millisecondsTimeout); CF public static bool TryEnter (object obj, TimeSpan timeout); CF public static bool Wait (object obj); CF public static bool Wait (object obj, int millisecondsTimeout); MS CF public static bool Wait (object obj, int millisecondsTimeout, bool exitContext); CF public static bool Wait (object obj, TimeSpan timeout); MS CF public static bool Wait (object obj, TimeSpan timeout, bool exitContext); }
F G H I J K L M N O P Q R
BG I believe the vast majority of managed code developers don’t need to know this class exists. In just about all cases where I’ve needed synchronization, I use the C# lock keyword (which of course uses Monitor.Enter and Exit), subclasses of WaitHandle like ManualResetEvent, then interlocked operations, in that order of frequency. While the Monitor class probably is useful in some contexts, it’s a little obscure to most users.
S T U V W
JR For Microsoft’s implementation of the CLI, thread synchronization using Monitor methods is not guaranteed to be fair. In other words, threads are not always synchronized in first-in/first-out order. For most applications, this is not a huge problem. It is more likely a problem for embedded applications or applications that control hardware. For these kinds of applications, managed code is a questionable direction to go anyway.
X Y Z
2278
Contents | Index
System.Threading
Monitor Monitor Class
Description The System.Threading.Monitor class controls access to objects by granting a single thread a lock for an object. Object locks provide the ability to restrict access to a block of code, commonly called a critical section. While a thread owns the lock for an object no other thread can acquire the lock for the object. Additionally, the System.Threading.Monitor class can be used to ensure that no other thread may access a section of application code being executed by the lock owner, unless the other thread is executing the code using a different locked object. The following information is maintained for each synchronized object: • • •
A B C D E F
A reference to the thread that currently holds the lock. A reference to a “ready queue,” which contains the threads that are ready to obtain the lock. A reference to a “waiting queue,” which contains the threads that are waiting for notification of a change in the state of the locked object.
G H I J
The following table describes the actions taken by threads that access synchronized objects:
K L
Action
Description
M N
enter
Acquires a lock for an object. Also marks the beginning of a critical section. No other thread can enter the critical section unless they are executing the instructions in the critical section using a different locked object. [Note: See the System.Threading.Monitor.Enter and System.Threading.Monitor.TryEnter methods.]
O P Q
wait
Releases the lock on an object in order to permit other threads to lock and access the object. The calling thread waits while another thread accesses the object. Pulse signals (see below) are used to notify waiting threads about changes to an object’s state. [Note: See System.Threading.Monitor.Wait.]
R S T
pulse (signal)
exit
Sends a signal to one or more waiting threads. The signal notifies a waiting thread that the state of the locked object has changed, and the owner of the lock is ready to release the lock. The waiting thread is placed in the object’s ready queue so that it may eventually receive the lock for the object. Once the thread has the lock, it can check the new state of the object to see if the required state has been reached. [Note: See System.Threading.Monitor.Pulse and System.Threading.Monitor.PulseAll.]
U V W X Y
Releases the lock on an object. Also marks the end of a critical section protected by the locked object. [Note: See System.Threading.Monitor.Exit.]
Z
2279
Contents | Index
Monitor
System.Threading
Monitor Class
The System.Threading.Monitor.Enter and System.Threading.Monitor.Exit methods are used to mark the beginning and end of a critical section. If the critical section is a set of contiguous instructions, then the lock acquired by the System.Threading.Monitor.Enter method guarantees that only a single thread can execute the enclosed code with the locked object. This facility is typically used to synchronize access to a static or instance method of a class. If an instance method requires synchronized thread access, the instance method invokes the System.Threading.Monitor.Enter and corresponding System.Threading.Monitor.Exit methods using itself (the current instance) as the object to lock. Since only one thread can hold the lock on the current instance, the method can only be executed by one thread at a time. Static methods are protected in a similar fashion using the System.Type object of the current instance as the locked object. [Note: The functionality provided by the System.Threading.Monitor.Enter and System.Threading.Monitor.Exit methods is identical to that provided by the C# lock statement. If a critical section spans an entire method, the locking facility described above can be achieved by placing the System.Runtime.CompilerServices.MethodImplAttribute on the method, and specifying the System.Runtime.CompilerServices.MethodImplOptions.Synchronized option. Using this attribute, the System.Threading.Monitor.Enter and System.Threading.Monitor.Exit statements are not needed. Note that the attribute causes the current thread to hold the lock until the method returns; if the lock can be released sooner, use the System.Threading.Monitor class (or C# lock statement) instead of the attribute. While it is possible for the System.Threading.Monitor.Enter and System.Threading.Monitor.Exit statements that lock and release a given object to cross member and/or class boundaries, this practice is strongly discouraged.]
A B C D E F G H I J K L M N O P Q
Example
R
using System; using System.Threading; using System.Collections;
S T
namespace Samples { public class MonitorSample { private static Hashtable ht = new Hashtable(); public static void Add(object key, object value) { Monitor.Enter(ht); ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); } public static bool AddNoWait(object key, object value)
U V W X Y Z
2280
Contents | Index
System.Threading
Monitor Monitor Class
{ if(Monitor.TryEnter(ht)) { ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); return true; } return false;
A B C D
} public static bool AddWithWaitTime(object key, object value, int waitTime) { if(Monitor.TryEnter(ht, waitTime)) { ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); return true; } return true; } public static void Display() { Monitor.Enter(ht); IDictionaryEnumerator ide = ht.GetEnumerator(); while(ide.MoveNext()) Console.WriteLine("Key: {0}, Value: {1}", ide.Key, ide.Value); Monitor.Exit(ht); } public static void StartHere(Object o) { int i = (int) o; Add(i, "Add"); i += 10; Console.WriteLine( "AddNoWait for thread {0} succeeded: {1}", o, AddNoWait(i, "AddNoWait")); i += 10; Console.WriteLine( "AddNoWait for thread {0} succeeded: {1}", o, AddNoWait(i, "AddNoWait")); i += 10; Console.WriteLine( "AddWithWaitTime for thread {0} succeeded: {1}", o, AddWithWaitTime(i, "AddWithWaitTime", 100)); if(Interlocked.Decrement(ref threads) == 0)
E F G H I J K L M N O P Q R S T U V W X Y Z
2281
Contents | Index
Monitor
System.Threading
Monitor Class
{ Monitor.Enter(ht); Monitor.Pulse(ht); Monitor.Exit(ht);
A
} } static int threads = 5; public static void Main() { Monitor.Enter(ht); for(int i = 0; i < threads; i++) { ThreadPool.QueueUserWorkItem( new WaitCallback(StartHere), i); } Monitor.Wait(ht); Monitor.Exit(ht); Display(); }
B C D E F G H I J
} }
K L
The output is
M
AddNoWait for thread 0 succeeded: False AddNoWait for thread 0 succeeded: False AddWithWaitTime for thread 0 succeeded: AddNoWait for thread 1 succeeded: False AddNoWait for thread 1 succeeded: False AddWithWaitTime for thread 1 succeeded: AddNoWait for thread 2 succeeded: False AddNoWait for thread 2 succeeded: False AddWithWaitTime for thread 2 succeeded: AddNoWait for thread 3 succeeded: False AddNoWait for thread 3 succeeded: False AddWithWaitTime for thread 3 succeeded: AddNoWait for thread 4 succeeded: True AddNoWait for thread 4 succeeded: True AddWithWaitTime for thread 4 succeeded: Key: 14, Value: AddNoWait Key: 34, Value: AddWithWaitTime Key: 33, Value: AddWithWaitTime Key: 32, Value: AddWithWaitTime Key: 31, Value: AddWithWaitTime Key: 24, Value: AddNoWait Key: 4, Value: Add Key: 3, Value: Add Key: 2, Value: Add Key: 1, Value: Add Key: 0, Value: Add
N O P Q R S T U V W X Y Z
True
True
True
True
True
2282
Contents | Index
System.Threading
Monitor Enter() Method
Monitor.Enter(System.Object) Method [ILASM]
.method public hidebysig static void Enter(object obj) [C#]
A
public static void Enter(object obj)
B C
Summary
D
Acquires an exclusive lock on the specified object.
E
Parameters
F G
Parameter
Description
obj
The System.Object on which to acquire the lock.
H I J
Description
K
This method acquires an exclusive lock on obj. A caller of this method is required to invoke System.Threading.Monitor.Exit once for each System.Threading.Monitor.Enter invoked. The caller of this method is blocked if another thread has obtained the lock by calling System.Threading.Monitor.Enter and specifying the same object. The caller is not blocked if the current thread holds the lock. The same thread can invoke System.Threading.Monitor.Enter more than once (and it will not block); however, an equal number of System.Threading.Monitor.Exit calls are required to be invoked before other threads waiting on the object will unblock. [Note: Invoking this member is identical to using the C# lock statement.]
L M N O P Q R S
Exceptions Exception
T U
Condition
V System.ArgumentNullException
obj is null.
W X Y Z
2283
Contents | Index
Monitor
System.Threading
Enter() Method
Example using System; using System.Threading; using System.Collections;
A B
namespace Samples { public class MonitorEnter { private static Hashtable ht = new Hashtable(); public static void Add(object key, object value) { Monitor.Enter(ht); ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); } public static void Display() { Monitor.Enter(ht); IDictionaryEnumerator ide = ht.GetEnumerator(); while(ide.MoveNext()) Console.WriteLine("Key: {0}, Value: {1}", ide.Key, ide.Value); Monitor.Exit(ht); } public static void StartHere(Object o) { Add(o, "Add"); if(Interlocked.Decrement(ref threads) == 0) threadsDone.Set(); } static int threads = 5; static AutoResetEvent threadsDone = new AutoResetEvent(false); public static void Main() { for(int i = 0; i < threads; i++) ThreadPool.QueueUserWorkItem( new WaitCallback(StartHere), i); threadsDone.WaitOne(); Display(); } } }
C D E F G H I J K L M N O P Q R S T U V W X Y Z
2284
Contents | Index
System.Threading
Monitor Exit() Method
The output is Key: Key: Key: Key: Key:
4, 3, 2, 1, 0,
Value: Value: Value: Value: Value:
Add Add Add Add Add
A B C D
Monitor.Exit(System.Object) Method
E
[ILASM]
F
.method public hidebysig static void Exit(object obj)
G
[C#]
public static void Exit(object obj)
H
Summary
I
Releases an exclusive lock on the specified System.Object.
J K
Parameters
L
Parameter
Description
obj
The System.Object on which to release the lock.
M N O P
Description
Q
This method releases an exclusive lock on obj. The caller is required to own the lock on obj. If the caller owns the lock on the specified object, and has made an equal number of System.Threading.Monitor.Exit and System.Threading.Monitor.Enter calls for the object, then the lock is released. If the caller has not invoked System.Threading.Monitor.Exit as many times as System.Threading.Monitor.Enter, the lock is not released. [Note: If the lock is released and there are other threads in the ready queue for the object, one of the threads will acquire the lock. If there are other threads in the waiting queue waiting to acquire the lock, they are not automatically moved to the ready queue when the owner of the lock calls System.Threading.Monitor.Exit. To move one or more waiting threads into the ready queue, call System.Threading.Monitor.Pulse or System.Threading.Monitor.PulseAll prior to invoking System.Threading.Monitor.Exit.]
R S T U V W X Y Z
2285
Contents | Index
Monitor
System.Threading
Exit() Method
Exceptions Exception
Condition
B
System.ArgumentNullException
obj is null.
C
System.Threading.SynchronizationLockException
The current thread does not own the lock for the specified object.
A
D E
Example
F
using System; using System.Threading; using System.Collections;
G H I
namespace Samples { public class MonitorExit { private static Hashtable ht = new Hashtable(); public static void Add(object key, object value) { Monitor.Enter(ht); ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); } public static void Display() { Monitor.Enter(ht); IDictionaryEnumerator ide = ht.GetEnumerator(); while(ide.MoveNext()) Console.WriteLine("Key: {0}, Value: {1}", ide.Key, ide.Value); Monitor.Exit(ht); } public static void StartHere(Object o) { Add(o, "Add"); if(Interlocked.Decrement(ref threads) == 0) threadsDone.Set(); } static int threads = 5; static AutoResetEvent threadsDone = new AutoResetEvent(false);
J K L M N O P Q R S T U V W X Y Z
2286
Contents | Index
System.Threading
Monitor Pulse() Method
public static void Main() { for(int i = 0; i < threads; i++) ThreadPool.QueueUserWorkItem( new WaitCallback(StartHere), i); threadsDone.WaitOne(); Display(); }
A B C D
} }
E F
The output is Key: Key: Key: Key: Key:
4, 3, 2, 1, 0,
Value: Value: Value: Value: Value:
G
Add Add Add Add Add
H I J K
Monitor.Pulse(System.Object) Method
L
[ILASM]
M
.method public hidebysig static void Pulse(object obj) [C#]
N
public static void Pulse(object obj)
O P
Summary
Q
Notifies the next waiting thread (if any) of a change in the specified locked object’s state.
R
Parameters
S
Parameter
Description
obj
The System.Object a thread may be waiting for.
T U V W
Description
X
The thread that currently owns the lock on the specified object invokes this method to signal the next thread in line for the lock (in the queue of threads waiting to acquire the lock on the object). Upon receiving the pulse, the waiting thread is moved to the ready queue. When the thread that invoked Pulse releases the lock, the next thread in the ready queue (which is not necessarily the thread that was pulsed) acquires the lock.
Y Z
2287
Contents | Index
Monitor
System.Threading
Pulse() Method
[Note: To signal a waiting object using Pulse, you must be the current owner of the lock. To signal multiple threads, use the System.Threading.Monitor.PulseAll method.] A
Exceptions
B C
Exception
Condition
E
System.ArgumentNullException
obj is null.
F
System.Threading.SynchronizationLockException
The calling thread does not own the lock for the specified object.
D
G H I
Example
J
using System; using System.Threading; using System.Collections;
K L
namespace Samples { public class MonitorPulse { private static Hashtable ht = new Hashtable(); public static void Add(object key, object value) { Monitor.Enter(ht); ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); } public static void Display() { Monitor.Enter(ht); IDictionaryEnumerator ide = ht.GetEnumerator(); while(ide.MoveNext()) Console.WriteLine("Key: {0}, Value: {1}", ide.Key, ide.Value); Monitor.Exit(ht); } public static void StartHere(Object o) { Add(o, "Add"); if(Interlocked.Decrement(ref threads) == 0)
M N O P Q R S T U V W X Y Z
2288
Contents | Index
System.Threading
Monitor PulseAll() Method
{ Monitor.Enter(ht); Monitor.Pulse(ht); Monitor.Exit(ht);
A
} } static int threads = 5; public static void Main() { Monitor.Enter(ht); for(int i = 0; i < threads; i++) { ThreadPool.QueueUserWorkItem( new WaitCallback(StartHere), i); } Monitor.Wait(ht); Monitor.Exit(ht); Display(); }
B C D E F G H I J K
} }
L
The output is Key: Key: Key: Key: Key:
4, 3, 2, 1, 0,
Value: Value: Value: Value: Value:
M N
Add Add Add Add Add
O P Q R
Monitor.PulseAll(System.Object) Method
S
[ILASM]
T
.method public hidebysig static void PulseAll(object obj)
U
[C#]
public static void PulseAll(object obj)
V W
Summary
X
Notifies all waiting threads (if any) of a change in the specified locked object’s state.
Y Z
2289
Contents | Index
Monitor
System.Threading
PulseAll() Method
Parameters Parameter
Description
obj
The System.Object that one or more threads may be waiting for.
A B C
Description
D
The thread that currently owns the lock on the specified object invokes this method to signal all threads waiting to acquire the lock on the object. After the signal is sent, the waiting threads are moved to the ready queue. When the thread that invoked PulseAll releases the lock, the next thread in the ready queue acquires the lock. [Note: To signal waiting objects using PulseAll, you must be the current owner of the lock. To signal a single thread, use the System.Threading.Monitor.Pulse method.]
E F G H I
Exceptions
J K
Exception
Condition
M
System.ArgumentNullException
obj is null.
N
System.Threading.SynchronizationLockException
The calling thread does not own the lock for the specified object.
L
O P
Example
Q
using System; using System.Threading; using System.Collections;
R S T
namespace Samples { public class MonitorPulseAll { private static Hashtable ht = new Hashtable(); public static void Add(object key, object value) { Monitor.Enter(ht); ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); } public static void Display()
U V W X Y Z
2290
Contents | Index
System.Threading
Monitor PulseAll() Method
{ Monitor.Enter(ht); IDictionaryEnumerator ide = ht.GetEnumerator(); while(ide.MoveNext()) Console.WriteLine("Key: {0}, Value: {1}", ide.Key, ide.Value); Monitor.Exit(ht);
A B C
} public static void StartHere(Object o) { Add(o, "Add"); if(Interlocked.Decrement(ref threads) == 0) { Monitor.Enter(ht); Monitor.PulseAll(ht); Monitor.Exit(ht); } else { Monitor.Enter(ht); Monitor.Wait(ht); Monitor.Exit(ht); } Console.WriteLine("Done"); } static int threads = 5; public static void Main() { Monitor.Enter(ht); for(int i = 0; i < threads; i++) { ThreadPool.QueueUserWorkItem( new WaitCallback(StartHere), i); } Monitor.Wait(ht); Monitor.Exit(ht); Display(); }
D E F G H I J K L M N O P Q R S T U V W
} }
X Y Z
2291
Contents | Index
Monitor
System.Threading
TryEnter() Method
The output is Done Done Key: Key: Key: Key: Key: Done Done Done
A B C D E F
4, 3, 2, 1, 0,
Value: Value: Value: Value: Value:
Add Add Add Add Add
G H
Monitor.TryEnter(System.Object) Method
I
[ILASM]
.method public hidebysig static bool TryEnter(object obj)
J
[C#]
public static bool TryEnter(object obj)
K L
Summary
M
Attempts to acquire an exclusive lock on the specified object.
N
Parameters
O P
Parameter
Description
obj
The System.Object on which to acquire the lock.
Q R S T
Return Value
U
true if the current thread acquired the lock; otherwise, false.
V
Description
W
If successful, this method acquires an exclusive lock on obj. This method returns immediately, whether or not the lock is available. This method is equivalent to System.Threading.Monitor.TryEnter(obj, 0).
X Y Z
2292
Contents | Index
System.Threading
Monitor TryEnter() Method
Exceptions Exception
Condition
System.ArgumentNullException
obj is null.
A B C
Example
D
using System; using System.Threading; using System.Collections;
E F G
namespace Samples { public class MonitorTryEnter { private static Hashtable ht = new Hashtable(); public static bool AddNoWait(object key, object value) { if(Monitor.TryEnter(ht)) { ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); return true; } return false; } public static void Display() { Monitor.Enter(ht); IDictionaryEnumerator ide = ht.GetEnumerator(); while(ide.MoveNext()) Console.WriteLine("Key: {0}, Value: {1}", ide.Key, ide.Value); Monitor.Exit(ht); } public static void StartHere(Object o) { int i = (int) o; Console.WriteLine( "AddNoWait for thread {0} succeeded: {1}", o, AddNoWait(o, "AddNoWait")); if(Interlocked.Decrement(ref threads) == 0) threadsDone.Set();
H I J K L M N O P Q R S T U V W X Y Z
2293
Contents | Index
Monitor
System.Threading
TryEnter() Method
} static int threads = 5; static AutoResetEvent threadsDone = new AutoResetEvent(false); public static void Main() { for(int i = 0; i < threads; i++) { ThreadPool.QueueUserWorkItem( new WaitCallback(StartHere), i); } threadsDone.WaitOne(); Display(); }
A B C D E F G H
} }
I
The output is
J K
AddNoWait for thread 1 succeeded: AddNoWait for thread 2 succeeded: AddNoWait for thread 3 succeeded: AddNoWait for thread 4 succeeded: AddNoWait for thread 0 succeeded: Key: 0, Value: AddNoWait
L M N
False False False False True
O P
Monitor.TryEnter(System.Object, System.Int32) Method
Q [ILASM]
R
.method public hidebysig static bool TryEnter(object obj, int32 millisecondsTimeout)
S
[C#]
T
public static bool TryEnter(object obj, int millisecondsTimeout)
U
Summary
V
Attempts, for the specified number of milliseconds, to acquire an exclusive lock on the specified object.
W X Y Z
2294
Contents | Index
System.Threading
Monitor TryEnter() Method
Parameters Parameter
Description
obj
The System.Object on which to acquire the lock.
millisecondsTimeout
A System.Int32 containing the maximum number of milliseconds to wait for the lock.
A B C D E
Return Value
F
true if the current thread acquired the lock; otherwise, false.
G
Description
H
If successful, this method acquires an exclusive lock on obj. If millisecondsTimeout equals System.Threading.Timeout.Infinite, this method is equivalent to System.Threading.Monitor.Enter(obj). If millisecondsTimeout equals zero, this method is equivalent to System.Threading.Monitor.TryEnter(obj).
I J K L
Exceptions
M
Exception
Condition
System.ArgumentNullException
obj is null.
System.ArgumentOutOfRangeException
millisecondsTimeout is negative, and not equal to System.Threading.Timeout.Infinite.
N O P Q R S
Example
T
using System; using System.Threading; using System.Collections;
U V
namespace Samples { public class MonitorTryEnter { private static Hashtable ht = new Hashtable(); public static bool AddNoWait(object key, object value) { if(Monitor.TryEnter(ht, 1000))
W X Y Z
2295
Contents | Index
Monitor
System.Threading
TryEnter() Method
{ ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); return true;
A
} return false;
B C
} public static void Display() { Monitor.Enter(ht); IDictionaryEnumerator ide = ht.GetEnumerator(); while(ide.MoveNext()) Console.WriteLine("Key: {0}, Value: {1}", ide.Key, ide.Value); Monitor.Exit(ht); } public static void StartHere(Object o) { int i = (int) o; Console.WriteLine( "AddNoWait for thread {0} succeeded: {1}", o, AddNoWait(o, "AddNoWait")); if(Interlocked.Decrement(ref threads) == 0) threadsDone.Set(); } static int threads = 5; static AutoResetEvent threadsDone = new AutoResetEvent(false); public static void Main() { for(int i = 0; i < threads; i++) { ThreadPool.QueueUserWorkItem( new WaitCallback(StartHere), i); } threadsDone.WaitOne(); Display(); }
D E F G H I J K L M N O P Q R S T U V W }
X }
Y Z
2296
Contents | Index
System.Threading
Monitor TryEnter() Method
The output is AddNoWait for thread 0 succeeded: AddNoWait for thread 1 succeeded: AddNoWait for thread 3 succeeded: AddNoWait for thread 4 succeeded: AddNoWait for thread 2 succeeded: Key: 2, Value: AddNoWait Key: 1, Value: AddNoWait Key: 0, Value: AddNoWait
True True False False True
A B C D E F
Monitor.TryEnter(System.Object, System.TimeSpan) Method
G
[ILASM]
H
.method public hidebysig static bool TryEnter(object obj, valuetype System.TimeSpan timeout)
I
[C#]
J
public static bool TryEnter(object obj, TimeSpan timeout)
K
Summary
L
Attempts, for the specified amount of time, to acquire an exclusive lock on the specified object.
M N
Parameters
O P
Parameter
Description
obj
The System.Object on which to acquire the lock.
R
timeout
A System.TimeSpan set to the maximum amount of time to wait for the lock.
S
Q
T
Return Value
U
true if the current thread acquires the lock; otherwise, false.
V W
Description
X
If successful, this method acquires an exclusive lock on obj. If the value of timeout converted to milliseconds equals System.Threading.Timeout.Infinite, this method is equivalent to System.Threading.Monitor.Enter(obj). If the value of timeout equals zero, this method is equivalent to System.Threading.Monitor.TryEnter(obj).
Y Z
2297
Contents | Index
Monitor
System.Threading
TryEnter() Method
Exceptions Exception
Condition
System.ArgumentNullException
obj is null.
System.ArgumentOutOfRangeException
The value of timeout in milliseconds is negative and is not equal to System.Threading.Timeout.Infinite, or is greater than System.Int32.MaxValue.
A B C D E F
Example
G
using System; using System.Threading; using System.Collections;
H I
namespace Samples { public class MonitorTryEnter { private static Hashtable ht = new Hashtable(); public static bool AddNoWait(object key, object value) { if(Monitor.TryEnter(ht, new TimeSpan(10000000))) { ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); return true; } return false; } public static void Display() { Monitor.Enter(ht); IDictionaryEnumerator ide = ht.GetEnumerator(); while(ide.MoveNext()) Console.WriteLine("Key: {0}, Value: {1}", ide.Key, ide.Value); Monitor.Exit(ht); } public static void StartHere(Object o) { int i = (int) o; Console.WriteLine(
J K L M N O P Q R S T U V W X Y Z
2298
Contents | Index
System.Threading
Monitor Wait() Method
"AddNoWait for thread {0} succeeded: {1}", o, AddNoWait(o, "AddNoWait")); if(Interlocked.Decrement(ref threads) == 0) threadsDone.Set();
A
} static int threads = 5; static AutoResetEvent threadsDone = new AutoResetEvent(false); public static void Main() { for(int i = 0; i < threads; i++) { ThreadPool.QueueUserWorkItem( new WaitCallback(StartHere), i); } threadsDone.WaitOne(); Display(); }
B C D E F G H I J
}
K
}
L
The output is
M AddNoWait for thread 0 succeeded: AddNoWait for thread 2 succeeded: AddNoWait for thread 1 succeeded: AddNoWait for thread 4 succeeded: AddNoWait for thread 3 succeeded: Key: 3, Value: AddNoWait Key: 1, Value: AddNoWait Key: 0, Value: AddNoWait
True False True False True
N O P Q R S
Monitor.Wait(System.Object) Method
T
[ILASM]
U
.method public hidebysig static bool Wait(object obj)
V
[C#]
W
public static bool Wait(object obj)
X
Summary
Y
Releases the lock on an object and blocks the current thread until it reacquires the lock.
Z
2299
Contents | Index
Monitor
System.Threading
Wait() Method
Parameters Parameter
Description
obj
The System.Object on which to wait.
A B C D
Return Value
E
true if the call returned because the caller reacquired the lock for the specified object. This method does not return if the lock is not reacquired.
F G
Description
H
This method reacquires an exclusive lock on obj. The thread that currently owns the lock on the specified object invokes this method in order to release the object so that another thread can access it. The caller is blocked while waiting to reacquire the lock. This method is called when the caller is waiting for a change in the state of the object, which occurs as a result of another thread’s operations on the object. When a thread calls Wait, it releases the lock on the object and enters the object’s waiting queue. The next thread in the object’s ready queue (if there is one) acquires the lock and has exclusive use of the object. All threads that call Wait remain in the waiting queue until they receive a signal via System.Threading.Monitor.Pulse or System.Threading.Monitor.PulseAll sent by the owner of the lock. If Pulse is sent, only the thread at the head of the waiting queue is affected. If PulseAll is sent, all threads that are waiting for the object are affected. When the signal is received, one or more threads leave the waiting queue and enter the ready queue. A thread in the ready queue is permitted to reacquire the lock. This method returns when the calling thread reacquires the lock on the object. Note that this method blocks indefinitely if the holder of the lock does not call System.Threading.Monitor.Pulse or System.Threading.Monitor.PulseAll. The caller executes System.Threading.Monitor.Wait once, regardless of the number of times System.Threading.Monitor.Enter has been invoked for the specified object. Conceptually, the System.Threading.Monitor.Wait method stores the number of times the caller invoked System.Threading.Monitor.Enter on the object and invokes System.Threading.Monitor.Exit as many times as necessary to fully release the locked object. The caller then blocks while waiting to reacquire the object. When the caller reacquires the lock, the system calls System.Threading.Monitor.Enter as many times as necessary to restore the saved Enter count for the caller. Calling System.Threading.Monitor.Wait releases the lock for the specified object only; if the caller is the owner of locks on other objects, these locks are not released.
I J K L M N O P Q R S T U V W X Y Z
2300
Contents | Index
System.Threading
Monitor Wait() Method
Exceptions Exception
Condition
System.ArgumentNullException
obj is null.
System.Threading.SynchronizationLockException
The calling thread does not own the lock for the specified object.
A B C D E
Example
F
using System; using System.Threading; using System.Collections;
G H
namespace Samples { public class MonitorWait { private static Hashtable ht = new Hashtable(); public static void Add(object key, object value) { Monitor.Enter(ht); ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); } public static bool AddNoWait(object key, object value) { if(Monitor.TryEnter(ht)) { ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); return true; } return false; } public static bool AddWithWaitTime(object key, object value, int waitTime) { if(Monitor.TryEnter(ht, waitTime)) { ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); return true; }
I J K L M N O P Q R S T U V W X Y Z
2301
Contents | Index
Monitor
System.Threading
Wait() Method
return true; } public static void Display() { Monitor.Enter(ht); IDictionaryEnumerator ide = ht.GetEnumerator(); while(ide.MoveNext()) Console.WriteLine("Key: {0}, Value: {1}", ide.Key, ide.Value); Monitor.Exit(ht); } public static void StartHere(Object o) { int i = (int) o; Add(i, "Add"); i += 10; Console.WriteLine( "AddNoWait for thread {0} succeeded: {1}", o, AddNoWait(i, "AddNoWait")); i += 10; Console.WriteLine( "AddNoWait for thread {0} succeeded: {1}", o, AddNoWait(i, "AddNoWait")); i += 10; Console.WriteLine( "AddWithWaitTime for thread {0} succeeded: {1}", o, AddWithWaitTime(i, "AddWithWaitTime", 100)); if(Interlocked.Decrement(ref threads) == 0) { Monitor.Enter(ht); Monitor.Pulse(ht); Monitor.Exit(ht); } } static int threads = 5; public static void Main() { Monitor.Enter(ht); for(int i = 0; i < threads; i++) { ThreadPool.QueueUserWorkItem( new WaitCallback(StartHere), i); } Monitor.Wait(ht); Monitor.Exit(ht); Display(); }
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z } }
2302
Contents | Index
System.Threading
Monitor Wait() Method
The output is AddNoWait for thread 0 succeeded: False AddNoWait for thread 0 succeeded: False AddWithWaitTime for thread 0 succeeded: True AddNoWait for thread 1 succeeded: False AddNoWait for thread 1 succeeded: False AddWithWaitTime for thread 1 succeeded: True
A B C D E
Monitor.Wait(System.Object, System.Int32) Method
F [ILASM]
.method public hidebysig static bool Wait(object obj, int32 millisecondsTimeout)
G
[C#]
H
public static bool Wait(object obj, int millisecondsTimeout)
I
Summary
J
Releases the lock on an object and blocks the current thread until it reacquires the lock or until a specified amount of time elapses.
K L M
Parameters
N
Parameter
Description
obj
The System.Object on which to wait.
P
A System.Int32 containing the maximum number of milliseconds to wait before this method returns.
Q
millisecondsTimeout
O
R S
Return Value
T
true if the lock was reacquired before the specified time elapsed; otherwise, false.
U V
Description
W
If successful, this method reacquires an exclusive lock on obj. This method behaves identically to System.Threading.Monitor.Wait(obj), except that it does not block indefinitely unless System.Threading.Timeout.Infinite is specified for millisecondsTimeout. Once the specified time has elapsed, this method returns a value that indicates whether the lock has been reacquired by the caller. If millisecondsTimeout equals 0, this method returns immediately.
X Y Z
2303
Contents | Index
Monitor
System.Threading
Wait() Method
[Note: This method is called when the caller is waiting for a change in the state of the object, which occurs as a result of another thread’s operations on the object. For additional details, see System.Threading.Monitor.Wait(obj).] A
Exceptions
B C
Exception
Condition
E
System.ArgumentNullException
obj is null.
F
System.Threading.SynchronizationLockException
The calling thread does not own the lock for the specified object.
System.ArgumentOutOfRangeException
The value of millisecondsTimeout is negative, and not equal to System.Threading.Timeout.Infinite.
D
G H I J K
Example
L
using System; using System.Threading; using System.Collections;
M N
namespace Samples { public class MonitorWait { private static Hashtable ht = new Hashtable(); public static void Add(object key, object value) { Monitor.Enter(ht); ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); } public static bool AddNoWait(object key, object value) { if(Monitor.TryEnter(ht)) { ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); return true; } return false; }
O P Q R S T U V W X Y Z
2304
Contents | Index
System.Threading
Monitor Wait() Method
public static bool AddWithWaitTime(object key, object value, int waitTime) { if(Monitor.TryEnter(ht, waitTime)) { ht.Add(key, value); Thread.Sleep(1000); Monitor.Exit(ht); return true; } return true; } public static void Display() { Monitor.Enter(ht); IDictionaryEnumerator ide = ht.GetEnumerator(); while(ide.MoveNext()) Console.WriteLine("Key: {0}, Value: {1}", ide.Key, ide.Value); Monitor.Exit(ht); } public static void StartHere(Object o) { int i = (int) o; Add(i, "Add"); i += 10; Console.WriteLine( "AddNoWait for thread {0} succeeded: {1}", o, AddNoWait(i, "AddNoWait")); i += 10; Console.WriteLine( "AddNoWait for thread {0} succeeded: {1}", o, AddNoWait(i, "AddNoWait")); i += 10; Console.WriteLine( "AddWithWaitTime for thread {0} succeeded: {1}", o, AddWithWaitTime(i, "AddWithWaitTime", 100)); if(Interlocked.Decrement(ref threads) == 0) { Monitor.Enter(ht); Monitor.Pulse(ht); Monitor.Exit(ht); } } static int threads = 5; public static void Main() {
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
2305
Contents | Index
Monitor
System.Threading
Wait() Method
Monitor.Enter(ht); for(int i = 0; i < threads; i++) { ThreadPool.QueueUserWorkItem( new WaitCallback(StartHere), i); } Monitor.Wait(ht, 2000); Console.WriteLine("First Display"); Display(); Monitor.Wait(ht); Monitor.Exit(ht); Console.WriteLine("Second Display"); Display();
A B C D E F G
} }
H
}
I
The output is
J K
AddNoWait for thread 0 succeeded: False AddNoWait for thread 0 succeeded: False AddWithWaitTime for thread 0 succeeded: AddNoWait for thread 1 succeeded: False AddNoWait for thread 1 succeeded: False AddWithWaitTime for thread 1 succeeded: AddNoWait for thread 2 succeeded: False AddNoWait for thread 2 succeeded: False AddWithWaitTime for thread 2 succeeded: AddNoWait for thread 4 succeeded: False AddNoWait for thread 4 succeeded: False First Display Key: 4, Value: Add Key: 2, Value: Add Key: 1, Value: Add Key: 0, Value: Add AddWithWaitTime for thread 4 succeeded: AddNoWait for thread 3 succeeded: True AddNoWait for thread 3 succeeded: True AddWithWaitTime for thread 3 succeeded: Second Display Key: 13, Value: AddNoWait Key: 33, Value: AddWithWaitTime Key: 23, Value: AddNoWait Key: 4, Value: Add Key: 3, Value: Add Key: 2, Value: Add Key: 1, Value: Add Key: 0, Value: Add
L M N O P Q R S T U V W X Y Z
True
True
True
True
True
2306
Contents | Index
System.Threading
Monitor Wait() Method
Monitor.Wait(System.Object, System.Int32, System.Boolean) Method [ILASM]
.method public hidebysig static bool Wait(object obj, int32 millisecondsTimeout, bool exitContext)
A
[C#]
B
public static bool Wait(object obj, int millisecondsTimeout, bool exitContext)
C
Summary
D
Waits for notification from an object that called the System.Threading.Monitor.Pulse or System.Threading.Monitor.PulseAll method or for a specified timer to elapse. This method also specifies whether the synchronization domain for the context (if in a synchronized context) is exited before the wait and reacquired.
E F G H
Parameters
I J
Parameter
Description
obj
The object on which to wait.
millisecondsTimeout
The number of milliseconds to wait before the method returns.
M
exitContext
true to exit and reacquire the synchronization domain for the context (if in a synchronized context) before the wait; otherwise, false.
N
K L
O P
Return Value
Q
true if the wait succeeded or did not time out; otherwise, false.
R
Description
S
This method acquires the monitor wait handle for the object. If this thread holds the monitor lock for the object, it releases it. On exit from the method, it reobtains the monitor lock. The thread that currently holds the lock on this object invokes this method in order to wait until a condition in the object’s state has been met. Shortly after the call to Wait, the thread that invoked Wait releases the lock and enters the waiting queue. At this point, the next thread in the ready queue (if there is one) is allowed to take control of the lock. The thread that invoked Wait remains in the waiting queue until either a thread that holds the lock invokes System.Threading.Monitor.PulseAll, or it is the next in the queue and a thread that holds the lock invokes System.Threading.Monitor.Pulse. However, if millisecondsTimeout elapses before another thread invokes this object’s System.Threading.Monitor.Pulse or System.Threading.Monitor.PulseAll
T U V W X Y Z
2307
Contents | Index
Monitor
System.Threading
Wait() Method
method, the original thread is moved to the ready queue in order to regain the lock. If the condition in the object’s state has not been met, the thread might call Wait again to reenter the waiting queue until it has been met. If milliseconds timeout equals 0, the thread that calls Wait releases the lock and then immediately enters the ready queue in order to regain the lock. Note that a synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object’s state. The System.Threading.Monitor.Pulse, System.Threading.Monitor.PulseAll, and Wait methods must be invoked from within a synchronized block of code.
A B C D E F G
Exceptions
H I
Exception
Condition
System.ArgumentNullException
The obj parameter is null.
System.Threading.SynchronizationLockException
Wait is not invoked from within a synchronized block of code.
System.Threading.ThreadInterruptedException
The thread that invokes Wait is later interrupted from the waiting state. This happens when another thread calls this thread’s System.Threading.Thread.Interrupt method.
J K L M N O P Q R
Monitor.Wait(System.Object, System.TimeSpan) Method
S
[ILASM]
T
.method public hidebysig static bool Wait(object obj, valuetype System.TimeSpan timeout)
U
[C#]
public static bool Wait(object obj, TimeSpan timeout)
V W
Summary
X
Releases the lock on an object and blocks the current thread until it reacquires the lock or until a specified amount of time elapses.
Y Z
2308
Contents | Index
System.Threading
Monitor Wait() Method
Parameters Parameter
Description
obj
The System.Object on which to wait.
timeout
A System.TimeSpan set to the maximum amount of time to wait before this method returns.
A B C D E
Return Value
F
true if the lock was reacquired before the specified time elapsed; otherwise, false.
G
Description
H
If successful, this method reacquires an exclusive lock on obj. This method behaves identically to System.Threading.Monitor.Wait(obj), except that it does not block indefinitely unless System.Threading.Timeout.Infinite milliseconds is specified for timeout. Once the specified time has elapsed, this method returns a value that indicates whether the lock has been reacquired by the caller. If timeout equals 0, this method returns immediately. [Note: This method is called when the caller is waiting for a change in the state of the object, which occurs as a result of another thread’s operations on the object. For additional details, see System.Threading.Monitor.Wait(obj).]
I J K L M N O P
Exceptions
Q
Exception
Condition
System.ArgumentNullException
obj is null.
System.Threading.SynchronizationLockException
The calling thread does not own the lock for the specified object.
System.ArgumentOutOfRangeException
If timeout is negative, and is not equal to System.Threading.Timeout.Infinite, or is greater than System.Int32.MaxValue.
R S T U V W X Y Z
2309
Contents | Index
Monitor
System.Threading
Wait() Method
Monitor.Wait(System.Object, System.TimeSpan, System.Boolean) Method [ILASM]
A
.method public hidebysig static bool Wait(object obj, valuetype System.TimeSpan timeout, bool exitContext)
B
[C#]
public static bool Wait(object obj, TimeSpan timeout, bool exitContext)
C D
Summary
E
Releases the lock on an object and blocks the current thread until it reacquires the lock, or until a specified amount of time elapses, optionally exiting the synchronization domain for the synchronized context before the wait and reacquiring the domain.
F G
Parameters
H I
Parameter
Description
obj
The object on which to wait.
timeout
A System.TimeSpan representing the amount of time to wait before this method returns.
exitContext
true to exit and reacquire the synchronization domain for the context (if in a synchronized context) before the wait; otherwise, false.
J K L M N O P
Return Value
Q
true if the wait succeeded or did not time out; otherwise, false.
R
Description
S
The thread that currently holds the lock on this object invokes this method in order to wait until a condition in the object’s state has been met. Shortly after the call to Wait, the thread that invoked Wait releases the lock and enters the waiting queue. At this point, the next thread in the ready queue (if there is one) is allowed to take control of the lock. The thread that invoked Wait remains in the waiting queue until either a thread that holds the lock invokes System.Threading.Monitor.PulseAll, or it is the next in the queue and a thread that holds the lock invokes System.Threading.Monitor.Pulse. However, if timeout milliseconds elapse before another thread invokes this object’s System.Threading.Monitor.Pulse or System.Threading.Monitor.PulseAll method, the original thread is moved to the ready queue in order to regain the lock. If the condition in the object’s state has not been met, the thread might call Wait again to reenter the waiting queue until it has been met.
T U V W X Y Z
2310
Contents | Index
System.Threading
Monitor Wait() Method
If timeout equals 0, the thread that calls Wait releases the lock and then immediately enters the ready queue in order to regain the lock. Note that a synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object’s state. The System.Threading.Monitor.Pulse, System.Threading.Monitor.PulseAll, and Wait methods must be invoked from within a synchronized block of code.
A B C D E
Exceptions
F G
Exception
Condition
System.ArgumentNullException
The obj parameter is null.
System.ArgumentException
The timeout parameter is negative or greater than System.Int32.MaxValue.
System.Threading.SynchronizationLockException
Wait is not invoked from within a synchronized block of code.
The thread that invokes Wait is later interrupted from the waiting state. This happens when another thread calls this thread’s System.Threading.Thread.Interrupt method.
M
System.Threading.ThreadInterruptedException
The timeout parameter is negative or greater than System.Int32.MaxValue.
P
H I
System.ArgumentOutOfRangeException
J K L
N O
Q R S T U V W X Y Z
2311
Contents | Index
System NotFiniteNumberException
Extended Numerics
Object ISerializable
Exception
NotStandardized
A
SystemException
B
ArithmeticException NotFiniteNumberException
C ExtendedNumerics
D E
Summary
F
Represents the error that occurs when an arithmetic operation cannot be performed on a floating-point value that is not a finite number.
G H
Type Summary
I
public class NotFiniteNumberException : ArithmeticException { // Constructors public NotFiniteNumberException (); CF public NotFiniteNumberException (double offendingNumber); public NotFiniteNumberException (string message); CF public NotFiniteNumberException (string message, double offendingNumber); CF public NotFiniteNumberException (string message, double offendingNumber, Exception innerException); MS CF protected NotFiniteNumberException (SerializationInfo info, StreamingContext context);
J K L M N O P Q
// Properties CF public double OffendingNumber { get; }
R S
// Methods MS CF public override void GetObjectData (SerializationInfo info, StreamingContext context); }
T U V
Description
W
This exception is thrown when an operand of an arithmetic operation is, and is not permitted to be, one of the following:
X Y
Positive infinity Negative infinity NaN (Not-a-Number)
Z
2313
Contents | Index
NotFiniteNumberException
System
NotFiniteNumberException() Constructor
[Note: Operations involving System.Double or System.Single operations throw this exception.] A
NotFiniteNumberException() Constructor
B C
[ILASM]
D
[C#]
public rtspecialname specialname instance void .ctor() public NotFiniteNumberException()
E F
Summary
G
Constructs and initializes a new instance of the System.NotFiniteNumberException class.
H I
Description
J
This constructor initializes the System.NotFiniteNumberException.Message property of the new instance to a system-supplied message that describes the error, such as “The number encountered was not a finite quantity.” This message takes into account the current system culture. This constructor initializes the System.NotFiniteNumberException.OffendingNumber property to zero. The System.NotFiniteNumberException.InnerException property is initialized to null.
K L M N O P
NotFiniteNumberException(System.Double) Constructor
Q [ILASM]
R
public rtspecialname specialname instance void .ctor(float64 offendingNumber) [C#]
S
public NotFiniteNumberException(double offendingNumber)
T
Summary
U
Constructs and initializes a new instance of the System.NotFiniteNumberException class.
V W
Parameters
X Y
Parameter
Description
offendingNumber
A System.Double that specifies the value of the argument that caused the Exception.
Z
2314
Contents | Index
System
NotFiniteNumberException NotFiniteNumberException() Constructor
Description This constructor initializes the System.NotFiniteNumberException.Message property of the new instance to a system-supplied message that describes the error, such as “The number encountered was not a finite quantity.” This message takes into account the current system culture. This constructor initializes the System.NotFiniteNumberException.OffendingNumber property using offendingNumber. The System.NotFiniteNumberException.InnerException property is initialized to null.
A B C D E F
NotFiniteNumberException(System.String) Constructor
G [ILASM]
H
public rtspecialname specialname instance void .ctor(string message) [C#]
I
public NotFiniteNumberException(string message)
J
Summary
K
Constructs and initializes a new instance of the System.NotFiniteNumberException class.
L M
Parameters
N O
Parameter
Description P
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
Q R S
Description
T
This constructor initializes the System.NotFiniteNumberException.Message property of the new instance using message, and initializes the System.NotFiniteNumberException.OffendingNumber property to zero. If message is null, the System.NotFiniteNumberException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.NotFiniteNumberException.InnerException property is initialized to null.
U V W X Y Z
2315
Contents | Index
NotFiniteNumberException
System
NotFiniteNumberException() Constructor
NotFiniteNumberException(System.String, System.Double) Constructor [ILASM]
A
public rtspecialname specialname instance void .ctor(string message, float64 offendingNumber)
B
[C#]
public NotFiniteNumberException(string message, double offendingNumber)
C D
Summary
E
Constructs a new instance of the System.NotFiniteNumberException class.
F
Parameters
G H
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
offendingNumber
A System.Double that specifies the value of the argument that caused the current exception.
I J K L M N O
Description
P
This constructor initializes the System.NotFiniteNumberException.Message property of the new instance using message and the OffendingNumber property using offendingNumber. If message is null, the System.NotFiniteNumberException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.NotFiniteNumberException.InnerException property is initialized to null.
Q R S T U V
NotFiniteNumberException(System.String, System.Double, System.Exception) Constructor
W X
[ILASM]
Y
public rtspecialname specialname instance void .ctor(string message, float64 offendingNumber, class System.Exception innerException)
Z
[C#]
public NotFiniteNumberException(string message, double offendingNumber, Exception innerException)
2316
Contents | Index
System
NotFiniteNumberException NotFiniteNumberException() Constructor
Summary Constructs and initializes a new instance of the System.NotFiniteNumberException class. A
Parameters
B C
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
offendingNumber
A System.Double that specifies the value of the argument that caused the current exception.
innerException
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
D E F G H I J K L
Description
M
This constructor initializes the System.NotFiniteNumberException.Message property of the new instance using message, the System.NotFiniteNumberException.OffendingNumber property using offendingNumber, and the System.NotFiniteNumberException.InnerException property using innerException. If message is null, the System.NotFiniteNumberException.Message property is initialized to the systemsupplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
N O P Q R S T
NotFiniteNumberException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
U
[ILASM]
V
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
W X
[C#]
Y
protected NotFiniteNumberException(SerializationInfo info, StreamingContext context)
Z
2317
Contents | Index
NotFiniteNumberException
System
OffendingNumber Property
Summary Initializes a new instance of the System.NotFiniteNumberException class with serialized data. A
Parameters
B C
Parameter
Description
E
info
The object that holds the serialized object data.
F
context
The contextual information about the source or destination.
D
G H
Description
I
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
J K L
NotFiniteNumberException.OffendingNumber Property
M
[ILASM]
.property float64 OffendingNumber { public hidebysig specialname instance float64 get_OffendingNumber() }
N O
[C#]
public double OffendingNumber { get; }
P Q
Summary
R
Gets the value of the argument that caused the current exception.
S
Property Value
T
A System.Double that contains the invalid value.
U V
Description
W
The System.NotFiniteNumberException.OffendingNumber property returns the same value as was passed into the constructor, or zero if no value was supplied.
X Y Z
2318
Contents | Index
System
NotFiniteNumberException GetObjectData() Method
NotFiniteNumberException.GetObjectData(System.Runtime.Serialization. SerializationInfo, System.Runtime.Serialization.StreamingContext) Method [ILASM]
A
.method public hidebysig virtual void GetObjectData(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
B C
[C#]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
D E
Summary
F
Sets the System.Runtime.Serialization.SerializationInfo object with the invalid number and additional exception information.
G H I
Parameters
J
Parameter
Description
info
The object that holds the serialized object data.
context
The contextual information about the source or destination.
K L M N O
Description
P
System.TypeLoadException.GetObjectData sets a System.Runtime.Serialization.SerializationInfo with all the exception object data targeted for serialization. During deserialization, the exception object is reconstituted from the System.Runtime.Serialization.SerializationInfo transmitted over the stream. For more information, see System.Runtime.Serialization.SerializationInfo.
Q R S T U
Exceptions
V
Exception
Condition
System.ArgumentNullException
The info object is null.
W X Y Z
2319
Contents | Index
System NotImplementedException
BCL
Object
A
Exception
B
ISerializable
NotStandardized
SystemException NotImplementedException
C D
Summary
E
Represents the error that occurs when a requested operation is not implemented for a given type.
F G
Type Summary
H
CF public class NotImplementedException : SystemException { // Constructors CF public NotImplementedException (); CF public NotImplementedException (string message); CF public NotImplementedException (string message, Exception innerException); MS CF protected NotImplementedException (SerializationInfo info, StreamingContext context); }
I J K L M N O
Description
P
[Note: A number of the types and constructs, specified elsewhere in this Standard, are not required of CLI implementations that conform only to the Kernel Profile. For example, the floating-point feature set consists of the floating-point data types System.Single and System.Double. If support for these is omitted from an implementation, any attempt to reference a signature that includes the floating-point data types results in an exception of type System.NotImplementedException.]
Q R S T U
Example
V
using System;
W namespace Samples { public class NotImplementedExceptionSample { public static void NotImplementedMethod(float f) { throw new NotImplementedException();
X Y Z
2320
Contents | Index
System
NotImplementedException NotImplementedException() Constructor
} public static void Main() { try { NotImplementedMethod(0); } catch(NotImplementedException e) { Console.WriteLine("Exception: {0}", e); } }
A B C D E F
} }
G
The output is
H I
Exception: System.NotImplementedException: The method or operation is not implemented. at Samples.NotImplementedExceptionSample.NotImplementedMethod(Single f) in C:\Books\BCL\Samples\System\NotImplementedException\NotImplementedException.cs:line 9 at Samples.NotImplementedExceptionSample.Main() in C:\Books\BCL\Samples\System\ NotImplementedException\NotImplementedException.cs:line 15
J K L M
NotImplementedException() Constructor
N
[ILASM]
O
public rtspecialname specialname instance void .ctor()
P
[C#]
public NotImplementedException()
Q R
Summary
S
Constructs and initializes a new instance of the System.NotImplementedException class.
T U
Description
V
This constructor initializes the System.NotImplementedException.Message property of the new instance to a system-supplied message that describes the error. This message takes into account the current system culture. The System.NotImplementedException.InnerException property is initialized to null.
W X Y Z
2321
Contents | Index
NotImplementedException
System
NotImplementedException() Constructor
NotImplementedException(System.String) Constructor [ILASM]
public rtspecialname specialname instance void .ctor(string message)
A
[C#]
public NotImplementedException(string message)
B C
Summary
D
Constructs and initializes a new instance of the System.NotImplementedException class.
E F
Parameters
G H
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
I J K L
Description
M
This constructor initializes the System.NotImplementedException.Message property of the new instance using message. If message is null, the System.NotImplementedException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.NotImplementedException.InnerException property is initialized to null.
N O P Q R S
NotImplementedException(System.String, System.Exception) Constructor
T
[ILASM]
U
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException) [C#]
V
public NotImplementedException(string message, Exception innerException)
W X
Summary
Y
Constructs and initializes a new instance of the System.NotImplementedException class.
Z
2322
Contents | Index
System
NotImplementedException NotImplementedException() Constructor
Parameters Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
A B C D E F
Description
G
This constructor initializes the System.NotImplementedException.Message property of the new instance using message, and the System.NotImplementedException.InnerException property using innerException. If message is null, the System.NotImplementedException.Message property is initialized to the systemsupplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
H I J K L M N
NotImplementedException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
O
[ILASM]
P
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
Q R
[C#]
S
protected NotImplementedException (SerializationInfo info, StreamingContext context);
T
Summary
U
Initializes a new instance of the NotImplementedException class with serialized data.
V
Parameters
W
Parameter
Description
info
The object that holds the serialized object data.
context
The contextual information about the source or destination.
X Y Z
2323
Contents | Index
System NotSupportedException
BCL
Object
A
Exception
B
ISerializable
NotStandardized
SystemException NotSupportedException
C D
Summary
E
Represents the error that occurs when an object cannot perform an operation.
F
Type Summary
G
public class NotSupportedException : SystemException { // Constructors public NotSupportedException (); public NotSupportedException (string message); public NotSupportedException (string message, Exception innerException); MS CF protected NotSupportedException (SerializationInfo info, StreamingContext context); }
H I J K L M N
Description
O
[Note: System.NotSupportedException is thrown when it is never possible for the object to perform the requested operation. A typical scenario is when a base class declares a method that derived classes are required to implement, and the method is invoked on the base class. When a method throws System.NotSupportedException this usually indicates that the derived classes must provide an implementation of the method, and callers must invoke the method on the derived class. For scenarios where it is sometimes possible for the object to perform the requested operation, and the object state determines whether the operation can be performed, see System.InvalidOperationException.]
P Q R S T U V
Example
W
using System; using System.IO;
X Y
namespace Samples { public class NotSupprotedExceptionSample { public static void Main()
Z
2324
Contents | Index
System
NotSupportedException NotSupportedException() Constructor
{ Byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; MemoryStream ms = new MemoryStream( bytes,0, bytes.Length, false, false); try { ms.WriteByte((Byte)0); } catch(NotSupportedException e) { Console.WriteLine("Exception: {0}", e); } finally { ms.Close(); }
A B C D E F G H I
} }
J
}
K
The output is
L M
Exception: System.NotSupportedException: Stream does not support writing. at System.IO.__Error.WriteNotSupported() at System.IO.MemoryStream.WriteByte(Byte value) at Samples.NotSupprotedExceptionSample.Main() in C:\Books\BCL\Samples\System\ NotSupportedException\NotSupportedException.cs:line 16
N O P Q
NotSupportedException() Constructor
R
[ILASM]
S
public rtspecialname specialname instance void .ctor()
T
[C#]
public NotSupportedException()
U
Summary
V
Constructs and initializes a new instance of the System.NotSupportedException class.
W X
Description
Y
This constructor initializes the System.NotSupportedException.Message property of the new instance to a system-supplied message that describes the error. This message takes into account the current system culture.
Z
2325
Contents | Index
NotSupportedException
System
NotSupportedException() Constructor
The System.NotSupportedException.InnerException property is initialized to null. A B
NotSupportedException(System.String) Constructor
C
[ILASM]
public rtspecialname specialname instance void .ctor(string message)
D
[C#]
public NotSupportedException(string message)
E F
Summary
G
Constructs and initializes a new instance of the System.NotSupportedException class.
H
Parameters
I J
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
K L M N O
Description
P
This constructor initializes the System.NotSupportedException.Message property of the new instance using message. If message is null, the System.NotSupportedException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.NotSupportedException.InnerException property is initialized to null.
Q R S T U
NotSupportedException(System.String, System.Exception) Constructor
V
[ILASM]
W
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
X
[C#]
public NotSupportedException(string message, Exception innerException)
Y Z
2326
Contents | Index
System
NotSupportedException NotSupportedException() Constructor
Summary Constructs and initializes a new instance of the System.NotSupportedException class. A
Parameters
B C
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
D E F G
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
H I J
Description
K
This constructor initializes the System.NotSupportedException.Message property of the new instance using message, and the System.NotSupportedException.InnerException property using innerException. If message is null, the System.NotSupportedException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
L M N O P Q
NotSupportedException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
R
[ILASM]
T
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
U
S
V
[C#]
W
protected NotSupportedException(SerializationInfo info, StreamingContext context)
X
Summary
Y
Initializes a new instance of the System.NotSupportedException class with serialized data.
Z
2327
Contents | Index
NotSupportedException
System
NotSupportedException() Constructor
Parameters Parameter
Description
info
The object that holds the serialized object data.
context
The contextual information about the source or destination.
A B C D E
Description
F
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
G H I J K L M N O P Q R S T U V W X Y Z
2328
Contents | Index
System NullReferenceException
BCL
Object Exception
ISerializable
NotStandardized
A B
SystemException NullReferenceException
C D
Summary
E
Represents the error that occurs when there is an attempt to dereference a null object reference.
F G
Type Summary
H
public class NullReferenceException : SystemException { // Constructors public NullReferenceException (); public NullReferenceException (string message); public NullReferenceException (string message, Exception innerException); MS CF protected NullReferenceException (SerializationInfo info, StreamingContext context); }
I J K L M N O
BA As hard as we tried in the BCL design to be language-neutral, sometimes it was
P
just impossible. The name of this exception seems obvious to most C# or C++ developers but not to a VB developer. The VB language uses the keyword “Nothing” to represent this concept. So getting a NullReferenceException frequently does not help the VB user determine what the problem is.
Q R S T
Description
U
[Note: Applications throw the System.ArgumentNullException rather than System.NullReferenceException.]
V W X Y Z
2329
Contents | Index
NullReferenceException
System
NullReferenceException() Constructor
Example using System; namespace Samples { public class NullReferenceExceptionSample { public static void Main() { string s = null; try { Console.WriteLine(s.ToUpper()); } catch(NullReferenceException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L
The output is
M
Exception: System.NullReferenceException: Object reference not set to an instance of an object. at Samples.NullReferenceExceptionSample.Main() in C:\Books\BCL\Samples\System\ NullReferenceException\NullReferenceException.cs:line 12
N O P Q R
NullReferenceException() Constructor
S
[ILASM]
public rtspecialname specialname instance void .ctor()
T
[C#]
public NullReferenceException()
U V
Summary
W
Constructs and initializes a new instance of the System.NullReferenceException class.
X Y
Description
Z
This constructor initializes the System.NullReferenceException.Message property of the new instance to a system-supplied message that describes the error, such as
2330
Contents | Index
System
NullReferenceException NullReferenceException() Constructor
“The value 'null' was found where an instance of an object was required.” This message takes into account the current system culture. The System.NullReferenceException.InnerException property is initialized to null.
A B C
NullReferenceException(System.String) Constructor
D [ILASM]
E
public rtspecialname specialname instance void .ctor(string message) [C#]
F
public NullReferenceException(string message)
G
Summary
H
Constructs and initializes a new instance of the System.NullReferenceException class.
I J
Parameters
K L
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
M N O P
Description
Q
This constructor initializes the System.NullReferenceException.Message property of the new instance using message. If message is null, the System.NullReferenceException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.NullReferenceException.InnerException property is initialized to null.
R S T U V W
NullReferenceException(System.String, System.Exception) Constructor
X
[ILASM]
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
Y Z
[C#]
public NullReferenceException(string message, Exception innerException)
2331
Contents | Index
NullReferenceException
System
NullReferenceException() Constructor
Summary Constructs and initializes a new instance of the System.NullReferenceException class. A
Parameters
B C D
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
E F G H I J
Description
K
This constructor initializes the System.NullReferenceException.Message property of the new instance using message, and the System.NullReferenceException.InnerException property using innerException. If message is null, the System.NullReferenceException.Message property is initialized to the systemsupplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
L M N O P Q
S
NullReferenceException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
T
[ILASM]
U
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
R
V
[C#]
W
protected NullReferenceException(SerializationInfo info, StreamingContext context)
X
Summary
Y
Initializes a new instance of the System.NullReferenceException class with serialized data.
Z
2332
Contents | Index
System
NullReferenceException NullReferenceException() Constructor
Parameters Parameter
Description
info
The object that holds the serialized object data.
context
The contextual information about the source or destination.
A B C D
Description
E
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
F G H I J K L M N O P Q R S T U V W X Y Z
2333
Contents | Index
System.Globalization NumberFormatInfo
BCL
Object ICloneable
A
NumberFormatInfo IFormatProvider
B C
Summary
D
Supplies culture-specific formatting information for string representations of numeric values.
E
Type Summary
F
public sealed class NumberFormatInfo : ICloneable, IFormatProvider { // Constructors public NumberFormatInfo ();
G H I J
// Properties public int CurrencyDecimalDigits { set; get; } public string CurrencyDecimalSeparator { set; get; } public string CurrencyGroupSeparator { set; get; } public int[] CurrencyGroupSizes { set; get; } public int CurrencyNegativePattern { set; get; } public int CurrencyPositivePattern { set; get; } public string CurrencySymbol { set; get; } public static NumberFormatInfo CurrentInfo { get; } public static NumberFormatInfo InvariantInfo { get; } public bool IsReadOnly { get; } public string NaNSymbol { set; get; } public string NegativeInfinitySymbol { set; get; } public string NegativeSign { set; get; } public int NumberDecimalDigits { set; get; } public string NumberDecimalSeparator { set; get; } public string NumberGroupSeparator { set; get; } public int[] NumberGroupSizes { set; get; } public int NumberNegativePattern { set; get; } public int PercentDecimalDigits { set; get; } public string PercentDecimalSeparator { set; get; } public string PercentGroupSeparator { set; get; } public int[] PercentGroupSizes { set; get; } public int PercentNegativePattern { set; get; } public int PercentPositivePattern { set; get; } public string PercentSymbol { set; get; } public string PerMilleSymbol { set; get; } public string PositiveInfinitySymbol { set; get; } public string PositiveSign { set; get; }
K L M N O P Q R S T U V W X Y Z
2334
Contents | Index
System.Globalization
NumberFormatInfo NumberFormatInfo Class
// Methods public object public object MS public static public static
Clone (); GetFormat (Type formatType); NumberFormatInfo GetInstance (IFormatProvider formatProvider); NumberFormatInfo ReadOnly (NumberFormatInfo nfi);
A
}
B C
Description
D
System.Globalization.NumberFormatInfo supplies symbols such as currency symbols and decimal separators. [Note: A System.Globalization.NumberFormatInfo instance typically contains the set of symbols for a specific language and culture. Instances of System.Globalization.NumberFormatInfo may be created to provide customized formatting information.]
E F G H
Example
I
using System; using System.Globalization;
J K
namespace Samples { public class NumberFormatInfoSample { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("CurrencyDecimalDigits: {0}", n.CurrencyDecimalDigits); Console.WriteLine("CurrencyDecimalSeparator: {0}", n.CurrencyDecimalSeparator); Console.WriteLine("CurrencyGroupSeparator: {0}", n.CurrencyGroupSeparator); Console.Write("CurrencyGroupSizes: "); int[] integers = n.CurrencyGroupSizes; foreach(int i in integers) Console.Write(i); Console.WriteLine(); Console.WriteLine("CurrencyNegativePattern: {0}", n.CurrencyNegativePattern); Console.WriteLine("CurrencyPositivePattern: {0}", n.CurrencyPositivePattern); Console.WriteLine("CurrencySymbol: {0}", n.CurrencySymbol); Console.WriteLine("IsReadOnly: {0}", n.IsReadOnly); Console.WriteLine("NaNSymbol: {0}",
L M N O P Q R S T U V W X Y Z
2335
Contents | Index
NumberFormatInfo
System.Globalization
NumberFormatInfo Class
n.NaNSymbol); Console.WriteLine("NegativeInfinitySymbol: {0}", n.NegativeInfinitySymbol); Console.WriteLine("NegativeSign: {0}", n.NegativeSign); Console.WriteLine("NumberDecimalDigits: {0}", n.NumberDecimalDigits); Console.WriteLine("NumberDecimalSeparator: {0}", n.NumberDecimalSeparator); Console.WriteLine("NumberGroupSeparator: {0}", n.NumberGroupSeparator); Console.Write("NumberGroupSizes: ", n.NumberGroupSizes); integers = n.NumberGroupSizes; foreach(int i in integers) Console.Write(i); Console.WriteLine(); Console.WriteLine("NumberNegativePattern: {0}", n.NumberNegativePattern); Console.WriteLine("PercentDecimalDigits: {0}", n.PercentDecimalDigits); Console.WriteLine("PercentDecimalSeparator: {0}", n.PercentDecimalSeparator); Console.WriteLine("PercentGroupSeparator: {0}", n.PercentGroupSeparator); Console.Write("PercentGroupSizes: "); integers = n.PercentGroupSizes; foreach(int i in integers) Console.Write(i); Console.WriteLine(); Console.WriteLine("PercentNegativePattern: {0}", n.PercentNegativePattern); Console.WriteLine("PercentPositivePattern: {0}", n.PercentPositivePattern); Console.WriteLine("PercentSymbol: {0}", n.PercentSymbol); Console.WriteLine("PerMilleSymbol: {0}", n.PerMilleSymbol); Console.WriteLine("PositiveInfinitySymbol: {0}", n.PositiveInfinitySymbol); Console.WriteLine("PositiveSign: {0}", n.PositiveSign);
A B C D E F G H I J K L M N O P Q R S T U V W X }
Y
} }
Z
2336
Contents | Index
System.Globalization
NumberFormatInfo NumberFormatInfo() Constructor
The output is CurrencyDecimalDigits: 2 CurrencyDecimalSeparator: . CurrencyGroupSeparator: , CurrencyGroupSizes: 3 CurrencyNegativePattern: 1 CurrencyPositivePattern: 0 CurrencySymbol: $ IsReadOnly: False NaNSymbol: NaN NegativeInfinitySymbol: -Infinity NegativeSign: NumberDecimalDigits: 2 NumberDecimalSeparator: . NumberGroupSeparator: , NumberGroupSizes: 3 NumberNegativePattern: 1 PercentDecimalDigits: 2 PercentDecimalSeparator: . PercentGroupSeparator: , PercentGroupSizes: 3 PercentNegativePattern: 0 PercentPositivePattern: 0 PercentSymbol: % PerMilleSymbol: % PositiveInfinitySymbol: Infinity PositiveSign: +
A B C D E F G H I J K L M N O P Q
NumberFormatInfo() Constructor
R
[ILASM]
S
public rtspecialname specialname instance void .ctor()
T
[C#]
public NumberFormatInfo()
U
Summary
V
Constructs and initializes a new instance of the System.Globalization.NumberFormatInfo class.
W
Description
Y
The new instance is not read-only, and is otherwise identical to the System.Globalization.NumberFormatInfo instance returned by the System.Globalization.NumberFormatInfo.InvariantInfo property.
Z
X
2337
Contents | Index
NumberFormatInfo
System.Globalization
CurrencyDecimalDigits Property
NumberFormatInfo.CurrencyDecimalDigits Property [ILASM]
.property int32 CurrencyDecimalDigits { public hidebysig specialname instance int32 get_CurrencyDecimalDigits() public hidebysig specialname instance void set_CurrencyDecimalDigits(int32 value) }
A B
[C#]
C
public int CurrencyDecimalDigits { get; set; }
D
Summary
E
Gets or sets the number of decimal places in currency values.
F G
Description
H
The culture-invariant value for this property is 2.
I
Exceptions
J K
Exception
Condition
System.ArgumentOutOfRangeException
The value specified for a set operation is less than 0 or greater than 99.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
L M N O P Q
Example
R
using System; using System.Globalization;
S namespace Samples { public class NumberFormatInfoCurrencyDecimalDigits { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("CurrencyDecimalDigits: {0}", n.CurrencyDecimalDigits); n.CurrencyDecimalDigits = 4; Console.WriteLine("CurrencyDecimalDigits: {0}", n.CurrencyDecimalDigits); decimal d = 42;
T U V W X Y Z
2338
Contents | Index
System.Globalization
NumberFormatInfo CurrencyDecimalSeparator Property
string s = "C"; Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n));
A
} }
B
}
C
The output is
D E
CurrencyDecimalDigits: 2 CurrencyDecimalDigits: 4 42 formatted with "C" yields $42.0000
F G H
NumberFormatInfo.CurrencyDecimalSeparator Property
I [ILASM]
J
.property string CurrencyDecimalSeparator { public hidebysig specialname instance string get_CurrencyDecimalSeparator() public hidebysig specialname instance void set_CurrencyDecimalSeparator(string value) }
K
[C#]
L
public string CurrencyDecimalSeparator { get; set; }
M
Summary
N
Gets or sets the symbol used as the decimal separator in currency values.
O P
Description
Q
The culture-invariant value for this property is “.”.
R S
Exceptions
T
Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
U V W X Y Z
2339
Contents | Index
NumberFormatInfo
System.Globalization
CurrencyGroupSeparator Property
Example using System; using System.Globalization;
A namespace Samples { public class NumberFormatInfoCurrencyDecimalSeparator { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("CurrencyDecimalSeparator: {0}", n.CurrencyDecimalSeparator); n.CurrencyDecimalSeparator = "!"; Console.WriteLine("CurrencyDecimalSeparator: {0}", n.CurrencyDecimalSeparator); decimal d = 42; string s = "C"; Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n)); } } }
B C D E F G H I J K L M N
The output is
O P
CurrencyDecimalSeparator: . CurrencyDecimalSeparator: ! 42 formatted with "C" yields $42!00
Q R S
NumberFormatInfo.CurrencyGroupSeparator Property
T U
[ILASM]
V
.property string CurrencyGroupSeparator { public hidebysig specialname instance string get_CurrencyGroupSeparator() public hidebysig specialname instance void set_CurrencyGroupSeparator(string value) }
W
[C#]
public string CurrencyGroupSeparator { get; set; }
X Y
Summary
Z
Gets or sets the symbol used to separate groups of digits to the left of the decimal point in currency values.
2340
Contents | Index
System.Globalization
NumberFormatInfo CurrencyGroupSeparator Property
Description The culture-invariant value for this property is “,”. A
Exceptions
B
Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
D
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
F
C
E
G H
Example
I
using System; using System.Globalization;
J K
namespace Samples { public class NumberFormatInfoCurrencyGroupSeparator { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("CurrencyGroupSeparator: {0}", n.CurrencyGroupSeparator); n.CurrencyGroupSeparator = "-"; Console.WriteLine("CurrencyGroupSeparator: {0}", n.CurrencyGroupSeparator); decimal d = 42000000; string s = "C"; Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n)); } } }
L M N O P Q R S T U V W X
The output is
Y CurrencyGroupSeparator: , CurrencyGroupSeparator: 42000000 formatted with "C" yields $42-000-000.00
Z
2341
Contents | Index
NumberFormatInfo
System.Globalization
CurrencyGroupSizes Property
NumberFormatInfo.CurrencyGroupSizes Property [ILASM]
.property class System.Int32[] CurrencyGroupSizes { public hidebysig specialname instance class System.Int32[] get_CurrencyGroupSizes() public hidebysig specialname instance void set_CurrencyGroupSizes(class System.Int32[] value) }
A B
[C#]
C
public int[] CurrencyGroupSizes { get; set; }
D
Summary
E
Gets or sets the number of digits in each group to the left of the decimal point in currency values.
F G
Description
H
All elements of the array except the last are required to be between 1 and 9, inclusive. The last element can be 0. The first element of the array defines the number of elements in the first group of digits located immediately to the left of the System.Globalization.NumberFormatInfo.CurrencyDecimalSeparator. Each subsequent element refers to the next group of digits located to the left of the previous group. If the last element of the array is not zero, any remaining digits are grouped based on the last element of the array. If the last element is zero, the remaining digits are not grouped. The culture-invariant value for this property is an array with a single element containing the value 3.
I J K L M N O P
Exceptions
Q R
Exception
Condition
System.ArgumentNullException
The array specified for a set operation is a null reference.
System.ArgumentOutOfRangeException
One of the elements in the array specified for a set operation is not between 0 and 9.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
S T U V W X Y Z
2342
Contents | Index
System.Globalization
NumberFormatInfo CurrencyNegativePattern Property
Example using System; using System.Globalization;
A namespace Samples { public class NumberFormatInfoCurrencyGroupSizes { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.Write("CurrencyGroupSizes: "); foreach(int i in n.CurrencyGroupSizes) Console.Write("{0} ", i); Console.WriteLine(); n.CurrencyGroupSizes = new int[]{2, 3}; Console.Write("CurrencyGroupSizes: "); foreach(int i in n.CurrencyGroupSizes) Console.Write("{0} ", i); Console.WriteLine(); decimal d = 42000000; string s = "C"; Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n)); } } }
B C D E F G H I J K L M N O P
The output is
Q R
CurrencyGroupSizes: 3 CurrencyGroupSizes: 2 3 42000000 formatted with "C" yields $420,000,00.00
S T U
NumberFormatInfo.CurrencyNegativePattern Property
V
[ILASM]
.property int32 CurrencyNegativePattern { public hidebysig specialname instance int32 get_CurrencyNegativePattern() public hidebysig specialname instance void set_CurrencyNegativePattern(int32 value) }
W X
[C#]
Y
public int CurrencyNegativePattern { get; set; }
Z
Summary Gets or sets the format of negative currency values. 2343
Contents | Index
NumberFormatInfo
System.Globalization
CurrencyNegativePattern Property
Property Value A System.Int32 between 0 and 15 inclusive, which specifies the format of negative currency values. A B
Description
C
The following table describes the valid values for this property. “$” is used as the value for System.Globalization.NumberFormatInfo.CurrencySymbol, “–” is used as the value for System.Globalization.NumberFormatInfo.NegativeSign, and 999 represents any numeric value.
D E F G
Value
Pattern
Value
Pattern
0
($999)
8
–999 $
J
1
–$999
9
–$ 999
K
2
$–999
10
999 $–
L
3
$999–
11
$ 999–
M
4
(999$)
12
$ –999
5
–999$
13
999–$
P
6
999–$
14
($ 999)
Q
7
999$–
15
(999 $)
H I
N O
R S
The culture-invariant value for this property is 0.
T
Exceptions
U V W X Y Z
Exception
Condition
System.ArgumentOutOfRangeException
The value specified for a set operation is less than 0 or greater than 15.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
2344
Contents | Index
System.Globalization
NumberFormatInfo CurrencyNegativePattern Property
Example using System; using System.Globalization;
A namespace Samples { public class NumberFormatInfoCurrencyNegativePattern { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("CurrencyNegativePattern: {0}", n.CurrencyNegativePattern); decimal d = -4200; string s = "C"; for(int i = 0; i < 16; i++) { n.CurrencyNegativePattern = i; Console.Write("CurrencyNegativePattern: {0} ,", i); Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n)); } } } }
B C D E F G H I J K L M N O P
The output is CurrencyNegativePattern: CurrencyNegativePattern: CurrencyNegativePattern: CurrencyNegativePattern: CurrencyNegativePattern: CurrencyNegativePattern: CurrencyNegativePattern: CurrencyNegativePattern: CurrencyNegativePattern: CurrencyNegativePattern: CurrencyNegativePattern: CurrencyNegativePattern: CurrencyNegativePattern: CurrencyNegativePattern: CurrencyNegativePattern: CurrencyNegativePattern: CurrencyNegativePattern:
Q 1 0 ,-4200 formatted with "C" yields ($4,200.00) 1 ,-4200 formatted with "C" yields -$4,200.00 2 ,-4200 formatted with "C" yields $-4,200.00 3 ,-4200 formatted with "C" yields $4,200.004 ,-4200 formatted with "C" yields (4,200.00$) 5 ,-4200 formatted with "C" yields -4,200.00$ 6 ,-4200 formatted with "C" yields 4,200.00-$ 7 ,-4200 formatted with "C" yields 4,200.00$8 ,-4200 formatted with "C" yields -4,200.00 $ 9 ,-4200 formatted with "C" yields -$ 4,200.00 10 ,-4200 formatted with "C" yields 4,200.00 $11 ,-4200 formatted with "C" yields $ 4,200.0012 ,-4200 formatted with "C" yields $ -4,200.00 13 ,-4200 formatted with "C" yields 4,200.00- $ 14 ,-4200 formatted with "C" yields ($ 4,200.00) 15 ,-4200 formatted with "C" yields (4,200.00 $)
R S T U V W X Y Z
2345
Contents | Index
NumberFormatInfo
System.Globalization
CurrencyPositivePattern Property
NumberFormatInfo.CurrencyPositivePattern Property [ILASM]
.property int32 CurrencyPositivePattern { public hidebysig specialname instance int32 get_CurrencyPositivePattern() public hidebysig specialname instance void set_CurrencyPositivePattern(int32 value) }
A B
[C#]
C
public int CurrencyPositivePattern { get; set; }
D
Summary
E
Gets or sets the format of positive currency values.
F G
Property Value
H
A System.Int32 between 0 and 3 inclusive, containing the format of positive currency values.
I J
Description
K
The following table describes the valid values for this property. “$” is used as the value for System.Globalization.NumberFormatInfo.CurrencySymbol, and 999 represents any numeric value.
L M N O
Value
Pattern
P
0
$999
1
999$
S
2
$ 999
T
3
999 $
Q R
U V
The culture-invariant value for this property is 0.
W X Y Z
2346
Contents | Index
System.Globalization
NumberFormatInfo CurrencyPositivePattern Property
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
The value specified for a set operation is less than 0 or greater than 3.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
A B C D E
Example
F
using System; using System.Globalization;
G H
namespace Samples { public class NumberFormatInfoCurrencyPositivePattern { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("CurrencyPositivePattern: {0}", n.CurrencyPositivePattern); decimal d = 4200; string s = "C"; for(int i = 0; i < 4; i++) { n.CurrencyPositivePattern = i; Console.Write("CurrencyPositivePattern: {0} ,", i); Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n)); } } } }
I J K L M N O P Q R S T U V W X
The output is CurrencyPositivePattern: CurrencyPositivePattern: CurrencyPositivePattern: CurrencyPositivePattern: CurrencyPositivePattern:
0 0 1 2 3
Y ,4200 ,4200 ,4200 ,4200
formatted formatted formatted formatted
with with with with
"C" "C" "C" "C"
yields yields yields yields
$4,200.00 4,200.00$ $ 4,200.00 4,200.00 $
Z
2347
Contents | Index
NumberFormatInfo
System.Globalization
CurrencySymbol Property
NumberFormatInfo.CurrencySymbol Property [ILASM]
.property string CurrencySymbol { public hidebysig specialname instance string get_CurrencySymbol() public hidebysig specialname instance void set_CurrencySymbol(string value) }
A B
[C#]
C
public string CurrencySymbol { get; set; }
D
Summary
E
Gets or sets the currency symbol.
F G
Description
H
The culture-invariant value for this property is the Unicode currency symbol 0x00a4.
I
Exceptions
J K
Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
L M N O P Q
Example
R
using System; using System.Globalization;
S namespace Samples { public class NumberFormatInfoCurrencySymbol { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("CurrencySymbol: {0}", n.CurrencySymbol); n.CurrencySymbol = "#"; Console.WriteLine("CurrencySymbol: {0}", n.CurrencySymbol); decimal d = 42;
T U V W X Y Z
2348
Contents | Index
System.Globalization
NumberFormatInfo CurrentInfo Property
string s = "C"; Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n));
A
} }
B
}
C
The output is
D
CurrencySymbol: $ CurrencySymbol: # 42 formatted with "C" yields #42.00
E F G H
NumberFormatInfo.CurrentInfo Property
I
[ILASM]
.property class System.Globalization.NumberFormatInfo CurrentInfo { public hidebysig static specialname class System.Globalization.NumberFormatInfo get_CurrentInfo() }
J K
[C#]
L
public static NumberFormatInfo CurrentInfo { get; }
M
Summary
N
Gets a System.Globalization.NumberFormatInfo instance containing formatting information for the current system culture.
O P
Example
Q
using System; using System.Globalization;
R S
namespace Samples { public class NumberFormatInfoCurrentInfo { public static void Main() { NumberFormatInfo n = NumberFormatInfo.CurrentInfo; Console.WriteLine("CurrencyDecimalDigits: {0}", n.CurrencyDecimalDigits); Console.WriteLine("CurrencyDecimalSeparator: {0}", n.CurrencyDecimalSeparator); Console.WriteLine("CurrencyGroupSeparator: {0}", n.CurrencyGroupSeparator); Console.Write("CurrencyGroupSizes: "); int[] integers = n.CurrencyGroupSizes;
T U V W X Y Z
2349
Contents | Index
NumberFormatInfo
System.Globalization
CurrentInfo Property
foreach(int i in integers) Console.Write(i); Console.WriteLine(); Console.WriteLine("CurrencyNegativePattern: {0}", n.CurrencyNegativePattern); Console.WriteLine("CurrencyPositivePattern: {0}", n.CurrencyPositivePattern); Console.WriteLine("CurrencySymbol: {0}", n.CurrencySymbol); Console.WriteLine("IsReadOnly: {0}", n.IsReadOnly); Console.WriteLine("NaNSymbol: {0}", n.NaNSymbol); Console.WriteLine("NegativeInfinitySymbol: {0}", n.NegativeInfinitySymbol); Console.WriteLine("NegativeSign: {0}", n.NegativeSign); Console.WriteLine("NumberDecimalDigits: {0}", n.NumberDecimalDigits); Console.WriteLine("NumberDecimalSeparator: {0}", n.NumberDecimalSeparator); Console.WriteLine("NumberGroupSeparator: {0}", n.NumberGroupSeparator); Console.Write("NumberGroupSizes: ", n.NumberGroupSizes); integers = n.NumberGroupSizes; foreach(int i in integers) Console.Write(i); Console.WriteLine(); Console.WriteLine("NumberNegativePattern: {0}", n.NumberNegativePattern); Console.WriteLine("PercentDecimalDigits: {0}", n.PercentDecimalDigits); Console.WriteLine("PercentDecimalSeparator: {0}", n.PercentDecimalSeparator); Console.WriteLine("PercentGroupSeparator: {0}", n.PercentGroupSeparator); Console.Write("PercentGroupSizes: "); integers = n.PercentGroupSizes; foreach(int i in integers) Console.Write(i); Console.WriteLine(); Console.WriteLine("PercentNegativePattern: {0}", n.PercentNegativePattern); Console.WriteLine("PercentPositivePattern: {0}", n.PercentPositivePattern); Console.WriteLine("PercentSymbol: {0}", n.PercentSymbol);
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
2350
Contents | Index
System.Globalization
NumberFormatInfo InvariantInfo Property
Console.WriteLine("PerMilleSymbol: {0}", n.PerMilleSymbol); Console.WriteLine("PositiveInfinitySymbol: {0}", n.PositiveInfinitySymbol); Console.WriteLine("PositiveSign: {0}", n.PositiveSign);
A B
}
C
} }
D
The output is
E F
CurrencyDecimalDigits: 2 CurrencyDecimalSeparator: . CurrencyGroupSeparator: , CurrencyGroupSizes: 3 CurrencyNegativePattern: 1 CurrencyPositivePattern: 0 CurrencySymbol: $ IsReadOnly: True NaNSymbol: NaN NegativeInfinitySymbol: -Infinity NegativeSign: NumberDecimalDigits: 2 NumberDecimalSeparator: . NumberGroupSeparator: , NumberGroupSizes: 3 NumberNegativePattern: 1 PercentDecimalDigits: 2 PercentDecimalSeparator: . PercentGroupSeparator: , PercentGroupSizes: 3 PercentNegativePattern: 0 PercentPositivePattern: 0 PercentSymbol: % PerMilleSymbol: % PositiveInfinitySymbol: Infinity PositiveSign: +
G H I J K L M N O P Q R S T U V W
NumberFormatInfo.InvariantInfo Property
X
[ILASM]
Y
.property class System.Globalization.NumberFormatInfo InvariantInfo { public hidebysig static specialname class System.Globalization.NumberFormatInfo get_InvariantInfo() }
Z
[C#]
public static NumberFormatInfo InvariantInfo { get; }
2351
Contents | Index
NumberFormatInfo
System.Globalization
InvariantInfo Property
Summary Gets a System.Globalization.NumberFormatInfo instance containing formatting information that is culture-independent and does not change. A B
Property Value
C
A read-only System.Globalization.NumberFormatInfo with property values which are universally supported. The property values of the returned System.Globalization.NumberFormatInfo are not impacted by changes to the current culture.
D E F
Description
G
The following table lists the property values of the System.Globalization.NumberFormatInfo returned by this property.
H I J
Property
K
CurrencyDecimalDigits
Default
Description
2
The number of decimal places in currency values.
CurrencyDecimalSeparator
"."
The string used as the decimal separator in currency values.
CurrencyGroupSeparator
","
The string used to separate groups of digits to the left of the decimal point in currency values.
CurrencyGroupSizes
3
The number of digits in each group to the left of the decimal point in currency values.
R
CurrencyNegativePattern
0
The format of negative currency values.
S
CurrencyPositivePattern
0
The format of positive currency values.
T
CurrencySymbol
0x00a4
The Unicode currency symbol.
NaNSymbol
"NaN"
The string used to represent undefined floatingpoint values.
"–Infinity"
The string used to represent negative infinities.
L M N O P Q
U V W
NegativeInfinitySymbol
X NegativeSign
"–"
The string used to indicate negative values.
Y NumberDecimalDigits
Z
NumberDecimalSeparator
2 "."
The default number of decimal places. The string used as the decimal separator.
2352
Contents | Index
System.Globalization
NumberFormatInfo InvariantInfo Property
Property
Default
Description
","
The string used to separate groups of digits to the left of the decimal point.
NumberGroupSizes
3
The number of digits in each group to the left of the decimal point.
NumberNegativePattern
1
The format of negative values.
2
The default number of decimal places in percent values.
PercentDecimalSeparator
"."
The string used as the decimal separator in percent values.
PercentGroupSeparator
","
The string used to separate groups of digits to the left of the decimal point in percent values.
NumberGroupSeparator
A B C D E
PercentDecimalDigits
F G
PercentGroupSizes
3
H I J
The number of digits in each group to the left of the decimal in percent values.
K L
PercentNegativePattern
0
The format of negative percent values.
M
PercentPositivePattern
0
The format of positive percent values.
N
PercentSymbol
"%"
The percent symbol.
"‰"
The per mille symbol.
O P
PerMilleSymbol PositiveInfinitySymbol PositiveSign
"Infinity" "+"
Q
The string used to represent positive infinities.
R
The string used to indicate positive values.
S T
Example
U
using System; using System.Globalization;
V W
namespace Samples { public class NumberFormatInfoInvariantInfo { public static void Main() { NumberFormatInfo n = NumberFormatInfo.InvariantInfo;
X Y Z
2353
Contents | Index
NumberFormatInfo
System.Globalization
InvariantInfo Property
Console.WriteLine("CurrencyDecimalDigits: {0}", n.CurrencyDecimalDigits); Console.WriteLine("CurrencyDecimalSeparator: {0}", n.CurrencyDecimalSeparator); Console.WriteLine("CurrencyGroupSeparator: {0}", n.CurrencyGroupSeparator); Console.Write("CurrencyGroupSizes: "); int[] integers = n.CurrencyGroupSizes; foreach(int i in integers) Console.Write(i); Console.WriteLine(); Console.WriteLine("CurrencyNegativePattern: {0}", n.CurrencyNegativePattern); Console.WriteLine("CurrencyPositivePattern: {0}", n.CurrencyPositivePattern); Console.WriteLine("CurrencySymbol: {0}", n.CurrencySymbol); Console.WriteLine("IsReadOnly: {0}", n.IsReadOnly); Console.WriteLine("NaNSymbol: {0}", n.NaNSymbol); Console.WriteLine("NegativeInfinitySymbol: {0}", n.NegativeInfinitySymbol); Console.WriteLine("NegativeSign: {0}", n.NegativeSign); Console.WriteLine("NumberDecimalDigits: {0}", n.NumberDecimalDigits); Console.WriteLine("NumberDecimalSeparator: {0}", n.NumberDecimalSeparator); Console.WriteLine("NumberGroupSeparator: {0}", n.NumberGroupSeparator); Console.Write("NumberGroupSizes: ", n.NumberGroupSizes); integers = n.NumberGroupSizes; foreach(int i in integers) Console.Write(i); Console.WriteLine(); Console.WriteLine("NumberNegativePattern: {0}", n.NumberNegativePattern); Console.WriteLine("PercentDecimalDigits: {0}", n.PercentDecimalDigits); Console.WriteLine("PercentDecimalSeparator: {0}", n.PercentDecimalSeparator); Console.WriteLine("PercentGroupSeparator: {0}", n.PercentGroupSeparator); Console.Write("PercentGroupSizes: "); integers = n.PercentGroupSizes; foreach(int i in integers)
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
2354
Contents | Index
System.Globalization
NumberFormatInfo InvariantInfo Property
Console.Write(i); Console.WriteLine(); Console.WriteLine("PercentNegativePattern: {0}", n.PercentNegativePattern); Console.WriteLine("PercentPositivePattern: {0}", n.PercentPositivePattern); Console.WriteLine("PercentSymbol: {0}", n.PercentSymbol); Console.WriteLine("PerMilleSymbol: {0}", n.PerMilleSymbol); Console.WriteLine("PositiveInfinitySymbol: {0}", n.PositiveInfinitySymbol); Console.WriteLine("PositiveSign: {0}", n.PositiveSign);
A B C D E F G
}
H
} }
I
The output is
J K
CurrencyDecimalDigits: 2 CurrencyDecimalSeparator: . CurrencyGroupSeparator: , CurrencyGroupSizes: 3 CurrencyNegativePattern: 0 CurrencyPositivePattern: 0 CurrencySymbol: Ï IsReadOnly: True NaNSymbol: NaN NegativeInfinitySymbol: -Infinity NegativeSign: NumberDecimalDigits: 2 NumberDecimalSeparator: . NumberGroupSeparator: , NumberGroupSizes: 3 NumberNegativePattern: 1 PercentDecimalDigits: 2 PercentDecimalSeparator: . PercentGroupSeparator: , PercentGroupSizes: 3 PercentNegativePattern: 0 PercentPositivePattern: 0 PercentSymbol: % PerMilleSymbol: % PositiveInfinitySymbol: Infinity PositiveSign: +
L M N O P Q R S T U V W X Y Z
2355
Contents | Index
NumberFormatInfo
System.Globalization
IsReadOnly Property
NumberFormatInfo.IsReadOnly Property [ILASM]
A
.property bool IsReadOnly { public hidebysig specialname instance bool get_IsReadOnly() }
B
[C#]
public bool IsReadOnly { get; }
C D
Summary
E
Gets a value indicating whether the current instance is read-only.
F
Property Value
G
true if the current instance is read-only; otherwise false.
H
Description
I
[Note: Attempting to perform an assignment to a property of a read-only System.Globalization.NumberFormatInfo causes a System.InvalidOperationException.]
J K L M
Example
N
using System; using System.Globalization;
O namespace Samples { public class NumberFormatInfoIsReadOnly { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("IsReadOnly: {0}", n.IsReadOnly); n = NumberFormatInfo.InvariantInfo; Console.WriteLine("IsReadOnly: {0}", n.IsReadOnly); n = NumberFormatInfo.CurrentInfo; Console.WriteLine("IsReadOnly: {0}", n.IsReadOnly); } } }
P Q R S T U V W X Y Z
2356
Contents | Index
System.Globalization
NumberFormatInfo NaNSymbol Property
The output is IsReadOnly: False IsReadOnly: True IsReadOnly: True
A B C
NumberFormatInfo.NaNSymbol Property
D
[ILASM]
E
.property string NaNSymbol { public hidebysig specialname instance string get_NaNSymbol() public hidebysig specialname instance void set_NaNSymbol(string value) }
F G
[C#]
public string NaNSymbol { get; set; }
H
Summary
I
Gets or sets the symbol that represents NaN (Not-a-Number) floating-point values.
J K
Description
L
The culture-invariant value for this property is “NaN”. [Note: For more information on NaN values, see System.Double or System.Single.]
M N
Exceptions
O
Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
P Q R S T U
Example
V
using System; using System.Globalization;
W X
namespace Samples { public class NumberFormatInfoCurrencyDecimalDigits { public static void Main() {
Y Z
2357
Contents | Index
NumberFormatInfo
System.Globalization
NegativeInfinitySymbol Property
CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("NaNSymbol: {0}", n.NaNSymbol); n.NaNSymbol = "NotANumber"; Console.WriteLine("NaNSymbol: {0}", n.NaNSymbol); Double d = Double.NaN; string s = "G"; Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n));
A B C D E }
F
}
G
}
H
The output is
I NaNSymbol: NaN NaNSymbol: NotANumber NaN formatted with "G" yields NotANumber
J K L M
NumberFormatInfo.NegativeInfinitySymbol Property
N
[ILASM]
.property string NegativeInfinitySymbol { public hidebysig specialname instance string get_NegativeInfinitySymbol() public hidebysig specialname instance void set_NegativeInfinitySymbol(string value) }
O P
[C#]
Q
public string NegativeInfinitySymbol { get; set; }
R
Summary
S
Gets or sets the symbol that represents negative infinity.
T U
Description
V
The culture-invariant value for this property is “–Infinity”. [Note: For more information on negative infinity, see System.Double or System.Single.]
W X Y Z
2358
Contents | Index
System.Globalization
NumberFormatInfo NegativeInfinitySymbol Property
Exceptions Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
A B C D E
Example
F
using System; using System.Globalization;
G H
namespace Samples { public class NumberFormatInfoNegativeInfinitySymbol { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("NegativeInfinitySymbol: {0}", n.NegativeInfinitySymbol); n.NegativeInfinitySymbol = "Negative Infinity"; Console.WriteLine("NegativeInfinitySymbol: {0}", n.NegativeInfinitySymbol); Double d = Double.NegativeInfinity; string s = "G"; Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n)); } } }
I J K L M N O P Q R S T U V
The output is
W NegativeInfinitySymbol: -Infinity NegativeInfinitySymbol: Negative Infinity -Infinity formatted with "G" yields Negative Infinity
X Y Z
2359
Contents | Index
NumberFormatInfo
System.Globalization
NegativeSign Property
NumberFormatInfo.NegativeSign Property [ILASM]
.property string NegativeSign { public hidebysig specialname instance string get_NegativeSign() public hidebysig specialname instance void set_NegativeSign(string value) }
A B
[C#]
C
public string NegativeSign { get; set; }
D
Summary
E
Gets or sets the symbol used to represent negative values.
F G
Description
H
The culture-invariant value for this property is “-”.
I
Exceptions
J K
Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
L M N O P Q
Example
R
using System; using System.Globalization;
S namespace Samples { public class NumberFormatInfoNegativeSign { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("NegativeSign: {0}", n.NegativeSign); n.NegativeSign = "minus"; Console.WriteLine("NegativeSign: {0}", n.NegativeSign); decimal d = -42;
T U V W X Y Z
2360
Contents | Index
System.Globalization
NumberFormatInfo NumberDecimalDigits Property
string s = "G"; Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n));
A
} }
B
}
C
The output is
D E
NegativeSign: NegativeSign: minus -42 formatted with "G" yields minus42
F G H
NumberFormatInfo.NumberDecimalDigits Property
I [ILASM]
J
.property int32 NumberDecimalDigits { public hidebysig specialname instance int32 get_NumberDecimalDigits() public hidebysig specialname instance void set_NumberDecimalDigits(int32 value) }
K
[C#]
L
public int NumberDecimalDigits { get; set; }
M
Summary
N
Gets or sets the number of decimal places for numeric values.
O P
Description
Q
The culture-invariant value for this property is 2.
R S
Exceptions
T
Exception
Condition
System.ArgumentOutOfRangeException
The value specified for a set operation is less than 0 or greater than 99.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
U V W X Y Z
2361
Contents | Index
NumberFormatInfo
System.Globalization
NumberDecimalSeparator Property
Example using System; using System.Globalization;
A namespace Samples { public class NumberFormatInfoNumberDecimalDigits { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("NumberDecimalDigits: {0}", n.NumberDecimalDigits); n.NumberDecimalDigits = 4; Console.WriteLine("NumberDecimalDigits: {0}", n.NumberDecimalDigits); float f = 42; string s = "F"; Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", f, s, f.ToString(s, n)); } } }
B C D E F G H I J K L M N
The output is
O P
NumberDecimalDigits: 2 NumberDecimalDigits: 4 42 formatted with "F" yields 42.0000
Q R S
NumberFormatInfo.NumberDecimalSeparator Property
T U
[ILASM]
V
.property string NumberDecimalSeparator { public hidebysig specialname instance string get_NumberDecimalSeparator() public hidebysig specialname instance void set_NumberDecimalSeparator(string value) }
W
[C#]
public string NumberDecimalSeparator { get; set; }
X Y
Summary
Z
Gets or sets the symbol used as the decimal separator for numeric values.
2362
Contents | Index
System.Globalization
NumberFormatInfo NumberDecimalSeparator Property
Description The culture-invariant value for this property is “.”. A
Exceptions
B
Exception
Condition
C
The value specified for a set operation is a null reference.
D
System.ArgumentNullException
The current instance is read-only and a set operation was attempted.
F
System.InvalidOperationException
E
G H
Example
I
using System; using System.Globalization;
J K
namespace Samples { public class NumberFormatInfoNumberDecimalSeparator { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("NumberDecimalSeparator: {0}", n.NumberDecimalSeparator); n.NumberDecimalSeparator = "!"; Console.WriteLine("NumberDecimalSeparator: {0}", n.NumberDecimalSeparator); float f = 42; string s = "F"; Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", f, s, f.ToString(s, n)); } } }
L M N O P Q R S T U V W X
The output is
Y Z
NumberDecimalSeparator: . NumberDecimalSeparator: ! 42 formatted with "F" yields 42!00
2363
Contents | Index
NumberFormatInfo
System.Globalization
NumberGroupSeparator Property
NumberFormatInfo.NumberGroupSeparator Property [ILASM]
.property string NumberGroupSeparator { public hidebysig specialname instance string get_NumberGroupSeparator() public hidebysig specialname instance void set_NumberGroupSeparator(string value) }
A B
[C#]
C
public string NumberGroupSeparator { get; set; }
D
Summary
E
Gets or sets the symbol used to separate groups of digits to the left of the decimal point for numeric values.
F G
Description
H
The culture-invariant value for this property is “,”.
I J
Exceptions
K L
Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
M N O P Q
Example
R
using System; using System.Globalization;
S T
namespace Samples { public class NumberFormatInfoNumberGroupSeparator { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("NumberGroupSeparator: {0}", n.NumberGroupSeparator); n.NumberGroupSeparator = "-"; Console.WriteLine("NumberGroupSeparator: {0}", n.NumberGroupSeparator);
U V W X Y Z
2364
Contents | Index
System.Globalization
NumberFormatInfo NumberGroupSizes Property
Decimal d = 42000000; string s = "N"; Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n));
A
}
B
}
C
}
D
The output is
E NumberGroupSeparator: , NumberGroupSeparator: 42000000 formatted with "N" yields 42-000-000.00
F G H
NumberFormatInfo.NumberGroupSizes Property
I
[ILASM]
J
.property class System.Int32[] NumberGroupSizes { public hidebysig specialname instance class System.Int32[] get_NumberGroupSizes() public hidebysig specialname instance void set_NumberGroupSizes(class System.Int32[] value) }
K L
[C#]
M
public int[] NumberGroupSizes { get; set; }
N
Summary
O
Gets or sets the number of digits in each group to the left of the decimal point for numeric values.
P Q
Description
R
All elements of the array except the last are required to be between 1 and 9, inclusive. The last element can be 0. The first element of the array defines the number of elements in the first group of digits located immediately to the left of the System.Globalization.NumberFormatInfo.NumberDecimalSeparator. Each subsequent element refers to the next group of digits located to the left of the previous group. If the last element of the array is not zero, any remaining digits are grouped based on the last element of the array. If the last element is zero, the remaining digits are not grouped. The culture-invariant value for this property is an array with a single element containing the value 3.
S T U V W X Y Z
2365
Contents | Index
NumberFormatInfo
System.Globalization
NumberGroupSizes Property
Exceptions Exception
Condition
System.ArgumentNullException
The array specified for a set operation is a null reference.
System.ArgumentOutOfRangeException
One of the elements in the array specified for a set operation is not between 0 and 9.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
A B C D E F G H
Example
I
using System; using System.Globalization;
J namespace Samples { public class NumberFormatInfoNumberGroupSizes { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.Write("NumberGroupSizes: "); int[] integers = n.NumberGroupSizes; foreach(int i in integers) Console.Write(i); Console.WriteLine(); n.NumberGroupSizes = new int[]{2, 4}; Console.Write("NumberGroupSizes: "); integers = n.NumberGroupSizes; foreach(int i in integers) Console.Write(i); Console.WriteLine(); Decimal d = 42000000; string s = "N"; Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n)); } } }
K L M N O P Q R S T U V W X Y Z
2366
Contents | Index
System.Globalization
NumberFormatInfo NumberNegativePattern Property
The output is NumberGroupSizes: 3 NumberGroupSizes: 24 42000000 formatted with "N" yields 42,0000,00.00
A B C
NumberFormatInfo.NumberNegativePattern Property
D
[ILASM]
E
.property int32 NumberNegativePattern { public hidebysig specialname instance int32 get_NumberNegativePattern() public hidebysig specialname instance void set_NumberNegativePattern(int32 value) }
F G
[C#]
public int NumberNegativePattern { get; set; }
H
Summary
I
Gets or sets the format of negative values.
J K
Property Value
L
A System.Int32 between 0 and 4 inclusive that specifies the format of negative values.
M
Description
N
The following table describes the valid values for this property. “–” is used as the value for System.Globalization.NumberFormatInfo.NegativeSign, and 999 represents any numeric value.
O P Q R
Value
Pattern
S
0
(999)
T
1
–999
2
– 999
3
999–
X
4
999 –
Y
U V W
Z
The culture-invariant value for this property is 1.
2367
Contents | Index
NumberFormatInfo
System.Globalization
NumberNegativePattern Property
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
The value specified for a set operation is less than 0 or greater than 4.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
A B C D E F
Example
G
using System; using System.Globalization;
H namespace Samples { public class NumberFormatInfoNumberNegativePattern { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("NumberNegativePattern: {0}", n.NumberNegativePattern); decimal d = -4200000; string s = "N"; for(int i = 0; i < 5; i++) { n.NumberNegativePattern = i; Console.Write("NumberNegativePattern: {0} ,", i); Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n)); } } } }
I J K L M N O P Q R S T U V W
The output is
X NumberNegativePattern: NumberNegativePattern: NumberNegativePattern: NumberNegativePattern: NumberNegativePattern: NumberNegativePattern:
Y Z
1 0 1 2 3 4
,-4200000 ,-4200000 ,-4200000 ,-4200000 ,-4200000
formatted formatted formatted formatted formatted
with with with with with
"N" "N" "N" "N" "N"
yields yields yields yields yields
(4,200,000.00) -4,200,000.00 - 4,200,000.00 4,200,000.004,200,000.00 -
2368
Contents | Index
System.Globalization
NumberFormatInfo PercentDecimalDigits Property
NumberFormatInfo.PercentDecimalDigits Property [ILASM]
.property int32 PercentDecimalDigits { public hidebysig specialname instance int32 get_PercentDecimalDigits() public hidebysig specialname instance void set_PercentDecimalDigits(int32 value) }
A B
[C#]
C
public int PercentDecimalDigits { get; set; }
D
Summary
E
Gets or sets the number of decimal places in percent values.
F
Description
G
The culture-invariant value for this property is 2.
H I
Exceptions
J
Exception
Condition
System.ArgumentOutOfRangeException
The value specified for a set operation is less than 0 or greater than 99.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
K L M N O P
Example
Q
using System; using System.Globalization;
R S
namespace Samples { public class NumberFormatInfoPercentDecimalDigits { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("PercentDecimalDigits: {0}", n.PercentDecimalDigits); n.PercentDecimalDigits = 3; Console.WriteLine("PercentDecimalDigits: {0}", n.PercentDecimalDigits); decimal d = 42;
T U V W X Y Z
2369
Contents | Index
NumberFormatInfo
System.Globalization
PercentDecimalSeparator Property
string s = "P"; Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n));
A
} }
B }
C
The output is
D E
PercentDecimalDigits: 2 PercentDecimalDigits: 3 42 formatted with "P" yields 4,200.000 %
F G H
NumberFormatInfo.PercentDecimalSeparator Property
I [ILASM]
J K
.property string PercentDecimalSeparator { public hidebysig specialname instance string get_PercentDecimalSeparator() public hidebysig specialname instance void set_PercentDecimalSeparator(string value) }
L
[C#]
public string PercentDecimalSeparator { get; set; }
M N
Summary
O
Gets or sets the symbol used as the decimal separator in percent values.
P
Description
Q
The culture-invariant value for this property is “.”.
R S
Exceptions
T U V
Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
W X Y Z
2370
Contents | Index
System.Globalization
NumberFormatInfo PercentGroupSeparator Property
Example using System; using System.Globalization;
A namespace Samples { public class NumberFormatInfoPercentDecimalSeparator { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("PercentDecimalSeparator: {0}", n.PercentDecimalSeparator); n.PercentDecimalSeparator = "!"; Console.WriteLine("PercentDecimalSeparator: {0}", n.PercentDecimalSeparator); decimal d = 42; string s = "P"; Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n)); } } }
B C D E F G H I J K L M N
The output is
O P
PercentDecimalSeparator: . PercentDecimalSeparator: ! 42 formatted with "P" yields 4,200!00 %
Q R S
NumberFormatInfo.PercentGroupSeparator Property
T
[ILASM]
U
.property string PercentGroupSeparator { public hidebysig specialname instance string get_PercentGroupSeparator() public hidebysig specialname instance void set_PercentGroupSeparator(string value) }
V
[C#]
W
public string PercentGroupSeparator { get; set; }
X Y
Summary
Z
Gets or sets the symbol used to separate groups of digits to the left of the decimal point in percent values.
2371
Contents | Index
NumberFormatInfo
System.Globalization
PercentGroupSeparator Property
Description The culture-invariant value for this property is “,”. A
Exceptions
B C
Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
D E F G H I
Example
J
using System; using System.Globalization;
K
namespace Samples { public class NumberFormatInfoPercentGroupSeparator { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("PercentGroupSeparator: {0}", n.PercentGroupSeparator); n.PercentGroupSeparator = "-"; Console.WriteLine("PercentGroupSeparator: {0}", n.PercentGroupSeparator); decimal d = 42; string s = "P"; Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n)); } } }
L M N O P Q R S T U V W X
The output is
Y Z
PercentGroupSeparator: , PercentGroupSeparator: 42 formatted with "P" yields 4-200.00 %
2372
Contents | Index
System.Globalization
NumberFormatInfo PercentGroupSizes Property
NumberFormatInfo.PercentGroupSizes Property [ILASM]
.property class System.Int32[] PercentGroupSizes { public hidebysig specialname instance class System.Int32[] get_PercentGroupSizes() public hidebysig specialname instance void set_PercentGroupSizes(class System.Int32[] value) }
A B
[C#]
C
public int[] PercentGroupSizes { get; set; }
D
Summary
E
Gets or sets the number of digits in each group to the left of the decimal point in percent values.
F G
Description
H
All elements of the array except the last are required to be between 1 and 9, inclusive. The last element can be 0. The first element of the array defines the number of elements in the first group of digits located immediately to the left of the System.Globalization.NumberFormatInfo.PercentDecimalSeparator. Each subsequent element refers to the next group of digits located to the left of the previous group. If the last element of the array is not zero, any remaining digits are grouped based on the last element of the array. If the last element is zero, the remaining digits are not grouped. The culture-invariant value for this property is an array with a single element containing the value 3.
I J K L M N O P
Exceptions
Q
Exception
Condition
System.ArgumentNullException
The array specified for a set operation is a null reference.
System.ArgumentOutOfRangeException
One of the elements in the array specified for a set operation is not between 0 and 9.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
R S T U V W X Y Z
2373
Contents | Index
NumberFormatInfo
System.Globalization
PercentNegativePattern Property
Example using System; using System.Globalization;
A namespace Samples { public class NumberFormatInfoPercentGroupSizes { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.Write("PercentGroupSizes: "); int[] integers = n.PercentGroupSizes; foreach(int i in integers) Console.Write(i); Console.WriteLine(); n.PercentGroupSizes = new int[]{2, 4}; Console.Write("PercentGroupSizes: "); integers = n.PercentGroupSizes; foreach(int i in integers) Console.Write("{0} ", i); Console.WriteLine(); Decimal d = 420000; string s = "P"; Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n)); } } }
B C D E F G H I J K L M N O P Q R
The output is
S
PercentGroupSizes: 3 PercentGroupSizes: 2 4 420000 formatted with "P" yields 42,0000,00.00 %
T U V W
NumberFormatInfo.PercentNegativePattern Property
X [ILASM]
Y
.property int32 PercentNegativePattern { public hidebysig specialname instance int32 get_PercentNegativePattern() public hidebysig specialname instance void set_PercentNegativePattern(int32 value) }
Z
[C#]
public int PercentNegativePattern { get; set; }
2374
Contents | Index
System.Globalization
NumberFormatInfo PercentNegativePattern Property
Summary Gets or sets the format of negative percent values.
Property Value
A
A System.Int32 between 0 and 2 inclusive that specifies the format of negative percent values.
B C D
Description
E
The following table describes the valid values for this property. “%” is used as the value for System.Globalization.NumberFormatInfo.PercentSymbol, “–” is used as the value for System.Globalization.NumberFormatInfo.NegativeSign, and 999 represents any numeric value.
F G H I
Value
Pattern
J
0
–999 %
K
1
–999%
2
–%999
L M N O
The culture-invariant value for this property is 0.
P Q
Exceptions
R
Exception
Condition
System.ArgumentOutOfRangeException
The value specified for a set operation is less than 0 or greater than 2.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
S T U V W X Y Z
2375
Contents | Index
NumberFormatInfo
System.Globalization
PercentPositivePattern Property
Example using System; using System.Globalization;
A namespace Samples { public class NumberFormatInfoNumberPercentNegativePattern { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("PercentNegativePattern: {0}", n.PercentNegativePattern); decimal d = -42000; string s = "P"; for(int i = 0; i < 3; i++) { n.PercentNegativePattern = i; Console.Write("PercentNegativePattern: {0} ,", i); Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n)); } } } }
B C D E F G H I J K L M N O P
The output is
Q R
PercentNegativePattern: PercentNegativePattern: PercentNegativePattern: PercentNegativePattern:
S T
0 0 ,-42000 formatted with "P" yields -4,200,000.00 % 1 ,-42000 formatted with "P" yields -4,200,000.00% 2 ,-42000 formatted with "P" yields -%4,200,000.00
U V
NumberFormatInfo.PercentPositivePattern Property
W
[ILASM]
.property int32 PercentPositivePattern { public hidebysig specialname instance int32 get_PercentPositivePattern() public hidebysig specialname instance void set_PercentPositivePattern(int32 value) }
X Y
[C#]
Z
public int PercentPositivePattern { get; set; }
2376
Contents | Index
System.Globalization
NumberFormatInfo PercentPositivePattern Property
Summary Gets or sets the format of positive percent values.
Description
A
The following table describes the valid values for this property. “%” is used as the value for System.Globalization.NumberFormatInfo.PercentSymbol, and 999 represents a numeric value.
B C D E
Value
Pattern
F
0
999 %
G
1
999%
2
%999
H I J K
The culture-invariant value for this property is 0.
L M
Exceptions
N
Exception
Condition
System.ArgumentOutOfRangeException
The value specified for a set operation is less than 0 or greater than 2.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
O P Q R S T
Example
U
using System; using System.Globalization;
V W
namespace Samples { public class NumberFormatInfoPercentPositivePattern { public static void Main() { CultureInfo c = new CultureInfo("en-NZ");
X Y Z
2377
Contents | Index
NumberFormatInfo
System.Globalization
PercentSymbol Property
NumberFormatInfo n = c.NumberFormat; Console.WriteLine("PercentPositivePattern: {0}", n.PercentPositivePattern); decimal d = 42000; string s = "P"; for(int i = 0; i < 3; i++) { n.PercentPositivePattern = i; Console.Write("PercentPositivePattern: {0} ,", i); Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n)); }
A B C D E F G
}
H
} }
I
The output is
J K
PercentPositivePattern: PercentPositivePattern: PercentPositivePattern: PercentPositivePattern:
L M
0 0 ,42000 formatted with "P" yields 4,200,000.00 % 1 ,42000 formatted with "P" yields 4,200,000.00% 2 ,42000 formatted with "P" yields %4,200,000.00
N O
NumberFormatInfo.PercentSymbol Property
P
[ILASM]
.property string PercentSymbol { public hidebysig specialname instance string get_PercentSymbol() public hidebysig specialname instance void set_PercentSymbol(string value) }
Q R
[C#]
S
public string PercentSymbol { get; set; }
T U
Summary
V
Gets or sets the symbol that represents percentage values.
W
Description
X
The culture-invariant value for this property is “%”.
Y Z
2378
Contents | Index
System.Globalization
NumberFormatInfo PercentSymbol Property
Exceptions Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
A B C D E
Example
F
using System; using System.Globalization;
G H
namespace Samples { public class NumberFormatInfoPercentSymbol { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("PercentSymbol: {0}", n.PercentSymbol); n.PercentSymbol = "#"; Console.WriteLine("PercentSymbol: {0}", n.PercentSymbol); decimal d = 420; string s = "P"; Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n)); } } }
I J K L M N O P Q R S T U
The output is
V W
PercentSymbol: % PercentSymbol: # 420 formatted with "P" yields 42,000.00 #
X Y Z
2379
Contents | Index
NumberFormatInfo
System.Globalization
PerMilleSymbol Property
NumberFormatInfo.PerMilleSymbol Property [ILASM]
.property string PerMilleSymbol { public hidebysig specialname instance string get_PerMilleSymbol() public hidebysig specialname instance void set_PerMilleSymbol(string value) }
A B
[C#]
C
public string PerMilleSymbol { get; set; }
D
Summary
E
Gets or sets the per mille symbol.
F G
Description
H
The culture-invariant value for this property is “‰”.
I
Exceptions
J K L
Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
M N O P
Example
Q
using System; using System.Globalization;
R
namespace Samples { public class NumberFormatInfoPerMilleSymbol { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("PerMilleSymbol: {0}", n.PerMilleSymbol); n.PerMilleSymbol = "#"; Console.WriteLine("PerMilleSymbol: {0}", n.PerMilleSymbol); } } }
S T U V W X Y Z
2380
Contents | Index
System.Globalization
NumberFormatInfo PositiveInfinitySymbol Property
The output is PerMilleSymbol: % PerMilleSymbol: #
A B
NumberFormatInfo.PositiveInfinitySymbol Property
C
[ILASM]
D
.property string PositiveInfinitySymbol { public hidebysig specialname instance string get_PositiveInfinitySymbol() public hidebysig specialname instance void set_PositiveInfinitySymbol(string value) }
E F
[C#]
G
public string PositiveInfinitySymbol { get; set; }
H
Summary
I
Gets or sets the symbol that represents positive infinity.
J
Description
K
The culture-invariant value for this property is “Infinity”. [Note: For more information on positive infinity, see System.Double or System.Single.]
L M N
Exceptions
O P
Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
Q R S T U V
Example
W
using System; using System.Globalization;
X Y
namespace Samples { public class NumberFormatInfoPositiveInfinitySymbol { public static void Main()
Z
2381
Contents | Index
NumberFormatInfo
System.Globalization
PositiveSign Property
{ CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("PositiveInfinitySymbol: {0}", n.PositiveInfinitySymbol); n.PositiveInfinitySymbol = "Positive Infinity"; Console.WriteLine("PositiveInfinitySymbol: {0}", n.PositiveInfinitySymbol); Double d = Double.PositiveInfinity; string s = "G"; Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", d, s, d.ToString(s, n));
A B C D E F }
G
}
H
}
I
The output is
J PositiveInfinitySymbol: Infinity PositiveInfinitySymbol: Positive Infinity Infinity formatted with "G" yields Positive Infinity
K L M N
NumberFormatInfo.PositiveSign Property
O
[ILASM]
.property string PositiveSign { public hidebysig specialname instance string get_PositiveSign() public hidebysig specialname instance void set_PositiveSign(string value) }
P Q
[C#]
R
public string PositiveSign { get; set; }
S
Summary
T
Gets or sets the symbol used to represent positive values.
U V
Description
W
The culture-invariant value for this property is “+”.
X Y Z
2382
Contents | Index
System.Globalization
NumberFormatInfo PositiveSign Property
Exceptions Exception
Condition
System.ArgumentNullException
The value specified for a set operation is a null reference.
System.InvalidOperationException
The current instance is read-only and a set operation was attempted.
A B C D E
Example
F
using System; using System.Globalization;
G H
namespace Samples { public class NumberFormatInfoPositiveSign { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("PositiveSign: {0}", n.PositiveSign); n.PositiveSign = "plus"; Console.WriteLine("PositiveSign: {0}", n.PositiveSign); int i = 42; string s = "E"; Console.WriteLine( "{0} formatted with \"{1}\" yields {2}", i, s, i.ToString(s, n)); } } }
I J K L M N O P Q R S T U V
The output is
W PositiveSign: + PositiveSign: plus 42 formatted with "E" yields 4.200000Eplus001
X Y Z
2383
Contents | Index
NumberFormatInfo
System.Globalization
Clone() Method
NumberFormatInfo.Clone() Method [ILASM]
.method public final hidebysig virtual object Clone()
A
[C#]
public object Clone()
B C
Summary
D
Creates a copy of the current instance.
E
Description
F
The System.Globalization.NumberFormatInfo.Clone method returns a new instance of System.Globalization.NumberFormatInfo with property values that are equal to the property values of the current instance. If the current instance is read-only, the clone is also read-only. [Note: This method is implemented to support the System.ICloneable interface.]
G H I J K L
NumberFormatInfo.GetFormat(System.Type) Method
M
[ILASM]
N
.method public final hidebysig virtual object GetFormat(class System.Type formatType)
O
[C#]
public object GetFormat(Type formatType)
P Q
Summary
R
Returns an object of the specified type that provides formatting services.
S
Parameters
T U V
Parameter
Description
formatType
The System.Type of the formatting object to be returned.
W X
Return Value
Y
A formatting object of the specified System.Type. If no formatting object of the specified type is available, or formatType is a null reference, returns the formatting object for the current culture.
Z
2384
Contents | Index
System.Globalization
NumberFormatInfo GetInstance() Method
Description [Note: This method is implemented to support the System.IFormatProvider interface.] A
NumberFormatInfo.GetInstance(System.IFormatProvider) Method
B
[ILASM]
C
.method public hidebysig static class System.Globalization.NumberFormatInfo GetInstance(class System.IFormatProvider formatProvider)
D
[C#]
E
public static NumberFormatInfo GetInstance(IFormatProvider formatProvider)
F
Summary
G
Gets the System.Globalization.NumberFormatInfo associated with the specified System.IFormatProvider.
H
Parameters
J
I
K
Parameter
formatProvider
Description
L
The System.IFormatProvider used to get the System.Globalization.NumberFormatInfo.
M N
-orO
null to get System.Globalization.NumberFormatInfo.CurrentInfo.
P Q
Description
R
This method uses the System.IFormatProvider.GetFormat method of formatProvider using System.Globalization.NumberFormatInfo as the type parameter. If formatProvider is null or if System.IFormatProvider.GetFormat returns null, this method returns System.Globalization.NumberFormatInfo.CurrentInfo. You can get a System.Globalization.NumberFormatInfo for a specific culture using one of the following methods:
S
• •
T U V W
Through the System.Globalization.CultureInfo.NumberFormat property. Through the System.Globalization.NumberFormatInfo.GetInstance method where formatProvider is a System.Globalization.CultureInfo.
X Y Z
A System.Globalization.NumberFormatInfo can be created only for the invariant culture or for specific cultures, not for neutral cultures. For more information about the 2385
Contents | Index
NumberFormatInfo
System.Globalization
ReadOnly() Method
invariant culture, specific cultures, and neutral cultures, see the System.Globalization.CultureInfo class. A
NumberFormatInfo.ReadOnly(System.Globalization.NumberFormatInfo) Method
B C
[ILASM]
D
.method public hidebysig static class System.Globalization.NumberFormatInfo ReadOnly(class System.Globalization.NumberFormatInfo nfi)
E
[C#]
F
public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi)
G H
Summary
I
Creates a read-only copy of the specified System.Globalization.NumberFormatInfo instance.
J
Parameters
K L M
Parameter
Description
nfi
A System.Globalization.NumberFormatInfo object to copy.
N O
Exceptions
P Q
Exception
Condition
R
System.ArgumentNullException
nfi is a null reference.
S T U V W X Y Z
2386
Contents | Index
System.Globalization
NumberFormatInfo ReadOnly() Method
Example using System; using System.Globalization;
A
namespace Samples { public class NumberFormatInfoReadOnly { public static void Main() { CultureInfo c = new CultureInfo("en-NZ"); NumberFormatInfo n = c.NumberFormat; Console.WriteLine("IsReadOnly: {0}", n.IsReadOnly); n = NumberFormatInfo.ReadOnly(n); Console.WriteLine("IsReadOnly: {0}", n.IsReadOnly); } } }
B C D E F G H I J
The output is
K L
IsReadOnly: False IsReadOnly: True
M N O P Q R S T U V W X Y Z
2387
Contents | Index
System.Globalization NumberStyles Enum
BCL
Object
A
IComparable
ValueType
B
Enum
IFormattable NumberStyles
C
IConvertible
NotStandardized
D
Summary
E
Specifies styles for System.String representations of numeric values.
F G
Type Summary public enum NumberStyles { AllowCurrencySymbol = 0x100, AllowDecimalPoint = 0x20, AllowExponent = 0x80, AllowHexSpecifier = 0x200, AllowLeadingSign = 0x4, AllowLeadingWhite = 0x1, AllowParentheses = 0x10, AllowThousands = 0x40, AllowTrailingSign = 0x8, AllowTrailingWhite = 0x2, Any = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign | AllowParentheses | AllowDecimalPoint | AllowThousands | AllowExponent | AllowCurrencySymbol, Currency = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign | AllowParentheses | AllowDecimalPoint | AllowThousands | AllowCurrencySymbol, Float = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowDecimalPoint | AllowExponent, HexNumber = AllowLeadingWhite | AllowTrailingWhite | AllowHexSpecifier, Integer = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign, None = 0x0, Number = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign | AllowDecimalPoint | AllowThousands, }
H I J K L M N O P Q R S T U V W X
BA This class is great example of defining the common combination of flags so that most users will not have to figure out how to put bitwise OR values together.
Y Z
2388
Contents | Index
System.Globalization
NumberStyles Enum NumberStyles Enum
Description System.Globalization.NumberStyles define the presence and/or location of various elements in a System.String representation of a numeric value. [Note: For example, the System.Globalization.NumberStyles.AllowParentheses style describes strings where the numeric value is enclosed in parentheses, such as “(432.00)”.] [Note: Where symbols such as a currency symbol are allowed in a System.Globalization.NumberStyles pattern, a System.Globalization.NumberFormatInfo instance defines the System.String representations of the symbols. System.Globalization.NumberStyles values are passed to methods that convert between System.String and numeric data types, such as the Parse methods implemented by numeric base types. To specify multiple System.Globalization.NumberStyles values, use the bitwise OR operator. For a list of the valid white space characters, see the System.String class.]
A B C D E F G H
Example
I
using System; using System.Globalization;
J K
namespace Samples { public class NumberStylesSample { public static void Main() { string s = "$42"; Console.WriteLine("Convert from String {0} yields {1}", s, Int32.Parse(s, NumberStyles.AllowCurrencySymbol)); s = "42.0"; Console.WriteLine("Convert from String {0} yields {1}", s, Int32.Parse(s, NumberStyles.AllowDecimalPoint)); s = "3.40282347E+38"; Console.WriteLine("Convert from String {0} yields {1}", s, Single.Parse(s, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint)); s = "2A"; Console.WriteLine("Convert from String {0} yields {1}", s, Int32.Parse(s, NumberStyles.AllowHexSpecifier)); s = "+42"; Console.WriteLine("Convert from String {0} yields {1}", s, Int32.Parse(s, NumberStyles.AllowLeadingSign));
L M N O P Q R S T U V W X Y Z
2389
Contents | Index
NumberStyles Enum
System.Globalization
NumberStyles Enum
s = "\n\t 42"; Console.WriteLine("Convert from String {0} yields {1}", s, Int32.Parse(s, NumberStyles.AllowLeadingWhite)); s = "(42)"; Console.WriteLine("Convert from String {0} yields {1}", s, Int32.Parse(s, NumberStyles.AllowParentheses)); s = "4,242"; Console.WriteLine("Convert from String {0} yields {1}", s, Int32.Parse(s, NumberStyles.AllowThousands)); s = "42-"; Console.WriteLine("Convert from String {0} yields {1}", s, Int32.Parse(s, NumberStyles.AllowTrailingSign)); s = "42\n\t "; Console.WriteLine("Convert from String {0} yields {1}", s, Int32.Parse(s, NumberStyles.AllowTrailingWhite)); s = "\n\t (42.0) "; Console.WriteLine("Convert from String {0} yields {1}", s, Int32.Parse(s, NumberStyles.Any)); s = "\t $4242.0 "; Console.WriteLine("Convert from String {0} yields {1}", s, Int32.Parse(s, NumberStyles.Currency)); s = "\t +3.40282347E+38 "; Console.WriteLine("Convert from String {0} yields {1}", s, Single.Parse(s, NumberStyles.Float)); s = " 2A "; Console.WriteLine("Convert from String {0} yields {1}", s, Int32.Parse(s, NumberStyles.HexNumber)); s = " +42 "; Console.WriteLine("Convert from String {0} yields {1}", s, Int32.Parse(s, NumberStyles.Integer)); s = "42"; Console.WriteLine("Convert from String {0} yields {1}", s, Int32.Parse(s, NumberStyles.None));
A B C D E F G H I J K L M N O P Q R S T U V W X Y }
Z
} }
2390
Contents | Index
System.Globalization
NumberStyles Enum AllowDecimalPoint Field
The output is Convert from String Convert from String Convert from String Convert from String Convert from String Convert from String 42 yields 42 Convert from String Convert from String Convert from String Convert from String yields 42 Convert from String (42.0) yields -42 Convert from String Convert from String Convert from String Convert from String Convert from String
$42 yields 42 42.0 yields 42 3.40282347E+38 yields 3.402823E+38 2A yields 42 +42 yields 42
A B C D
(42) yields -42 4,242 yields 4242 42- yields -42 42
E F G H
$4242.0 yields 4242 +3.40282347E+38 yields 3.402823E+38 2A yields 42 +42 yields 42 42 yields 42
I J K L M
NumberStyles.AllowCurrencySymbol Field
N [ILASM]
O
.field public static literal valuetype System.Globalization.NumberStyles AllowCurrencySymbol
P
[C#]
AllowCurrencySymbol = 0x100
Q R
Summary
S
Specifies that a currency symbol is allowed. [Note: See System.Globalization.NumberFormatInfo.CurrencySymbol.]
T U V
NumberStyles.AllowDecimalPoint Field
W [ILASM]
X
.field public static literal valuetype System.Globalization.NumberStyles AllowDecimalPoint
Y
[C#]
AllowDecimalPoint = 0x20
Z
2391
Contents | Index
NumberStyles Enum
System.Globalization
AllowExponent Field
Summary Specifies that a decimal point is allowed. [Note: See System.Globalization.NumberFormatInfo.NumberDecimalSeparator, System.Globalization.NumberFormatInfo.PercentDecimalSeparator, and System.Globalization.NumberFormatInfo.CurrencyDecimalSeparator.]
A B C D
NumberStyles.AllowExponent Field
E
[ILASM]
F
.field public static literal valuetype System.Globalization.NumberStyles AllowExponent
G
[C#]
AllowExponent = 0x80
H I
Summary
J
Specifies that exponential notation is allowed. This style is used for values in one of the following forms:
K L
[-]m.ddddddE+xx [-]m.ddddddE-xx [-]m.dddddde+xx [-]m.dddddde-xx
M N O
One or more non-zero digits (m) precede the decimal separator (“.”). A minus sign (“–”) can precede m. The type performing the conversion determines the number of decimal places (dddddd) in the string, and maximum and minimum values for xx and m. The exponent (+/–xx) consists of either a plus or minus sign followed by at least one digit.
P Q R S
NumberStyles.AllowHexSpecifier Field
T
[ILASM]
U
.field public static literal valuetype System.Globalization.NumberStyles AllowHexSpecifier
V
[C#]
W
AllowHexSpecifier = 0x200
X Y
Summary
Z
Specifies that hexadecimal representation (Base 16) is allowed. Valid hexadecimal values include the numeric digits 0–9 and the hexadecimal digits A–F, and a–f. The hexadecimal
2392
Contents | Index
System.Globalization
NumberStyles Enum AllowParentheses Field
digits can be in upper- or lowercase. Hexadecimal values can be left-padded with zeros. Strings parsed using this style are not permitted to be prefixed with “0x”. A
NumberStyles.AllowLeadingSign Field
B
[ILASM]
C
.field public static literal valuetype System.Globalization.NumberStyles AllowLeadingSign
D
[C#]
E
AllowLeadingSign = 0x4
F
Summary
G
Specifies that a leading sign symbol is allowed. [Note: See System.Globalization.NumberFormatInfo.PositiveSign and System.Globalization.NumberFormatInfo.NegativeSign.]
H I J K
NumberStyles.AllowLeadingWhite Field
L
[ILASM]
.field public static literal valuetype System.Globalization.NumberStyles AllowLeadingWhite
M N
[C#]
AllowLeadingWhite = 0x1
O
Summary
P
Specifies that the string can be prefixed with white space characters.
Q R
NumberStyles.AllowParentheses Field
S
[ILASM]
T
.field public static literal valuetype System.Globalization.NumberStyles AllowParentheses
U
[C#]
V
AllowParentheses = 0x10
W
Summary
X
Specifies that one pair of balanced parentheses is allowed.
Y Z
2393
Contents | Index
NumberStyles Enum
System.Globalization
AllowThousands Field
NumberStyles.AllowThousands Field [ILASM]
A
.field public static literal valuetype System.Globalization.NumberStyles AllowThousands
B
[C#]
AllowThousands = 0x40
C D
Summary
E
Specifies that group separators are allowed; for instance, separating the hundreds from the thousands. [Note: See System.Globalization.NumberFormatInfo.NumberGroupSeparator, System.Globalization.NumberFormatInfo.PercentGroupSeparator, and System.Globalization.NumberFormatInfo.CurrencyGroupSeparator.]
F G H I
NumberStyles.AllowTrailingSign Field
J
[ILASM]
.field public static literal valuetype System.Globalization.NumberStyles AllowTrailingSign
K L
[C#]
AllowTrailingSign = 0x8
M N
Summary
O
Specifies that a trailing sign symbol is allowed. [Note: See System.Globalization.NumberFormatInfo.PositiveSign and System.Globalization.NumberFormatInfo.NegativeSign.]
P Q R S
NumberStyles.AllowTrailingWhite Field
T
[ILASM]
U
.field public static literal valuetype System.Globalization.NumberStyles AllowTrailingWhite [C#]
V
AllowTrailingWhite = 0x2
W X
Summary
Y
Specifies that the string can be suffixed with white space characters.
Z
2394
Contents | Index
System.Globalization
NumberStyles Enum Currency Field
NumberStyles.Any Field [ILASM]
.field public static literal valuetype System.Globalization.NumberStyles Any
A
[C#]
Any = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign | AllowParentheses | AllowDecimalPoint | AllowThousands | AllowExponent | AllowCurrencySymbol
B C D
Summary
E
Specifies that System.Globalization.NumberStyles.AllowLeadingWhite, System.Globalization.NumberStyles.AllowTrailingWhite, System.Globalization.NumberStyles.AllowLeadingSign, System.Globalization.NumberStyles.AllowTrailingSign, System.Globalization.NumberStyles.AllowParentheses, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.NumberStyles.AllowThousands, System.Globalization.NumberStyles.AllowCurrencySymbol and System.Globalization.NumberStyles.AllowExponent styles are allowed.
F G H I J K L
NumberStyles.Currency Field
M
[ILASM]
N
.field public static literal valuetype System.Globalization.NumberStyles Currency
O
[C#]
Currency = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign | AllowParentheses | AllowDecimalPoint | AllowThousands | AllowCurrencySymbol
P Q R
Summary
S
Specifies that System.Globalization.NumberStyles.AllowLeadingWhite, System.Globalization.NumberStyles.AllowTrailingWhite, System.Globalization.NumberStyles.AllowLeadingSign, System.Globalization.NumberStyles.AllowTrailingSign, System.Globalization.NumberStyles.AllowParentheses, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.NumberStyles.AllowThousands, and System.Globalization.NumberStyles.AllowCurrencySymbol styles are allowed.
T U V W X Y Z
2395
Contents | Index
NumberStyles Enum
System.Globalization
Float Field
NumberStyles.Float Field [ILASM]
.field public static literal valuetype System.Globalization.NumberStyles Float
A
[C#]
Float = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowDecimalPoint | AllowExponent
B C D
Summary
E
Specifies that System.Globalization.NumberStyles.AllowLeadingWhite, System.Globalization.NumberStyles.AllowTrailingWhite, System.Globalization.NumberStyles.AllowLeadingSign, System.Globalization.NumberStyles.AllowDecimalPoint, and System.Globalization.NumberStyles.AllowExponent styles are allowed.
F G H I J
NumberStyles.HexNumber Field
K
[ILASM]
L
.field public static literal valuetype System.Globalization.NumberStyles HexNumber
M
HexNumber = AllowLeadingWhite | AllowTrailingWhite | AllowHexSpecifier
[C#]
N
Summary
O
Specifies that System.Globalization.NumberStyles.AllowLeadingWhite, System.Globalization.NumberStyles.AllowTrailingWhite, System.Globalization.NumberStyles.AllowHexSpecifier styles are allowed.
P Q R S
NumberStyles.Integer Field
T
[ILASM]
.field public static literal valuetype System.Globalization.NumberStyles Integer
U
[C#]
V
Integer = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign
W
Summary
X
Specifies that System.Globalization.NumberStyles.AllowLeadingWhite, System.Globalization.NumberStyles.AllowTrailingWhite, and System.Globalization.NumberStyles.AllowLeadingSign styles are allowed.
Y Z
2396
Contents | Index
System.Globalization
NumberStyles Enum Number Field
NumberStyles.None Field [ILASM]
.field public static literal valuetype System.Globalization.NumberStyles None [C#]
A
None = 0x0
B C
Summary
D
Specifies that no styles are allowed.
E F
NumberStyles.Number Field
G
[ILASM]
H
.field public static literal valuetype System.Globalization.NumberStyles Number [C#]
I
Number = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign | AllowDecimalPoint | AllowThousands
J K
Summary
L
Specifies that System.Globalization.NumberStyles.AllowLeadingWhite, System.Globalization.NumberStyles.AllowTrailingWhite, System.Globalization.NumberStyles.AllowLeadingSign, System.Globalization.NumberStyles.AllowTrailingSign, System.Globalization.NumberStyles.AllowDecimalPoint, and System.Globalization.NumberStyles.AllowThousands styles are allowed.
M N O P Q R S T U V W X Y Z
2397
Contents | Index
BCL
System Object
Summary Provides support for classes. This class is the root of the object hierarchy.
A B
Type Summary
C
public class Object { // Constructors public Object ();
D E F
// Methods public virtual bool Equals (object obj); CF public static bool Equals (object objA, object objB); ~object () ; public virtual int GetHashCode (); public Type GetType (); protected object MemberwiseClone (); CF public static bool ReferenceEquals (object objA, object objB); public virtual string ToString ();
G H I J K L
}
M N
BA The static Equals method on Object was a relatively late addition to the class.
O
We added it only after seeing a large number of utility versions of the same code. The common problem nearly everyone had with the instance version of Equals is that you had to make sure the value was not null before calling the Equals method. So to check to see if instances a and b were equal you had to write the error-prone code:
P Q R S
if (a != null && a.Equals(b) ) //they are equal
T
To make matters worse, in many cases if A and B are both null, they should be treated as equal. So that made the code completely untenable:
U V
if ((a == null && b == null) || (a != null && a.Equals(b)) //they are equal
W
After recognizing this pattern we decided to canonicalize it in the static Equals method of Object.
X Y
continued Z
2399
Contents | Index
Object
System
Object Class
JM As with any group of travelers, the ECMA standard committee had to come up with ways to amuse each other. Early on in the standardization effort, I fell victim to a classic standardization amusement. Each month the committee would go out to a local restaurant for dinner where someone would mention to the waitstaff that it was my birthday. This happened every month for almost a year and half. This class was discussed at my third “birthday” party.
A B C D
JR I think it’s unfortunate that Object offers Equals and GetHashCode methods since these concepts are meaningless for most types. And, IComparable exists which is a superset of Equals. The whole equality thing got kind of messed up. The semantic of Object’s Equals method is to offer value equality. However, Object’s Equals method is really identity: do the two object references refer to the same, exact object? On the other hand, ValueType’s Equals method is truly value equality, not identity. C#’s == operator does identity for reference types and value equality for value types. But a type can overload the == operator for reference types making it value equality. But a programmer can obtain identity for reference types by casting both sides of the == operator to Object ensuring that the overloaded == operator method doesn’t get called. In my Applied Microsoft .NET Framework Programming book, it took me about 10 pages to explain all the ins and outs of equality and identity.
E F G H I J K L M N O
Description
P
[Note: Classes derived from System.Object may override the following methods of the System.Object class:]
Q R
Example
S
using System;
T
namespace Samples { public class ObjectSample { public static void Main() { Object o = new Object(); Console.WriteLine("Are they equal: {0}", o.Equals(new Object())); Console.WriteLine("Are they equal: {0}", o.Equals(o)); Console.WriteLine("GetHashcode yields {0}", o.GetHashCode());
U V W X Y Z
2400
Contents | Index
System
Object Object() Constructor
Console.WriteLine("GetHashcode yields {0}", new Object().GetHashCode()); Console.WriteLine("o.ToString(): {0}", o.ToString()); }
A
} }
B C
The output is
D Are they equal: False Are they equal: True GetHashcode yields 3 GetHashcode yields 5 o.ToString(): System.Object
E F G H
Object() Constructor
I
[ILASM]
J
public rtspecialname specialname instance void .ctor()
K
[C#]
L
public Object()
M
Summary
N
Constructs a new instance of the System.Object class.
O
Usage
P
This constructor is called by constructors in derived classes, but it can also be used to directly create an instance of the Object class. This might be useful, for example, if you need to obtain a reference to an object so that you can synchronize on it, as might be the case when using the C# lock statement.
Q R S T
Example
U
using System; using System.Reflection;
V W
namespace Samples { public class ObjectConstructor { public static void Main() { Object o = new Object(); Console.WriteLine("Are they equal: {0}",
X Y Z
2401
Contents | Index
Object
System
Equals() Method
o.Equals(new Object())); Console.WriteLine("Are they equal: {0}", o.Equals(o)); Console.WriteLine("Are they equal: {0}", Object.Equals(o, new Object())); Console.WriteLine("Are they equal: {0}", Object.Equals(o, o)); Console.WriteLine("GetHashcode yields {0}", o.GetHashCode()); Console.WriteLine("GetHashcode yields {0}", new Object().GetHashCode());
A B C D E }
F
} }
G
The output is
H I
Are they equal: False Are they equal: True Are they equal: False Are they equal: True GetHashcode yields 3 GetHashcode yields 5
J K L M N
Object.Equals(System.Object) Method
O
[ILASM]
P
.method public hidebysig virtual bool Equals(object obj)
Q
[C#]
public virtual bool Equals(object obj)
R S
Summary
T
Determines whether the specified System.Object is equal to the current instance.
U
Parameters
V W X
Parameter
Description
obj
The System.Object to compare with the current instance.
Y Z
Return Value true if obj is equal to the current instance; otherwise, false. 2402
Contents | Index
System
Object Equals() Method
Behaviors The statements listed below are required to be true for all implementations of the System.Object.Equals method. In the list, x, y, and z represent non-null object references: A
• •
x.Equals(x) returns true. x.Equals(y) returns the same value as y.Equals(x).
• •
If (x.Equals(y) && y.Equals(z)) returns true, then x.Equals(z) returns true. Successive invocations of x.Equals(y) return the same value as long as the objects referenced by x and y are not modified. x.Equals(null) returns false for non-null x.
•
B C D E F G
See System.Object.GetHashCode for additional required behaviors pertaining to the System.Object.Equals method. [Note: Implementations of System.Object.Equals should not throw exceptions.]
H
Default
J
The System.Object.Equals method tests for referential equality, which means that System.Object.Equals returns true if the specified instance of Object and the current instance are the same instance; otherwise, it returns false.
K
I
L M
How and When to Override
N
For some kinds of objects, it is desirable to have System.Object.Equals test for value equality instead of referential equality. Such implementations of Equals return true if the two objects have the same “value”, even if they are not the same instance. The definition of what constitutes an object’s “value” is up to the implementer of the type, but it is typically some or all of the data stored in the instance variables of the object. For example, the value of a System.String is based on the characters of the string; the Equals method of the System.String class returns true for any two string instances that contain exactly the same characters in the same order. When the Equals method of a base class provides value equality, an override of Equals in a class derived from that base class should invoke the inherited implementation of Equals. It is recommended (but not required) that types overriding System.Object.Equals also override System.Object.GetHashCode. Hashtables cannot be relied on to work correctly if this recommendation is not followed. If your programming language supports operator overloading, and if you choose to overload the equality operator for a given type, that type should override the Equals method. Such implementations of the Equals method should return the same results as the equality operator. Following this guideline will help ensure that class library code
O P Q R S T U V W X Y Z
2403
Contents | Index
Object
System
Equals() Method
using Equals (such as System.Collections.ArrayList and System.Collections.Hashtable) behaves in a manner that is consistent with the way the equality operator is used by application code. If you are implementing a value type, you should follow these guidelines:
A B
•
C
•
D E
Consider overriding Equals to gain increased performance over that provided by the default implementation of Equals on System.ValueType. If you override Equals and the language supports operator overloading, you should overload the equality operator for your value type. For reference types, the guidelines are as follows:
F G
•
H I
•
J K L
•
M
Consider overriding Equals on a reference type if the semantics of the type are based on the fact that the type represents some value(s). For example, reference types such as Point and BigNumber should override Equals. Most reference types should not overload the equality operator, even if they override Equals. However, if you are implementing a reference type that is intended to have value semantics, such as a complex number type, you should override the equality operator. If you implement System.IComparable on a given type, you should override Equals on that type.
N
Usage
O
The System.Object.Equals method is called by methods in collections classes that perform search operations, including the System.Array.IndexOf method and the System.Collections.ArrayList.Contains method.
P Q R S
Example
T
Example 1
U
using System;
V
namespace Samples { public class ObjectEquals { public static void Main() { Object object1 = new Object(); Object object2 = new Object(); Console.WriteLine(object1.Equals(object2)); object1 = object2;
W X Y Z
2404
Contents | Index
System
Object Equals() Method
Console.WriteLine(object1.Equals(object2)); } } }
A
The output is
B C
False True
D
Example 2 The following example shows a Point class that overrides the System.Object.Equals method to provide value equality and a class Point3D, which is derived from Point. Because Point’s override of System.Object.Equals is the first in the inheritance chain to introduce value equality, the Equals method of the base class (which is inherited from System.Object and checks for referential equality) is not invoked. However, Point3D.Equals invokes Point.Equals because Point implements Equals in a manner that provides value equality.
E F G H I J K
using System;
L namespace Samples { public class Point: object { int x, y; public override bool Equals(Object o) { if(o == null || GetType() != o.GetType()) return false; Point p = (Point) o; return (x == p.x) && (y == p.y); } public override int GetHashCode() { return x ^ y; } } class Point3D: Point { int z; public override bool Equals(Object o) { return base.Equals(o) && z == ((Point3D)o).z; } public override int GetHashCode()
M N O P Q R S T U V W X Y Z
2405
Contents | Index
Object
System
Equals() Method
{ return base.GetHashCode() ^ z; } } public class ObjectEquals { public static void Main() { Point3D p = new Point3D(); Console.WriteLine("Equals: {0}", p.Equals(new Point3D())); Console.WriteLine("Hashcode: {0}", p.GetHashCode()); } }
A B C D E F }
G
The output is
H I
Equals: True Hashcode: 0
J K
The Point.Equals method checks that the o argument is non-null and that it references an instance of the same type as this object. If either of those checks fails, the method returns false. The System.Object.Equals method uses System.Object.GetType to determine whether the runtime types of the two objects are identical. (Note that typeof is not used here because it returns the static type.) If instead the method had used a check of the form o is Point; the check would return true in cases where obj is an instance of a subclass of Point, even though obj and the current instance are not of the same runtime type. Having verified that both objects are of the same type, the method casts o to type Point and returns the result of comparing the instance variables of the two objects. In Point3D.Equals, the inherited Equals method is invoked before anything else is done; the inherited Equals method checks to see that o is non-null, that o is an instance of the same class as this object, and that the inherited instance variables match. Only when the inherited Equals returns true does the method compare the instance variables introduced in the subclass. Specifically, the cast to Point3D is not executed unless o has been determined to be of type Point3D or a subclass of Point3D.
L M N O P Q R S T U V
Example 3 In the previous example, operator == (the equality operator) is used to compare the individual instance variables. In some cases, it is appropriate to use the System.Object.Equals method to compare instance variables in an Equals implementation, as shown in the following example:
W X Y Z
2406
Contents | Index
System
Object Equals() Method
using System; namespace Samples { public class Rectangle { Point a = new Point(), b = new Point(); public override bool Equals(Object o) { if(o == null || GetType() != o.GetType()) return false; Rectangle r = (Rectangle)o; return a.Equals(r.a) && b.Equals(r.b); } public override int GetHashCode() { return a.GetHashCode() ^ b.GetHashCode(); } } public class ObjectEquals { public static void Main() { Rectangle r = new Rectangle(); Console.WriteLine("Are they equal: {0}", Object.Equals(r, new Rectangle())); Console.WriteLine("Are they equal: {0}", r.Equals(r)); } } }
A B C D E F G H I J K L M N O P Q R
The output is
S Are they equal: True Are they equal: True
T U
Example 4 In some languages, such as C#, operator overloading is supported. When a type overloads operator ==, it should also override the System.Object.Equals method to provide the same functionality. This is typically accomplished by writing the Equals method in terms of the overloaded operator ==. For example:
V W X Y Z
2407
Contents | Index
Object
System
Equals() Method
using System; namespace Samples { public struct Complex { double re, im; public override bool Equals(Object obj) { return obj is Complex && this == (Complex)obj; } public override int GetHashCode() { return re.GetHashCode() ^ im.GetHashCode(); } public static bool operator ==(Complex x, Complex y) { return x.re == y.re && x.im == y.im; } public static bool operator !=(Complex x, Complex y) { return !(x == y); } } public class ObjectEquals { public static void Main() { Complex c = new Complex(); Console.WriteLine("Are they equal: {0}", Object.Equals( c, new Complex())); Console.WriteLine("Are they equal: {0}", Object.Equals(c, c)); } } }
A B C D E F G H I J K L M N O P Q R S T U
The output is
V
Are they equal: True Are they equal: True
W X
Because Complex is a C# struct (a value type), it is known that there will be no subclasses of Complex. Therefore, the System.Object.Equals method need not compare the GetType() results for each object, but can instead use the is operator to check the type of the obj parameter.
Y Z
2408
Contents | Index
System
Object Equals() Method
Example 5 using System; namespace Samples { public class ObjectEquals { private readonly string s; public ObjectEquals(string s) { this.s = s; } public override bool Equals(object o) { if(null == o) return false; if(this.GetType() != o.GetType()) return false; return Object.Equals(s, ((ObjectEquals)o).s); } public override int GetHashCode() { return s.GetHashCode(); } public static void Main() { Object o = new Object(); Console.WriteLine("Are they equal: {0}", o.Equals(new Object())); Console.WriteLine("Are they equal: {0}", o.Equals(o)); o = new ObjectEquals("damien"); Console.WriteLine("Are they equal: {0}", o.Equals(o)); Console.WriteLine("Are they equal: {0}", o.Equals(new ObjectEquals("damien"))); Console.WriteLine("Are they equal: {0}", o.Equals(new ObjectEquals("brad"))); } } }
A B C D E F G H I J K L M N O P Q R S T U V W X
The output is Are Are Are Are Are
they they they they they
equal: equal: equal: equal: equal:
Y
False True True True False
Z
2409
Contents | Index
Object
System
Equals() Method
Object.Equals(System.Object, System.Object) Method [ILASM]
.method public hidebysig static bool Equals(object objA, object objB)
A
[C#]
public static bool Equals(object objA, object objB)
B C
Summary
D
Determines whether two object references are equal.
E
Parameters
F G
Parameter
Description
I
objA
First object to compare.
J
objB
Second object to compare.
H
K L
Return Value
M
true if one or more of the following statements is true:
N
objA and objB refer to the same object, objA and objB are both null references, objA is not null and objA.Equals(objB) returns true;
O P
otherwise returns false.
Q R
Description
S
This static method checks for null references before it calls objA.Equals(objB) and returns false if either objA or objB is null. If the Equals(object obj) implementation throws an exception, this method throws an exception.
T U V
Example
W
using System;
X
namespace Samples { public class ObjectEquals { public static void Main() {
Y Z
2410
Contents | Index
System
Object Finalize() Method
Object o = new Object(); Console.WriteLine("Are they equal: {0}", Object.Equals( o, new Object())); Console.WriteLine("Are they equal: {0}", Object.Equals( o, o));
A B C
} }
D
}
E
The output is
F
Are they equal: False Are they equal: True
G H I
Object.Finalize() Method
J
[ILASM]
K
.method family hidebysig virtual void Finalize()
L
[C#]
~Object()
M
Summary
N
Allows a System.Object to perform cleanup operations before the memory allocated for the System.Object is automatically reclaimed.
O P Q
Behaviors
R
During execution, System.Object.Finalize is automatically called after an object becomes inaccessible, unless the object has been exempted from finalization by a call to System.GC.SuppressFinalize. During shutdown of an application domain, System.Object.Finalize is automatically called on objects that are not exempt from finalization, even those that are still accessible. System.Object.Finalize is automatically called only once on a given instance, unless the object is reregistered using a mechanism such as System.GC.ReRegisterForFinalize and System.GC.SuppressFinalize has not been subsequently called. Conforming implementations of the CLI are required to make every effort to ensure that for every object that has not been exempted from finalization, the System.Object.Finalize method is called after the object becomes inaccessible. However, there may be some circumstances under which Finalize is not called. Conforming CLI implementations are required to explicitly specify the conditions under which Finalize is not guaranteed to be
S T U V W X Y Z
2411
Contents | Index
Object
System
GetHashCode() Method
called. [Note: For example, Finalize might not be guaranteed to be called in the event of equipment failure, power failure, or other catastrophic system failures.] In addition to System.GC.ReRegisterForFinalize and System.GC.SuppressFinalize, conforming implementations of the CLI are allowed to provide other mechanisms that affect the behavior of System.Object.Finalize. Any mechanisms provided are required to be specified by the CLI implementation. The order in which the Finalize methods of two objects are run is unspecified, even if one object refers to the other. The thread on which Finalize is run is unspecified. Every implementation of System.Object.Finalize in a derived type is required to call its base type’s implementation of Finalize. This is the only case in which application code calls System.Object.Finalize.
A B C D E F G H
Default
I
The System.Object.Finalize implementation does nothing.
J
How and When to Override
K
A type should implement Finalize when it uses unmanaged resources such as file handles or database connections that must be released when the managed object that uses them is reclaimed. Because Finalize methods may be invoked in any order (including from multiple threads), synchronization may be necessary if the Finalize method may interact with other objects, whether accessible or not. Furthermore, since the order in which Finalize is called is unspecified, implementers of Finalize (or of destructors implemented through overriding Finalize) must take care to correctly handle references to other objects, as their Finalize method may already have been invoked. In general, referenced objects should not be considered valid during finalization. See the System.IDisposable interface for an alternate means of disposing of resources.
L M N O P Q R S T
Usage
U
For C# developers: Destructors are the C# mechanism for performing cleanup operations. Destructors provide appropriate safeguards, such as automatically calling the base type’s destructor. In C# code, System.Object.Finalize cannot be called or overridden.
V W X Y
Object.GetHashCode() Method
Z
[ILASM]
.method public hidebysig virtual int32 GetHashCode() [C#]
public virtual int GetHashCode()
2412
Contents | Index
System
Object GetHashCode() Method
Summary Generates a hash code for the current instance.
Description
A
System.Object.GetHashCode serves as a hash function for a specific type. [Note: A hash function is used to quickly generate a number (a hash code) corresponding to the value of an object. Hash functions are used with hashtables. A good hash function algorithm rarely generates hash codes that collide. For more information about hash functions, see The Art of Computer Programming, Vol. 3, by Donald E. Knuth.]
B C D E F
Behaviors
G
All implementations of System.Object.GetHashCode are required to ensure that for any two object references x and y, if x.Equals(y) == true, then x.GetHashCode() == y.GetHashCode(). Hash codes generated by System.Object.GetHashCode need not be unique. Implementations of System.Object.GetHashCode are not permitted to throw exceptions.
H I J K L
Default
M
The System.Object.GetHashCode implementation attempts to produce a unique hash code for every object, but the hash codes generated by this method are not guaranteed to be unique. Therefore, System.Object.GetHashCode may generate the same hash code for two different instances.
N O P
How and When to Override
Q
It is recommended (but not required) that types overriding System.Object.GetHashCode also override System.Object.Equals. Hashtables cannot be relied on to work correctly if this recommendation is not followed.
R
Usage
U
Use this method to obtain the hash code of an object. Hash codes should not be persisted (i.e., in a database or file) as they are allowed to change from run to run.
V
S T
W X Y Z
2413
Contents | Index
Object
System
GetHashCode() Method
Example Example 1 In some cases, System.Object.GetHashCode is implemented to simply return an integer value. The following example illustrates an implementation of System.Int32.GetHashCode, which returns an integer value:
A B C
using System;
D namespace Samples { public struct Int32 { int value; //other methods... public override int GetHashCode() { return value; } } }
E F G H I J K L
O
Example 2 Frequently, a type has multiple data members that can participate in generating the hash code. One way to generate a hash code is to combine these fields using an XOR (exclusive or) operation, as shown in the following example:
P
using System;
M N
Q
namespace Samples { public struct Point { int x; int y; //other methods... public override int GetHashCode() { return x ^ y; } } }
R S T U V W X Y
Example 3 The following example illustrates another case where the type’s fields are combined using XOR (exclusive or) to generate the hash code. Notice that in this example, the fields repre-
Z
2414
Contents | Index
System
Object GetHashCode() Method
sent user-defined types, each of which implements System.Object.GetHashCode (and should implement System.Object.Equals as well): using System;
A
namespace Samples { public class SomeType { public override int GetHashCode() { return 0; } } public class AnotherType { public override int GetHashCode() { return 1; } } public class LastType { public override int GetHashCode() { return 2; } } public class MyClass { SomeType a = new SomeType(); AnotherType b = new AnotherType(); LastType c = new LastType(); public override int GetHashCode () { return a.GetHashCode() ^ b.GetHashCode() ^ c.GetHashCode(); } } }
B C D E F G H I J K L M N O P Q R S T U V W
Avoid implementing System.Object.GetHashCode in a manner that results in circular references. In other words, if AClass.GetHashCode calls BClass.GetHashCode, it should not be the case that BClass.GetHashCode calls AClass.GetHashCode.
X Y Z
Example 4 In some cases, the data member of the class in which you are implementing System.Object.GetHashCode is bigger than a System.Int32. In such cases, you could combine 2415
Contents | Index
Object
System
GetHashCode() Method
the high-order bits of the value with the low-order bits using an XOR operation, as shown in the following example: A
using System;
B
namespace Samples { public struct Int64 { long value; //other methods... public override int GetHashCode() { return ((int)value ^ (int)(value >> 32)); } } }
C D E F G H I
Example 5
J
using System; using System.Reflection;
K L
namespace Samples { public class ObjectGetHashCode { private readonly string s; public override bool Equals(object o) { if(null == o) return false; if(this.GetType() != o.GetType()) return false; return Object.Equals(s, ((ObjectGetHashCode)o).s); } public ObjectGetHashCode(string s) { this.s = s; } public override int GetHashCode() { return s.GetHashCode(); } public static void Main() { Object o = new Object(); Console.WriteLine("GetHashcode yields {0}", o.GetHashCode()); Console.WriteLine("GetHashcode yields {0}",
M N O P Q R S T U V W X Y Z
2416
Contents | Index
System
Object GetType() Method
new Object().GetHashCode()); o = new ObjectGetHashCode( "Programming in the .NET Environment"); Console.WriteLine("GetHashcode yields {0}", o.GetHashCode());
A
}
B
} }
C
The output is
D E
GetHashcode yields 2 GetHashcode yields 5 GetHashcode yields 617752486
F G H
Object.GetType() Method
I
[ILASM]
.method public hidebysig instance class System.Type GetType()
J
[C#]
K
public Type GetType()
L
Summary
M
Gets the type of the current instance.
N
Return Value
O
The instance of System.Type that represents the runtime type (the exact type) of the current instance.
P Q
Description
R
For two objects x and y that have identical runtime types, System.Object.ReferenceEquals(x.GetType(),y.GetType()) returns true.
S T U
Example
V
using System; using System.Reflection;
W X
namespace Samples { public class ObjectGetType { public static void Main() { object[] objects = new object[] {new object(),
Y Z
2417
Contents | Index
Object
System
MemberwiseClone() Method
42, "damien", "brad"}; foreach(object o in objects) Console.WriteLine(o.GetType()); object anObject = new Object(); Type t = anObject.GetType(); Console.WriteLine("Type: {0}", t); MemberInfo[] members = t.GetMembers(); foreach(MemberInfo m in members) Console.WriteLine("Member: {0}", m);
A B C D E
}
F
} }
G
The output is
H
System.Object System.Int32 System.String System.String Type: System.Object Member: Int32 GetHashCode() Member: Boolean Equals(System.Object) Member: System.String ToString() Member: Boolean Equals(System.Object, System.Object) Member: Boolean ReferenceEquals(System.Object, System.Object) Member: System.Type GetType() Member: Void .ctor()
I J K L M N O P Q R
Object.MemberwiseClone() Method
S
[ILASM]
.method family hidebysig instance object MemberwiseClone()
T
[C#]
protected object MemberwiseClone()
U V
Summary
W
Creates a shallow copy of the current instance.
X
Return Value
Y
A shallow copy of the current instance. The runtime type (the exact type) of the returned object is the same as the runtime type of the object that was copied.
Z
2418
Contents | Index
System
Object MemberwiseClone() Method
Description System.Object.MemberwiseClone creates a new instance of the same type as the current instance and then copies each of the object’s non-static fields in a manner that depends on whether the field is a value type or a reference type. If the field is a value type, a bit-bybit copy of all the field’s bits is performed. If the field is a reference type, only the reference is copied. The algorithm for performing a shallow copy is as follows (in pseudo-code):
A B C
for each instance field f in this instance if (f is a value type) bitwise copy the field if (f is a reference type) copy the reference end for loop
D E F G H
[Note: This mechanism is referred to as a shallow copy because it copies rather than clones the non-static fields.] Because System.Object.MemberwiseClone implements the above algorithm, for any object, a, the following statements are required to be true:
I J K
• • •
a.MemberwiseClone() is not identical to a. a.MemberwiseClone().GetType() is identical to a.GetType(). System.Object.MemberwiseClone does not call any of the type’s constructors.
L M N
[Note: If System.Object.Equals has been overridden, a.MemberwiseClone(). Equals(a) might return false.]
O P
Usage
Q
For an alternate copying mechanism, see System.ICloneable. System.Object.MemberwiseClone is protected (rather than public) to ensure that from verifiable code it is only possible to clone objects of the same class as the one performing the operation (or one of its subclasses). Although cloning an object does not directly open security holes, it does allow an object to be created without running any of its constructors. Since these constructors may establish important invariants, objects created by cloning may not have these invariants established, and this may lead to incorrect program behavior. For example, a constructor might add the new object to a linked list of all objects of this class, and cloning the object would not add the new object to that list—thus operations that relied on the list to locate all instances would fail to notice the cloned object. By making the method protected, only objects of the same class (or a subclass) can produce a clone and implementers of those classes are (presumably) aware of the appropriate invariants and can arrange for them to be true without necessarily calling a constructor.
R S T U V W X Y Z
2419
Contents | Index
Object
System
MemberwiseClone() Method
Example The following example shows a class called MyClass as well as a representation of the instance of MyClass returned by System.Object.MemberwiseClone. A using System;
B namespace Samples { public class MyBaseClass { public static string CompanyName = "My Company"; private int age = 42; private string name = "Sam"; } public class MyDerivedClass: MyBaseClass { public static void Main() { MyDerivedClass m1 = new MyDerivedClass(); MyDerivedClass m2 = (MyDerivedClass) m1.MemberwiseClone(); Console.WriteLine("m1.Equals(m2): {0}", m1.Equals(m2)); } } }
C D E F G H I J K L M N
The output is
O
m1.Equals(m2): False
P
A graphical representation of m1 and m2 might look like this:
Q R
42
S
m1
T
"Sam"
U V W X
42
Y
m2
Z
2420
Contents | Index
System
Object ReferenceEquals() Method
Object.ReferenceEquals(System.Object, System.Object) Method [ILASM]
.method public hidebysig static bool ReferenceEquals(object objA, object objB)
A
[C#]
public static bool ReferenceEquals(object objA, object objB)
B
Summary
C
Determines whether two object references are identical.
D E
Parameters
F
Parameter
Description
G
objA
First object to compare.
H
objB
Second object to compare.
I J
Return Value
K
True if objA and objB refer to the same object or are both null references; otherwise, false.
L
Description
M
This static method provides a way to compare two objects for reference equality. It does not call any user-defined code, including overrides of System.Object.Equals.
N O
Example
P
using System; using System.Reflection;
Q R
namespace Samples { public class ObjectReferenceEquals { public static void Main() { Object o = new Object(); Console.WriteLine("Are they equal: {0}", Object.ReferenceEquals( o, new Object())); Console.WriteLine("Are they equal: {0}", Object.ReferenceEquals( o, o)); } } }
S T U V W X Y Z
2421
Contents | Index
Object
System
ToString() Method
The output is Are they equal: False Are they equal: True
A B C
Object.ToString() Method
D
[ILASM]
.method public hidebysig virtual string ToString()
E
[C#]
public virtual string ToString()
F G
Summary
H
Creates and returns a System.String representation of the current instance.
I
Behaviors
J
System.Object.ToString returns a string whose content is intended to be understood by humans. Where the object contains culture-sensitive data, the string representation returned by System.Object.ToString takes into account the current system culture. For example, for an instance of the System.Double class whose value is zero, the implementation of System.Double.ToString might return “0.00” or “0,00” depending on the current UI culture. [Note: Although there are no exact requirements for the format of the returned string, it should as much as possible reflect the value of the object as perceived by the user.]
K L M N O P Q
Default
R
System.Object.ToString is equivalent to calling System.Object.GetType to obtain the System.Type object for the current instance and then returning the result of calling the System.Object.ToString implementation for that type. [Note: The value returned includes the full name of the type.]
S T U V
How and When to Override
W
It is recommended, but not required, that System.Object.ToString be overridden in a derived class to return values that are meaningful for that type. For example, the base data types, such as System.Int32, implement System.Object.ToString so that it returns the string form of the value the object represents. Subclasses that require more control over the formatting of strings than System.Object.ToString provides should implement System.IFormattable, whose System.Object.ToString method uses the culture of the current thread.
X Y Z
2422
Contents | Index
System
Object ToString() Method
Example using System; namespace Samples { public class ObjectToString { public override string ToString() { return this.GetType().ToString(); } public static void Main() { Object[] objects = new Object[] {new Object(), 42, "Hello world!", new ObjectToString()}; foreach(Object o in objects) Console.WriteLine(o.ToString()); } } }
A B C D E F G H I J K L M
The output is
N System.Object 42 Hello world! Samples.ObjectToString
O P Q R S T U V W X Y Z
2423
Contents | Index
System ObjectDisposedException
BCL
Object
A
Exception
B
ISerializable
NotStandardized
SystemException InvalidOperationException
C
ObjectDisposedException
D E
Summary
F
Represents the error that occurs when an operation is performed on a disposed object.
G
Type Summary
H
public class ObjectDisposedException : InvalidOperationException { // Constructors public ObjectDisposedException (string objectName); public ObjectDisposedException (string objectName, string message); MS CF protected ObjectDisposedException (SerializationInfo info, StreamingContext context);
I J K L M N
// Properties CF public override string Message { get; } public string ObjectName { get; }
O P
// Methods MS CF public override void GetObjectData (SerializationInfo info, StreamingContext context); }
Q R S T
Description
U
[Note: For additional information about disposing objects, see the System.IDisposable interface.]
V W
Example
X
using System; using System.IO;
Y
namespace Samples { public class ObjectDisposedExceptionSample {
Z
2424
Contents | Index
System
ObjectDisposedException ObjectDisposedException() Constructor
public static void Main() { MemoryStream ms = new MemoryStream(16); ms.Close(); try { ms.ReadByte(); } catch(ObjectDisposedException e) { Console.WriteLine("Exception: {0}", e); } }
A B C D E F
}
G
}
H
The output is
I
Exception: System.ObjectDisposedException: Cannot access a closed Stream. at System.IO.__Error.StreamIsClosed() at System.IO.MemoryStream.ReadByte() at Samples.ObjectDisposedExceptionSample.Main() in C:\Books\BCL\Samples\System\ ObjectDisposedException\ObjectDisposedException.cs:line 14
J K L M N
ObjectDisposedException(System.String) Constructor
O
[ILASM]
P
public rtspecialname specialname instance void .ctor(string objectName)
Q
[C#]
public ObjectDisposedException(string objectName)
R
Summary
S
Constructs and initializes a new instance of the System.ObjectDisposedException class.
T U V
Parameters
W
Parameter
Description
X
objectName
A System.String containing the name of the disposed object.
Y Z
2425
Contents | Index
ObjectDisposedException
System
ObjectDisposedException() Constructor
Description This constructor initializes the System.ObjectDisposedException.ObjectName property of the new instance using objectName. The System.ObjectDisposedException.Message property is initialized to a system-supplied message that describes the error and includes objectname. This message takes into account the current system culture. The System.ObjectDisposedException.InnerException property of the new instance is initialized to null. [Note: If objectName is null, the System.ObjectDisposedException.Message property contains only an error message.]
A B C D E F G
ObjectDisposedException(System.String, System.String) Constructor
H
[ILASM]
I
public rtspecialname specialname instance void .ctor(string objectName, string message)
J
[C#]
public ObjectDisposedException(string objectName, string message)
K L
Summary
M
Constructs and initializes a new instance of the System.ObjectDisposedException class.
N O
Parameters
P Q
Parameter
Description
R
objectName
A System.String containing the name of the disposed object.
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
S T U V
Description
W
This constructor initializes the System.ObjectDisposedException.Message property of the new instance using message, and the System.ObjectDisposedException.ObjectName property using objectName. If message is null, the System.ObjectDisposedException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments.
X Y Z
2426
Contents | Index
System
ObjectDisposedException Message Property
The System.ObjectDisposedException.InnerException property of the new instance is initialized to null. A
ObjectDisposedException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
B C
[ILASM]
D
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
E F
[C#]
protected ObjectDisposedException(SerializationInfo info, StreamingContext context)
G H
Summary
I
Initializes a new instance of the System.ObjectDisposedException class with serialized data.
J K L
Parameters
M
Parameter
Description
info
The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown.
O
The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination.
Q
context
N
P
R S
ObjectDisposedException.Message Property
T
[ILASM]
U
.property string Message { public hidebysig virtual specialname string get_Message() }
V
[C#]
W
public override string Message { get; }
X
Summary
Y
Gets the message that describes the error.
Z
2427
Contents | Index
ObjectDisposedException
System
ObjectName Property
Description If the System.ObjectDisposedException.ObjectName property is not null, the message includes the name of the object. [Note: This property overrides System.Exception.Message.]
A B C
ObjectDisposedException.ObjectName Property
D [ILASM]
E
.property string ObjectName { public hidebysig specialname instance string get_ObjectName() }
F
[C#]
G
public string ObjectName { get; }
H
Summary
I
Gets the name of the disposed object.
J K
Description
L
[Note: If this property is not null or System.String.Empty, the value of this property is included in the string returned by the System.ObjectDisposedException.Message property.]
M N O
ObjectDisposedException.GetObjectData(System.Runtime.Serialization. SerializationInfo, System.Runtime.Serialization.StreamingContext) Method
P Q
[ILASM]
R
.method public hidebysig virtual void GetObjectData(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
S T
[C#]
U
public override void GetObjectData(SerializationInfo info, StreamingContext context)
V
Summary
W
Retrieves the System.Runtime.Serialization.SerializationInfo object with the parameter name and additional exception information.
X Y Z
2428
Contents | Index
System
ObjectDisposedException GetObjectData() Method
Parameters Parameter
Description
info
The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown.
context
The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
2429
Contents | Index
System ObsoleteAttribute
BCL
Object
A
Attributre
B
ObsoleteAttribute
C
Summary
D
Indicates that the target of the current attribute will be removed in future versions of the assembly in which the target is contained.
E F
Type Summary
G
public sealed class ObsoleteAttribute : Attribute { // Constructors public ObsoleteAttribute (); public ObsoleteAttribute (string message); public ObsoleteAttribute (string message, bool error);
H I J K L
// Properties public bool IsError { get; } public string Message { get; }
M N
}
O P
BA You’ll notice that this attribute is sealed. In general I am not a huge fan of sealing classes by default, but for custom attributes that you expect to be looked up at runtime it is a good idea to seal them, because then reflection can use a slightly faster code path to look them up.
Q R S T
Description
U
[Note: Marking an item as obsolete provides consumers of that item the information that the item will be not be available in future versions of the assembly in which it is contained. A System.ObsoleteAttribute has a System.ObsoleteAttribute.Message property that can be used to suggest alternative ways of obtaining the functionality provided by the item, i.e., a workaround. This class also has a System.ObsoleteAttribute.IsError property that designates whether a compiler will treat usage of the obsolete item as an error. If this property is false, the compiler will issue a warning if the obsolete item is used and the compiler supports the generation of such warnings. This attribute can be applied to any
V W X Y Z
2430
Contents | Index
System
ObsoleteAttribute ObsoleteAttribute() Constructor
valid attribute target except assemblies, parameters, and return values. For a complete list of valid attribute targets, see System.AttributeTargets.]
Example
A
using System;
B C
namespace Samples { public class ObsoleteAttributeSample { [ObsoleteAttribute("Use NewMethod")] public static void OldMethod() { Console.WriteLine("Hi world!"); } public static void NewMethod() { Console.WriteLine("Hello world!"); } public static void Main() { OldMethod(); } } }
D E F G H I J K L M N O
An example compile-time result is
P Microsoft (R) Program Maintenance Utility Version 7.00.9466 Copyright (C) Microsoft Corporation. All rights reserved.
Q R
csc /debug ObsoleteAttribute.cs Microsoft (R) Visual C# .NET Compiler version 7.00.9466 for Microsoft (R) .NET Framework version 1.0.3705 Copyright (C) Microsoft Corporation 2001. All rights reserved.
S T U
ObsoleteAttribute.cs(18,7): warning CS0618: 'Samples.ObsoleteAttributeSample.OldMethod()' is obsolete: 'Use NewMethod'
V W X
ObsoleteAttribute() Constructor
Y
[ILASM]
Z
public rtspecialname specialname instance void .ctor() [C#]
public ObsoleteAttribute()
2431
Contents | Index
ObsoleteAttribute
System
ObsoleteAttribute() Constructor
Summary Constructs and initializes a new instance of the System.ObsoleteAttribute class. A
Description
B
This constructor is equivalent to System.ObsoleteAttribute(null, false). The compiler does not treat an item with this attribute as an error.
C D
Example
E
using System;
F namespace Samples { public class ObsoleteAttributeConstructor { [ObsoleteAttribute] public static void OldMethod() { Console.WriteLine("Hi world!"); } public static void NewMethod() { Console.WriteLine("Hello world!"); } public static void Main() { OldMethod(); } } }
G H I J K L M N O P Q R
An example compile-time result is
S T
Microsoft (R) Program Maintenance Utility Version 7.00.9466 Copyright (C) Microsoft Corporation. All rights reserved.
U
csc /debug ObsoleteAttribute.cs Microsoft (R) Visual C# .NET Compiler version 7.00.9466 for Microsoft (R) .NET Framework version 1.0.3705 Copyright (C) Microsoft Corporation 2001. All rights reserved.
V W X
ObsoleteAttribute.cs(18,7): warning CS0612: 'Samples.ObsoleteAttributeConstructor.OldMethod()' is obsolete
Y Z
2432
Contents | Index
System
ObsoleteAttribute ObsoleteAttribute() Constructor
ObsoleteAttribute(System.String) Constructor [ILASM]
public rtspecialname specialname instance void .ctor(string message) [C#]
A
public ObsoleteAttribute(string message)
B C
Summary
D
Constructs and initializes a new instance of the System.ObsoleteAttribute class with the specified System.String that contains suggested workarounds.
E F
Parameters
G
Parameter
Description
message
The System.String that contains suggested workarounds.
H I J K
Description
L
This constructor is equivalent to System.ObsoleteAttribute(message, false). The compiler does not treat an item with this attribute as an error.
M N
Example
O
using System; using System.Reflection;
P Q
namespace Samples { public class ObsoleteAttributeConstructor { [ObsoleteAttribute("Use NewMethod")] public static void OldMethod() { Console.WriteLine("Hi world!"); } public static void NewMethod() { Console.WriteLine("Hello world!"); } public static void Main() { OldMethod(); } } }
R S T U V W X Y Z
2433
Contents | Index
ObsoleteAttribute
System
ObsoleteAttribute() Constructor
An example compile-time result is Microsoft (R) Program Maintenance Utility Version 7.00.9466 Copyright (C) Microsoft Corporation. All rights reserved.
A B
csc /debug ObsoleteAttribute.cs Microsoft (R) Visual C# .NET Compiler version 7.00.9466 for Microsoft (R) .NET Framework version 1.0.3705 Copyright (C) Microsoft Corporation 2001. All rights reserved.
C D E
ObsoleteAttribute.cs(19,7): warning CS0618: 'Samples.ObsoleteAttributeConstructor.OldMethod()' is obsolete: 'Use NewMethod'
F G H
ObsoleteAttribute(System.String, System.Boolean) Constructor
I
[ILASM]
public rtspecialname specialname instance void .ctor(string message, bool error)
J
[C#]
public ObsoleteAttribute(string message, bool error)
K L
Summary
M
Constructs and initializes a new instance of the System.ObsoleteAttribute class with a System.String that contains suggested workarounds and a System.Boolean that indicates whether the compiler treats usage of the target of the current instance as an error.
N O P
Parameters
Q R
Parameter
Description
S
message
A System.String that contains suggested workarounds.
error
A System.Boolean that indicates whether the compiler treats usage of the target of the current instance as an error.
T U V W
Description
X
Respectively, the System.ObsoleteAttribute.Message property and the System.ObsoleteAttribute.IsError property of the new instance are initialized as message and error.
Y Z
2434
Contents | Index
System
ObsoleteAttribute IsError Property
Example using System; namespace Samples { public class ObsoleteAttributeConstructor { [ObsoleteAttribute("Use NewMethod", false)] public static void OldMethod() { Console.WriteLine("Hi world!"); } public static void NewMethod() { Console.WriteLine("Hello world!"); } public static void Main() { OldMethod(); } } }
A B C D E F G H I J K L M
An example compile-time result is
N Microsoft (R) Program Maintenance Utility Version 7.00.9466 Copyright (C) Microsoft Corporation. All rights reserved.
O P
csc /debug ObsoleteAttribute.cs Microsoft (R) Visual C# .NET Compiler version 7.00.9466 for Microsoft (R) .NET Framework version 1.0.3705 Copyright (C) Microsoft Corporation 2001. All rights reserved.
Q R S
ObsoleteAttribute.cs(18,7): error CS0619: 'Samples.ObsoleteAttributeConstructor.OldMethod()' is obsolete: 'Use NewMethod'
T U
NMAKE : fatal error U1077: 'csc' : return code '0x1' Stop.
V W
ObsoleteAttribute.IsError Property
X
[ILASM]
Y
.property bool IsError { public hidebysig specialname instance bool get_IsError() }
Z
[C#]
public bool IsError { get; }
2435
Contents | Index
ObsoleteAttribute
System
IsError Property
Summary Gets a System.Boolean that indicates whether the compiler treats usage of the target of the current instance as an error. A B
Property Value
C
true if the compiler treats usage of the target of the current instance as an error; otherwise, false.
D E
Description
F
The default value of this property is false.
G
Example
H
using System; using System.Reflection;
I J
namespace Samples { public class ObsoleteAttributeIsError { [ObsoleteAttribute("Use NewMethod", true)] public static void OldMethod() { Console.WriteLine("Hi world!"); } public static void NewMethod() { Console.WriteLine("Hello world!"); } public static void Main() { Type t = typeof(ObsoleteAttributeIsError); MethodInfo m = t.GetMethod("OldMethod"); Object[] objects = m.GetCustomAttributes(false); foreach(Object o in objects) if(o is ObsoleteAttribute) Console.WriteLine("Is error: {0}", ((ObsoleteAttribute)o).IsError); } } }
K L M N O P Q R S T U V W X Y Z
2436
Contents | Index
System
ObsoleteAttribute Message Property
The output is Is error: True
A B
ObsoleteAttribute.Message Property
C [ILASM]
D
.property string Message { public hidebysig specialname instance string get_Message() }
E
[C#]
public string Message { get; }
F G
Summary
H
Gets a System.String that contains suggested workarounds for the target of the current instance.
I J
Description
K
The current instance contains a suggested workaround message if and only if such a message was specified when the current instance was constructed. If no workaround was specified for the current instance, the value of this property is null.
L M N
Example
O
using System; using System.Reflection;
P Q
namespace Samples { public class ObsoleteAttributeMessage { [ObsoleteAttribute("Use NewMethod", true)] public static void OldMethod() { Console.WriteLine("Hi world!"); } public static void NewMethod() { Console.WriteLine("Hello world!"); }
R S T U V W X Y Z
2437
Contents | Index
ObsoleteAttribute
System
Message Property
public static void Main() { Type t = typeof(ObsoleteAttributeMessage); MethodInfo m = t.GetMethod("OldMethod"); Object[] objects = m.GetCustomAttributes(false); foreach(Object o in objects) if(o is ObsoleteAttribute) Console.WriteLine("Message: {0}", ((ObsoleteAttribute)o).Message); }
A B C D }
E }
F
The output is
G H
Message: Use NewMethod
I J K L M N O P Q R S T U V W X Y Z
2438
Contents | Index
System OutOfMemoryException
BCL
Object Exception
ISerializable
NotStandardized
A B
SystemException OutOfMemoryException
C D
Summary
E
Represents the error that occurs when insufficient memory prevents the current memory allocation from succeeding.
F G
Type Summary
H
public class OutOfMemoryException : SystemException { // Constructors public OutOfMemoryException (); public OutOfMemoryException (string message); public OutOfMemoryException (string message, Exception innerException); MS CF protected OutOfMemoryException (SerializationInfo info, StreamingContext context); }
I J K L M N
Example
O
using System; using System.Drawing;
P Q
namespace Samples { public class OutOfMemoryExceptionSample { public static void Main() { try { Image i = Image.FromFile("BookCover.pdf"); } catch(OutOfMemoryException e) { Console.WriteLine("Exception: {0}" , e); } } } }
R S T U V W X Y Z
2439
Contents | Index
OutOfMemoryException
System
OutOfMemoryException() Constructor
The output is Exception: System.OutOfMemoryException: Out of memory. at System.Drawing.Image.FromFile(String filename, Boolean useEmbeddedColorManagement) at System.Drawing.Image.FromFile(String filename) at Samples.OutOfMemoryExceptionSample.Main() in C:\Books\BCL\Samples\System\ OutOfMemoryException\OutOfMemoryException.cs:line 12
A B C D E
OutOfMemoryException() Constructor
F [ILASM]
G
public rtspecialname specialname instance void .ctor()
H
[C#]
public OutOfMemoryException()
I J
Summary
K
Constructs and initializes a new instance of the System.OutOfMemoryException class.
L
Description
M
This constructor initializes the System.OutOfMemoryException.Message property of the new instance to a system-supplied message that describes the error, such as “There was not enough memory to continue the execution of the program.” This message takes into account the current system culture. The System.OutOfMemoryException.InnerException property is initialized to null.
N O P Q R S
OutOfMemoryException(System.String) Constructor
T
[ILASM]
public rtspecialname specialname instance void .ctor(string message)
U
[C#]
V
public OutOfMemoryException(string message)
W
Summary
X
Constructs and initializes a new instance of the System.OutOfMemoryException class.
Y Z
2440
Contents | Index
System
OutOfMemoryException OutOfMemoryException() Constructor
Parameters Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
A B C D
Description
E
This constructor initializes the System.OutOfMemoryException.Message property of the new instance using message. If message is null, the System.OutOfMemoryException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.OutOfMemoryException.InnerException property is initialized to null.
F G H I J
OutOfMemoryException(System.String, System.Exception) Constructor
K
[ILASM]
L
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
M
[C#]
N
public OutOfMemoryException(string message, Exception innerException)
O
Summary
P
Constructs and initializes a new instance of the System.OutOfMemoryException class.
Q R
Parameters
S
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
T U V W X Y Z
2441
Contents | Index
OutOfMemoryException
System
OutOfMemoryException() Constructor
Description This constructor initializes the System.OutOfMemoryException.Message property of the new instance using message, and the System.OutOfMemoryException.InnerException property using innerException. If message is null, the System.OutOfMemoryException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
A B C D E F G
OutOfMemoryException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
H
[ILASM]
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
I J
[C#]
K
protected OutOfMemoryException(SerializationInfo info, StreamingContext context)
L M
Summary
N
Initializes a new instance of the System.OutOfMemoryException class with serialized data.
O
Parameters
P Q
Parameter
Description
S
info
The object that holds the serialized object data.
T
context
The contextual information about the source or destination.
R
U V
Description
W
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
X Y Z
2442
Contents | Index
System OverflowException
BCL
Object Exception
ISerializable
NotStandardized
A B
SystemException ArithmeticException
C
OverflowException
D E
Summary
F
Represents the error that occurs when the result of an arithmetic operation is too large to be represented by the destination type.
G H
Type Summary
I
public class OverflowException : ArithmeticException { // Constructors public OverflowException (); public OverflowException (string message); public OverflowException (string message, Exception innerException); MS CF protected OverflowException (SerializationInfo info, StreamingContext context); }
J K L M N O P
Description
Q
In languages that detect overflow, this is the exception that gets thrown. For example, in C#, the checked keyword is used to detect overflow conditions. A System.OverflowException exception occurs only in a checked context.
R S T
Example
U
using System;
V
namespace Samples { public class OverflowExceptionSample { public static void Main() { try { string s = Int64.MaxValue.ToString();
W X Y Z
2443
Contents | Index
OverflowException
System
OverflowException() Constructor
int i = Int32.Parse(s); } catch(OverflowException e) { Console.WriteLine("Exception: {0}" , e); }
A B }
C
} }
D
The output is
E F
Exception: System.OverflowException: Value was either too large or too small for an Int32. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s) at Samples.OverflowExceptionSample.Main() in C:\Books\BCL\Samples\System\ OverflowException\OverflowException.cs:line 12
G H I J K
OverflowException() Constructor
L
[ILASM]
M
public rtspecialname specialname instance void .ctor() [C#]
N
public OverflowException()
O P
Summary
Q
Constructs and initializes a new instance of the System.OverflowException class.
R
Description
S
This constructor initializes the System.OverflowException.Message property of the new instance to a system-supplied message that describes the error. This message takes into account the current system culture. The System.OverflowException.InnerException property is initialized to null.
T U V W X
OverflowException(System.String) Constructor
Y
[ILASM]
public rtspecialname specialname instance void .ctor(string message)
Z
[C#]
public OverflowException(string message)
2444
Contents | Index
System
OverflowException OverflowException() Constructor
Summary Constructs and initializes a new instance of the System.OverflowException class. A
Parameters
B
Parameter
Description
C
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
D
message
E F G
Description
H
This constructor initializes the System.OverflowException.Message property of the new instance using message. If message is null, the System.OverflowException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.OverflowException.InnerException property is initialized to null.
I J K L M
OverflowException(System.String, System.Exception) Constructor
N [ILASM]
O
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
P
[C#]
Q
public OverflowException(string message, Exception innerException)
R
Summary
S
Constructs and initializes a new instance of the System.OverflowException class.
T
Parameters
U
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
V W
innerException
X Y
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
Z
2445
Contents | Index
OverflowException
System
OverflowException() Constructor
Description This constructor initializes the System.OverflowException.Message property of the new instance using message, and the System.OverflowException.InnerException property using innerException. If message is null, the System.OverflowException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
A B C D E F G
OverflowException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
H
[ILASM]
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
I J
[C#]
K
protected OverflowException(SerializationInfo info, StreamingContext context)
L
Summary
M
Initializes a new instance of the System.OverflowException class with serialized data.
N O
Parameters
P Q
Parameter
Description
R
info
The object that holds the serialized object data.
context
The contextual information about the source or destination.
S T U
Description
V
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
W X Y Z
2446
Contents | Index
System.IO Path
BCL
Object
A
Path
B
Summary
C
Performs operations on System.String instances that contain file or directory path information.
D E
Type Summary
F
public sealed class Path { // Fields public static readonly char AltDirectorySeparatorChar = '/'; public static readonly char DirectorySeparatorChar = '\\'; MS public static readonly char[] InvalidPathChars = {'\"', '<', '>', '|', '\0', '\b', (Char)16, (Char)17, (Char)18, (Char)20, (Char)21, (Char)22, (Char)23, (Char)24, (Char)25 }; public static readonly char PathSeparator = ';'; MS public static readonly char VolumeSeparatorChar = ':';
G H I J K L M N O
// Methods public static string ChangeExtension (string path, string extension); public static string Combine (string path1, string path2); public static string GetDirectoryName (string path); public static string GetExtension (string path); public static string GetFileName (string path); public static string GetFileNameWithoutExtension (string path); public static string GetFullPath (string path); public static string GetPathRoot (string path); public static string GetTempFileName (); public static string GetTempPath (); public static bool HasExtension (string path); public static bool IsPathRooted (string path);
P Q R S T U V W X
}
Y Z
2447
Contents | Index
Path
System.IO
Path Class
JM The Combine method had an interesting ride in the standardization process. It was originally part of the Path class, then removed because it was thought to be too platform-specific, then added back because it was decided it was not any more platform-specific than any of the other methods in this class.
A B
KG Users often expect that the Path class actually interacts with the FileSystem, but in truth, it only performs string manipulations. This provides a great mechanism for interacting with other I/O classes, but can seem obscure. Be wary when using this class. A common assumption is that members such as GetFullPath() will only return a valid value if the path exists. However, all the API does is check the string to see if it is rooted, and if not, then provides a root for it (based on the current directory) and concatenates this with the string to provide a result. Path itself never checks against the file system for its operations since it can’t guess your intent. You would simply need to create the file.
C D E F G H I J
Description
K
A path is a string that provides the location of a file or directory. A path does not necessarily point to a location on disk; for example, a path may map to a location in memory or on a device. Paths are composed of the components described below. Component names are shown in italics and the following table describes the symbols used in component definitions:
L M N O P Q R S
Symbol
Description
<>
Indicates a path component.
{}
Indicates a grouping; either all components in a grouping are present, or none is permitted to be present.
*
Indicates that the component or grouping that immediately precedes this symbol can appear zero, one, or multiple times.
?
Indicates that the component or grouping that immediately precedes this symbol can appear zero or one times.
+
Indicates string concatenation.
T U V W X Y Z
2448
Contents | Index
System.IO
Path Path Class
The components that define a path are as follows: •
•
•
•
•
•
Directory Name: A string that specifies one or more directory levels in a file system. If a directory name contains multiple levels, a directory separator character separates the levels; however, a directory name does not begin or end with a directory separator character. In the example path C:/foo/bar/bat.txt, the directory name is “foo/bar”. System.IO.Path.GetDirectoryName returns the directory name component of a path. Note that this method does include a beginning separator character if one is included in the specified path. Directory Separator Character: An implementation-defined constant string containing a single printable non-alphanumeric character used to separate levels in a file system. In the example path C:/foo/bar/bat.txt, the directory separator character is “/”. The System.IO.Path.DirectorySeparatorChar and System.IO.Path.AltDirectorySeparatorChar store implementation-defined directory separator characters. Extension: A string that consists of the characters at the end of a file name, from and including the last extension separator character. The minimum and maximum lengths of extension components are platform-specific. In the example path C:/foo/bar/bat.txt, the extension is “.txt”. The System.IO.Path.GetExtension method returns the extension component of a path. Extension Separator Character: An implementation-defined constant string composed of a single character that appears after the last character in the file base component indicating the beginning of the extension component. If the extension separator character is the first character in a file name, it is not interpreted as an extension separator character. If more than one extension separator character appears in a file name, only the last occurrence is the extension separator character; all other occurrences are part of the file base component. In the example path C:/foo/bar/bat.txt, the extension separator character is “.”. File Base: A string containing the filename with the extension component removed. In the example path C:/foo/bar/bat.txt, the file base is “bat”. The System.IO.Path.GetFileNameWithoutExtension method returns the file base component of a path. File Name: A string containing all information required to uniquely identify a file within a directory. This component is defined as follows:
A B C D E F G H I J K L M N O P Q R S T U V
{+<extension>}?
•
W
The file name component is commonly referred to as a relative file name. In the example path C:/foo/bar/bat.txt, the file name is “bat.txt”. The System.IO.Path.GetFileName method returns the file name component of a path. Full Directory Name: A string containing all information required to uniquely identify a directory within a file system. This component is defined as follows:
X Y Z
<path root>+
2449
Contents | Index
Path
System.IO
Path Class
A
The full directory name component is commonly referred to as the absolute directory name. In the example path C:/foo/bar/bat.txt, the full directory name is “C:/foo/bar “. Full Path: A string containing all information required to uniquely identify a file within a file system. This component is defined as follows:
B
++
C
The full path component is commonly referred to as the absolute file name. In the example path C:/foo/bar/bat.txt, the full path is “C:/foo/bar/bat.txt”. The System.IO.Path.GetFullPath method returns the full path component. Path Root: A string containing all information required to uniquely identify the highest level in a file system. The component is defined as follows:
•
D E
•
F G
{+}?+
H I J
•
K L M
•
N O P Q R S T U V W X Y Z
In the example path C:/foo/bar/bat.txt, the path root is "C:/". The System.IO.Path.GetPathRoot method returns the path root component. Volume Identifier: A string composed of a single alphabetic character that uniquely defines a drive or volume in a file system. This component is optional; on systems that do not support volume identifiers, this component is required to be a zero length string. In the example path C:/foo/bar/bat.txt, the path root is “C:”. In the example path, \\myserver\myshare\foo\bar\baz.txt the path root is “\\myserver\myshare”. Volume Separator Character: A string composed of a single alphabetic character used to separate the volume identifier from other components in a path. This component can appear in a path only if a volume identifier is present. This component is optional; on systems that do not support the volume identifier component, the volume separator character component is required to be a zero length string. The exact format of a path is determined by the current platform. For example, on Windows systems a path can start with a volume identifier, while this element is not present in Unix system paths. On some systems, paths containing file names can contain extensions. The format of an extension is platform-dependent; for example, some systems limit extensions to three characters, while others do not. The current platform and possibly the current file system determine the set of characters used to separate the elements of a path, and the set of characters that cannot be used when specifying paths. Because of these differences, the fields of the System.IO.Path class as well as the exact behavior of some members of the System.IO.Path class are determined by the current platform and/or file system. A path contains either absolute or relative location information. Absolute paths fully specify a location: the file or directory can be uniquely identified regardless of the current location. A full path or full directory name component is present in an absolute path. Relative paths specify a partial location: the current working directory
2450
Contents | Index
System.IO
Path Path Class
is used as the starting point when locating a file specified with a relative path. [Note: To determine the current working directory, call System.IO.Directory.GetCurrentDirectory.] Most members of the Path class do not interact with the file system and do not verify the existence of the file or directory specified by a path string. System.IO.Path members that modify a path string, such as System.IO.Path.ChangeExtension, have no effect on files and directories in the file system. System.IO.Path members do, however, validate the contents of a specified path string, and throw System.ArgumentException if the string contains characters that are not valid in path strings, as defined by the current platform and file system. Implementations are required to preserve the case of file and directory path strings, and to be case-sensitive if and only if the current platform is case-sensitive.
A B C D E F G H
Example
I
using System; using System.IO;
J K
namespace Samples { public class PathSamples { public static void Main() { Console.WriteLine( "Path.AltDirectorySeparatorChar: {0}", Path.AltDirectorySeparatorChar); Console.WriteLine( "Path.DirectorySeparatorChar: {0}", Path.DirectorySeparatorChar); Console.Write("Path.InvalidPathChars: "); foreach(char c in Path.InvalidPathChars) Console.Write(c); Console.WriteLine(); Console.WriteLine( "Path.PathSeparator={0}", Path.PathSeparator); Console.WriteLine( "Path.VolumeSeparatorChar={0}", Path.VolumeSeparatorChar); string s = Path.GetFullPath("s.text"); Console.WriteLine("ChangeExtension: {0}", Path.ChangeExtension(s, "txt")); Console.WriteLine("Combine: {0}", Path.Combine( Path.GetDirectoryName(s),
L M N O P Q R S T U V W X Y Z
2451
Contents | Index
Path
System.IO
Path Class
"Path.cs")); Console.WriteLine("GetExtension: {0}", Path.GetExtension(s)); Console.WriteLine("GetFileName: {0}", Path.GetFileName(s)); Console.WriteLine( "GetFileNameWithoutExtension: {0}", Path.GetFileNameWithoutExtension(s)); Console.WriteLine("GetFullPath: {0}", Path.GetFullPath("Path.cs")); Console.WriteLine("GetPathRoot: {0}", Path.GetPathRoot(s)); s = Path.GetTempFileName(); Console.WriteLine("GetTempFileName: {0}", s); File.Delete(s); Console.WriteLine("GetTempPath: {0}", Path.GetTempPath()); Console.WriteLine("HasExtension {0}: {1}", s ,Path.HasExtension(s)); s = Path.GetFileNameWithoutExtension(s); Console.WriteLine("HasExtension {0}: {1}", s ,Path.HasExtension(s)); Console.WriteLine("IsPathRooted {0}: {1}", s ,Path.IsPathRooted(s));
A B C D E F G H I J K L M }
N
} }
O
The output is
P Q
Path.AltDirectorySeparatorChar: / Path.DirectorySeparatorChar: \ Path.InvalidPathChars: "<>| ↕¶§ ↕↑↓ Path.PathSeparator=; Path.VolumeSeparatorChar=: ChangeExtension: C:\Books\BCL\Samples\System.IO\Path\s.txt Combine: C:\Books\BCL\Samples\System.IO\Path\Path.cs GetExtension: .text GetFileName: s.text GetFileNameWithoutExtension: s GetFullPath: C:\Books\BCL\Samples\System.IO\Path\Path.cs GetPathRoot: C:\ GetTempFileName: C:\DOCUME~1\damien\LOCALS~1\Temp\tmp73.tmp GetTempPath: C:\DOCUME~1\damien\LOCALS~1\Temp\ HasExtension C:\DOCUME~1\damien\LOCALS~1\Temp\tmp73.tmp: True HasExtension tmp73: False IsPathRooted tmp73: False
R
—
S T U V W X Y Z
2452
Contents | Index
System.IO
Path AltDirectorySeparatorChar Field
Path.AltDirectorySeparatorChar Field [ILASM]
.field public static initOnly valuetype System.Char AltDirectorySeparatorChar
A
[C#]
public static readonly char AltDirectorySeparatorChar = '//'
B
Summary
C
Provides a string containing an alternate single printable non-alphanumeric character used to separate directory levels in a hierarchical file system.
D
Description
F
This field can be set to the same value as System.IO.Path.DirectorySeparatorChar. [Note: System.IO.Path.AltDirectorySeparatorChar and System.IO.Path.DirectorySeparatorChar are both valid for separating directory levels in a path string. The value of this field is a slash ('/') on Windows systems and a backslash ('\') on Unix systems.]
G
E
H I J K
Example
L
using System; using System.IO;
M
namespace Samples { public class PathAltDirectorySeparatorChar { public static void Main() { Console.WriteLine( "Path.AltDirectorySeparatorChar: {0}", Path.AltDirectorySeparatorChar); Console.WriteLine( "Path.DirectorySeparatorChar: {0}", Path.DirectorySeparatorChar); Console.Write("Path.InvalidPathChars: "); foreach(char c in Path.InvalidPathChars) Console.Write(c); Console.WriteLine(); Console.WriteLine( "Path.PathSeparator={0}", Path.PathSeparator); Console.WriteLine( "Path.VolumeSeparatorChar={0}", Path.VolumeSeparatorChar); } } }
N O P Q R S T U V W X Y Z
2453
Contents | Index
Path
System.IO
DirectorySeparatorChar Field
The output is Path.AltDirectorySeparatorChar: / Path.DirectorySeparatorChar: \ Path.InvalidPathChars: "<>|↕¶§ ↕↑↓ Path.PathSeparator=; Path.VolumeSeparatorChar=:
A
—
B C D E
Path.DirectorySeparatorChar Field
F
[ILASM]
.field public static initOnly valuetype System.Char DirectorySeparatorChar
G
[C#]
public static readonly char DirectorySeparatorChar = '\\'
H I
Summary
J
Provides a string containing a single printable non-alphanumeric character used to separate directory levels in a hierarchical file system.
K L
Description
M
[Note: System.IO.Path.AltDirectorySeparatorChar and System.IO.Path.DirectorySeparatorChar are both valid for separating directory levels in a path string. The value of this field is a backslash ('\') on Windows systems and a slash ('/') on Unix systems.]
N O P
Example
Q
using System; using System.IO;
R S
namespace Samples { public class PathDirectorySeparatorChar { public static void Main() { Console.WriteLine( "Path.AltDirectorySeparatorChar: {0}", Path.AltDirectorySeparatorChar); Console.WriteLine( "Path.DirectorySeparatorChar: {0}", Path.DirectorySeparatorChar); Console.Write("Path.InvalidPathChars: "); foreach(char c in Path.InvalidPathChars) Console.Write(c);
T U V W X Y Z
2454
Contents | Index
System.IO
Path InvalidPathChars Field
Console.WriteLine(); Console.WriteLine( "Path.PathSeparator={0}", Path.PathSeparator); Console.WriteLine( "Path.VolumeSeparatorChar={0}", Path.VolumeSeparatorChar);
A B C
} }
D
}
E
The output is
F
Path.AltDirectorySeparatorChar: / Path.DirectorySeparatorChar: \ Path.InvalidPathChars: "<>|↕¶§ ↕↑↓ Path.PathSeparator=; Path.VolumeSeparatorChar=:
G H
—
I J K
Path.InvalidPathChars Field
L
[ILASM]
.field public static initOnly class System.Char[] InvalidPathChars
M
[C#]
N
public static readonly char[] InvalidPathChars = { '\"', '<', '>', '|', '\0', '\b', (Char)16, (Char)17, (Char)18, (Char)20, (Char)21, (Char)22, (Char)23, (Char)24, (Char)25 }
O P
Summary
Q
Provides a platform-specific array of characters that cannot be specified in path string arguments passed to members of the System.IO.Path class.
R S T
Description
U
This array is not guaranteed to contain the complete set of characters that are invalid in file and directory names. The full set of invalid characters can vary by file system. For example, on Windows-based desktop platforms, invalid path characters might include quote (“), less than (<), greater than (>), pipe (|), backspace (\b), null (\0), and Unicode characters 16 through 18 and 20 through 25.
V W X Y Z
2455
Contents | Index
Path
System.IO
PathSeparator Field
Path.PathSeparator Field [ILASM]
.field public static initOnly valuetype System.Char PathSeparator
A
[C#]
public static readonly char PathSeparator = ';'
B C
Summary
D
Provides a platform-specific separator character used to separate path strings in environment variables.
E F
Example
G
using System; using System.IO;
H I
namespace Samples { public class PathPathSeparator { public static void Main() { Console.WriteLine( "Path.AltDirectorySeparatorChar: {0}", Path.AltDirectorySeparatorChar); Console.WriteLine( "Path.DirectorySeparatorChar: {0}", Path.DirectorySeparatorChar); Console.Write("Path.InvalidPathChars: "); foreach(char c in Path.InvalidPathChars) Console.Write(c); Console.WriteLine(); Console.WriteLine( "Path.PathSeparator={0}", Path.PathSeparator); Console.WriteLine( "Path.VolumeSeparatorChar={0}", Path.VolumeSeparatorChar); } } }
J K L M N O P Q R S T U V W X
The output is
Y
Path.AltDirectorySeparatorChar: / Path.DirectorySeparatorChar: \ Path.InvalidPathChars: "<>|↕¶§ ↕↑↓ Path.PathSeparator=; Path.VolumeSeparatorChar=:
Z
—
2456
Contents | Index
System.IO
Path ChangeExtension() Method
Path.VolumeSeparatorChar Field [ILASM]
.field public static initOnly valuetype System.Char VolumeSeparatorChar [C#]
A
public static readonly char VolumeSeparatorChar = ':'
B C
Summary
D
Provides a platform-specific volume separator character.
E
Description
F
The value of this field is a colon (':') on Windows and Macintosh, and a slash ('/') on Unix operating systems. This is most useful for parsing paths such as “c:\windows” or “MacVolume:System Folder.”
G H I J
Path.ChangeExtension(System.String, System.String) Method
K [ILASM]
L
.method public hidebysig static string ChangeExtension(string path, string extension) [C#]
M
public static string ChangeExtension(string path, string extension)
N
Summary
O
Changes the extension component of the specified path string.
P Q
Parameters
R
Parameter
Description
S
path
A System.String containing the path information to modify.
T
extension
A System.String containing the new extension. Specify null to remove an existing extension from path.
U V W
Return Value
X
A System.String containing the modified path information. Platforms that do not support this feature return path unmodified.
Y Z
2457
Contents | Index
Path
System.IO
Combine() Method
Description The exact behavior of this method is platform-specific. This method checks path for invalid characters as defined by the current platform and file system. A
Exceptions
B C
Exception
Condition
System.ArgumentException
path contains one or more implementation-defined invalid characters.
D E F G
Example
H
using System; using System.IO;
I
namespace Samples { public class PathChangeExtension { public static void Main() { string s = Path.GetFullPath("s.text"); Console.WriteLine( "Before ChangeExtension: {0}", s); Console.WriteLine("ChangeExtension: {0}", Path.ChangeExtension(s, "txt")); } } }
J K L M N O P Q R S
The output is
T
Before ChangeExtension: C:\Books\BCL\Samples\System.IO\Path\ ChangeExtension(System.String,System.String)\s.text ChangeExtension: C:\Books\BCL\Samples\System.IO\Path\ ChangeExtension(System.String,System.String)\s.txt
U V W X
Path.Combine(System.String, System.String) Method
Y [ILASM]
Z
.method public hidebysig static string Combine(string path1, string path2) [C#]
public static string Combine(string path1, string path2)
2458
Contents | Index
System.IO
Path Combine() Method
Summary Concatenates two path strings. A
Parameters
B
Parameter
Description
C
path1
A System.String containing the first path.
D
path2
A System.String containing the second path.
E F G
Return Value
H
A System.String containing path1 followed by path2. If one of the specified paths is a zero length string, this method returns the other path. If path2 contains an absolute path, this method returns path2.
I J K
Description
L
If path1 does not end with a valid separator character (System.IO.Path.DirectorySeparatorChar or System.IO.Path.AltDirectorySeparatorChar), DirectorySeparatorChar is appended to path1 prior to the concatenation.
M N O
Exceptions
P
Exception
Condition
System.ArgumentNullException
path1 or path2 is null.
System.ArgumentException
path1 or path2 contains one or more implementationdefined invalid characters.
Q R S T U V
Example
W
using System; using System.IO;
X Y
namespace Samples { public class PathCombine { public static void Main()
Z
2459
Contents | Index
Path
System.IO
GetDirectoryName() Method
{ string s = Path.GetFullPath("s.text"); s = Path.Combine(Path.GetDirectoryName(s), "Path.cs"); Console.WriteLine("Combine: {0}", s); Console.WriteLine("GetExtension: {0}", Path.GetExtension(s)); Console.WriteLine("GetFileName: {0}", Path.GetFileName(s));
A B C D
} }
E
}
F
The output is
G
Combine: C:\Books\BCL\Samples\System.IO\Path\ Combine(System.String,System.String)\Path.cs GetExtension: .cs GetFileName: Path.cs
H I J K L
Path.GetDirectoryName(System.String) Method
M
[ILASM]
.method public hidebysig static string GetDirectoryName(string path)
N
[C#]
O
public static string GetDirectoryName(string path)
P
Summary
Q
Returns the directory name component of the specified path string.
R
Parameters
S T
Parameter
Description
path
A System.String containing the path of a file or directory.
U V W
Return Value
X
A System.String containing directory information for path, or null if path denotes a root directory, is the empty string, or is null. Returns System.String.Empty if path does not contain directory information.
Y Z
2460
Contents | Index
System.IO
Path GetDirectoryName() Method
Description The string returned by this method consists of all characters between the first and last System.IO.Path.DirectorySeparatorChar or System.IO.Path.AltDirectorySeparatorChar character in path. The first separator character is included, but the last separator character is not included in the returned string.
A B C
Exceptions
D
Exception
Condition
System.ArgumentException
path contains one or more implementation-defined invalid characters.
E F G H
Example
I
using System; using System.IO;
J K
namespace Samples { public class PathGetDirectoryName { public static void Main() { string s = Path.GetFullPath("s.text"); Console.WriteLine("GetDirectoryName: {0}", Path.GetDirectoryName(s)); Console.WriteLine("GetExtension: {0}", Path.GetExtension(s)); Console.WriteLine("GetFileName: {0}", Path.GetFileName(s)); Console.WriteLine( "GetFileNameWithoutExtension: {0}", Path.GetFileNameWithoutExtension(s)); } } }
L M N O P Q R S T U V W
The output is
X Y
GetDirectoryName: C:\Books\BCL\Samples\System.IO\Path\ GetDirectoryName(System.String) GetExtension: .text GetFileName: s.text GetFileNameWithoutExtension: s
Z
2461
Contents | Index
Path
System.IO
GetExtension() Method
Path.GetExtension(System.String) Method [ILASM]
.method public hidebysig static string GetExtension(string path)
A
[C#]
public static string GetExtension(string path)
B C
Summary
D
Returns the extension component of the specified path string.
E
Parameters
F G
Parameter
Description
path
A System.String containing the path information from which to get the extension.
H I J K
Return Value
L
A System.String containing the extension of path, null, or System.String.Empty. If path is null, returns null. If path does not have extension information, returns System.String.Empty. The extension returned by this method includes the platform-specific extension separator character used to separate the extension from the rest of the path. Platforms that do not support this feature return path unmodified.
M N O P Q
Description
R
The exact behavior of this method is platform-specific. The character used to separate the extension from the rest of the path is platform-specific.
S T
Exceptions
U V
Exception
Condition
System.ArgumentException
path contains one or more implementation-defined invalid characters.
W X Y Z
2462
Contents | Index
System.IO
Path GetFileName() Method
Example using System; using System.IO;
A namespace Samples { public class GetExtension { public static void Main() { string s = Path.GetFullPath("s.text"); Console.WriteLine("GetExtension: {0}", Path.GetExtension(s)); Console.WriteLine("GetFileName: {0}", Path.GetFileName(s)); Console.WriteLine( "GetFileNameWithoutExtension: {0}", Path.GetFileNameWithoutExtension(s)); } } }
B C D E F G H I J K L
The output is
M
GetExtension: .text GetFileName: s.text GetFileNameWithoutExtension: s
N O P Q
Path.GetFileName(System.String) Method
R
[ILASM]
S
.method public hidebysig static string GetFileName(string path) [C#]
T
public static string GetFileName(string path)
U
Summary
V
Returns the file name, including the extension, if any, of the specified path string.
W X Y Z
2463
Contents | Index
Path
System.IO
GetFileName() Method
Parameters Parameter
Description
path
A System.String containing the path information from which to obtain the filename and extension.
A B C D
Return Value
E
A System.String consisting of the characters after the last directory character in path. If the last character of path is a directory separator character, returns System.String.Empty. If path is null, returns null. Platforms that do not support this feature return path unmodified.
F G H
Description
I
The directory separator characters used to determine the start of the file name are System.IO.Path.DirectorySeparatorChar and System.IO.Path.AltDirectorySeparatorChar.
J K L
Exceptions
M N
Exception
Condition
System.ArgumentException
path contains one or more implementation-defined invalid characters.
O P Q R
Example
S
using System; using System.IO;
T namespace Samples { public class PathGetFileName { public static void Main() { string s = Path.GetFullPath("s.text"); Console.WriteLine("GetFileName: {0}", Path.GetFileName(s)); Console.WriteLine("GetExtension: {0}", Path.GetExtension(s));
U V W X Y Z
2464
Contents | Index
System.IO
Path GetFileNameWithoutExtension() Method
Console.WriteLine( "GetFileNameWithoutExtension: {0}", Path.GetFileNameWithoutExtension(s)); }
A
} }
B C
The output is
D GetFileName: s.text GetExtension: .text GetFileNameWithoutExtension: s
E F G
Path.GetFileNameWithoutExtension(System.String) Method
H
[ILASM]
I
.method public hidebysig static string GetFileNameWithoutExtension(string path)
J
[C#]
public static string GetFileNameWithoutExtension(string path)
K L
Summary
M
Returns the file base component of the specified path string without the extension.
N
Parameters
O
Parameter
Description
path
A System.String containing the path of the file.
P Q R S
Return Value
T
A System.String consisting of the string returned by System.IO.Path.GetFileName, minus the platform-specific extension separator character and extension. Platforms that do not support this feature return path unmodified.
U V W
Description
X
[Note: For additional details, see System.IO.Path.GetFileName.]
Y Z
2465
Contents | Index
Path
System.IO
GetFullPath() Method
Exceptions Exception
Condition
System.ArgumentException
path contains one or more implementation-defined invalid characters.
A B C D
Example
E
using System; using System.IO;
F G
namespace Samples { public class PathGetFileNameWithoutExtension { public static void Main() { string s = Path.GetFullPath("s.text"); Console.WriteLine("GetFileName: {0}", Path.GetFileName(s)); Console.WriteLine("GetExtension: {0}", Path.GetExtension(s)); Console.WriteLine( "GetFileNameWithoutExtension: {0}", Path.GetFileNameWithoutExtension(s)); } } }
H I J K L M N O P Q R
The output is
S GetFileName: s.text GetExtension: .text GetFileNameWithoutExtension: s
T U V W
Path.GetFullPath(System.String) Method
X
[ILASM]
.method public hidebysig static string GetFullPath(string path)
Y
[C#]
public static string GetFullPath(string path)
Z
2466
Contents | Index
System.IO
Path GetFullPath() Method
Summary Returns information required to uniquely identify a file within a file system. A
Parameters
B
Parameter
Description
path
A System.String containing the file or directory for which to obtain absolute path information.
C D E F
Return Value
G
A System.String containing the fully qualified (absolute) location of path.
H
Description
I
The absolute path includes all information required to locate a file or directory on a system. The file or directory specified by path is not required to exist; however if path does exist, the caller is required to have permission to obtain path information for path. Note that unlike most members of the System.IO.Path class, this method accesses the file system.
J K L M
Exceptions
N
Exception
Condition
System.ArgumentException
path is a zero-length string, contains only white space, or contains one or more implementationdefined invalid characters.
O P Q R
The system could not retrieve the absolute path.
S System.Security.SecurityException
The caller does not have the required permissions.
System.ArgumentNullException
path is null.
U
System.IO.PathTooLongException
The length of path or the absolute path information for path exceeds the system-defined maximum length.
V
T
W X Y Z
2467
Contents | Index
Path
System.IO
GetPathRoot() Method
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission to access path information. See System.Security.Permissions.FileIOPermissionAccess.PathDiscovery.
A B C D E
Example
F
using System; using System.IO;
G namespace Samples { public class GetFullPath { public static void Main() { string s = Path.GetFullPath("s.text"); Console.WriteLine("GetFullPath: {0}", s); Console.WriteLine("GetFileName: {0}", Path.GetFileName(s)); Console.WriteLine("GetExtension: {0}", Path.GetExtension(s)); Console.WriteLine( "GetFileNameWithoutExtension: {0}", Path.GetFileNameWithoutExtension(s)); } } }
H I J K L M N O P Q R S
The output is
T GetFullPath: C:\Books\BCL\Samples\System.IO\Path\GetFullPath(System.String)\s.text GetFileName: s.text GetExtension: .text GetFileNameWithoutExtension: s
U V W X
Path.GetPathRoot(System.String) Method
Y
[ILASM]
Z
.method public hidebysig static string GetPathRoot(string path) [C#]
public static string GetPathRoot(string path)
2468
Contents | Index
System.IO
Path GetPathRoot() Method
Summary Returns the path root component of the specified path. A
Parameters
B
Parameter
Description
C
A System.String containing the path from which to obtain root directory information.
D
path
E F
Return Value
G
A System.String containing the root directory of path, or null if path is null. Returns System.String.Empty if the specified path does not contain root information. Platforms that do not support this feature return path unmodified.
H I J
Description
K
This method does not verify that the path exists. The exact behavior of this method is platform-specific.
L M
Exceptions
N O
Exception
Condition P
System.ArgumentException
path contains one or more implementation-defined invalid characters or is equal to System.String.Empty.
Q R S
Example
T
using System; using System.IO;
U V
namespace Samples { public class GetPathRoot { public static void Main() { string s = Path.GetFullPath("s.text"); Console.WriteLine("GetFullPath: {0}", Path.GetFullPath("Path.cs"));
W X Y Z
2469
Contents | Index
Path
System.IO
GetTempFileName() Method
Console.WriteLine("GetPathRoot: {0}", Path.GetPathRoot(s)); } }
A
}
B
The output is
C
GetFullPath: C:\Books\BCL\Samples\System.IO\Path\GetPathRoot(System.String)\Path.cs GetPathRoot: C:\
D E F
Path.GetTempFileName() Method
G H
[ILASM]
I
[C#]
.method public hidebysig static string GetTempFileName() public static string GetTempFileName()
J K
Summary
L
Returns a unique temporary file name and creates a 0-byte file by that name on disk.
M
Return Value
N
A System.String containing the name of the temporary file. Platforms that do not support this feature return System.String.Empty.
O P Q
Example
R
using System; using System.IO;
S
namespace Samples { public class PathGetTempFileName { public static void Main() { string s = Path.GetTempFileName(); Console.WriteLine("GetTempFileName: {0}", s); File.Delete(s); Console.WriteLine("GetTempPath: {0}", Path.GetTempPath()); } } }
T U V W X Y Z
2470
Contents | Index
System.IO
Path GetTempPath() Method
The output is GetTempFileName: C:\DOCUME~1\damien\LOCALS~1\Temp\tmp8E.tmp GetTempPath: C:\DOCUME~1\damien\LOCALS~1\Temp\
A B
Path.GetTempPath() Method
C
[ILASM]
D
.method public hidebysig static string GetTempPath()
E
[C#]
public static string GetTempPath()
F G
Summary
H
Returns the path information of a temporary directory.
I
Return Value
J
A System.String containing the full directory name of a temporary directory. The information returned by this method is platform-specific. Platforms that do not support this feature return System.String.Empty.
K L M
Description
N
On platforms that provide a mechanism for users to discover this information (for example, by checking an environment variable), implementations of the CLI return the same information as the platform-specific mechanism.
O P Q
Exceptions
R
Exception
Condition
System.Security.SecurityException
The caller does not have the required permission.
S T U V
Permissions
W
Permission
Description
System.Security.Permissions.EnvironmentPermission
Requires unrestricted access to environment variables. See System.Security.Permissions.PermissionState.Unrestricted.
X Y Z
2471
Contents | Index
Path
System.IO
HasExtension() Method
Example using System; using System.IO;
A namespace Samples { public class PathGetTempPath { public static void Main() { string s = Path.GetTempFileName(); Console.WriteLine("GetTempFileName: {0}", s); File.Delete(s); Console.WriteLine("GetTempPath: {0}", Path.GetTempPath()); } } }
B C D E F G H I J
The output is
K L
GetTempFileName: C:\DOCUME~1\damien\LOCALS~1\Temp\tmp91.tmp GetTempPath: C:\DOCUME~1\damien\LOCALS~1\Temp\
M N O
Path.HasExtension(System.String) Method
P
[ILASM]
.method public hidebysig static bool HasExtension(string path)
Q
[C#]
public static bool HasExtension(string path)
R S
Summary
T
Returns a System.Boolean indicating whether the specified path includes an extension component.
U V
Parameters
W X Y
Parameter
Description
path
A System.String containing the path to search for an extension.
Z
2472
Contents | Index
System.IO
Path HasExtension() Method
Return Value true if path includes a file extension. Platforms that do not support this feature return false. A
Exceptions
B C
Exception
Condition
System.ArgumentException
path contains one or more implementation-defined invalid characters.
D E F G
Example
H
using System; using System.IO;
I J
namespace Samples { public class PathHasExtension { public static void Main() { string s = Path.GetFullPath("s.text"); Console.WriteLine("HasExtension {0}: {1}", s ,Path.HasExtension(s)); Console.WriteLine("ChangeExtension: {0}", Path.ChangeExtension(s, "txt")); s = Path.GetFileNameWithoutExtension(s); Console.WriteLine("HasExtension {0}: {1}", s ,Path.HasExtension(s)); } } }
K L M N O P Q R S T U
The output is
V HasExtension C:\Books\BCL\Samples\System.IO\Path\HasExtension(System.String)\ s.text: True ChangeExtension: C:\Books\BCL\Samples\System.IO\Path\HasExtension(System.String)\ s.txt HasExtension s: False
W X Y Z
2473
Contents | Index
Path
System.IO
IsPathRooted() Method
Path.IsPathRooted(System.String) Method [ILASM]
.method public hidebysig static bool IsPathRooted(string path)
A
[C#]
public static bool IsPathRooted(string path)
B C
Summary
D
Returns a System.Boolean indicating whether the specified path string contains a path root component.
E F
Parameters
G H
Parameter
Description
path
A System.String containing the path to test.
I J K
Return Value
L
true if path contains an absolute path; false if path contains relative path information. Platforms that do not support this feature return false.
M N
Description
O
[Note: This method does not access file systems or verify the existence of the specified path.]
P Q
Exceptions
R S
Exception
Condition
System.ArgumentException
path contains one or more implementation-defined invalid characters.
T U V W
Example
X
using System; using System.IO;
Y namespace Samples { public class PathIsPathRooted {
Z
2474
Contents | Index
System.IO
Path IsPathRooted() Method
public static void Main() { string s = Path.GetFullPath("s.text"); Console.WriteLine("IsPathRooted {0}: {1}", s, Path.IsPathRooted(s)); s = Path.GetFileName(s); Console.WriteLine("IsPathRooted {0}: {1}", s, Path.IsPathRooted(s)); }
A B C D E
}
F
}
G
The output is
H IsPathRooted C:\Books\BCL\Samples\System.IO\Path\IsPathRooted(System.String)\ s.text: True IsPathRooted s.text: False
I J K L M N O P Q R S T U V W X Y Z
2475
Contents | Index
System.IO PathTooLongException
BCL
Object
A
Exception
B
ISerializable
NotStandardized
SystemException IOException
C
PathTooLongException
D E
Summary
F
Represents the error that occurs when a directory or file name is longer than the systemdefined maximum length.
G H
Type Summary
I
public class PathTooLongException : IOException { // Constructors public PathTooLongException(); public PathTooLongException(string message); public PathTooLongException(string message, Exception innerException); MS CF protected PathTooLongException (SerializationInfo info, StreamingContext context); }
J K L M N O P
Example
Q
using System; using System.IO;
R namespace Samples { public class PathTooLongExceptionSample { public static void Main() { try { string p = @"This\Is\A\Very\Long\Path\" + @"But\It\Is\Only\An\Example\"; string s = @"C:\" + p + p + p + p + p + p + "filename.txt"; FileStream fs = File.Create(s); }
S T U V W X Y Z
2476
Contents | Index
System.IO
PathTooLongException PathTooLongException() Constructor
catch(PathTooLongException e) { Console.WriteLine("Exception: {0}", e); }
A
} }
B
}
C
The output is
D E
Exception: System.IO.PathTooLongException: The path is too long after being fully qualified. Make sure path is less than 260 characters. at System.IO.Path.nGetFullPathHelper(String path, Char[] invalidPathChars, Char[] whitespaceChars, Char directorySeparator, Char altDirectorySeparator, Boolean fullCheck, String& newPath) at System.IO.Path.GetFullPathInternal(String path) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean useAsync, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize) at System.IO.File.Create(String path) at Samples.PathTooLongExceptionSample.Main() in C:\Books\BCL\Samples\System.IO\ PathTooLongException\PathTooLongException.cs:line 16
F G H I J K L M N O
PathTooLongException() Constructor
P
[ILASM]
public rtspecialname specialname instance void .ctor()
Q
[C#]
R
public PathTooLongException()
S
Summary
T
Constructs and initializes a new instance of the System.IO.PathTooLongException class.
U V
Description
W
This constructor initializes the System.IO.PathTooLongException.Message property of the new instance to a system-supplied message that describes the error, such as “The supplied path is too long.” This message takes into account the current system culture. The System.IO.PathTooLongException.InnerException property of the new instance is initialized to null.
X Y Z
2477
Contents | Index
PathTooLongException
System.IO
PathTooLongException() Constructor
PathTooLongException(System.String) Constructor [ILASM]
public rtspecialname specialname instance void .ctor(string message)
A
[C#]
public PathTooLongException(string message)
B C
Summary
D
Constructs and initializes a new instance of the System.IO.PathTooLongException class.
E F
Parameters
G H
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
I J K L
Description
M
This constructor initializes the System.IO.PathTooLongException.Message property of the new instance using message. If message is null, the System.IO.PathTooLongException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.IO.PathTooLongException.InnerException property of the new instance is initialized to null.
N O P Q R S
PathTooLongException(System.String, System.Exception) Constructor
T
[ILASM]
U
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
V
[C#]
W
public PathTooLongException(string message, Exception innerException)
X
Summary
Y
Constructs and initializes a new instance of the System.IO.PathTooLongException class.
Z
2478
Contents | Index
System.IO
PathTooLongException PathTooLongException() Constructor
Parameters Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
A
innerException
B C D
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
E F G
Description
H
This constructor initializes the System.IO.PathTooLongException.Message property of the new instance using message and the System.IO.PathTooLongException.InnerException property using innerException. If message is null, the System.IO.PathTooLongException.Message property is initialized to the systemsupplied message provided by the constructor that takes no arguments. [Note: For more information on inner exceptions, see System.Exception.InnerException.]
I J K L M N
PathTooLongException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
O P
[ILASM]
Q
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
R
[C#]
S
protected PathTooLongException(SerializationInfo info, StreamingContext context)
T U
Summary
V
Initializes a new instance of the System.IO.PathTooLongException class with the specified serialization and context information.
W X Y Z
2479
Contents | Index
PathTooLongException
System.IO
PathTooLongException() Constructor
Parameters Parameter
Description
info
The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown.
context
The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
2480
Contents | Index
System.Security PermissionSet
BCL
IDictionary ISecurityEncodable Object PermissionSet
NotStandardized
ICollection
A
IEnumerable
B
IStackWalk
C
NotStandardized
IDeserializationCallback
D
NotStandardized
E
Summary
F
Represents a collection that can contain different kinds of permissions and perform security operations.
G H
Type Summary
I
CF public class PermissionSet : ISecurityEncodable, ICollection, IEnumerable, IStackWalk, IDeserializationCallback { // Constructors CF public PermissionSet (PermissionSet permSet); CF public PermissionSet (PermissionState state);
J K L M N
MS MS MS MS
// CF CF CF CF
// CF CF MS CF MS CF
CF CF CF CF CF CF CF CF
Properties public virtual public virtual public virtual public virtual
O
int Count { get; } bool IsReadOnly { get; } bool IsSynchronized { get; } object SyncRoot { get; }
P Q R
Methods public virtual IPermission AddPermission(IPermission perm); public virtual void Assert(); public bool ContainsNonCodeAccessPermissions (); public static byte[] ConvertPermissionSet (string inFormat, byte[] inData, string outFormat); public virtual PermissionSet Copy (); public virtual void CopyTo (Array array, int index); public virtual void Demand(); public virtual void Deny(); public virtual void FromXml (SecurityElement et); public virtual IEnumerator GetEnumerator(); public virtual bool IsSubsetOf(PermissionSet target); public virtual void PermitOnly();
S T U V W X Y Z
2481
Contents | Index
PermissionSet
System.Security
PermissionSet Class
CF public override string ToString (); CF public virtual SecurityElement ToXml (); CF public virtual PermissionSet Union(PermissionSet other);
A
// Explicit Interface Members MS CF void IDeserializationCallback.OnDeserialization (object sender); }
B C D
Description
E
[Note: Use System.Security.PermissionSet to perform operations on different permission types as a group.] The XML encoding of a System.Security.PermissionSet instance is defined below in EBNF format. The following conventions are used:
F G H
• • • •
I J K L
•
M
•
N O
• • •
P Q R S
All non-literals in the grammar below are shown in normal type. All literals are in bold font. The following meta-language symbols are used: '*' represents a meta-language symbol suffixing an expression that can appear zero or more times. '?' represents a meta-language symbol suffixing an expression that can appear zero or one time. '+' represents a meta-language symbol suffixing an expression that can appear one or more times. '(',')' is used to group literals, non-literals, or a mixture of literals and non-literals. '|' denotes an exclusive disjunction between two expressions. '::= ' denotes a production rule where a left hand non-literal is replaced by a right hand expression containing literals, non-literals, or both. The XML encoding of a System.Security.PermissionSet instance is as follows:
T PermissionSet::= ( ) | ( DnsPermissionXML ?
U V W X Y Z
2482
Contents | Index
System.Security
PermissionSet PermissionSet Class
SocketPermissionXML ? WebPermissionXML ? EnvironmentPermissionXML ? FileIOPermissionXML ? ReflectionPermissionXML ? SecurityPermissionXML ? CustomPermissionXML * )
A B C D
CustomPermissionXML represents any custom permission. The XML encoding for custom permissions makes use of the following symbols:
E
•
G
• • • •
•
F
ClassName is the name of the class implementing the permission. AssemblyName is the name of the assembly that contains the class implementing the permission. Version is the version number indicating the version of the assembly implementing the permission. StrongNamePublicKeyToken is the strong name public key token constituting the strong name of the assembly that implements the permission. version is version information for the custom permission. Format and content are defined by the author of the custom permission. PermissionAttributes is any attribute and attribute value on the System.Security.IPermission element used by the permission to represent a particular permission state, for example, unrestricted= "true". Format and content are defined by the author of the custom permission. PermissionXML is any valid XML used by the permission to represent permission state. Format and content are defined by the author of the custom permission.
H I J K L M N O P Q R
The XML encoding of a custom permission instance is as follows:
S CustomPermissionXML ::= (PermissionXML)?
T U V W X Y Z
2483
Contents | Index
PermissionSet
System.Security
PermissionSet Class
Example using using using using
A
System; System.Security; System.Security.Permissions; System.IO;
B namespace Samples { public class PermissionSetSample { private const string environmentVariable = "USERNAME"; private const string filename = "FileIOPermission.txt"; public static void Main() { PermissionSet ps1 = new PermissionSet(PermissionState.None); EnvironmentPermission ep = new EnvironmentPermission( EnvironmentPermissionAccess.Read, environmentVariable); ps1.AddPermission(ep); PermissionSet ps2 = new PermissionSet(PermissionState.None); string s = Path.GetFullPath(filename); FileIOPermission fp = new FileIOPermission( FileIOPermissionAccess.Read | FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, s); ps2.AddPermission(fp); PermissionSet ps = ps1.Union(ps2); Console.WriteLine("Count: {0}", ps.Count); Console.WriteLine("Is read only: {0}", ps.IsReadOnly); Console.WriteLine( "Contains Non-CodeAccessPermissions: {0}", ps.ContainsNonCodeAccessPermissions()); Console.WriteLine( "ps1.IsSubsetOf(ps): {0}", ps1.IsSubsetOf(ps)); Console.WriteLine( "ps.IsUnrestricted(): {0}", ps.IsUnrestricted()); Console.WriteLine(ps);
C D E F G H I J K L M N O P Q R S T U V W X Y Z
2484
Contents | Index
System.Security
PermissionSet PermissionSet Class
ps.Assert(); TestAccess(); CodeAccessPermission.RevertAssert(); ps.Deny(); TestAccess(); CodeAccessPermission.RevertDeny(); ps.PermitOnly(); TestAccess(); CodeAccessPermission.RevertPermitOnly();
A B C D
} public static void TestAccess() { try { Console.WriteLine("Variable {0} Value: {1}", environmentVariable, Environment.GetEnvironmentVariable( environmentVariable)); } catch(Exception) { Console.WriteLine("Variable {0} cannot be read", environmentVariable); } try { FileStream fs = new FileStream( filename, FileMode.OpenOrCreate); Console.WriteLine("File {0} can be accessed", filename); fs.Close(); } catch (Exception) { Console.WriteLine("File {0} cannot be accessed", filename); } }
E F G H I J K L M N O P Q R S T U V
}
W
}
X
The output is
Y
Count: 2 Is read only: False Contains Non-CodeAccessPermissions: False ps1.IsSubsetOf(ps): True
Z
2485
Contents | Index
PermissionSet
System.Security
PermissionSet() Constructor
ps.IsUnrestricted(): False
A B C D E F G H I
Variable USERNAME Value: damien File FileIOPermission.txt can be accessed Variable USERNAME cannot be read File FileIOPermission.txt cannot be accessed Variable USERNAME Value: damien File FileIOPermission.txt can be accessed
J K L M N O
PermissionSet(System.Security.PermissionSet) Constructor
P
[ILASM]
Q
public rtspecialname specialname instance void .ctor(class System.Security.PermissionSet permSet)
R
[C#]
public PermissionSet(PermissionSet permSet)
S T
Summary
U
Constructs a new instance of the System.Security.PermissionSet class with the values of the specified System.Security.PermissionSet instance.
V W
Parameters
X Y
Parameter
Description
permSet
The System.Security.PermissionSet instance with which to initialize the values of the new instance, or null to initialize an empty permission set.
Z
2486
Contents | Index
System.Security
PermissionSet PermissionSet() Constructor
Description If permSet is not null, the new instance is initialized with copies of the objects in permSet, not references to those objects. If permSet is null, the new instance contains no permissions. [Note: To add a permission to an empty System.Security.PermissionSet, use System.Security.PermissionSet.AddPermission.]
A B C
Exceptions
D
Exception
Condition
System.ArgumentException
permSet is not null and is not an instance of System.Security.PermissionSet.
E F G H
Example
I
using System; using System.Security; using System.Security.Permissions;
J K L
namespace Samples { public class PermissionSetConstructor { private const string environmentVariable = "USERNAME"; public static void Main() { PermissionSet ps1 = new PermissionSet(PermissionState.None); EnvironmentPermission ep = new EnvironmentPermission( EnvironmentPermissionAccess.Read, environmentVariable); ps1.AddPermission(ep); PermissionSet ps2 = new PermissionSet(ps1); Console.WriteLine(ps2); } } }
M N O P Q R S T U V W X Y Z
2487
Contents | Index
PermissionSet
System.Security
PermissionSet() Constructor
The output is
A B C D E F
PermissionSet(System.Security.Permissions.PermissionState) Constructor
G
[ILASM]
H
public rtspecialname specialname instance void .ctor(valuetype System.Security.Permissions.PermissionState state) [C#]
I
public PermissionSet(PermissionState state)
J K
Summary
L
Constructs a new instance of the System.Security.PermissionSet class with the specified value.
M
Parameters
N O
Parameter
Description
state
A System.Security.Permissions.PermissionState value. This value is either System.Security.Permissions.PermissionState.None or System.Security.Permissions.PermissionState.Unrestricted, to specify fully restricted or fully unrestricted access.
P Q R S T
Description
U
[Note: The new instance contains no permissions. To add a permission to the new instance, use System.Security.PermissionSet.AddPermission.]
V W
Exceptions
X Y
Exception
Condition
System.ArgumentException
state is not a valid System.Security.Permissions.PermissionState value.
Z
2488
Contents | Index
System.Security
PermissionSet Count Property
Example using System; using System.Security; using System.Security.Permissions;
A B
namespace Samples { public class PermissionSetConstructor { private const string environmentVariable = "USERNAME"; public static void Main() { PermissionSet ps = new PermissionSet(PermissionState.None); EnvironmentPermission ep = new EnvironmentPermission( EnvironmentPermissionAccess.Read, environmentVariable); ps.AddPermission(ep); Console.WriteLine(ps); } } }
C D E F G H I J K L M N
The output is
O
P Q R S T U
PermissionSet.Count Property
V
[ILASM]
.property int32 Count { public hidebysig virtual specialname int32 get_Count() }
W
[C#]
X
public virtual int Count { get; }
Y
Summary
Z
Gets the number of permission objects contained in the permission set.
2489
Contents | Index
PermissionSet
System.Security
IsReadOnly Property
Description In the None or Unrestricted state this returns zero, because no actual permission object instances are used. A B
PermissionSet.IsReadOnly Property
C
[ILASM]
D
.property bool IsReadOnly { public hidebysig virtual specialname bool get_IsReadOnly() }
E
[C#]
F
public virtual bool IsReadOnly { get; }
G
Summary
H
Gets a value indicating whether the collection is read-only.
I J
Property Value
K
Always false.
L M
Description
N
A System.Security.PermissionSet cannot be read-only, so this property is always false.
O P
PermissionSet.IsSynchronized Property
Q
[ILASM]
R
.property bool IsSynchronized { public hidebysig virtual specialname bool get_IsSynchronized() }
S
[C#]
T
public virtual bool IsSynchronized { get; }
U
Summary
V
Gets a value indicating whether the collection is guaranteed to be thread safe.
W X
Property Value
Y
Always false.
Z
2490
Contents | Index
System.Security
PermissionSet AddPermission() Method
Description System.Security.PermissionSet does not automatically handle thread safety, so this property is always false. This method is required to support System.Collections.ICollection.
A B C
PermissionSet.SyncRoot Property
D [ILASM]
E
.property object SyncRoot { public hidebysig virtual specialname object get_SyncRoot() }
F
[C#]
G
public virtual object SyncRoot { get; }
H
Summary
I
Gets the root object of the current collection.
J
Description
K
This method is required to support System.Collections.ICollection.
L M
PermissionSet.AddPermission(System.Security.IPermission) Method
N
[ILASM]
O
.method public hidebysig virtual class System.Security.IPermission AddPermission(class System.Security.IPermission perm)
P
[C#]
Q
public virtual IPermission AddPermission(IPermission perm)
R
Summary
S
Adds the specified System.Security.IPermission object to the current instance if that permission does not already exist in the current instance.
T U
Parameters
V W
Parameter
Description X
perm
The System.Security.IPermission object to add.
Y Z
2491
Contents | Index
PermissionSet
System.Security
AddPermission() Method
Return Value If perm is null, returns null. If a permission of the same type as perm already exists in the current instance, the union of the existing permission and perm is added to the current instance and is returned.
A B C
Behaviors
D
The System.Security.IPermission is added if perm is not null and a permission of the same type as perm does not already exist in the current instance.
E F
Usage
G
Use this method to add permission objects to the current instance.
H
Exceptions
I J
Exception
Condition
K
System.ArgumentException
perm is not a System.Security.IPermission object.
L M
Example
N
using System; using System.Security; using System.Security.Permissions;
O P
namespace Samples { public class PermissionSetAddPermission { private const string environmentVariable = "USERNAME"; public static void Main() { PermissionSet ps = new PermissionSet(PermissionState.None); EnvironmentPermission ep = new EnvironmentPermission( EnvironmentPermissionAccess.Read, environmentVariable); ps.AddPermission(ep); Console.WriteLine(ps); } } }
Q R S T U V W X Y Z
2492
Contents | Index
System.Security
PermissionSet Assert() Method
The output is
A B C D E
PermissionSet.Assert() Method
F
[ILASM]
G
.method public hidebysig virtual void Assert()
H
[C#]
public virtual void Assert()
I
Summary
J
Asserts that calling code can access the resources identified by the permissions contained in the current instance through the code that calls this method, even if callers have not been granted permission to access the resource.
K L M
Description
N
[Note: This method is the only way to assert multiple permissions at the same time within a frame because only a single assert can be active on a frame at one time; subsequent asserts will result in an exception.]
O P Q
Usage
R
Use this method to insure that all callers can access a set of secured resources.
S T
Exceptions
U
Exception
System.Security.SecurityException
Condition
V
The asserting code does not have sufficient permission to call this method.
W
-or-
X
This method was called with permissions already asserted for the current stack frame.
Y Z
2493
Contents | Index
PermissionSet
System.Security
Assert() Method
Permissions Permission
Description
System.Security.Permissions.SecurityPermission
Requires permission to perform the assertion security operation. See System.Security.Permissions.SecurityPermissionFlag.Assertion.
A B C D E
Example
F
using System; using System.Security; using System.Security.Permissions;
G
namespace Samples { public class PermissionSetAssert { private const string ev = "USERNAME"; public static void Main() { PermissionSet ps = new PermissionSet(PermissionState.Unrestricted); ps.Assert(); TestAccess(); CodeAccessPermission.RevertAssert(); ps.Deny(); TestAccess(); CodeAccessPermission.RevertDeny(); ps.PermitOnly(); TestAccess(); CodeAccessPermission.RevertPermitOnly(); } public static void TestAccess() { try { Console.WriteLine("Variable {0} Value: {1}", ev, Environment.GetEnvironmentVariable( ev)); } catch(Exception) { Console.WriteLine("Variable {0} cannot be read", ev); } } } }
H I J K L M N O P Q R S T U V W X Y Z
2494
Contents | Index
System.Security
PermissionSet ConvertPermissionSet() Method
The output is Variable USERNAME Value: damien Variable USERNAME cannot be read Variable USERNAME Value: damien
A B C
PermissionSet.ContainsNonCodeAccessPermissions() Method
D
[ILASM]
E
.method public hidebysig instance bool ContainsNonCodeAccessPermissions()
F
[C#]
public bool ContainsNonCodeAccessPermissions()
G
Summary
H
Gets a value indicating whether the System.Security.PermissionSet contains permissions that are not derived from System.Security.CodeAccessPermission.
I
Return Value
K
true if the System.Security.PermissionSet contains permissions that are not derived from System.Security.CodeAccessPermission; otherwise, false.
L
J
M N
PermissionSet.ConvertPermissionSet(System.String, System.Byte[], System.String) Method
O
[ILASM]
Q
.method public hidebysig static class System.Byte[] ConvertPermissionSet(string inFormat, class System.Byte[] inData, string outFormat)
R
P
[C#]
S
public static byte[] ConvertPermissionSet(string inFormat, byte[] inData, string outFormat)
T U
Summary
V
This method is for internal use only.
W
Return Value
X
An encryption of the System.Security.PermissionSet with the specified format.
Y Z
Description The method is used internally, and is not for use by application code.
2495
Contents | Index
PermissionSet
System.Security
Copy() Method
PermissionSet.Copy() Method [ILASM]
.method public hidebysig virtual class System.Security.PermissionSet Copy()
A
[C#]
public virtual PermissionSet Copy()
B C
Summary
D
Returns a new System.Security.PermissionSet containing copies of the objects in the current instance.
E F
Behaviors
G
This method creates copies of the permission objects in the current instance, and adds them to the new instance.
H I
Default
J
This method calls the System.Security.PermissionSet constructor that takes a System.Security.PermissionSet argument, and passes the current instance as that parameter.
K L M
Usage
N
Use this method to create a new System.Security.PermissionSet instance containing permissions that are identical to the permissions contained in the current instance.
O P Q
Example
R
using System; using System.Security; using System.Security.Permissions;
S T
namespace Samples { public class PermissionSetCopy { private const string ev = "USERNAME"; public static void Main() { PermissionSet ps = new PermissionSet(PermissionState.None); EnvironmentPermission ep =
U V W X Y Z
2496
Contents | Index
System.Security
PermissionSet CopyTo() Method
new EnvironmentPermission( EnvironmentPermissionAccess.Read, ev); ps.AddPermission(ep); PermissionSet ps1 = ps.Copy(); ep = new EnvironmentPermission( EnvironmentPermissionAccess.Write, ev); ps1.AddPermission(ep); Console.WriteLine(ps); Console.WriteLine(ps1);
A B C D E
}
F
} }
G
The output is
H I
J K L M N
O P Q R S T
PermissionSet.CopyTo(System.Array, System.Int32) Method
U [ILASM]
V
.method public hidebysig virtual void CopyTo(class System.Array array, int32 index)
W
[C#]
X
public virtual void CopyTo(Array array, int index)
Y
Summary
Z
Copies the permission objects in the current instance to the specified location in the specified System.Array.
2497
Contents | Index
PermissionSet
System.Security
CopyTo() Method
Parameters Parameter
Description
array
The destination System.Array.
index
A System.Int32 that specifies the zero-based starting position in the array at which to begin copying.
A B C D E
Description
F
[Note: This method is implemented to support the System.Collections.ICollection interface.]
G H I
Default
J
The default implementation uses the System.Array.SetValue(System.Object, System.Int32) method to add the value to the array.
K
How and When to Override
L
Override this method to customize the manner in which elements are added to array.
M N
Exceptions
O P Q
Exception
Condition
System.ArgumentException
array has more than one dimension.
System.IndexOutOfRangeException
index is outside the range of allowable values for array.
System.ArgumentNullException
array is null.
R S T U V
Example
W
using using using using
X Y
System; System.Security; System.Security.Permissions; System.IO;
namespace Samples { public class PermissionSetCopyTo {
Z
2498
Contents | Index
System.Security
PermissionSet CopyTo() Method
private const string environmentVariable = "USERNAME"; private const string filename = "FileIOPermission.txt"; public static void Main() { PermissionSet ps = new PermissionSet(PermissionState.None); EnvironmentPermission ep = new EnvironmentPermission( EnvironmentPermissionAccess.Read, environmentVariable); ps.AddPermission(ep); ep = new EnvironmentPermission( EnvironmentPermissionAccess.Write, environmentVariable); ps.AddPermission(ep); string s = Path.GetFullPath(filename); FileIOPermission fp = new FileIOPermission( FileIOPermissionAccess.Read | FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, s); ps.AddPermission(fp); Array a = Array.CreateInstance(typeof(IPermission), ps.Count); ps.CopyTo(a, 0); foreach(IPermission ip in a) Console.WriteLine(ip); }
A B C D E F G H I J K L M N O P Q
}
R
}
S
The output is
T
U V W X
Y Z
2499
Contents | Index
PermissionSet
System.Security
Demand() Method
Write="C:\Books\BCL\Samples\System.Security\PermissionSet\ CopyTo(System.Array,System.Int32)\FileIOPermission.txt" Append="C:\Books\BCL\Samples\System.Security\PermissionSet\ CopyTo(System.Array,System.Int32)\FileIOPermission.txt"/>
A B
PermissionSet.Demand() Method
C
[ILASM]
D
.method public hidebysig virtual void Demand()
E
[C#]
public virtual void Demand()
F G
Summary
H
Forces a System.Security.SecurityException if all callers do not have the permissions specified by the objects contained in the current instance.
I J
Behaviors
K
The permission check for System.Security.PermissionSet.Demand begins with the immediate caller of the code that calls this method and continues until all callers have been checked or a caller has been found that is not granted the demanded permission, in which case a System.Security.SecurityException exception is thrown. If the current instance is empty, a call to System.Security.PermissionSet.Demand succeeds.
L M N O P
Usage
Q
Use this method to ensure in a single operation that all callers have all permissions contained in a permission set.
R S
Exceptions
T U
Exception
Condition
System.Security.SecurityException
A caller does not have the permission specified by the current instance.
V W X Y Z
2500
Contents | Index
System.Security
PermissionSet Demand() Method
Example using System; using System.Security; using System.Security.Permissions;
A B
namespace Samples { public class PermissionSetDemand { public static void Main() { PermissionSet ps = new PermissionSet(PermissionState.Unrestricted); ps.Assert(); TestAccess(ps); CodeAccessPermission.RevertAssert(); ps.Deny(); TestAccess(ps); CodeAccessPermission.RevertDeny(); ps.PermitOnly(); TestAccess(ps); CodeAccessPermission.RevertPermitOnly(); } public static void TestAccess(PermissionSet ps) { try { ps.Demand(); Console.WriteLine("Demand succeeded"); } catch(Exception) { Console.WriteLine("Demand Failed"); } } } }
C D E F G H I J K L M N O P Q R S T U V
The output is
W Demand succeeded Demand Failed Demand succeeded
X Y Z
2501
Contents | Index
PermissionSet
System.Security
Deny() Method
PermissionSet.Deny() Method [ILASM]
.method public hidebysig virtual void Deny()
A
[C#]
public virtual void Deny()
B C
Summary
D
Denies access to the resources secured by the objects contained in the current instance through the code that calls this method.
E F
Description
G
This is the only way to deny multiple permissions at the same time within a frame because only a single deny can be active on a frame at one time; subsequent denies will result in an exception.
H I J
Behaviors
K
This method is required to prevent callers from accessing all resources protected by the objects in the current instance even if the callers had been granted permission to access them. A call to System.Security.PermissionSet.Deny is effective until the calling code returns.
L M N O
Usage
P
Use this method to force all security checks for the objects contained in the current instance to fail.
Q R
Exceptions
S T
Exception
Condition
System.Security.SecurityException
A previous call to Deny has already restricted the permissions for the current stack frame.
U V W X Y Z
2502
Contents | Index
System.Security
PermissionSet Deny() Method
Example using System; using System.Security; using System.Security.Permissions;
A B
namespace Samples { public class PermissionSetDeny { private const string ev = "USERNAME"; public static void Main() { PermissionSet ps = new PermissionSet(PermissionState.None); ps.Assert(); TestAccess(); CodeAccessPermission.RevertAssert(); ps.Deny(); TestAccess(); CodeAccessPermission.RevertDeny(); ps.PermitOnly(); TestAccess(); CodeAccessPermission.RevertPermitOnly(); } public static void TestAccess() { try { Console.WriteLine("Variable {0} Value: {1}", ev, Environment.GetEnvironmentVariable( ev)); } catch(Exception) { Console.WriteLine("Variable {0} cannot be read", ev); } } } }
C D E F G H I J K L M N O P Q R S T U V W X
The output is
Y Z
Variable USERNAME Value: damien Variable USERNAME Value: damien Variable USERNAME cannot be read
2503
Contents | Index
PermissionSet
System.Security
FromXml() Method
PermissionSet.FromXml(System.Security.SecurityElement) Method [ILASM]
A
.method public hidebysig virtual void FromXml(class System.Security.SecurityElement et)
B
[C#]
public virtual void FromXml(SecurityElement et)
C D
Summary
E
Reconstructs the state of a System.Security.PermissionSet object using the specified XML encoding.
F G
Parameters
H I
Parameter
Description
et
A System.Security.SecurityElement instance containing the XML encoding to use to reconstruct the state of a System.Security.PermissionSet object.
J K L M
Description
N
[Note: For the XML encoding for this class, see the System.Security.PermissionSet class page.]
O P
Behaviors
Q
When this call completes, the objects in the current instance are required to be identical to the objects in the System.Security.PermissionSet encoded in et.
R S
How and When to Override
T
Override this method to reconstruct subclasses of System.Security.PermissionSet.
U V
Usage
W
Applications do not typically call this method; it is called by the system.
X Y Z
2504
Contents | Index
System.Security
PermissionSet FromXml() Method
Exceptions Exception
Condition
System.ArgumentNullException
et is null.
System.ArgumentException
et does not contain an XML encoding for a System.Security.PermissionSet instance.
A B C D
An error occurred while reconstructing et.
E F
Example
G
using System; using System.Security; using System.Security.Permissions;
H I
namespace Samples { public class PermissionSetFromXml { private const string ev = "USERNAME"; public static void Main() { PermissionSet ps = new PermissionSet(PermissionState.None); EnvironmentPermission ep = new EnvironmentPermission( EnvironmentPermissionAccess.Read, ev); ps.AddPermission(ep); SecurityElement se = ps.ToXml(); Console.WriteLine(se); PermissionSet ps1 = new PermissionSet(PermissionState.None); ps1.FromXml(se); Console.WriteLine(ps1); } } }
J K L M N O P Q R S T U V W X
The output is
Y
Z
2505
Contents | Index
PermissionSet
System.Security
GetEnumerator() Method
version="1" Read="USERNAME"/>
A
B C D E F G
PermissionSet.GetEnumerator() Method
H
[ILASM]
I
.method public hidebysig virtual class System.Collections.IEnumerator GetEnumerator()
J
[C#]
public virtual IEnumerator GetEnumerator()
K L
Summary
M
Returns an enumerator used to iterate over the permissions in the current instance.
N
Description
O
[Note: This method is implemented to support the System.Collections.ICollection interface, which supports the System.Collections.IEnumerable interface.]
P Q R
How and When to Override
S
Override this method to customize the enumerator returned by this method.
T
Example
U
using using using using
V W X
System; System.Security; System.Security.Permissions; System.Collections;
namespace Samples { public class PermissionSetGetEnumerator { private const string ev = "USERNAME"; public static void Main()
Y Z
2506
Contents | Index
System.Security
PermissionSet IsSubsetOf() Method
{ PermissionSet ps = new PermissionSet(PermissionState.None); EnvironmentPermission ep = new EnvironmentPermission( EnvironmentPermissionAccess.Read, ev); ps.AddPermission(ep); ep = new EnvironmentPermission( EnvironmentPermissionAccess.Write, ev); ps.AddPermission(ep); IEnumerator ie = ps.GetEnumerator(); while(ie.MoveNext()) Console.WriteLine(ie.Current);
A B C D E F G H
} }
I
}
J
The output is
K
L M N O
PermissionSet.IsSubsetOf(System.Security.PermissionSet) Method
P
[ILASM]
Q
.method public hidebysig virtual bool IsSubsetOf(class System.Security.PermissionSet target)
R
[C#]
S
public virtual bool IsSubsetOf(PermissionSet target)
T
Summary
U
Determines whether the current instance is a subset of the specified object.
V W
Parameters
X
Parameter
Description
target
A System.Security.PermissionSet instance that is to be tested for the subset relationship.
Y Z
2507
Contents | Index
PermissionSet
System.Security
IsSubsetOf() Method
Return Value true if the current instance is a subset of target; otherwise, false. If the current instance is unrestricted, and target is not, returns false. If target is unrestricted, returns true. A B
Description
C
[Note: The current instance is a subset target if all demands that succeed for the current instance also succeed for target. That is, the current instance is a subset of target if target contains at least the permissions contained in the current instance. If this method returns true, the current instance does not describe a level of access to a set of resources that is not already described by target.]
D E F G
Usage
H
Use this method to determine if all permissions contained in the current instance are also contained in target.
I J
Example
K
using System; using System.Security; using System.Security.Permissions;
L M
namespace Samples { public class PermissionSetIsSubsetOf { private const string environmentVariable = "USERNAME"; private const string filename = "FileIOPermission.txt"; public static void Main() { PermissionSet ps1 = new PermissionSet(PermissionState.None); EnvironmentPermission ep = new EnvironmentPermission( EnvironmentPermissionAccess.Read, environmentVariable); ps1.AddPermission(ep); PermissionSet ps2 = new PermissionSet(PermissionState.None); string s = Path.GetFullPath(filename); FileIOPermission fp = new FileIOPermission( FileIOPermissionAccess.Read | FileIOPermissionAccess.Write |
N O P Q R S T U V W X Y Z
2508
Contents | Index
System.Security
PermissionSet PermitOnly() Method
FileIOPermissionAccess.Append, s); ps2.AddPermission(fp); PermissionSet ps = ps1.Union(ps2); Console.WriteLine( "ps1.IsSubsetOf(ps): {0}", ps1.IsSubsetOf(ps)); Console.WriteLine( "ps1.IsSubsetOf(ps1): {0}", ps1.IsSubsetOf(ps1)); Console.WriteLine( "ps.IsSubsetOf(ps1): {0}", ps.IsSubsetOf(ps1));
A B C D E F
}
G
} }
H I
The output is
J ps1.IsSubsetOf(ps): True ps1.IsSubsetOf(ps1): True ps.IsSubsetOf(ps1): False
K L M
PermissionSet.PermitOnly() Method
N
[ILASM]
O
.method public hidebysig virtual void PermitOnly()
P
[C#]
public virtual void PermitOnly()
Q R
Summary
S
Specifies that only the resources described by the current instance can be accessed by calling code, even if the code has been granted permission to access other resources.
T U
Description
V
[Note: System.Security.PermissionSet.PermitOnly is similar to System.Security.PermissionSet.Deny in that both methods cause access to fail where it might otherwise succeed. The difference is that System.Security.PermissionSet.Deny specifies permissions for which to refuse access, while System.Security.PermissionSet.PermitOnly specifies the only permissions that will succeed. This is the only way to permit multiple permissions at the same time within a stack frame because only a single permit at a time can be active on a frame; subsequent permits will result in an exception.]
W X Y Z
2509
Contents | Index
PermissionSet
System.Security
PermitOnly() Method
Behaviors Callers are required to be prevented from accessing resources not secured by the contents of the current instance, even if a caller has been granted permission to access such resources. A System.Security.PermissionSet.PermitOnly is in effect until the calling code returns to its caller.
A B C
Usage
D
Use this method to limit access to a specified set of resources.
E
Exceptions
F G
Exception
Condition
System.Security.SecurityException
A previous call to PermitOnly has already set the permissions for the current stack frame.
H I J K
Example
L
using System; using System.Security; using System.Security.Permissions;
M N
namespace Samples { public class PermissionSetPermitOnly { private const string ev = "USERNAME"; public static void Main() { PermissionSet ps = new PermissionSet(PermissionState.Unrestricted); ps.Assert(); TestAccess(); CodeAccessPermission.RevertAssert(); ps.Deny(); TestAccess(); CodeAccessPermission.RevertDeny(); ps.PermitOnly(); TestAccess(); CodeAccessPermission.RevertPermitOnly(); } public static void TestAccess() { try
O P Q R S T U V W X Y Z
2510
Contents | Index
System.Security
PermissionSet ToString() Method
{ Console.WriteLine("Variable {0} Value: {1}", ev, Environment.GetEnvironmentVariable(ev));
A
} catch(Exception) { Console.WriteLine("Variable {0} cannot be read", ev); }
B C D
}
E
}
F
}
G
The output is
H Variable USERNAME Value: damien Variable USERNAME cannot be read Variable USERNAME Value: damien
I J K
PermissionSet.ToString() Method
L
[ILASM]
M
.method public hidebysig virtual string ToString()
N
[C#]
O
public override string ToString()
P
Summary
Q
Returns a System.String representation of the state of the current instance.
R
Return Value
S
A System.String containing the XML representation of the state of the current instance.
T U
Description
V
[Note: This method overrides System.Object.ToString.]
W
Example
X
using System; using System.Security; using System.Security.Permissions;
Y Z
namespace Samples
2511
Contents | Index
PermissionSet
System.Security
ToXml() Method
{ public class PermissionSetToString { private const string ev = "USERNAME"; public static void Main() { PermissionSet ps = new PermissionSet(PermissionState.None); EnvironmentPermission ep = new EnvironmentPermission( EnvironmentPermissionAccess.Read, ev); ps.AddPermission(ep); Console.WriteLine(ps.ToString()); } }
A B C D E F G H I
}
J
The output is
K
L M N O P Q
PermissionSet.ToXml() Method
R S
[ILASM]
T
[C#]
.method public hidebysig virtual class System.Security.SecurityElement ToXml() public virtual SecurityElement ToXml()
U V
Summary
W
Returns the XML encoding of the current instance.
X
Return Value
Y
A System.Security.SecurityElement containing an XML encoding of the state of the current instance.
Z
2512
Contents | Index
System.Security
PermissionSet ToXml() Method
How and When to Override Override this method to return an object containing the XML encoding for types derived from System.Security.PermissionSet. A
Usage
B
This method is called by the system.
C
Example
D
using System; using System.Security; using System.Security.Permissions;
E F G
namespace Samples { public class PermissionSetToXml { private const string ev = "USERNAME"; public static void Main() { PermissionSet ps = new PermissionSet(PermissionState.None); EnvironmentPermission ep = new EnvironmentPermission( EnvironmentPermissionAccess.Read, ev); ps.AddPermission(ep); SecurityElement se = ps.ToXml(); Console.WriteLine(se); PermissionSet ps1 = new PermissionSet(PermissionState.None); ps1.FromXml(se); Console.WriteLine(ps1); } } }
H I J K L M N O P Q R S T U V
The output is
W
X Y Z
2513
Contents | Index
PermissionSet
System.Security
Union() Method
A B C D
PermissionSet.Union(System.Security.PermissionSet) Method
E
[ILASM]
F
.method public hidebysig virtual class System.Security.PermissionSet Union(class System.Security.PermissionSet other)
G
[C#]
H
public virtual PermissionSet Union(PermissionSet other)
I J
Summary
K
Returns a System.Security.PermissionSet object that is the union of the current instance and the specified object.
L
Parameters
M N
Parameter
Description
other
A System.Security.PermissionSet instance to be combined with the current instance.
O P Q R
Return Value
S
A new System.Security.PermissionSet instance that represents the union of the current instance and other. If the current instance or other is unrestricted, returns a System.Security.PermissionSet instance that is unrestricted.
T U V
Description
W
The result of a call to System.Security.PermissionSet.Union is a new System.Security.PermissionSet instance that represents all the operations represented by the current instance as well as all the operations represented by other. If either set is unrestricted, the union is unrestricted, as well.
X Y Z
2514
Contents | Index
System.Security
PermissionSet Union() Method
Usage Use this method to create a System.Security.PermissionSet instance that contains all of the permissions of the current instance and other. A
Example
B
using using using using
C
System; System.Security; System.Security.Permissions; System.IO;
D E
namespace Samples { public class PermissionSetUnion { private const string environmentVariable = "USERNAME"; private const string filename = "FileIOPermission.txt"; public static void Main() { PermissionSet ps1 = new PermissionSet(PermissionState.None); EnvironmentPermission ep = new EnvironmentPermission( EnvironmentPermissionAccess.Read, environmentVariable); ps1.AddPermission(ep); PermissionSet ps2 = new PermissionSet(PermissionState.None); string s = Path.GetFullPath(filename); FileIOPermission fp = new FileIOPermission( FileIOPermissionAccess.Read | FileIOPermissionAccess.Write | FileIOPermissionAccess.Append, s); ps2.AddPermission(fp); PermissionSet ps = ps1.Union(ps2); Console.WriteLine("Count: {0}", ps.Count); Console.WriteLine(ps); } } }
F G H I J K L M N O P Q R S T U V W X Y Z
2515
Contents | Index
PermissionSet
System.Security
OnDeserialization() Method
The output is Count: 2
A B C D E F G H I J K L
IDeserializationCallback.OnDeserialization(System.Object) Method
M
[ILASM]
.method private final hidebysig virtual void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(object sender)
N O
[C#]
P
void IDeserializationCallback.OnDeserialization(object sender)
Q
Summary
R
Implemented to support the System.Runtime.Serialization.IDeserializationCallback interface. [Note: For more information, see System.Runtime.Serialization.IDeserializationCallback.OnDeserialization.]
S T U V W X Y Z
2516
Contents | Index
System.Security.Permissions PermissionState Enum
BCL
Object
A
IComparable
ValueType Enum
B
IFormattable PermissionState
IConvertible
NotStandardized
C D
Summary
E
Represents a value specifying whether an entity, at creation, should have full or no access to resources.
F G
Type Summary CF public enum PermissionState CF None = 0, CF Unrestricted = 1, }
H {
I J K
Description
L
[Note: Code access permission objects supply a constructor that takes a System.Security.Permissions.PermissionState value specifying that the new instance is either fully restricted (System.Security.Permissions.PermissionState.None) or unrestricted (System.Security.Permissions.PermissionState.Unrestricted). A fully restricted permission object disallows access to a resource; an unrestricted permission object allows full access to a resource. For example, a fully restricted System.Security.Permissions.FileIOPermission object disallows access to files and directories, while an unrestricted object of the same type allows full access to all files and directories in the file system.]
M N O P Q R S
Example
T
using System; using System.Security; using System.Security.Permissions;
U V
namespace Samples { public class PermissionStateSample { public static void Main() { PermissionSet ps1 = new PermissionSet(PermissionState.None); EnvironmentPermission ep =
W X Y Z
2517
Contents | Index
PermissionState Enum
System.Security.Permissions
None Field
new EnvironmentPermission( EnvironmentPermissionAccess.Read, "USERNAME"); ps1.AddPermission(ep); PermissionSet ps2 = new PermissionSet(PermissionState.Unrestricted); PermissionSet ps = ps1.Union(ps2); Console.WriteLine( "ps1.IsUnrestricted(): {0}", ps1.IsUnrestricted()); Console.WriteLine( "ps2.IsUnrestricted(): {0}", ps2.IsUnrestricted()); Console.WriteLine( "ps.IsUnrestricted(): {0}", ps.IsUnrestricted());
A B C D E F G }
H }
I
}
J
The output is
K
ps1.IsUnrestricted(): False ps2.IsUnrestricted(): True ps.IsUnrestricted(): True
L M N
PermissionState.None Field
O
[ILASM]
P
.field public static literal valuetype System.Security.Permissions.PermissionState None
Q
[C#]
None = 0
R S
Summary
T
Specifies access to the resource protected by the permission is not allowed.
U V
PermissionState.Unrestricted Field
W
[ILASM]
X
.field public static literal valuetype System.Security.Permissions.PermissionState Unrestricted [C#]
Y
Unrestricted = 1
Z
Summary Specifies full access to the resource protected by the permission. 2518
Contents | Index
System Random
BCL
Object
A
Random
B
Summary
C
Generates pseudo-random numbers.
D E
Type Summary public class Random { // Constructors public Random (); public Random (int Seed);
F G H I
// Methods public virtual int Next (); public virtual int Next (int maxValue); public virtual int Next (int minValue, int maxValue); public virtual void NextBytes (byte[] buffer); public virtual double NextDouble (); MS protected virtual double Sample ();
J K L M
}
N O
KG The Random class provides a great mechanism for generating “pseudo”-random numbers. Don’t use it for mission-critical random generations, however, since it can’t be considered reliable enough for truly random generation.
P Q R S
Description
T
Instances of this class are initialized using a “seed,” or starting value. The series of numbers generated by instances of the class are repeatable: given the same seed value, all instances of this class generate the same series of numbers. [Note: The numbers generated by this class are chosen with equal probability from a finite set of numbers. The numbers are generated by a definite mathematical algorithm and are therefore not truly random, but are sufficiently random for practical purposes. For this reason, the numbers are considered to be pseudo-random.]
U V W X Y Z
2519
Contents | Index
Random
System
Random Class
Example using System; namespace Samples { public class RandomSample { public static void Main() { Random r = new Random(); DisplayNumbers(r, 4); r = new Random(); DisplayNumbers(r, 4); r = new Random(unchecked( (int)DateTime.Now.Ticks)); DisplayNumbers(r, 4); Byte[] bytes = new Byte[4]; r.NextBytes(bytes); Console.WriteLine("Bytes"); foreach(Byte b in bytes) Console.Write("{0} ", b); Console.WriteLine(); } public static void DisplayNumbers(Random r, int number) { Console.WriteLine("Integers"); for(int i = 0; i < number; i++) Console.Write("{0} ", r.Next()); Console.WriteLine(); Console.WriteLine("Doubles"); for(int i = 0; i < number; i++) Console.Write("{0} ", r.NextDouble()); Console.WriteLine(); } } }
A B C D E F G H I J K L M N O P Q R S T
The output is
U V
Integers 610101060 182710372 541839654 1122923352 Doubles 0.0368340453304509 0.107627541342577 0.0506987171483686 0.135695314563669 Integers 1091681015 41376261 520106915 1411608088 Doubles 0.551691442984944 0.84660560816834 0.531265693032772 0.152539342712862 Integers 620796866 1169353365 91436196 2009606433
W X Y Z
2520
Contents | Index
System
Random Random() Constructor
Doubles 0.948118089208434 0.42210969953896 0.893776561084099 0.835302507428128 Bytes 220 87 84 101
A B
Random() Constructor
C
[ILASM]
D
public rtspecialname specialname instance void .ctor()
E
[C#]
public Random()
F
Summary
G
Constructs a new instance of the Random class using System.Environment.TickCount as the seed value.
H
Description
J
This constructor is equivalent to System.Random(System.Environment.TickCount). [Note: When generating random numbers on high-performance systems, the system clock value may not produce the desired behavior. For details, see the System.Random(System.Int32) constructor.]
K
I
L M N O
Example
P
using System;
Q namespace Samples { public class RandomConstructor { public static void Main() { Random r = new Random(); DisplayNumbers(r, 4); r = new Random(); DisplayNumbers(r, 4); } public static void DisplayNumbers( Random r, int number) { Console.WriteLine("Integers"); for(int i = 0; i < number; i++) Console.Write("{0} ", r.Next()); Console.WriteLine();
R S T U V W X Y Z
2521
Contents | Index
Random
System
Random() Constructor
Console.WriteLine("Doubles"); for(int i = 0; i < number; i++) Console.Write("{0} ", r.NextDouble()); Console.WriteLine();
A
} }
B
}
C
The output is
D
Integers 534599988 1970616552 1572848393 1531957239 Doubles 0.544662795283209 0.564757734334449 0.487008893623487 0.689520894405209 Integers 431193064 1884226405 899133484 1891249467 Doubles 0.505242122572494 0.473077805933113 0.384585146039997 0.211685767030197
E F G H I J K
Random(System.Int32) Constructor
L
[ILASM]
public rtspecialname specialname instance void .ctor(int32 Seed)
M
[C#]
public Random(int Seed)
N O
Summary
P
Constructs a new instance of the Random class using the specified seed value.
Q
Parameters
R S
Parameter
Description
Seed
A System.Int32 used as the starting value for the pseudo-random number sequence.
T U V W
Description
X
[Note: To construct instances that produce different random number sequences, invoke this constructor using different seed values such as may be produced by the system clock. Note, however, that on high-performance systems, the system clock may not change between invocations of the constructor, in which case the seed value will be the same for different instances of Random. When this is the case, additional operations are required to have the seed values differ in each invocation.]
Y Z
2522
Contents | Index
System
Random Random() Constructor
Example using System; namespace Samples { public class RandomSample { public static void Main() { Random r = new Random(unchecked( (int)DateTime.Now.Ticks)); DisplayNumbers(r, 4); r = new Random(0); DisplayNumbers(r, 4); r = new Random(0); DisplayNumbers(r, 4); } public static void DisplayNumbers(Random r, int number) { Console.WriteLine("Integers"); for(int i = 0; i < number; i++) Console.Write("{0} ", r.Next()); Console.WriteLine(); Console.WriteLine("Doubles"); for(int i = 0; i < number; i++) Console.Write("{0} ", r.NextDouble()); Console.WriteLine(); } } }
A B C D E F G H I J K L M N O P Q
The output is
R S
Integers 1797309174 1416444663 46599787 99589755 Doubles 0.133466786301447 0.297470272657215 0.782007330461409 0.638022299687388 Integers 1559595546 1755192844 1649316166 1198642031 Doubles 0.206033154021033 0.558884794618415 0.906027066011926 0.442177873310716 Integers 1559595546 1755192844 1649316166 1198642031 Doubles 0.206033154021033 0.558884794618415 0.906027066011926 0.442177873310716
T U V W X Y Z
2523
Contents | Index
Random
System
Next() Method
Random.Next() Method [ILASM]
.method public hidebysig virtual int32 Next()
A
[C#]
public virtual int Next()
B C
Summary
D
Returns a pseudo-random number between 0 and System.Int32.MaxValue.
E
How and When to Override
F
Override this method to customize the algorithm used to generate the return value.
G H
Example
I
using System;
J
namespace Samples { public class RandomNext { public static void Main() { Random r = new Random(); DisplayNumbers(r, 4); r = new Random(0); DisplayNumbers(r, 4); r = new Random(0); DisplayNumbers(r, 4); } public static void DisplayNumbers(Random r, int number) { Console.WriteLine("Integers"); for(int i = 0; i < number; i++) Console.Write("{0} ", r.Next()); Console.WriteLine(); } } }
K L M N O P Q R S T U V W
The output is
X Integers 349836920 1406257971 272815387 1680925065 Integers 1559595546 1755192844 1649316166 1198642031 Integers 1559595546 1755192844 1649316166 1198642031
Y Z
2524
Contents | Index
System
Random Next() Method
Random.Next(System.Int32) Method [ILASM]
.method public hidebysig virtual int32 Next(int32 maxValue) [C#]
A
public virtual int Next(int maxValue)
B C
Summary
D
Returns a pseudo-random positive number less than the specified maximum.
E
Parameters
F G
Parameter
Description
maxValue
The upper bound of the random number to be generated. maxValue is required to be greater than or equal to zero.
H I J K
Return Value
L
A System.Int32 set to a pseudo-random value greater than or equal to zero and less than maxValue. If maxValue is zero, returns zero.
M N
How and When to Override
O
Override this method to customize the algorithm used to generate the return value.
P
Usage
Q
Use this method to generate a pseudo-random number less than the specified maximum value.
R
Exceptions
T
S
U
Exception
Condition
V
System.ArgumentOutOfRangeException
maxValue is less than zero.
W X Y Z
2525
Contents | Index
Random
System
Next() Method
Example using System; namespace Samples { public class RandomNext { public static void Main() { Random r = new Random(); DisplayNumbers(r, 4, 42); r = new Random(0); DisplayNumbers(r, 4, 42); r = new Random(0); DisplayNumbers(r, 4, 42); } public static void DisplayNumbers( Random r, int number, int max) { Console.WriteLine("Integers"); for(int i = 0; i < number; i++) Console.Write("{0} ", r.Next(max)); Console.WriteLine(); } } }
A B C D E F G H I J K L M N O
The output is
P
Integers 12 19 25 9 Integers 30 34 32 23 Integers 30 34 32 23
Q R S T U V
Random.Next(System.Int32, System.Int32) Method
W
[ILASM]
X
.method public hidebysig virtual int32 Next(int32 minValue, int32 maxValue) [C#]
Y
public virtual int Next(int minValue, int maxValue)
Z
Summary Returns a pseudo-random number within a specified range. 2526
Contents | Index
System
Random Next() Method
Parameters Parameter
Description
minValue
The lower bound of the random number returned.
maxValue
The upper bound of the random number returned.
A B C D
Return Value
E
A pseudo-random number greater than or equal to minValue and less than maxValue. If minValue and maxValue are equal, this value is returned.
F G H
How and When to Override
I
Override this method to customize the algorithm used to generate the return value.
J
Usage
K
Use this method to generate pseudo-random numbers in a specified range.
L M
Exceptions
N
Exception
Condition
O
System.ArgumentOutOfRangeException
minValue is greater than maxValue.
P Q R
Example
S
using System;
T
namespace Samples { public class RandomNext { public static void Main() { Random r = new Random(); DisplayNumbers(r, 4, 42, 4242); r = new Random(0); DisplayNumbers(r, 4, 42, 4242); r = new Random(0); DisplayNumbers(r, 4, 42, 4242); }
U V W X Y Z
2527
Contents | Index
Random
System
NextBytes() Method
public static void DisplayNumbers( Random r, int number, int min, int max) { Console.WriteLine("Integers"); for(int i = 0; i < number; i++) Console.Write("{0} ", r.Next(min, max)); Console.WriteLine(); }
A B C D
} }
E F
The output is
G Integers 1741 594 4114 2352 Integers 3092 3474 3267 2386 Integers 3092 3474 3267 2386
H I J K L M
Random.NextBytes(System.Byte[]) Method
N
[ILASM]
.method public hidebysig virtual void NextBytes(class System.Byte[] buffer)
O
[C#]
public virtual void NextBytes(byte[] buffer)
P Q
Summary
R
Populates the elements of a specified array of bytes with random numbers.
S
Parameters
T U
Parameter
Description
buffer
An array of bytes to be populated with random numbers.
V W X Y
Behaviors
Z
Each element of the array of bytes is set to a random number greater than or equal to zero, and less than or equal to System.Byte.MaxValue.
2528
Contents | Index
System
Random NextDouble() Method
How and When to Override Override this method to customize the algorithm used to generate the return value.
Usage
A
Use the NextByte method to populate a System.Byte array with random numbers.
B C
Exceptions
D
Exception
Condition
System.ArgumentNullException
buffer is a null reference.
E F G H
Example
I
using System;
J namespace Samples { public class RandomNextBytes { public static void Main() { Random r = new Random(); Byte[] bytes = new Byte[8]; r.NextBytes(bytes); Console.WriteLine("Bytes"); foreach(Byte b in bytes) Console.Write("{0} ", b); Console.WriteLine(); } } }
K L M N O P Q R S T
The output is
U V
Bytes 77 179 161 50 109 91 171 159
W X
Random.NextDouble() Method
Y
[ILASM]
Z
.method public hidebysig virtual float64 NextDouble() [C#]
public virtual double NextDouble()
2529
Contents | Index
Random
System
NextDouble() Method
Summary Returns a random number between 0.0 and 1.0. A
Description
B
This member must be implemented if the Extended Numerics Library is present in the implementation.
C D
Usage
E
Use this method to generate a pseudo-random number greater than or equal to zero, and less than one.
F G
Example
H
using System;
I namespace Samples { public class RandomNextDouble { public static void Main() { Random r = new Random(); DisplayNumbers(r, 4); r = new Random(unchecked( (int)DateTime.Now.Ticks)); DisplayNumbers(r, 4); r = new Random(0); DisplayNumbers(r, 4); r = new Random(0); DisplayNumbers(r, 4); } public static void DisplayNumbers(Random r, int number) { Console.WriteLine("Doubles"); for(int i = 0; i < number; i++) Console.Write("{0} ", r.NextDouble()); Console.WriteLine(); } } }
J K L M N O P Q R S T U V W X Y
The output is
Z
Doubles 0.280873246621747 0.358544709793546 0.22385113324218 0.482497283016563
2530
Contents | Index
System
Random Sample() Method
Doubles 0.126723673253657 0.0319675039648858 0.47859630104089 0.295361068237275 Doubles 0.72624326996796 0.817325359590969 0.768022689394663 0.558161191436537 Doubles 0.72624326996796 0.817325359590969 0.768022689394663 0.558161191436537
A B C
Random.Sample() Method
D
[ILASM]
E
.method family hidebysig virtual float64 Sample() [C#] protected virtual double Sample()
F G H
Summary
I
Returns a random number between 0.0 and 1.0.
J
Description
K
Create a derived class of System.Random to override this method and produce a different distribution.
L M N O P Q R S T U V W X Y Z
2531
Contents | Index
System RankException
BCL
Object
A
Exception
B
ISerializable
NotStandardized
SystemException RankException
C D
Summary
E
Represents the error that occurs when an array with an incorrect number of dimensions is passed to a method.
F G
Type Summary
H
public class RankException : SystemException { // Constructors public RankException (); public RankException (string message); public RankException (string message, Exception innerException); MS CF protected RankException (SerializationInfo info, StreamingContext context); }
I J K L M N
Example
O
using System;
P
namespace Samples { public class RankExceptionSample { public static void Main() { try { Array a = Array.CreateInstance( typeof(int), 5); Array b = Array.CreateInstance( typeof(int), 5, 5); Array.Copy(a, b, 5); } catch(RankException e) { Console.WriteLine("Exception: {0}" , e); } } } }
Q R S T U V W X Y Z
2532
Contents | Index
System
RankException RankException() Constructor
The output is Exception: System.RankException: The specified arrays must have the same number of dimensions. at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length) at System.Array.Copy(Array sourceArray, Array destinationArray, Int32 length) at Samples.RankExceptionSample.Main() in C:\Books\BCL\Samples\System\ RankException\RankException.cs:line 15
A B C D E
RankException() Constructor
F
[ILASM]
G
public rtspecialname specialname instance void .ctor()
H
[C#]
I
public RankException()
J
Summary
K
Constructs and initializes a new instance of the System.RankException class.
L
Description
M
This constructor initializes the System.RankException.Message property of the new instance to a system-supplied message that describes the error, such as “The two arrays must have the same number of dimensions.” This message takes into account the current system culture. The System.RankException.InnerException property is initialized to null.
N O P Q R
RankException(System.String) Constructor
S
[ILASM]
T
public rtspecialname specialname instance void .ctor(string message)
U
[C#]
public RankException(string message)
V W
Summary
X
Constructs and initializes a new instance of the System.RankException class.
Y Z
2533
Contents | Index
RankException
System
RankException() Constructor
Parameters Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
A B C D E
Description
F
This constructor initializes the System.RankException.Message property of the new instance using message. If message is null, the System.RankException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.RankException.InnerException property is initialized to null.
G H I J
RankException(System.String, System.Exception) Constructor
K [ILASM]
L
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
M
[C#]
public RankException(string message, Exception innerException)
N O
Summary
P
Constructs and initializes a new instance of the System.RankException class.
Q
Parameters
R S
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
T U V W X Y Z
2534
Contents | Index
System
RankException RankException() Constructor
Description This constructor initializes the System.RankException.Message property of the new instance using message, and the System.RankException.InnerException property using innerException. If message is null, the System.RankException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
A B C D E F
RankException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
G
[ILASM]
H
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
I J
[C#]
K
protected RankException(SerializationInfo info, StreamingContext context)
L
Summary
M
Initializes a new instance of the System.RankException class with serialized data.
N O
Parameters
P
Parameter
Description
Q
info
The object that holds the serialized object data.
R
context
The contextual information about the source or destination.
S T U
Description
V
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
W X Y Z
2535
Contents | Index
System SByte Structure
BCL
Object ValueType SByte
IComparable
A
IFormattable
B
IConvertible
C
NotStandardized
D
Summary
E
Represents an 8-bit signed integer. This type is not CLS-compliant.
F
Type Summary
G
public struct SByte : IComparable, IFormattable, IConvertible { // Fields public const sbyte MaxValue = 127; public const sbyte MinValue = -128;
H I J K
// Methods public int CompareTo (object obj); public override bool Equals (object obj); public override int GetHashCode (); MS CF public TypeCode GetTypeCode (); public static sbyte Parse (string s); public static sbyte Parse (string s, NumberStyles style); public static sbyte Parse (string s, NumberStyles style, IFormatProvider provider); CF public static sbyte Parse (string s, IFormatProvider provider); public override string ToString (); public string ToString (string format); public string ToString (string format, IFormatProvider provider); public string ToString (IFormatProvider provider);
L M N O P Q R S T
// MS MS MS MS MS MS MS MS MS MS MS MS
Explicit Interface Members bool IConvertible.ToBoolean(IFormatProvider provider); byte IConvertible.ToByte(IFormatProvider provider); char IConvertible.ToChar(IFormatProvider provider); DateTime IConvertible.ToDateTime(IFormatProvider provider); decimal IConvertible.ToDecimal(IFormatProvider provider); double IConvertible.ToDouble(IFormatProvider provider); short IConvertible.ToInt16(IFormatProvider provider); int IConvertible.ToInt32(IFormatProvider provider); long IConvertible.ToInt64(IFormatProvider provider); sbyte IConvertible.ToSByte(IFormatProvider provider); float IConvertible.ToSingle(IFormatProvider provider); object IConvertible.ToType(Type type,IFormatProvider provider);
U V W X Y Z
2537
Contents | Index
SByte Structure
System
SByte Structure
MS ushort IConvertible.ToUInt16(IFormatProvider provider); MS uint IConvertible.ToUInt32(IFormatProvider provider); MS ulong IConvertible.ToUInt64(IFormatProvider provider); }
A B
BA See System.Byte for my thoughts on the naming of this class.
C D E
Description
F
The System.SByte data type represents integer values ranging from negative 128 to positive 127; that is, hexadecimal 0x80 to 0x7F.
G H
Example
I
using System;
J
namespace Samples { public class SByteSample { public static void Main() { sbyte max = sbyte.MaxValue, min = sbyte.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); Console.WriteLine("Is {0} equal to {1}: {2}", max, max, max.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", max, min, max.Equals(min)); Console.WriteLine("{0} has hashcode of: {1}", max, max.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", min, min.GetHashCode()); string s = max.ToString(); Console.WriteLine("\"{0}\" parsed from string yields: {1}", s, SByte.Parse(s)); s = min.ToString(); Console.WriteLine("\"{0}\" parsed from string yields: {1}", s, SByte.Parse(s)); string[] formats = {"c", "d", "e", "f", "g", "n", "p", "x" }; foreach(string f in formats) Console.WriteLine("{0}: {1}", max, max.ToString(f)); } } }
K L M N O P Q R S T U V W X Y Z
2538
Contents | Index
System
SByte Structure MaxValue Field
The output is MaxValue: 127 MinValue: -128 Is 127 equal to 127: True Is 127 equal to -128: False 127 has hashcode of: 32639 -128 has hashcode of: 32640 "127" parsed from string yields: 127 "-128" parsed from string yields: -128 127: $127.00 127: 127 127: 1.270000e+002 127: 127.00 127: 127 127: 127.00 127: 12,700.00 % 127: 7f
A B C D E F G H I J K
SByte.MaxValue Field
L [ILASM]
.field public static literal int8 MaxValue
M
[C#]
N
public const sbyte MaxValue = 127
O
Summary
P
Contains the maximum value for the System.SByte type.
Q R
Description
S
The value of this constant is 127 (hexadecimal 0X7F).
T
Example
U
using System; using System;
V W
namespace Samples { public class SByteMaxValue { public static void Main() { System.SByte max = SByte.MaxValue, min = SByte.MinValue;
X Y Z
2539
Contents | Index
SByte Structure
System
MinValue Field
Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); } }
A
}
B
The output is
C MaxValue: 127 MinValue: -128
D E F
SByte.MinValue Field
G
[ILASM]
H
.field public static literal int8 MinValue [C#]
I
public const sbyte MinValue = -128
J
Summary
K
Contains the minimum value for the System.SByte type.
L M
Description
N
The value of this constant is –128 (hexadecimal 0x80).
O
Example
P
using System;
Q
namespace Samples { public class SByteMinValue { public static void Main() { System.SByte max = SByte.MaxValue, min = SByte.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); } } }
R S T U V W X Y
The output is
Z
MaxValue: 127 MinValue: -128
2540
Contents | Index
System
SByte Structure CompareTo() Method
SByte.CompareTo(System.Object) Method [ILASM]
.method public final hidebysig virtual int32 CompareTo(object obj) [C#]
A
public int CompareTo(object obj)
B C
Summary
D
Returns the sort order of the current instance compared to the specified System.Object.
E
Parameters
F G
Parameter
Description
obj
The System.Object to compare to the current instance.
H I J
Return Value
K
A System.Int32 containing a value that reflects the sort order of the current instance as compared to obj. The following table defines the conditions under which the return value is a negative number, zero, or a positive number.
L M N O
Return Value
Description
any negative number
Current instance < obj.
Q
zero
Current instance == obj.
R
any positive number
Current instance > obj, or obj is a null reference.
P
S T U
Description
V
[Note: This method is implemented to support the System.IComparable interface.]
W
Exceptions
X Y
Exception
Condition
System.ArgumentException
obj is not a System.SByte and is not a null reference.
Z
2541
Contents | Index
SByte Structure
System
Equals() Method
Example using System; namespace Samples { public class SByteCompareTo { private static string CompareSBytes(sbyte s1, sbyte s2) { int i = s1.CompareTo(s2); if(0 == i) return String.Format("{0} is equal to {1}", s1, s2); if(i > 0) return String.Format("{0} is greater than {1}", s1, s2); else return String.Format("{0} is less than {1}", s1, s2); } public static void Main() { sbyte max = sbyte.MaxValue, min = sbyte.MinValue; Console.WriteLine(CompareSBytes(min, min)); Console.WriteLine(CompareSBytes(max, min)); Console.WriteLine(CompareSBytes(min, max)); } } }
A B C D E F G H I J K L M N O P
The output is
Q -128 is equal to -128 127 is greater than -128 -128 is less than 127
R S T U
SByte.Equals(System.Object) Method
V
[ILASM]
.method public hidebysig virtual bool Equals(object obj)
W
[C#]
public override bool Equals(object obj)
X Y
Summary
Z
Determines whether the current instance and the specified System.Object represent the same type and value.
2542
Contents | Index
System
SByte Structure GetHashCode() Method
Parameters Parameter
Description
obj
The System.Object to compare to the current instance.
A B C
Return Value
D
true if obj represents the same type and value as the current instance. If obj is a null reference or is not an instance of System.SByte, returns false.
E
Description
G
[Note: This method overrides System.Object.Equals.]
H
F
I
Example
J
using System;
K
namespace Samples { public class SByteEquals { public static void Main() { System.SByte max = SByte.MaxValue, min = SByte.MinValue; Console.WriteLine("Is {0} equal to {1}: {2}", max, max, max.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", max, min, max.Equals(min)); } } }
L M N O P Q R S T
The output is
U V
Is 127 equal to 127: True Is 127 equal to -128: False
W X
SByte.GetHashCode() Method
Y
[ILASM]
Z
.method public hidebysig virtual int32 GetHashCode() [C#]
public override int GetHashCode()
2543
Contents | Index
SByte Structure
System
GetTypeCode() Method
Summary Generates a hash code for the current instance. A
Description
B
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
C D
Example
E
using System;
F
namespace Samples { public class SByteGetHashCode { public static void Main() { System.SByte max = SByte.MaxValue, zero = 0, min = SByte.MinValue; Console.WriteLine("{0} has hashcode of: {1}", max, max.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", zero, zero.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", min, min.GetHashCode()); } } }
G H I J K L M N O P Q
The output is
R S
127 has hashcode of: 32639 0 has hashcode of: 0 -128 has hashcode of: 32640
T U V
SByte.GetTypeCode() Method
W
[ILASM]
X
.method public final hidebysig virtual valuetype System.TypeCode GetTypeCode() [C#]
Y
public TypeCode GetTypeCode()
Z
Summary Returns the System.TypeCode for value type System.SByte. 2544
Contents | Index
System
SByte Structure Parse() Method
SByte.Parse(System.String) Method [ILASM]
.method public hidebysig static int8 Parse(string s) [C#]
A
public static sbyte Parse(string s)
B C
Summary
D
Returns the specified System.String converted to a System.SByte value.
E
Parameters
F G
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Integer style.
H I J K
Description
L
This version of System.SByte.Parse is equivalent to System.SByte.Parse(s, System.Globalization.NumberStyles.Integer, null). The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.] This method is not CLS-compliant. For a CLS-compliant alternative use System.Int16.Parse(System.String).
M N O P Q R
Exceptions
S
Exception
Condition
T
System.ArgumentException
s is a null reference.
U
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.SByte.MaxValue or less than System.SByte.MinValue.
V W X Y Z
2545
Contents | Index
SByte Structure
System
Parse() Method
Example using System; namespace Samples { public class SByteParse { public static void Main() { string s; try { s = SByte.MaxValue.ToString(); Console.WriteLine("Parse String {0} yields s, SByte.Parse(s)); s = "0"; Console.WriteLine("Parse String {0} yields s, SByte.Parse(s)); s = SByte.MinValue.ToString(); Console.WriteLine("Parse String {0} yields s, SByte.Parse(s)); s = String.Empty; Console.WriteLine("Parse String {0} yields s, SByte.Parse(s)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = (SByte.MaxValue + 1).ToString(); Console.WriteLine("Parse String {0} yields s, SByte.Parse(s)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
A B C D E F G H I J K L M N O P Q R S T U V W X Y
{1}",
{1}",
{1}",
{1}",
{1}",
The output is
Z Parse String 127 yields 127 Parse String 0 yields 0
2546
Contents | Index
System
SByte Structure Parse() Method
Parse String -128 yields -128 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.SByte.Parse(String s, NumberStyles style, IFormatProvider provider) at System.SByte.Parse(String s) at Samples.SByteParse.Main() in C:\Books\BCL\Samples\System\SByte\ Parse(System.String)\SByte.cs:line 22 Exception: System.OverflowException: Value was either too large or too small for a signed byte. at System.SByte.Parse(String s, NumberStyles style, IFormatProvider provider) at System.SByte.Parse(String s) at Samples.SByteParse.Main() in C:\Books\BCL\Samples\System\SByte\ Parse(System.String)\SByte.cs:line 32
A B C D E F G H
SByte.Parse(System.String, System.Globalization.NumberStyles) Method
I [ILASM]
J
.method public hidebysig static int8 Parse(string s, valuetype System.Globalization.NumberStyles style)
K
[C#]
public static sbyte Parse(string s, NumberStyles style)
L M
Summary
N
Returns the specified System.String converted to a System.SByte value.
O
Parameters Parameter
P Q
Description
R
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Integer style.
S T U V W X
Description
Y
This version of System.SByte.Parse is equivalent to System.SByte.Parse(s, style, null).
Z
2547
Contents | Index
SByte Structure
System
Parse() Method
The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.] This method is not CLS-compliant. For a CLS-compliant alternative use System.Int16.Parse(System.String,System.Globalization.NumberStyles).
A B C D
Exceptions
E
Exception
Condition
G
System.ArgumentNullException
s is a null reference.
H
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.SByte.MaxValue or less than System.SByte.MinValue.
F
I J K L M
Example
N
using System; using System.Globalization;
O
namespace Samples { public class SByteParse { public static void Main() { string s; try { s = "$0"; Console.WriteLine("From string {0} yields {1}", s, SByte.Parse(s, NumberStyles.AllowCurrencySymbol)); s = String.Format("${0}", (SByte.MaxValue).ToString()); Console.WriteLine("From string {0} yields {1}", s, SByte.Parse(s, NumberStyles.AllowCurrencySymbol)); s = String.Format("({0})", (SByte.MaxValue).ToString()); Console.WriteLine("From string {0} yields {1}", s, SByte.Parse(s,
P Q R S T U V W X Y Z
2548
Contents | Index
System
SByte Structure Parse() Method
NumberStyles.AllowParentheses)); s = String.Empty; Console.WriteLine("From string {0} yields {1}", s, SByte.Parse(s, NumberStyles.Any));
A B
} catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = (SByte.MaxValue + 1).ToString(); Console.WriteLine("From String {0} yields {1}", s, SByte.Parse(s, NumberStyles.Any)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
C D E F G H I J K
}
L
} }
M N
The output is
O
From string $0 yields 0 From string $127 yields 127 From string (127) yields -127 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.SByte.Parse(String s, NumberStyles style, IFormatProvider provider) at System.SByte.Parse(String s, NumberStyles style) at Samples.SByteParse.Main() in C:\Books\BCL\Samples\System\SByte\ Parse(System.String,System.Globalization.NumberStyles)\SByte.cs:line 29 Exception: System.OverflowException: Value was either too large or too small for a signed byte. at System.SByte.Parse(String s, NumberStyles style, IFormatProvider provider) at System.SByte.Parse(String s, NumberStyles style) at Samples.SByteParse.Main() in C:\Books\BCL\Samples\System\SByte\ Parse(System.String,System.Globalization.NumberStyles)\SByte.cs:line 41
P Q R S T U V W X Y Z
2549
Contents | Index
SByte Structure
System
Parse() Method
SByte.Parse(System.String, System.Globalization.NumberStyles, System.IFormatProvider) Method [ILASM]
A
.method public hidebysig static int8 Parse(string s, valuetype System.Globalization.NumberStyles style, class System.IFormatProvider provider)
B
[C#]
C
public static sbyte Parse(string s, NumberStyles style, IFormatProvider provider)
D
Summary
E
Returns the specified System.String converted to a System.SByte value.
F
Parameters
G H I J
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Integer style.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
K L M N O P Q
Description
R
The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. This method is not CLS-compliant. For a CLS-compliant alternative use System.Int16.Parse(System.String, System.Globalization.NumberStyles, System.IFormatProvider).
S T U V W X Y Z
2550
Contents | Index
System
SByte Structure Parse() Method
Exceptions Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
C
s represents a number greater than System.SByte.MaxValue or less than System.SByte.MinValue.
D
System.OverflowException
A B
E F
Example
G
using System; using System.Globalization;
H I
namespace Samples { public class SByteParse { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; string s = " ~0"; Console.WriteLine("From string {0} yields {1}", s, SByte.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowLeadingSign, c)); s = "(1)"; Console.WriteLine("Parse String {0} yields {1}", s, SByte.Parse(s, NumberStyles.AllowParentheses, c)); s = "!1"; Console.WriteLine("Parse String {0} yields {1}", s, SByte.Parse(s, NumberStyles.Any, c)); } } }
J K L M N O P Q R S T U V W X Y Z
2551
Contents | Index
SByte Structure
System
Parse() Method
The output is From string ~0 yields 0 Parse String (1) yields -1 Parse String !1 yields -1
A B C
SByte.Parse(System.String, System.IFormatProvider) Method
D
[ILASM]
E
.method public hidebysig static int8 Parse(string s, class System.IFormatProvider provider)
F
[C#]
G
public static sbyte Parse(string s, IFormatProvider provider)
H
Summary
I
Returns the specified string converted to a System.SByte value.
J K
Parameters
L M N
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Integer style.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
O P Q R S
Description
T
This version of System.SByte.Parse is equivalent to System.SByte.Parse(s, System.Globalization.NumberStyles.Integer, provider). The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. This method is not CLS-compliant. For a CLS-compliant alternative use System.Int16.Parse(System.String, System.IFormatProvider).
U V W X Y Z
2552
Contents | Index
System
SByte Structure Parse() Method
Exceptions Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
C
s represents a number greater than System.SByte.MaxValue or less than System.SByte.MinValue.
D
System.OverflowException
A B
E F G
Example
H
using System; using System.Globalization; namespace Samples { public class SByteParse { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; try { s = "~0"; Console.WriteLine("Parse String {0} yields s, SByte.Parse(s, c)); s = (SByte.MaxValue).ToString(); Console.WriteLine("Parse String {0} yields s, SByte.Parse(s, c)); s = "!1"; Console.WriteLine("Parse String {0} yields s, SByte.Parse(s, c)); s = String.Empty; Console.WriteLine("Parse String {0} yields s, SByte.Parse(s, c)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e);
I J K L M N O P Q R {1}",
S T
{1}",
U V
{1}",
W X
{1}",
Y Z
2553
Contents | Index
SByte Structure
System
ToString() Method
} try { s = (SByte.MaxValue + 1).ToString(); Console.WriteLine("Parse String {0} yields {1}", s, SByte.Parse(s, c)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E }
F
} }
G
The output is
H I
Parse String ~0 yields 0 Parse String 127 yields 127 Parse String !1 yields -1 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.SByte.Parse(String s, NumberStyles style, IFormatProvider provider) at System.SByte.Parse(String s, IFormatProvider provider) at Samples.SByteParse.Main() in C:\Books\BCL\Samples\System\SByte\ Parse(System.String,System.IFormatProvider)\SByte.cs:line 27 Exception: System.OverflowException: Value was either too large or too small for a signed byte. at System.SByte.Parse(String s, NumberStyles style, IFormatProvider provider) at System.SByte.Parse(String s, IFormatProvider provider) at Samples.SByteParse.Main() in C:\Books\BCL\Samples\System\SByte\ Parse(System.String,System.IFormatProvider)\SByte.cs:line 37
J K L M N O P Q R S T
SByte.ToString() Method
U
[ILASM]
.method public hidebysig virtual string ToString()
V
[C#]
W
public override string ToString()
X
Summary
Y
Returns a System.String representation of the value of the current instance.
Z
2554
Contents | Index
System
SByte Structure ToString() Method
Return Value A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the current system culture. A
Description
B
This version of System.SByte.ToString is equivalent to System.SByte.ToString (null, null). [Note: This method overrides System.Object.ToString.]
C D E
Example
F
using System; using System.Globalization;
G H
namespace Samples { public class SbyteToString { public static void Main() { System.SByte max = SByte.MaxValue, min = SByte.MinValue; Console.WriteLine("{0}.ToString yields {1}", max, max.ToString()); Console.WriteLine("{0}.ToString yields {1}", min, min.ToString()); } } }
I J K L M N O P Q R
The output is
S 127.ToString yields 127 -128.ToString yields -128
T U V
SByte.ToString(System.String) Method
W [ILASM]
.method public hidebysig instance string ToString(string format)
X
[C#]
Y
public string ToString(string format)
Z
2555
Contents | Index
SByte Structure
System
ToString() Method
Summary Returns a System.String representation of the value of the current instance. A
Parameters
B C
Parameter
Description
format
A System.String that specifies the format of the returned string. [Note: For a list of valid values, see System.SByte.ToString(System.String, System.IFormatProvider).]
D E F G
Return Value
H
A System.String representation of the current instance formatted as specified by format. The string takes into account the current system culture.
I J
Description
K
This version of System.SByte.ToString is equivalent to System.SByte.ToString (format, null). If format is a null reference, the general format specifier “G” is used.
L M N
Exceptions
O P
Exception
Condition
System.FormatException
format is invalid.
Q R S
Example
T
using System;
U namespace Samples { public class Parse { public static void { System.SByte max min string[] formats
V W X Y Z
Main() = SByte.MaxValue, = SByte.MinValue; = {"C", "c", "D", "d", "E", "e", "F", "f", "G", "g", "N", "n", "P", "p", "X", "x"};
2556
Contents | Index
System
SByte Structure ToString() Method
foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\"): {2}", max, f, max.ToString(f)); foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\") yields {2}", min, f, min.ToString(f));
A B
}
C
} }
D
The output is 127.ToString("C"): 127.ToString("c"): 127.ToString("D"): 127.ToString("d"): 127.ToString("E"): 127.ToString("e"): 127.ToString("F"): 127.ToString("f"): 127.ToString("G"): 127.ToString("g"): 127.ToString("N"): 127.ToString("n"): 127.ToString("P"): 127.ToString("p"): 127.ToString("X"): 127.ToString("x"): -128.ToString("C") -128.ToString("c") -128.ToString("D") -128.ToString("d") -128.ToString("E") -128.ToString("e") -128.ToString("F") -128.ToString("f") -128.ToString("G") -128.ToString("g") -128.ToString("N") -128.ToString("n") -128.ToString("P") -128.ToString("p") -128.ToString("X") -128.ToString("x")
E F
$127.00 $127.00 127 127 1.270000E+002 1.270000e+002 127.00 127.00 127 127 127.00 127.00 12,700.00 % 12,700.00 % 7F 7f yields -$128.00 yields -$128.00 yields -128 yields -128 yields -1.280000E+002 yields -1.280000e+002 yields -128.00 yields -128.00 yields -128 yields -128 yields -128.00 yields -128.00 yields -12,800.00 % yields -12,800.00 % yields 80 yields 80
G H I J K L M N O P Q R S T U V W X Y Z
2557
Contents | Index
SByte Structure
System
ToString() Method
SByte.ToString(System.String, System.IFormatProvider) Method [ILASM]
A
.method public final hidebysig virtual string ToString(string format, class System.IFormatProvider provider)
B
[C#]
public string ToString(string format, IFormatProvider provider)
C D
Summary
E
Returns a System.String representation of the value of the current instance.
F
Parameters
G H
Parameter
Description
format
A System.String containing a character that specifies the format of the returned string.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo instance containing culture-specific formatting information.
I J K L M N
Return Value
O
A System.String representation of the current instance formatted as specified by format. The string takes into account the formatting information in the System.Globalization.NumberFormatInfo instance supplied by provider.
P Q R
Description
S
If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. If format is a null reference, the general format specifier “G” is used. [Note: For a detailed description of formatting, see the System.IFormattable interface. This method is implemented to support the System.IFormattable interface.] The following table lists the characters that are valid for the System.SByte type.
T U V W X Y Z
2558
Contents | Index
System
SByte Structure ToString() Method
Format Characters
Description
"C", "c"
Currency format.
A
"D", "d"
Decimal format.
B
"E", "e"
Exponential notation format.
"F", "f"
Fixed-point format.
"G", "g"
General format.
F
"N", "n"
Number format.
G
"P", "p"
Percent format.
"X", "x"
Hexadecimal format.
C D E
H I J K
Exceptions
L
Exception
Condition
System.FormatException
format is invalid.
M N O P
Example
Q
using System; using System.Globalization;
R S
namespace Samples { public class SByteToString { public static void Main() { System.SByte max = SByte.MaxValue, min = SByte.MinValue; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; n.CurrencySymbol = "#"; string[] formats = {"C", "c", "D", "d", "E", "e",
T U V W X Y Z
2559
Contents | Index
SByte Structure
System
ToString() Method
"F", "f", "G", "g", "N", "n", "P", "p", "X", "x"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\", c) yields {2}", max, f, max.ToString(f, c)); foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\",n) yields {2}", min, f, min.ToString(f, c));
A B C }
D
} }
E F
The output is
G 127.ToString("C", c) 127.ToString("c", c) 127.ToString("D", c) 127.ToString("d", c) 127.ToString("E", c) 127.ToString("e", c) 127.ToString("F", c) 127.ToString("f", c) 127.ToString("G", c) 127.ToString("g", c) 127.ToString("N", c) 127.ToString("n", c) 127.ToString("P", c) 127.ToString("p", c) 127.ToString("X", c) 127.ToString("x", c) -128.ToString("C",n) -128.ToString("c",n) -128.ToString("D",n) -128.ToString("d",n) -128.ToString("E",n) -128.ToString("e",n) -128.ToString("F",n) -128.ToString("f",n) -128.ToString("G",n) -128.ToString("g",n) -128.ToString("N",n) -128.ToString("n",n) -128.ToString("P",n) -128.ToString("p",n) -128.ToString("X",n) -128.ToString("x",n)
H I J K L M N O P Q R S T U V W X Y Z
yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields yields
#127.00 #127.00 127 127 1.270000E~002 1.270000e~002 127.00 127.00 127 127 127.00 127.00 12,700.00 % 12,700.00 % 7F 7f !#128.00 !#128.00 !128 !128 !1.280000E~002 !1.280000e~002 !128.00 !128.00 !128 !128 !128.00 !128.00 !12,800.00 % !12,800.00 % 80 80
2560
Contents | Index
System
SByte Structure ToString() Method
SByte.ToString(System.IFormatProvider) Method [ILASM]
.method public final hidebysig virtual string ToString(class System.IFormatProvider provider)
A
[C#]
B
public string ToString(IFormatProvider provider)
C
Summary
D
Returns a System.String representation of the value of the current instance.
E F
Parameters
G
Parameter
Description
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
H I J K
Return Value
L
A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the formatting information in the System.Globalization.NumberFormatInfo instance supplied by provider.
M N O
Description
P
This version of System.SByte.ToString is equivalent to System.SByte.ToString (“G”, provider). If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used.
Q R S T
Example
U
using System; using System.Globalization;
V W
namespace Samples { public class SByteToString { public static void Main() { System.SByte max = SByte.MaxValue, min = SByte.MinValue;
X Y Z
2561
Contents | Index
SByte Structure
System
ToBoolean() Method
CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; Console.WriteLine("{0}.ToString yields {1}", max, max.ToString(c)); Console.WriteLine("{0}.ToString yields {1}", min, min.ToString(c));
A B C }
D
} }
E F
The output is
G 127.ToString yields 127 -128.ToString yields !128
H I J
IConvertible.ToBoolean(System.IFormatProvider) Method
K [ILASM]
L
.method private final hidebysig virtual bool System.IConvertible.ToBoolean(class System.IFormatProvider provider)
M
[C#]
bool IConvertible.ToBoolean(IFormatProvider provider)
N O
Summary
P
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToBoolean.]
Q R S
IConvertible.ToByte(System.IFormatProvider) Method
T
[ILASM]
U
.method private final hidebysig virtual unsigned int8 System.IConvertible.ToByte(class System.IFormatProvider provider)
V
[C#]
byte IConvertible.ToByte(IFormatProvider provider)
W X
Summary
Y
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToByte.]
Z
2562
Contents | Index
System
SByte Structure ToDecimal() Method
IConvertible.ToChar(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual valuetype System.Char System.IConvertible.ToChar(class System.IFormatProvider provider)
A
[C#]
B
char IConvertible.ToChar(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToChar.]
E F G
IConvertible.ToDateTime(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual valuetype System.DateTime System.IConvertible.ToDateTime(class System.IFormatProvider provider)
J
[C#]
K
DateTime IConvertible.ToDateTime(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDateTime.]
N O P
IConvertible.ToDecimal(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual decimal System.IConvertible.ToDecimal(class System.IFormatProvider provider)
S
[C#]
T
decimal IConvertible.ToDecimal(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDecimal.]
W X Y Z
2563
Contents | Index
SByte Structure
System
ToDouble() Method
IConvertible.ToDouble(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual float64 System.IConvertible.ToDouble(class System.IFormatProvider provider)
B
[C#]
double IConvertible.ToDouble(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDouble.]
F G H
IConvertible.ToInt16(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual int16 System.IConvertible.ToInt16(class System.IFormatProvider provider)
K
[C#]
short IConvertible.ToInt16(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt16.]
O P Q
IConvertible.ToInt32(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual int32 System.IConvertible.ToInt32(class System.IFormatProvider provider)
T
[C#]
int IConvertible.ToInt32(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt32.]
X Y Z
2564
Contents | Index
System
SByte Structure ToSingle() Method
IConvertible.ToInt64(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual int64 System.IConvertible.ToInt64(class System.IFormatProvider provider)
A
[C#]
B
long IConvertible.ToInt64(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt64.]
E F G
IConvertible.ToSByte(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual int8 System.IConvertible.ToSByte(class System.IFormatProvider provider)
J
[C#]
K
sbyte IConvertible.ToSByte(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSByte.]
N O P
IConvertible.ToSingle(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual float32 System.IConvertible.ToSingle(class System.IFormatProvider provider)
S
[C#]
T
float IConvertible.ToSingle(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSingle.]
W X Y Z
2565
Contents | Index
SByte Structure
System
ToType() Method
IConvertible.ToType(System.Type, System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual object System.IConvertible.ToType(class System.Type type, class System.IFormatProvider provider)
B
[C#]
object IConvertible.ToType(Type type, IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToType.]
F G H
IConvertible.ToUInt16(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual unsigned int16 System.IConvertible.ToUInt16(class System.IFormatProvider provider)
K
[C#]
ushort IConvertible.ToUInt16(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt16.]
O P Q
IConvertible.ToUInt32(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual unsigned int32 System.IConvertible.ToUInt32(class System.IFormatProvider provider)
T
[C#]
uint IConvertible.ToUInt32(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt32.]
X Y Z
2566
Contents | Index
System
SByte Structure ToUInt64() Method
IConvertible.ToUInt64(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual unsigned int64 System.IConvertible.ToUInt64(class System.IFormatProvider provider)
A
[C#]
B
ulong IConvertible.ToUInt64(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt64.]
E F G H I J K L M N O P Q R S T U V W X Y Z
2567
Contents | Index
System.Security.Permissions SecurityAction Enum
BCL
Object
A
IComparable
ValueType
B
Enum
IFormattable SecurityAction
C
IConvertible
NotStandardized
D
Summary
E
Specifies security actions that can be performed using declarative security.
F G
Type Summary CF public enum SecurityAction CF Assert = 3, CF Demand = 2, CF Deny = 4, CF InheritanceDemand= 7, CF LinkDemand = 6, CF PermitOnly = 5, CF RequestMinimum = 8, CF RequestOptional = 9, CF RequestRefuse = 10, }
H I J K L M N
{
O
Description
P
[Note: For information about using declarative security and security actions, see Partition II of the CLI Specification.] [Note: Declarative security is specified using types derived from System.Security.Permissions.SecurityAttribute. The following table describes the attribute targets supported by each of the security actions. For additional information on attribute targets, see System.Attribute.]
Q R S T U
Example
V
using System; using System.Security; using System.Security.Permissions;
W X
[assembly:EnvironmentPermissionAttribute( SecurityAction.RequestMinimum, Read="COMPUTERNAME;USERNAME")]
Y Z
namespace Samples
2568
Contents | Index
System.Security.Permissions
SecurityAction Enum Assert Field
{ public class SecurityActionSample { public static void Main() { string[] v = {"USERNAME", "COMPUTERNAME"}; foreach(string s in v) Console.WriteLine("Variable {0} Value: {1}", s, Environment.GetEnvironmentVariable(s));
A B C D E
}
F
} }
G
The output is
H I
Variable USERNAME Value: damien Variable COMPUTERNAME Value: PROJECT42
J K
SecurityAction.Assert Field
L
[ILASM]
M
.field public static literal valuetype System.Security.Permissions.SecurityAction Assert
N
[C#]
O
Assert = 3
P
Summary
Q
Specifies that callers of the code performing the assert need not have the permissions specified by the current security attribute, and that a check for any such permission can stop after the code that asserted it. [Note: An assert can change the default behavior of a security check (such as that caused by a Demand, LinkDemand, etc.).] This action can be applied to classes and methods. [Note: This action should only be used by code that can assure that its callers cannot manipulate it to abuse the asserted permission.]
R S T U V W
Example
X
using System; using System.Security; using System.Security.Permissions;
Y Z
namespace Samples {
2569
Contents | Index
SecurityAction Enum
System.Security.Permissions
Assert Field
public class SecurityActionAssert { [EnvironmentPermissionAttribute( SecurityAction.Assert, Read="COMPUTERNAME;USERNAME")] public static void DisplayWithAssert() { string[] v = {"USERNAME", "COMPUTERNAME"}; foreach(string s in v) Console.WriteLine("Variable {0} Value: {1}", s, Environment.GetEnvironmentVariable(s)); } public static void DisplayWithoutAssert() { string[] v = {"USERNAME", "COMPUTERNAME"}; foreach(string s in v) Console.WriteLine("Variable {0} Value: {1}", s, Environment.GetEnvironmentVariable(s)); } static void Main(string[] args) { try { EnvironmentPermission p = new EnvironmentPermission( EnvironmentPermissionAccess.Read, "COMPUTERNAME"); p.Deny(); DisplayWithAssert(); DisplayWithoutAssert(); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } }
A B C D E F G H I J K L M N O P Q R S T U V
}
W
The output is
X Variable USERNAME Value: damien Variable COMPUTERNAME Value: PROJECT42 Variable USERNAME Value: damien Exception: System.Security.SecurityException: Request for the permission of type System.Security.Permissions.EnvironmentPermission, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed.
Y Z
2570
Contents | Index
System.Security.Permissions
SecurityAction Enum Demand Field
at System.Security.SecurityRuntime.FrameDescHelper(FrameSecurityDescriptor secDesc, IPermission demand, PermissionToken permToken) at System.Security.CodeAccessSecurityEngine.Check(PermissionToken permToken, CodeAccessPermission demand, StackCrawlMark& stackMark, Int32 checkFrames, Int32 unrestrictedOverride) at System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark) at System.Security.CodeAccessPermission.Demand() at System.Environment.GetEnvironmentVariable(String variable) at Samples.SecurityActionAssert.DisplayWithoutAssert() in C:\Books\BCL\Samples\ System.Security\Permissions\SecurityAction\Assert\SecurityAction.cs:line 24 at Samples.SecurityActionAssert.Main(String[] args) in C:\Books\BCL\Samples\ System.Security\Permissions\SecurityAction\Assert\SecurityAction.cs:line 38
A B C D E F G
The state of the failed permission was:
H I J K
SecurityAction.Demand Field
L
[ILASM]
M
.field public static literal valuetype System.Security.Permissions.SecurityAction Demand
N
[C#]
O
Demand = 2
P
Summary
Q
Specified that all callers are required to have the permissions specified by the current security attribute. This action can be applied to classes and methods.
R
Example
T
S
U
using System; using System.Security; using System.Security.Permissions;
V W
namespace Samples { public class SecurityActionDemand { private const string VARIABLE = "USERNAME"; [EnvironmentPermissionAttribute( SecurityAction.Demand, Read=VARIABLE)]
X Y Z
2571
Contents | Index
SecurityAction Enum
System.Security.Permissions
Deny Field
public static void ReadVariable() { Console.WriteLine("{0}: {1}", VARIABLE, Environment.GetEnvironmentVariable(VARIABLE)); } public static void Main() { EnvironmentPermission p = new EnvironmentPermission( EnvironmentPermissionAccess.Read, VARIABLE); try { p.Assert(); ReadVariable(); CodeAccessPermission.RevertAssert(); p.Deny(); ReadVariable(); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } }
A B C D E F G H I J K L M
} }
N O
The output is
P
USERNAME: damien Exception: System.Security.SecurityException: Request failed. at System.Security.SecurityRuntime.FrameDescSetHelper(FrameSecurityDescriptor secDesc, PermissionSet demandSet, PermissionSet& alteredDemandSet) at Samples.SecurityActionDemand.ReadVariable() in C:\Books\BCL\Samples\ System.Security\Permissions\SecurityAction\Demand\SecurityAction.cs:line 15 at Samples.SecurityActionDemand.Main() in C:\Books\BCL\Samples\System.Security\ Permissions\SecurityAction\Demand\SecurityAction.cs:line 30
Q R S T U V W
SecurityAction.Deny Field
X
[ILASM]
Y
.field public static literal valuetype System.Security.Permissions.SecurityAction Deny
Z
[C#]
Deny = 4
2572
Contents | Index
System.Security.Permissions
SecurityAction Enum Deny Field
Summary Specifies that access to the resource or operation described by the current security attribute be denied to callers, even if they have been granted permission to access it. [Note: System.Security.Permissions.SecurityAction.Deny causes a security check for the permissions specified by the current security attribute to fail even when it would otherwise succeed.] This action can be applied to classes and methods.
A B C
Example
D
using System; using System.Security; using System.Security.Permissions;
E F G
namespace Samples { public class SecurityActionDeny { private const string VARIABLE = "USERNAME"; [EnvironmentPermissionAttribute( SecurityAction.Deny, Read=VARIABLE)] public static void ReadVariableWithDeny() { Console.WriteLine("{0}: {1}", VARIABLE, Environment.GetEnvironmentVariable(VARIABLE)); } [EnvironmentPermissionAttribute( SecurityAction.Demand, Read=VARIABLE)] public static void ReadVariableWithDemand() { Console.WriteLine("{0}: {1}", VARIABLE, Environment.GetEnvironmentVariable(VARIABLE)); } public static void Main() { try { ReadVariableWithDemand(); ReadVariableWithDeny(); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
H I J K L M N O P Q R S T U V W X Y Z
2573
Contents | Index
SecurityAction Enum
System.Security.Permissions
InheritanceDemand Field
The output is USERNAME: damien Exception: System.Security.SecurityException: Request for the permission of type System.Security.Permissions.EnvironmentPermission, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed. at System.Security.SecurityRuntime.FrameDescHelper(FrameSecurityDescriptor secDesc, IPermission demand, PermissionToken permToken) at System.Security.CodeAccessSecurityEngine.Check(PermissionToken permToken, CodeAccessPermission demand, StackCrawlMark& stackMark, Int32 checkFrames, Int32 unrestrictedOverride) at System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark) at System.Security.CodeAccessPermission.Demand() at System.Environment.GetEnvironmentVariable(String variable) at Samples.SecurityActionDeny.ReadVariableWithDeny() in C:\Books\BCL\Samples\ System.Security\Permissions\SecurityAction\Deny\SecurityAction.cs:line 15 at Samples.SecurityActionDeny.ReadVariableWithDeny() in C:\Books\BCL\Samples\ System.Security\Permissions\SecurityAction\Deny\SecurityAction.cs:line 15 at Samples.SecurityActionDeny.Main() in C:\Books\BCL\Samples\System.Security\ Permissions\SecurityAction\Deny\SecurityAction.cs:line 31
A B C D E F G H I J K L
The state of the failed permission was:
M N O P Q
SecurityAction.InheritanceDemand Field
R
[ILASM]
S
.field public static literal valuetype System.Security.Permissions.SecurityAction InheritanceDemand
T
[C#]
InheritanceDemand = 7
U V
Summary
W
Specifies the permissions that a derived class is required to have. When the target is a class, classes inheriting from the target are required to have the permissions specified by the current security attribute. When the target is a method, classes overriding the target are required to have the permissions specified by the current security attribute. This action can be applied to classes and methods.
X Y Z
2574
Contents | Index
System.Security.Permissions
SecurityAction Enum InheritanceDemand Field
Example The following example uses a base class, BaseClass, defined in one file and a derived class, SecurityActionInheritanceDemand, defined in another file. A using System; using System.Security; using System.Security.Permissions;
B C D
namespace Samples { [PermissionSetAttribute( SecurityAction.InheritanceDemand, Name="FullTrust")] public class BaseClass { public void MethodToCall() { Console.WriteLine("Hello world!"); } } }
E F G H I J K L
using System; using System.Security; using System.Security.Permissions;
M N
[assembly: PermissionSetAttribute( SecurityAction.RequestRefuse, Name="FullTrust")]
O P Q
namespace Samples { public class SecurityActionInheritanceDemand: BaseClass { public static void Main() { try { SecurityActionInheritanceDemand s = new SecurityActionInheritanceDemand(); s.MethodToCall(); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
R S T U V W X Y Z
2575
Contents | Index
SecurityAction Enum
System.Security.Permissions
LinkDemand Field
The output is (please note the exception is not caught by the exception handler code in the program): Unhandled Exception: System.Security.SecurityException: Request failed.
A B C
SecurityAction.LinkDemand Field
D
[ILASM]
E
.field public static literal valuetype System.Security.Permissions.SecurityAction LinkDemand
F
[C#]
LinkDemand = 6
G H
Summary
I
Specifies that the immediate caller be required to have the specified permissions. This action can be applied to classes and methods.
J K
Example
L
The following example uses a component, ClassToCall, defined in one file and a client class, SecurityActionInheritanceDemand, defined in another file.
M N
P
using using using using
Q
[assembly: AssemblyKeyFile("Sample.Key")]
O
System; System.Security; System.Security.Permissions; System.Reflection;
R namespace Samples { public class ClassToCall { [StrongNameIdentityPermissionAttribute( SecurityAction.LinkDemand, PublicKey= "00240000048000009400000006020000" + "00240000525341310004000001000100" + "097DAF2736C75761208E3DECBAE39F1F" + "4F819CE677E5C91E3B167CA093902449" + "20B4A1C07683081725BE90431DC4AF4A" + "7FC3FDB428A0581896388BC8370F3D34" + "DE1FF10B95ED7652B1DA0E4DB2507077" + "07E700B344D2C0DB97FAA8BD75FD9AD8" + "D55B657043521947CA83918B1A4897A3" +
S T U V W X Y Z
2576
Contents | Index
System.Security.Permissions
SecurityAction Enum PermitOnly Field
"696A2C26F0305B7F98493EFDA1E230C6")] public static void MethodToCall() { Console.WriteLine("Hello world!"); }
A
}
B
}
C using using using using
System; System.Security; System.Security.Permissions; System.Reflection;
D E F
[assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyKeyFile("Sample.Key")]
G H
namespace Samples { public class SecurityActionLinkDemand { public static void Main() { ClassToCall.MethodToCall(); } } }
I J K L M N O
The output is:
P Hello world!
Q R
SecurityAction.PermitOnly Field
S
[ILASM]
T
.field public static literal valuetype System.Security.Permissions.SecurityAction PermitOnly
U
[C#]
V
PermitOnly = 5
W
Summary
X
Specifies that access is limited to only those resources or operations specified by the current security attribute, even if the code has been granted permission to access others. A security check for a permission not described by the current security attribute fails regardless of whether or not callers have been granted this permission. This action can be applied to classes and methods.
Y Z
2577
Contents | Index
SecurityAction Enum
System.Security.Permissions
PermitOnly Field
Example using System; using System.Security; using System.Security.Permissions;
A B
namespace Samples { public class SecurityActionPermitOnly { [EnvironmentPermissionAttribute( SecurityAction.PermitOnly, Read="USERNAME")] public static void ReadVariables() { Console.WriteLine("Variable {0} Value: {1}", "USERNAME", Environment.GetEnvironmentVariable( "USERNAME")); Console.WriteLine("Variable {0} Value: {1}", "COMPUTERNAME", Environment.GetEnvironmentVariable( "COMPUTERNAME")); } static void Main(string[] args) { try { ReadVariables(); } catch(Exception e) { Console.WriteLine("Exception {0}", e); } } } }
C D E F G H I J K L M N O P Q R S T U
The output is:
V W
Variable USERNAME Value: damien Exception System.Security.SecurityException: Request for the permission of type System.Security.Permissions.EnvironmentPermission, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed. at System.Security.SecurityRuntime.FrameDescHelper(FrameSecurityDescriptor secDesc, IPermission demand, PermissionToken permToken)
X Y Z
2578
Contents | Index
System.Security.Permissions
SecurityAction Enum RequestMinimum Field
at System.Security.CodeAccessSecurityEngine.Check(PermissionToken permToken, CodeAccessPermission demand, StackCrawlMark& stackMark, Int32 checkFrames, Int32 unrestrictedOverride) at System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark) at System.Security.CodeAccessPermission.Demand() at System.Environment.GetEnvironmentVariable(String variable) at Samples.SecurityActionPermitOnly.ReadVariables() in C:\Books\BCL\Samples\ System.Security\Permissions\SecurityAction\PermitOnly\SecurityAction.cs:line 18 at Samples.SecurityActionPermitOnly.ReadVariables() in C:\Books\BCL\Samples\ System.Security\Permissions\SecurityAction\PermitOnly\SecurityAction.cs:line 14 at Samples.SecurityActionPermitOnly.Main(String[] args) in C:\Books\BCL\Samples\ System.Security\Permissions\SecurityAction\PermitOnly\SecurityAction.cs:line 27
A B C D E F G
The state of the failed permission was:
H I J K
SecurityAction.RequestMinimum Field
L
[ILASM]
M
.field public static literal valuetype System.Security.Permissions.SecurityAction RequestMinimum
N
[C#]
O
RequestMinimum = 8
P
Summary
Q
Specifies that the current security attribute describes the minimum permissions required for an assembly to run. This action can be applied to assemblies.
R
Example
T
S
U
using System; using System.Security; using System.Security.Permissions;
V W
[assembly:EnvironmentPermissionAttribute( SecurityAction.RequestMinimum, Read="COMPUTERNAME;USERNAME")]
X Y Z
namespace Samples { public class SecurityActionRequestMinimum
2579
Contents | Index
SecurityAction Enum
System.Security.Permissions
RequestOptional Field
{ public static void Main() { string[] v = {"USERNAME", "COMPUTERNAME"}; foreach(string s in v) Console.WriteLine("Variable {0} Value: {1}", s, Environment.GetEnvironmentVariable(s)); }
A B C D
} }
E F
The output is:
G Variable USERNAME Value: damien Variable COMPUTERNAME Value: PROJECT42
H I J
SecurityAction.RequestOptional Field
K [ILASM]
L
.field public static literal valuetype System.Security.Permissions.SecurityAction RequestOptional
M
[C#]
RequestOptional = 9
N O
Summary
P
Specifies that the current security attribute describes optional permissions that an assembly can be granted. This action can be applied to assemblies.
Q R
Example
S
using System; using System.Security; using System.Security.Permissions;
T U
[assembly:EnvironmentPermissionAttribute( SecurityAction.RequestOptional, Read="COMPUTERNAME")] [assembly:EnvironmentPermissionAttribute( SecurityAction.RequestMinimum, Read="USERNAME")]
V W X Y
namespace Samples { public class SecurityActionRequestOptional {
Z
2580
Contents | Index
System.Security.Permissions
SecurityAction Enum RequestRefuse Field
public static void Main() { Console.WriteLine("Variable {0} Value: {1}", "USERNAME", Environment.GetEnvironmentVariable( "USERNAME")); Console.WriteLine("Variable {0} Value: {1}", "COMPUTERNAME", Environment.GetEnvironmentVariable( "COMPUTERNAME")); }
A B C D E
} }
F G
The output is:
H
Variable USERNAME Value: damien Variable COMPUTERNAME Value: PROJECT42
I J
SecurityAction.RequestRefuse Field
K
[ILASM]
L
.field public static literal valuetype System.Security.Permissions.SecurityAction RequestRefuse
M
[C#]
N
RequestRefuse = 10
O
Summary
P
Specifies that the current security attribute describes resources or operations that an assembly cannot access. This action can be applied to assemblies.
Q
Example
S
The following example uses a base class, BaseClass, defined in one file and a derived class, SecurityActionRequestRefuse, defined in another file.
T
R
U V
using System; using System.Security; using System.Security.Permissions;
W X
namespace Samples { [PermissionSetAttribute( SecurityAction.InheritanceDemand, Name="FullTrust")] public class BaseClass
Y Z
2581
Contents | Index
SecurityAction Enum
System.Security.Permissions
RequestRefuse Field
{ public void MethodToCall() { Console.WriteLine("Hello world!"); }
A }
B }
C using System; using System.Security; using System.Security.Permissions;
D E F
[assembly: PermissionSetAttribute( SecurityAction.RequestRefuse, Name="FullTrust")]
G H
namespace Samples { public class SecurityActionRequestRefuse: BaseClass { public static void Main() { SecurityActionRequestRefuse s = new SecurityActionRequestRefuse(); s.MethodToCall(); } } }
I J K L M N O P
The output is:
Q
Unhandled Exception: System.Security.SecurityException: Request failed.
R S T U V W X Y Z
2582
Contents | Index
System.Security.Permissions SecurityAttribute
BCL
Object
A
Attribute SecurityAttribute
B
CodeAccessSecurityAttribute
C
EnvironmentPermissionAttribute
D
FileIOPermissionAttribute
E
SecurityPermissionAttribute
F G
Summary
H
This is the base class for attributes used by the security system.
I
Type Summary
J
CF public abstract class SecurityAttribute : Attribute { // Constructors CF public SecurityAttribute (SecurityAction action);
K L M
// Properties MS CF public SecurityAction Action { set; get; } CF public bool Unrestricted { set; get; }
N O P
// Methods CF public abstract IPermission CreatePermission ();
Q
}
R
Example
S
using System; using System.Security; using System.Security.Permissions;
T U V
[assembly:EnvironmentPermissionAttribute( SecurityAction.RequestMinimum, Read="COMPUTERNAME;USERNAME")]
W X
namespace Samples { public class SecurityAttribute { public static void Main() {
Y Z
2583
Contents | Index
SecurityAttribute
System.Security.Permissions
SecurityAttribute() Constructor
string[] v = {"USERNAME", "COMPUTERNAME"}; foreach(string s in v) Console.WriteLine("Variable {0} Value: {1}", s, Environment.GetEnvironmentVariable(s));
A B }
C
} }
D
The output is:
E F
Variable USERNAME Value: damien Variable COMPUTERNAME Value: PROJECT42
G H
SecurityAttribute(System.Security.Permissions.SecurityAction) Constructor
I J K
[ILASM]
L
[C#]
.class public abstract serializable SecurityAttribute extends System.Attribute public SecurityAttribute (SecurityAction action)
M N
Summary
O
Constructs and initializes a new instance of System.Security.Permissions.SecurityAttribute with the specified System.Security.Permissions.SecurityAction.
P Q
Parameters
R S
Parameter
Description
action
A System.Security.Permissions.SecurityAction value.
T U V
Exceptions
W X Y Z
Exception
Condition
System.ArgumentException
action is not a valid System.Security.Permissions.SecurityAction value.
2584
Contents | Index
System.Security.Permissions
SecurityAttribute Unrestricted Property
SecurityAttribute.Action Property [ILASM]
.property valuetype System.Security.Permissions.SecurityAction Action { public hidebysig specialname instance valuetype System.Security.Permissions.SecurityAction get_Action() public hidebysig specialname instance void set_Action(valuetype System.Security.Permissions.SecurityAction value) }
A B C
[C#]
D
public SecurityAction Action { get; set; }
E
Summary
F
Gets or sets a security action.
G
Property Value
H
One of the System.Security.Permissions.SecurityAction values.
I J
Description
K
This property is inherited by all classes implementing custom attributes for declarative security.
L M N
SecurityAttribute.Unrestricted Property
O
[ILASM]
P
.property bool Unrestricted { public hidebysig specialname instance bool get_Unrestricted() public hidebysig specialname instance void set_Unrestricted(bool value) }
Q
[C#]
R
public bool Unrestricted { get; set; }
S T
Summary
U
Gets or sets full (unrestricted) permission to the resource protected by the current instance.
V
Property Value
W
true if full access to the protected resource is declared or is being set; otherwise, false.
X Y Z
2585
Contents | Index
SecurityAttribute
System.Security.Permissions
CreatePermission() Method
SecurityAttribute.CreatePermission() Method [ILASM]
A
.method public hidebysig virtual abstract class System.Security.IPermission CreatePermission()
B
[C#]
public abstract IPermission CreatePermission()
C D
Summary
E
Returns a System.Security.IPermission object that contains the security information of the current instance.
F G
Behaviors
H
Returns an instance of the permission type that corresponds to the current attribute. The returned object contains the security information of the current attribute.
I J
How and When to Override
K
Override this method to create an instance of the permission type that corresponds to the current attribute. For example, the CreatePermission implementation of System.Security.Permissions.SecurityPermissionAttribute creates an instance of the System.Security.Permissions.SecurityPermission class.
L M N O
Usage
P
Security information specified using attributes is stored in metadata. The security information in the metadata is created using the permission object returned by this method.
Q R S T U V W X Y Z
2586
Contents | Index
System.Security SecurityElement
BCL
Object
A
SecurityElement
B
Summary
C
Represents the XML object model for encoding security objects.
D E
Type Summary CF public sealed class SecurityElement { // Properties MS CF public Hashtable Attributes { set; get; } MS CF public ArrayList Children { set; get; } MS CF public string Tag { set; get; } MS CF public string Text { set; get; }
F G H I J
MS MS MS MS MS MS MS MS MS MS
// CF CF CF CF CF CF CF CF CF CF CF
Methods public void AddAttribute (string name, string value); public void AddChild (SecurityElement child); public string Attribute (string name); public bool Equal (SecurityElement other); public static string Escape (string str); public static bool IsValidAttributeName (string name); public static bool IsValidAttributeValue (string value); public static bool IsValidTag (string tag); public static bool IsValidText (string text); public string SearchForTextOfTag (string tag); public override string ToString ();
K L M N O P Q R
}
S
Description
T
The simple XML object model for an element consists of the following parts:
U
• • • •
The tag is the element name. The attributes are zero or more name/value attribute pairs on the element. The children are zero or more elements nested within and . An attribute name must be at least one character, and cannot be null. If element-based value representation is used, elements with a text string that is null are represented in the form; otherwise, text is delimited by the and tokens. Both forms can be combined with attributes, which are shown if present.
V W X Y Z
2587
Contents | Index
SecurityElement
System.Security
SecurityElement Class
•
A B
The tags, attributes, and text are case-sensitive. The XML form contains quotation marks and escape sequences where necessary. String values that include characters invalid for use in XML result in a System.ArgumentException. These rules apply to all properties and methods.
[Note: This class is intended to be a lightweight implementation of a simple XML object model for use within the security system, and not for use as a general XML object model. It is strongly suggested that properties of a security element are expressed as attributes, and property values are expressed as attribute values. Specifically, avoid nesting text within tags. For any text representation a representation of type is usually available. Using attribute-based XML representations aids in readability. For performance reasons, character validity is checked only when the element is encoded into XML form, and not on every set of a property or method call. Static methods allow explicit checking where needed. This class is used only by the system; applications cannot create instances of the System.Security.SecurityElement type.]
C D E F G H I J
Example
K
using System; using System.Security; using System.Security.Permissions;
L M
namespace Samples { public class SecurityElementSample { public static void Main() { EnvironmentPermission p1 = new EnvironmentPermission( EnvironmentPermissionAccess.Read, "COMPUTERNAME"); SecurityElement s = p1.ToXml(); Console.WriteLine(s.ToString()); } } }
N O P Q R S T U V W
The output is:
X
Y Z
2588
Contents | Index
System.Security
SecurityElement Children Property
SecurityElement.Attributes Property [ILASM]
.property class System.Collections.Hashtable Attributes { public hidebysig specialname instance class System.Collections.Hashtable get_Attributes() public hidebysig specialname instance void set_Attributes(class System.Collections.Hashtable value) }
A B C
[C#]
public Hashtable Attributes { get; set; }
D
Summary
E
Gets or sets the attributes of an XML element as name/value pairs.
F G
Property Value
H
The System.Collections.Hashtable object for the attribute values of the XML element.
I
Description
J
Each attribute is stored in the System.Collections.Hashtable as a name/value pair. Names and values in attributes should contain only valid XML attribute characters. Use System.Security.SecurityElement.Escape to remove invalid characters from the string. There is no support for quoted strings, so strings for name/value pairs should not contain quotes or other characters requiring quoting.
K
M
Exceptions
P
L
N O
Q
Exception
Condition
System.ArgumentException
The name or value of the System.Collections.Hashtable object is invalid.
R S T U V
SecurityElement.Children Property
W [ILASM]
X
.property class System.Collections.ArrayList Children { public hidebysig specialname instance class System.Collections.ArrayList get_Children() public hidebysig specialname instance void set_Children(class System.Collections.ArrayList value) }
Y Z
[C#]
public ArrayList Children { get; set; }
2589
Contents | Index
SecurityElement
System.Security
Tag Property
Summary Gets or sets the array of child elements of the XML element. A
Property Value
B
The ordered child elements of the XML element as security elements.
C
Description
D
If a System.Security.SecurityElement contains both System.Security.SecurityElement.Text and System.Security.SecurityElement.Children, System.Security.SecurityElement.Text will appear first.
E F G
Exceptions
H I J
Exception
Condition
System.ArgumentNullException
A child of the XML parent node is null.
K L M
SecurityElement.Tag Property
N
[ILASM]
O
.property string Tag { public hidebysig specialname instance string get_Tag() public hidebysig specialname instance void set_Tag(string value) }
P
[C#]
public string Tag { get; set; }
Q R
Summary
S
Gets or sets the tag name of an XML element.
T
Description
U
In XML, the tag appears in the script below:
V text
W
If this element has child elements, the children will replace text. Assign only valid XML tag strings to this property. Use System.Security.SecurityElement.Escape to remove invalid characters from the string.
X Y Z
2590
Contents | Index
System.Security
SecurityElement AddAttribute() Method
Exceptions Exception
Condition
System.ArgumentNullException
The tag is null.
System.ArgumentException
The tag is not valid in XML.
A B C D E
SecurityElement.Text Property
F
[ILASM]
G
.property string Text { public hidebysig specialname instance string get_Text() public hidebysig specialname instance void set_Text(string value) }
H
[C#]
I
public string Text { get; set; }
J
Summary
K
Gets or sets the text within an XML element.
L
Description
M
The text should not contain XML special characters. Use System.Security.SecurityElement.Escape to remove invalid characters from the string. If a System.Security.SecurityElement contains both System.Security.SecurityElement.Text and System.Security.SecurityElement.Children, System.Security.SecurityElement.Text will appear first.
N O P Q R
Exceptions
S
Exception
Condition
System.ArgumentException
The text is not valid in XML.
T U V W X
SecurityElement.AddAttribute(System.String, System.String) Method
Y [ILASM]
Z
.method public hidebysig instance void AddAttribute(string name, string value) [C#]
public void AddAttribute(string name, string value)
2591
Contents | Index
SecurityElement
System.Security
AddChild() Method
Summary Adds a name/value attribute to an XML element. A
Parameters
B C
Parameter
Description
D
name
The name of the attribute.
value
The value of the attribute.
E F G
Description
H
Names and values in attributes should only contain valid XML attribute characters. XML attribute names must be unique. Use System.Security.SecurityElement.Escape to remove invalid characters from the string. There is no support for quoted strings, so strings for name/value pairs should not contain quotes or other characters requiring quoting.
I J K L
Exceptions
M N
Exception
Condition
System.ArgumentNullException
The name parameter or value parameter is null.
O P Q
The name parameter or value parameter is invalid in XML.
R System.ArgumentException S
-orAn attribute with the name specified by the name parameter already exists.
T U V
SecurityElement.AddChild(System.Security.SecurityElement) Method
W
[ILASM]
X
.method public hidebysig instance void AddChild(class System.Security.SecurityElement child)
Y
[C#]
Z
public void AddChild(SecurityElement child)
2592
Contents | Index
System.Security
SecurityElement Attribute() Method
Summary Adds a child element to the XML element. A
Parameters
B
Parameter
Description
C
child
The child element to add.
D E F
Description
G
The child element is added following any previously existing child elements.
H
Exceptions
I
Exception
Condition
System.ArgumentNullException
The child parameter is null.
J K L M N
SecurityElement.Attribute(System.String) Method
O [ILASM]
.method public hidebysig instance string Attribute(string name)
P
[C#]
Q
public string Attribute(string name)
R
Summary
S
Finds an attribute by name in an XML element.
T U
Parameters
V
Parameter
Description
name
The name of the attribute for which to search.
W X Y Z
Return Value The value associated with the named attribute, or null if no attribute with name exists.
2593
Contents | Index
SecurityElement
System.Security
Equal() Method
Description With XML as follows, Attribute(“B”) would return “456”. A
text
B
Exceptions
C D
Exception
Condition
System.ArgumentNullException
The name parameter is null.
E F G H
SecurityElement.Equal(System.Security.SecurityElement) Method
I
[ILASM]
J
.method public hidebysig instance bool Equal(class System.Security.SecurityElement other)
K
[C#]
L
public bool Equal(SecurityElement other)
M
Summary
N
Compares two XML element objects for equality.
O
Parameters
P Q
Parameter
Description
other
An XML element object to which to compare the current XML element object.
R S T U
Return Value
V
true if the tag, attribute names and values, child elements, and text fields in the current XML element are identical to their counterparts in the other parameter; otherwise, false.
W X
Description
Y
If there are child elements, comparison extends recursively to them. There is no support for comparing different XML representations of the same characters.
Z
2594
Contents | Index
System.Security
SecurityElement Escape() Method
SecurityElement.Escape(System.String) Method [ILASM]
.method public hidebysig static string Escape(string str) [C#]
A
public static string Escape(string str)
B C
Summary
D
Replaces invalid XML characters in a string with their valid XML equivalent.
E
Parameters
F G
Parameter
Description
str
The string within which to escape invalid characters.
H I J
Return Value
K
The input string with invalid characters replaced.
L M
Description
N
Use this method to replace invalid characters in a string before using the string in a System.Security.SecurityElement. If invalid characters are used in a System.Security.SecurityElement without being escaped, a System.ArgumentException is thrown. The following table shows the invalid XML characters and their escaped equivalents.
O P Q R
Invalid XML Character
S
Replaced With
T
"<"
"<"
U
">"
">"
V
"\""
"""
"\'"
"'"
"&"
"&"
W X Y Z
2595
Contents | Index
SecurityElement
System.Security
IsValidAttributeName() Method
SecurityElement.IsValidAttributeName(System.String) Method [ILASM]
.method public hidebysig static bool IsValidAttributeName(string name)
A
[C#]
public static bool IsValidAttributeName(string name)
B C
Summary
D
Determines whether a string is a valid attribute name.
E
Parameters
F G
Parameter
Description
name
The attribute name to test for validity.
H I J K
Return Value
L
true if the name parameter is a valid XML attribute name; otherwise, false.
M
Description
N
This method can be used to test an attribute before adding it to a security element.
O P
SecurityElement.IsValidAttributeValue(System.String) Method
Q
[ILASM]
R
.method public hidebysig static bool IsValidAttributeValue(string value) [C#]
S
public static bool IsValidAttributeValue(string value)
T U
Summary
V
Determines whether a string is a valid attribute value.
W
Parameters
X Y Z
Parameter
Description
value
The attribute value to test for validity.
2596
Contents | Index
System.Security
SecurityElement IsValidText() Method
Return Value true if the value parameter is a valid XML attribute value; otherwise, false.
Description
A
This method can be used to test an attribute before adding it to a security element.
B C D
SecurityElement.IsValidTag(System.String) Method
E [ILASM]
.method public hidebysig static bool IsValidTag(string tag)
F
[C#]
G
public static bool IsValidTag(string tag)
H
Summary
I
Determines whether a string is a valid tag.
J K
Parameters
L
Parameter
Description
tag
The tag to test for validity.
M N O P
Return Value
Q
true if the tag parameter is a valid XML tag; otherwise, false.
R
Description
S
This can be used to test a System.Security.SecurityElement.Tag before setting it.
T U
SecurityElement.IsValidText(System.String) Method
V
[ILASM]
W
.method public hidebysig static bool IsValidText(string text)
X
[C#]
Y
public static bool IsValidText(string text)
Z
Summary Determines whether a string is valid as text within an XML element.
2597
Contents | Index
SecurityElement
System.Security
SearchForTextOfTag() Method
Parameters Parameter
Description
text
The text to test for validity.
A B C D
Return Value
E
true if the text parameter is a valid XML text element; otherwise, false.
F
Description
G
This method can be used to test System.Security.SecurityElement.Text before setting it.
H I J
SecurityElement.SearchForTextOfTag(System.String) Method
K
[ILASM]
L
.method public hidebysig instance string SearchForTextOfTag(string tag) [C#]
M
public string SearchForTextOfTag(string tag)
N
Summary
O
Finds a child by its tag name and returns the contained text.
P Q
Parameters
R S T
Parameter
Description
tag
The tag for which to search in child elements.
U V
Return Value
W
The text contents of the first child element with the specified tag value.
X Y Z
2598
Contents | Index
System.Security
SecurityElement ToString() Method
Description This method is equivalent to the following: A
String SearchForTextOfTag(String tag) { SecurityElement element = this.SearchForChildByTag(tag); return element.Text; }
B C D
With XML as follows, SearchForTextOfTag("second") would return “text2”.
E
text1 <second>text2 thetag>
F G
Exceptions
H
Exception
Condition
System.ArgumentNullException
tag is null.
I J K L M
SecurityElement.ToString() Method
N
[ILASM]
.method public hidebysig virtual string ToString()
O
[C#]
P
public override string ToString()
Q
Summary
R
Returns a System.String representation of the current instance.
S
Description
T
[Note: The XML in the System.String returned by this method represents the state of a permission object. To obtain the XML schema used to encode that object, see the class page for the particular permission object. This method overrides System.Object.ToString.]
U V W X Y Z
2599
Contents | Index
System.Security SecurityException
BCL
Object
A
Exception
B
ISerializable
NotStandardized
SystemException
C
SecurityException
D
Summary
E
Represents the error that occurs when an application does not have the permissions required to access a resource or perform a secured operation.
F G
Type Summary
H
public class SecurityException : SystemException { // Constructors public SecurityException (); public SecurityException (string message); public SecurityException (string message, Exception inner); MS CF public SecurityException (string message, Type type); MS CF public SecurityException (string message, Type type, string state); MS CF protected SecurityException (SerializationInfo info, StreamingContext context);
I J K L M N O P Q
// MS CF 1.1 MS CF MS CF MS CF 1.1
R S
Properties public string GrantedSet { get; } public string PermissionState { get; } public Type PermissionType { get; } public string RefusedSet { get; }
T // Methods MS CF public override void GetObjectData (SerializationInfo info, StreamingContext context); MS CF public override string ToString ();
U V W
}
X Y
Description
Z
[Note: For more information about permissions and security, see Partition V of the CLI specification. The following IL instructions throw System.Security.SecurityException:]
2600
Contents | Index
System.Security
SecurityException SecurityException Class
Example using System; using System.Security; using System.Security.Permissions;
A B
namespace Samples {
C
public class SecurityExceptionSample { [EnvironmentPermissionAttribute( SecurityAction.PermitOnly, Read="USERNAME")] static void Main(string[] args) { string s = "COMPUTERNAME"; try { Console.WriteLine("Variable {0} Value: {1}", s, Environment.GetEnvironmentVariable(s)); } catch(SecurityException e) { Console.WriteLine("Exception {0}", e); } } }
D E F G H I J K L M N O
}
P
The output is:
Q R
Exception System.Security.SecurityException: Request for the permission of type System.Security.Permissions.EnvironmentPermission, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed. at System.Security.SecurityRuntime.FrameDescHelper(FrameSecurityDescriptor secDesc, IPermission demand, PermissionToken permToken) at System.Security.CodeAccessSecurityEngine.Check(PermissionToken permToken, CodeAccessPermission demand, StackCrawlMark& stackMark, Int32 checkFrames, Int32 unrestrictedOverride) at System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark) at System.Security.CodeAccessPermission.Demand() at System.Environment.GetEnvironmentVariable(String variable) at Samples.SecurityExceptionSample.Main(String[] args) in C:\Books\BCL\Samples\ System.Security\SecurityException\SecurityException.cs:line 18
S T U V W X Y Z
2601
Contents | Index
SecurityException
System.Security
SecurityException() Constructor
SecurityException() Constructor [ILASM]
public rtspecialname specialname instance void .ctor()
A
[C#]
public SecurityException()
B C
Summary
D
Constructs and initializes a new instance of the System.Security.SecurityException class.
E F
Description
G
This constructor initializes the System.Security.SecurityException.Message property of the new instance to a system-supplied message that describes the error, such as “A security violation has occurred.” This message takes into account the current system culture. The System.Security.SecurityException.InnerException property of the new instance is initialized to null.
H I J K L M
SecurityException(System.String) Constructor
N [ILASM]
O
public rtspecialname specialname instance void .ctor(string message) [C#]
P
public SecurityException(string message)
Q R
Summary
S
Constructs and initializes a new instance of the System.Security.SecurityException class.
T
Parameters
U V
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
W X Y Z
2602
Contents | Index
System.Security
SecurityException SecurityException() Constructor
Description This constructor initializes the System.Security.SecurityException.Message property of the new instance using message. If message is null, the System.Security.SecurityException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.Security.SecurityException.InnerException property of the new instance is initialized to null.
A B C D E
SecurityException(System.String, System.Exception) Constructor
F
[ILASM]
G
public rtspecialname specialname instance void .ctor(string message, class System.Exception inner)
H
[C#]
I
public SecurityException(string message, Exception inner)
J
Summary
K
Constructs and initializes a new instance of the System.Security.SecurityException class.
L M
Parameters
N
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
O P
inner
Q R S
An instance of System.Security.SecurityException that is the cause of the current exception. If inner is non-null, then the current exception was raised in a catch block handling inner.
T U V
Description
W
This constructor initializes the System.Security.SecurityException.Message property of the new instance using message and the System.Security.SecurityException.InnerException property using inner. If message is null, the System.Security.SecurityException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For more information on inner exceptions, see System.Exception.InnerException.]
X Y Z
2603
Contents | Index
SecurityException
System.Security
SecurityException() Constructor
SecurityException(System.String, System.Type) Constructor [ILASM]
A
public rtspecialname specialname instance void .ctor(string message, class System.Type type)
B
[C#]
public SecurityException(string message, Type type)
C D
Summary
E
Initializes a new instance of the System.Security.SecurityException class with a specified error message and the permission type that caused the exception to be thrown.
F G
Parameters
H I J K
Parameter
Description
message
The error message that explains the reason for the exception.
type
The type of the permission that caused the exception to be thrown.
L M
Description
N
The following table shows the initial property values for an instance of System.Security.SecurityException.
O P Q
Property
Value
S
System.Exception.InnerException
null
T
System.Exception.Message
The error message string.
R
U V W
SecurityException(System.String, System.Type, System.String) Constructor
X
[ILASM]
Y
public rtspecialname specialname instance void .ctor(string message, class System.Type type, string state) [C#]
Z
public SecurityException(string message, Type type, string state)
2604
Contents | Index
System.Security
SecurityException SecurityException() Constructor
Summary Initializes a new instance of the System.Security.SecurityException class with a specified error message, the permission type that caused the exception to be thrown, and the state.
A B
Parameters
C D
Parameter
Description
message
The error message that explains the reason for the exception.
type
The type of the permission that caused the exception to be thrown.
G
state
The state of the permission that caused the exception to be thrown.
H
E F
I
Description
J
The following table shows the initial property values for an instance of System.Security.SecurityException.
K L M
Property
Value
System.Exception.InnerException
null
System.Exception.Message
The error message string.
N O P Q R S
SecurityException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
T U
[ILASM]
V
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
W
[C#]
X
protected SecurityException(SerializationInfo info, StreamingContext context)
Y
Summary
Z
Initializes a new instance of the System.Security.SecurityException class with serialized data. 2605
Contents | Index
SecurityException
System.Security
GrantedSet Property
Parameters Parameter
Description
info
The object that holds the serialized object data.
context
The contextual information about the source or destination.
A B C D E
Description
F
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
G H I
SecurityException.GrantedSet Property
J
[ILASM]
K
.property string GrantedSet { public hidebysig specialname instance string get_GrantedSet() }
L
[C#]
public string GrantedSet { get; }
M N
Summary
O
Gets the granted permission set of the assembly, which caused the System.Security.SecurityException.
P Q
Property Value
R
The XML representation of the granted set of the assembly.
S
Description
T
This property might not contain relevant data in security exceptions other than exceptions involving checks for the System.Security.AllowPartiallyTrustedCallersAttribute.
U V W X Y Z
2606
Contents | Index
System.Security
SecurityException PermissionState Property
Exceptions Exception
Condition A
The code that calls this method does not have System.Security.Permissions.SecurityPermissionFlag.ControlEvidence. System.Security.SecurityException
B C
-or-
D
The code that calls this method does not have System.Security.Permissions.SecurityPermissionFlag.ControlPolicy.
E F G
Permissions
H
Permission
Description
System.Security.Permissions.SecurityPermission
For the ability to provide evidence. Associated enumeration: System.Security.Permissions.SecurityPermissionFlag.ControlEvidence.
I J
System.Security.Permissions.SecurityPermission
K L M
For the ability to view policy. Associated enumeration: System.Security.Permissions.SecurityPermissionFlag.ControlPolicy.
N O P
SecurityException.PermissionState Property
Q
[ILASM]
R
.property string PermissionState { public hidebysig specialname instance string get_PermissionState() }
S
[C#]
T
public string PermissionState { get; }
U
Summary
V
Gets the state of the permission that threw the exception.
W X Y Z
2607
Contents | Index
SecurityException
System.Security
PermissionType Property
Permissions Permission
Description
System.Security.Permissions.SecurityPermission
For the ability to modify policy and evidence. Associated enumeration: System.Security.Permissions.SecurityPermissionFlag.ControlEvidence,System.Security.Permissions.SecurityPermissionFlag.ControlPolicy.
A B C D E F
SecurityException.PermissionType Property
G
[ILASM]
H
.property class System.Type PermissionType { public hidebysig specialname instance class System.Type get_PermissionType() }
I
[C#]
J
public Type PermissionType { get; }
K
Summary
L
Gets the type of the permission that threw the exception.
M N
SecurityException.RefusedSet Property
O [ILASM]
P
.property string RefusedSet { public hidebysig specialname instance string get_RefusedSet() }
Q
[C#]
public string RefusedSet { get; }
R S
Summary
T
Gets the refused permission set of the assembly, which caused the System.Security.SecurityException.
U V
Property Value
W
The XML representation of the refused set of the assembly.
X
Description
Y
This property might not contain relevant data in security exceptions other than exceptions involving checks for the System.Security.AllowPartiallyTrustedCallersAttribute.
Z
2608
Contents | Index
System.Security
SecurityException GetObjectData() Method
Exceptions Exception
Condition A
The code that calls this method does not have System.Security.Permissions.SecurityPermissionFlag.ControlEvidence. System.Security.SecurityException
B C
-or-
D
The code that calls this method does not have System.Security.Permissions.SecurityPermissionFlag.ControlPolicy.
E F G
Permissions
H
Permission
Description
System.Security.Permissions.SecurityPermission
For the ability to provide evidence. Associated enumeration: System.Security.Permissions.SecurityPermissionFlag.ControlEvidence.
I J
System.Security.Permissions.SecurityPermission
K L M
For the ability to view policy. Associated enumeration: System.Security.Permissions.SecurityPermissionFlag.ControlPolicy.
N O P
SecurityException.GetObjectData(System.Runtime.Serialization. SerializationInfo, System.Runtime.Serialization.StreamingContext) Method
Q
[ILASM]
S
.method public hidebysig virtual void GetObjectData(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
T
R
U
[C#]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
V W
Summary
X
Sets the System.Runtime.Serialization.SerializationInfo with information about the System.Security.SecurityException.
Y Z
2609
Contents | Index
SecurityException
System.Security
ToString() Method
Parameters Parameter
Description
info
The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown.
context
The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination.
A B C D E
Description
F
GetObjectData sets a System.Runtime.Serialization.SerializationInfo with all the exception object data targeted for serialization. During deserialization, the exception is reconstituted from the SerializationInfo transmitted over the stream.
G H I
Exceptions
J K
Exception
Condition
L
System.ArgumentNullException
The info parameter is null.
M N
SecurityException.ToString() Method
O
[ILASM]
P
.method public hidebysig virtual string ToString() [C#]
Q
public override string ToString()
R S
Summary
T
Returns a representation of the current System.Security.SecurityException.
U
Permissions
V W X Y Z
Permission
Description
System.Security.Permissions.SecurityPermission
For the ability to provide evidence. Associated enumeration: System.Security.Permissions.SecurityPermissionFlag.ControlEvidence.
System.Security.Permissions.SecurityPermission
For the ability to view policy. Associated enumeration: System.Security.Permissions.SecurityPermissionFlag.ControlPolicy.
2610
Contents | Index
System.Security.Permissions SecurityPermission
BCL
ISecurityEncodable IStackWalk
Object CodeAccessPermission
NotStandardized
A
NotStandardized
B
IPermission
SecurityPermission
IUnrestrictedPermission
NotStandardized
C D
Type Summary
E
CF public sealed class SecurityPermission : CodeAccessPermission, IUnrestrictedPermission { // Constructors CF public SecurityPermission (PermissionState state); CF public SecurityPermission (SecurityPermissionFlag flag);
F G H I
// Properties MS CF public SecurityPermissionFlag Flags { set; get; } // CF CF CF CF MS CF CF CF }
J K
Methods public override IPermission Copy (); public override void FromXml (SecurityElement esd); public override IPermission Intersect (IPermission target); public override bool IsSubsetOf (IPermission target); public bool IsUnrestricted (); public override SecurityElement ToXml (); public override IPermission Union (IPermission target);
L M N O P Q
Summary
R
Describes a set of security permissions applied to code.
S
Description
T
The System.Security.Permissions.SecurityPermissionFlag enumeration defines the permissions secured by this class. The XML encoding of a System.Security.Permissions.SecurityPermission instance is defined below in EBNF format. The following conventions are used:
U
• • •
V W X
All non-literals in the grammar below are shown in normal type. All literals are in bold font. The following meta-language symbols are used: – Constructs and initializes a new instance of the System.Collections.Hashtable class with the specified initial capacity.
Y Z
2611
Contents | Index
SecurityPermission
System.Security.Permissions
SecurityPermission Class
– '*' represents a meta-language symbol suffixing an expression that can appear zero or more times. '?' represents a meta-language symbol suffixing an expression that can appear zero or one time. – '+' represents a meta-language symbol suffixing an expression that can appear one or more times. – '(',')' is used to group literals, non-literals, or a mixture of literals and non-literals. – '|' denotes an exclusive disjunction between two expressions. – '::= ' denotes a production rule where a left-hand non-literal is replaced by a righthand expression containing literals, non-literals, or both. – BuildVersion refers to the build version of the shipping CLI. This is a dotted build number such as '2412.0'. – ECMAPubKeyToken ::= b77a5c561934e089 – SecurityPermissionFlag = Assertion | ControlThread | Execution | SkipVerification | UnmanagedCode
A B C D E F G H I
Each SecurityPermissionFlag literal can appear in the XML no more than once. For example, Flags=Assertion,Assertion is illegal.
J K
SecurityPermission ::=
L M N O P Q R S T U V
Example
W
using System; using System.Security; using System.Security.Permissions;
X Y
namespace Samples { public class SecurityPermissionSample { public static void Main()
Z
2612
Contents | Index
System.Security.Permissions
SecurityPermission SecurityPermission() Constructor
{ try { SecurityPermission sp = new SecurityPermission( SecurityPermissionFlag.Assertion); DoAssert(); sp.Deny(); DoAssert(); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); }
A B C D E F
} [SecurityPermissionAttribute( SecurityAction.Demand, Assertion=true)] public static void DoAssert() { EnvironmentPermission p = new EnvironmentPermission( EnvironmentPermissionAccess.Read, "USERNAME"); p.Assert(); Console.WriteLine("Assert succeeded"); }
G H I J K L M
}
N
}
O
The output is:
P
Assert succeeded Exception: System.Security.SecurityException: Request failed. at System.Security.SecurityRuntime.FrameDescSetHelper(FrameSecurityDescriptor secDesc, PermissionSet demandSet, PermissionSet& alteredDemandSet) at Samples.SecurityPermissionSample.DoAssert() in C:\Books\BCL\Samples\ System.Security\Permissions\SecurityPermission\SecurityPermission.cs:line 29 at Samples.SecurityPermissionSample.Main() in C:\Books\BCL\Samples\ System.Security\Permissions\SecurityPermission\SecurityPermission.cs:line 18
Q R S T U V
SecurityPermission(System.Security.Permissions.PermissionState) Constructor
W
[ILASM]
X
public rtspecialname specialname instance void .ctor(valuetype System.Security.Permissions.PermissionState state)
Y
[C#]
Z
public SecurityPermission(PermissionState state)
2613
Contents | Index
SecurityPermission
System.Security.Permissions
SecurityPermission() Constructor
Summary Constructs a new instance of the System.Security.Permissions.SecurityPermission class with the specified System.Security.Permissions.PermissionState value.
A B
Parameters
C D
Parameter
Description
state
A System.Security.Permissions.PermissionState value. This value is either System.Security.Permissions.PermissionState.None or System.Security.Permissions.PermissionState.Unrestricted, respectively yielding fully restricted or fully unrestricted access to all security variables.
E F G H I
Exceptions
J K L M
Exception
Condition
System.ArgumentException
state is not a valid System.Security.Permissions.PermissionState value.
N O
Example
P
using System; using System.Security; using System.Security.Permissions;
Q R
namespace Samples { public class SecurityPermissionConstructor { public static void Main() { try { SecurityPermission sp = new SecurityPermission( PermissionState.Unrestricted); DoAssert(); sp.Deny(); DoAssert(); }
S T U V W X Y Z
2614
Contents | Index
System.Security.Permissions
SecurityPermission SecurityPermission() Constructor
catch(Exception e) { Console.WriteLine("Exception: {0}", e); }
A
} [SecurityPermissionAttribute( SecurityAction.Demand, Assertion=true)] public static void DoAssert() { EnvironmentPermission p = new EnvironmentPermission( EnvironmentPermissionAccess.Read, "USERNAME"); p.Assert(); Console.WriteLine("Assert succeeded"); }
B C D E F G H
}
I
}
J
The output is:
K Assert succeeded Exception: System.Security.SecurityException: Request failed. at System.Security.SecurityRuntime.FrameDescSetHelper(FrameSecurityDescriptor secDesc, PermissionSet demandSet, PermissionSet& alteredDemandSet) at Samples.SecurityPermissionConstructor.DoAssert() in C:\Books\BCL\Samples\ System.Security\Permissions\SecurityPermission\SecurityPermission(System.Security. Permissions.PermissionState)\SecurityPermission.cs:line 29 at Samples.SecurityPermissionConstructor.Main() in C:\Books\BCL\Samples\ System.Security\Permissions\SecurityPermission\SecurityPermission(System.Security. Permissions.PermissionState)\SecurityPermission.cs:line 18
L M N O P Q R S
SecurityPermission(System.Security.Permissions.SecurityPermissionFlag) Constructor
T U
[ILASM]
V
public rtspecialname specialname instance void .ctor(valuetype System.Security.Permissions.SecurityPermissionFlag flag)
W
[C#]
public SecurityPermission(SecurityPermissionFlag flag)
X Y
Summary
Z
Constructs a new instance of the System.Security.Permissions.SecurityPermission class with the specified System.Security.Permissions.SecurityPermissionFlag value. 2615
Contents | Index
SecurityPermission
System.Security.Permissions
SecurityPermission() Constructor
Parameters Parameter
Description
flag
One or more System.Security.Permissions.SecurityPermissionFlag values. Specify multiple values for flag using the bitwise OR operator.
A B C D
Exceptions
E F
Exception
Condition
System.ArgumentException
flag is not a valid System.Security.Permissions.SecurityPermissionFlag value.
G H I J
Example
K
using System; using System.Security; using System.Security.Permissions;
L M
namespace Samples { public class SecurityPermissionConstructor { public static void Main() { try { SecurityPermission sp = new SecurityPermission( SecurityPermissionFlag.Assertion); DoAssert(); sp.Deny(); DoAssert(); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } [SecurityPermissionAttribute( SecurityAction.Demand, Assertion=true)] public static void DoAssert() { EnvironmentPermission p =
N O P Q R S T U V W X Y Z
2616
Contents | Index
System.Security.Permissions
SecurityPermission Flags Property
new EnvironmentPermission( EnvironmentPermissionAccess.Read, "USERNAME"); p.Assert(); Console.WriteLine("Assert succeeded");
A
}
B
}
C
}
D
The output is:
E Assert succeeded Exception: System.Security.SecurityException: Request failed. at System.Security.SecurityRuntime.FrameDescSetHelper(FrameSecurityDescriptor secDesc, PermissionSet demandSet, PermissionSet& alteredDemandSet) at Samples.SecurityPermissionConstructor.DoAssert() in C:\Books\BCL\Samples\ System.Security\Permissions\SecurityPermission\SecurityPermission(System.Security. Permissions.SecurityPermissionFlag)\SecurityPermission.cs:line 29 at Samples.SecurityPermissionConstructor.Main() in C:\Books\BCL\Samples\ System.Security\Permissions\SecurityPermission\SecurityPermission(System.Security. Permissions.SecurityPermissionFlag)\SecurityPermission.cs:line 18
F G H I J K L M
SecurityPermission.Flags Property
N
[ILASM]
O
.property valuetype System.Security.Permissions.SecurityPermissionFlag Flags { public hidebysig specialname instance valuetype System.Security.Permissions. SecurityPermissionFlag get_Flags() public hidebysig specialname instance void set_Flags(valuetype System.Security.Permissions.SecurityPermissionFlag value) }
P Q
[C#]
R
public SecurityPermissionFlag Flags { get; set; }
S
Summary
T
Gets or sets the security permission flags.
U
Property Value
V
The state of the current permission, represented by a bitwise OR combination of any permission bits defined by System.Security.Permissions.SecurityPermissionFlag.
W
Description
Y
Individual permission bits can be determined by performing an AND operation against this value and checking for nonzero.
Z
X
2617
Contents | Index
SecurityPermission
System.Security.Permissions
Copy() Method
Exceptions Exception
Condition
System.ArgumentException
An attempt is made to set this property to an invalid value. See System.Security.Permissions.SecurityPermissionFlag for the valid values.
A B C D E
SecurityPermission.Copy() Method
F [ILASM]
G
.method public hidebysig virtual class System.Security.IPermission Copy() [C#]
H
public override IPermission Copy()
I
Summary
J
Returns a System.Security.Permissions.SecurityPermission object containing the same values as the current instance.
K L
Description
M
[Note: The object returned by this method represents the same access to resources as the current instance. This method overrides System.Security.CodeAccessPermission.Copy and is implemented to support the System.Security.IPermission interface.]
N O P
Example
Q
using System; using System.Security; using System.Security.Permissions;
R S
namespace Samples { public class SecurityPermissionCopy { public static void Main() { SecurityPermission sp = new SecurityPermission( SecurityPermissionFlag.Assertion); Console.WriteLine(sp.ToXml()); IPermission ip = sp.Copy(); Console.WriteLine(ip.ToXml()); } } }
T U V W X Y Z
2618
Contents | Index
System.Security.Permissions
SecurityPermission FromXml() Method
The output is:
A B C
D E F G
SecurityPermission.FromXml(System.Security.SecurityElement) Method
H
[ILASM]
I
.method public hidebysig virtual void FromXml(class System.Security.SecurityElement esd)
J
[C#]
public override void FromXml(SecurityElement esd)
K L
Summary
M
Reconstructs the state of a System.Security.Permissions.SecurityPermission object using the specified XML encoding.
N O
Parameters
P
Parameter
Description
esd
A System.Security.SecurityElement instance containing the XML encoding to use to reconstruct the state of a System.Security.Permissions.SecurityPermission object.
Q R S T U
Description
V
The state of the current instance is changed to the state encoded in esd. [Note: For the XML encoding for this class, see the System.Security.Permissions.SecurityPermission class page. This method overrides System.Security.CodeAccessPermission.FromXml.]
W X Y Z
2619
Contents | Index
SecurityPermission
System.Security.Permissions
FromXml() Method
Exceptions Exception
Condition
System.ArgumentNullException
esd is null.
System.ArgumentException
esd does not contain the encoding for a System.Security.Permissions.SecurityPermission instance.
A B C D
The version number of esd is not valid.
E F
Example
G
using System; using System.Security; using System.Security.Permissions;
H I
namespace Samples { public class SecurityPermissionFromXml { public static void Main() { SecurityPermission sp = new SecurityPermission( SecurityPermissionFlag.Assertion); SecurityElement se = sp.ToXml(); SecurityPermission sp1 = new SecurityPermission( PermissionState.None); Console.WriteLine(sp1); sp1.FromXml(se); Console.WriteLine(sp1); } } }
J K L M N O P Q R S T U
The output is:
V
W X Y
Z
2620
Contents | Index
System.Security.Permissions
SecurityPermission Intersect() Method
SecurityPermission.Intersect(System.Security.IPermission) Method [ILASM]
.method public hidebysig virtual class System.Security.IPermission Intersect(class System.Security.IPermission target)
A
[C#]
B
public override IPermission Intersect(IPermission target)
C
Summary
D
Returns a System.Security.Permissions.SecurityPermission object that is the intersection of the current instance and the specified object.
E
Parameters
G
F
H
Parameter
Description
target
A System.Security.Permissions.SecurityPermission object that is of the same type as the current instance to be intersected with the current instance.
I J K L M
Return Value
N
A new System.Security.Permissions.SecurityPermission instance that represents the intersection of the current instance and target. If the intersection is empty, or target is null, returns null. If the current instance is unrestricted, returns a copy of target. If target is unrestricted, returns a copy of the current instance.
O P Q
Description
R
[Note: The intersection of two permissions is a permission that secures the resources and operations secured by both permissions. Specifically, it represents the minimum permission such that any demand that passes both permissions will also pass their intersection. This method overrides System.Security.CodeAccessPermission.Intersect and is implemented to support the System.Security.IPermission interface.]
S T U V W
Exceptions
X
Exception
Condition
Y
target is not null and is not of type System.Security.Permissions.SecurityPermission.
Z
System.ArgumentException
2621
Contents | Index
SecurityPermission
System.Security.Permissions
IsSubsetOf() Method
Example using System; using System.Security; using System.Security.Permissions;
A B
namespace Samples { public class SecurityPermissionIntersect { public static void Main() { SecurityPermission sp1 = new SecurityPermission( SecurityPermissionFlag.Assertion); SecurityPermission sp2 = new SecurityPermission( SecurityPermissionFlag.AllFlags); IPermission ip = sp1.Intersect(sp2); Console.WriteLine(ip); } } }
C D E F G H I J K L M
The output is:
N
O P Q R
SecurityPermission.IsSubsetOf(System.Security.IPermission) Method
S [ILASM]
T
.method public hidebysig virtual bool IsSubsetOf(class System.Security.IPermission target)
U
[C#]
V
public override bool IsSubsetOf(IPermission target)
W
Summary
X
Determines whether the current instance is a subset of the specified object.
Y Z
2622
Contents | Index
System.Security.Permissions
SecurityPermission IsSubsetOf() Method
Parameters Parameter
Description
target
A System.Security.Permissions.SecurityPermission object of the same type as the current instance that is to be tested for the subset relationship with the current instance.
A B C D
Return Value
E
true if the current instance is a subset of target; otherwise, false. If the current instance is unrestricted, and target is not, returns false. If target is unrestricted, returns true. If target is null and the current instance was initialized with System.Security.Permissions.SecurityPermissionFlag.NoFlags, returns true. If target is null and the current instance was initialized with any value other than NoFlags, returns false.
F G H I J
Description
K
[Note: The current instance is a subset of target if the current instance specifies a set of accesses to resources that is wholly contained by target. For example, a permission that represents read access to a file is a subset of a permission that represents read and write access to the file. This method overrides System.Security.CodeAccessPermission.IsSubsetOf and is implemented to support the System.Security.IPermission interface.]
L M N O
Exceptions
P
Exception
Condition
System.ArgumentException
target is not null and is not of type System.Security.Permissions.SecurityPermission.
Q R S T U
Example
V
using System; using System.Security; using System.Security.Permissions;
W X
namespace Samples { public class SecurityPermissionIsSubsetOf { public static void Main() {
Y Z
2623
Contents | Index
SecurityPermission
System.Security.Permissions
IsUnrestricted() Method
SecurityPermission sp1 = new SecurityPermission( SecurityPermissionFlag.Assertion); SecurityPermission sp2 = new SecurityPermission( SecurityPermissionFlag.AllFlags); Console.WriteLine( "sp1.IsSubsetOf(sp2): {0}", sp1.IsSubsetOf(sp2)); Console.WriteLine( "sp1.IsSubsetOf(sp1): {0}", sp1.IsSubsetOf(sp1)); Console.WriteLine( "sp2.IsSubsetOf(sp1): {0}", sp2.IsSubsetOf(sp1));
A B C D E F G H
} }
I
}
J
The output is:
K sp1.IsSubsetOf(sp2): True sp1.IsSubsetOf(sp1): True sp2.IsSubsetOf(sp1): False
L M N O
SecurityPermission.IsUnrestricted() Method
P
[ILASM]
.method public final hidebysig virtual bool IsUnrestricted()
Q
[C#]
R
public bool IsUnrestricted()
S
Summary
T
Returns a value indicating whether the current permission is unrestricted.
U V
Return Value
W
true if the current permission is unrestricted; otherwise, false.
X
Description
Y
An unrestricted permission represents access to any and all resources protected by the permission.
Z
2624
Contents | Index
System.Security.Permissions
SecurityPermission ToXml() Method
SecurityPermission.ToXml() Method [ILASM]
.method public hidebysig virtual class System.Security.SecurityElement ToXml() [C#]
A
public override SecurityElement ToXml()
B
Summary
C
Returns the XML encoding of the current instance.
D E
Return Value
F
A System.Security.SecurityElement containing an XML encoding of the state of the current instance.
G H
Description
I
[Note: For the XML encoding for this class, see the System.Security.Permissions.SecurityPermission class page. This method overrides System.Security.CodeAccessPermission.ToXml.]
J K L
Example
M
using System; using System.Security; using System.Security.Permissions;
N O
namespace Samples { public class SecurityPermissionToXml { public static void Main() { SecurityPermission sp = new SecurityPermission( SecurityPermissionFlag.Assertion); SecurityElement se = sp.ToXml(); Console.WriteLine(se); } } }
P Q R S T U V W X
The output is:
Y
Z
2625
Contents | Index
SecurityPermission
System.Security.Permissions
Union() Method
SecurityPermission.Union(System.Security.IPermission) Method [ILASM]
A
.method public hidebysig virtual class System.Security.IPermission Union(class System.Security.IPermission target)
B
[C#]
public override IPermission Union(IPermission target)
C D
Summary
E
Returns a System.Security.Permissions.SecurityPermission object that is the union of the current instance and the specified object.
F
Parameters
G H
Parameter
Description
target
A System.Security.Permissions.SecurityPermission object of the same type as the current instance to be combined with the current instance.
I J K L
Return Value
M
A new System.Security.Permissions.SecurityPermission instance that represents the union of the current instance and target. If the current instance or target is unrestricted, returns a System.Security.Permissions.SecurityPermission instance that is unrestricted. If target is null, returns a copy of the current instance using the System.Security.IPermission.Copy method.
N O P Q
Description
R
[Note: The result of a call to System.Security.Permissions.SecurityPermission.Union is a permission that represents all of the access to security permissions represented by the current instance as well as the security permissions represented by target. Any demand that passes either the current instance or target passes their union. This method overrides System.Security.CodeAccessPermission.Union and is implemented to support the System.Security.IPermission interface.]
S T U V W
Exceptions
X Y
Exception
Condition
System.ArgumentException
target is not null and is not of type System.Security.Permissions.SecurityPermission.
Z
2626
Contents | Index
System.Security.Permissions
SecurityPermission Union() Method
Example using System; using System.Security; using System.Security.Permissions;
A B
namespace Samples { public class SecurityPermissionUnion { public static void Main() { SecurityPermission sp1 = new SecurityPermission( SecurityPermissionFlag.Assertion); SecurityPermission sp2 = new SecurityPermission( SecurityPermissionFlag.ControlEvidence); IPermission ip = sp1.Union(sp2); Console.WriteLine(ip); } } }
C D E F G H I J K L M
The output is:
N
O P Q R S T U V W X Y Z
2627
Contents | Index
System.Security.Permissions SecurityPermissionAttribute
BCL
Object
A
Attribute SecurityAttribute
B
CodeAccessSecurityAttribute
C
SecurityPermissionAttribute
D E
Summary
F
Used to apply a security action and a set of security permissions to program code.
G
Type Summary
H
CF public sealed class SecurityPermissionAttribute : CodeAccessSecurityAttribute { // Constructors CF public SecurityPermissionAttribute(SecurityAction action);
I J K L
MS MS MS MS MS MS MS MS
M N O P Q
MS MS MS MS MS
R S T
// CF CF CF CF CF CF CF CF CF CF CF CF CF CF
Properties public bool Assertion { set; get; } public bool ControlAppDomain { set; get; } public bool ControlDomainPolicy { set; get; } public bool ControlEvidence { set; get; } public bool ControlPolicy { set; get; } public bool ControlPrincipal { set; get; } public bool ControlThread { set; get; } public bool Execution { set; get; } public SecurityPermissionFlag Flags { set; get; } public bool Infrastructure { set; get; } public bool RemotingConfiguration { set; get; } public bool SerializationFormatter { set; get; } public bool SkipVerification { set; get; } public bool UnmanagedCode { set; get; }
U // Methods CF public override IPermission CreatePermission();
V }
W X
Description
Y
[Note: The security permissions are defined in the System.Security.Permissions.SecurityPermissionFlag enumeration and are specified using the System.Security.Permissions.SecurityPermissionAttribute.Flags property. The security information declared by a security attribute is stored in the metadata of
Z
2628
Contents | Index
System.Security.Permissions
SecurityPermissionAttribute SecurityPermissionAttribute Class
the attribute target, and is accessed by the system at runtime. Security attributes are used for declarative security only. For imperative security, use the corresponding permission class, System.Security.Permissions.SecurityPermission. The allowable System.Security.Permissions.SecurityPermissionAttribute targets are determined by the System.Security.Permissions.SecurityAction passed to the constructor.]
A B C
Example
D
using System; using System.Security; using System.Security.Permissions;
E F G
namespace Samples { public class SecurityPermissionAttributeSample { public static void Main() { try { SecurityPermission sp = new SecurityPermission( SecurityPermissionFlag.Assertion); DoAssert(); sp.Deny(); DoAssert(); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } [SecurityPermissionAttribute( SecurityAction.Demand, Assertion=true)] public static void DoAssert() { Console.WriteLine("In method: DoAssert()"); EnvironmentPermission p = new EnvironmentPermission( EnvironmentPermissionAccess.Read, "USERNAME"); p.Assert(); Console.WriteLine("Assert succeeded"); } } }
H I J K L M N O P Q R S T U V W X Y Z
2629
Contents | Index
SecurityPermissionAttribute
System.Security.Permissions
SecurityPermissionAttribute() Constructor
The output is: In method: DoAssert() Assert succeeded Exception: System.Security.SecurityException: Request failed. at System.Security.SecurityRuntime.FrameDescSetHelper(FrameSecurityDescriptor secDesc, PermissionSet demandSet, PermissionSet& alteredDemandSet) at Samples.SecurityPermissionAttributeSample.DoAssert() in C:\Books\BCL\ Samples\System.Security\Permissions\SecurityPermissionAttribute\SecurityPermission Attribute.cs:line 29 at Samples.SecurityPermissionAttributeSample.Main() in C:\Books\BCL\Samples\ System.Security\Permissions\SecurityPermissionAttribute\SecurityPermissionAttribut e.cs:line 18
A B C D E F G H
SecurityPermissionAttribute(System.Security.Permissions.SecurityAction) Constructor
I J
[ILASM]
K
public rtspecialname specialname instance void .ctor(valuetype System.Security.Permissions.SecurityAction action)
L
[C#]
public SecurityPermissionAttribute(SecurityAction action)
M N
Summary
O
Constructs and initializes a new instance of the System.Security.Permissions.SecurityPermissionAttribute class with the specified System.Security.Permissions.SecurityAction value.
P Q R
Parameters
S T
Parameter
Description
U
action
A System.Security.Permissions.SecurityAction value.
V W
Exceptions
X Y
Exception
Condition
System.ArgumentException
action is not a valid System.Security.Permissions.SecurityAction value.
Z
2630
Contents | Index
System.Security.Permissions
SecurityPermissionAttribute ControlDomainPolicy Property
SecurityPermissionAttribute.Assertion Property [ILASM]
.property bool Assertion { public hidebysig specialname instance bool get_Assertion() public hidebysig specialname instance void set_Assertion(bool value) }
A B
[C#]
C
public bool Assertion { get; set; }
D
Summary
E
Gets or sets a value indicating whether permission to assert that all this code’s callers have the requisite permission for the operation is declared.
F G
Property Value
H
true if permission to assert is declared; otherwise, false.
I J
SecurityPermissionAttribute.ControlAppDomain Property
K
[ILASM]
L
.property bool ControlAppDomain { public hidebysig specialname instance bool get_ControlAppDomain() public hidebysig specialname instance void set_ControlAppDomain(bool value) }
M N
[C#]
O
public bool ControlAppDomain { get; set; }
P
Summary
Q
Gets or sets a value indicating whether permission to manipulate System.AppDomain is declared.
R S
Property Value
T
true if permission to manipulate System.AppDomain is declared; otherwise, false.
U V
SecurityPermissionAttribute.ControlDomainPolicy Property
W
[ILASM]
X
.property bool ControlDomainPolicy { public hidebysig specialname instance bool get_ControlDomainPolicy() public hidebysig specialname instance void set_ControlDomainPolicy(bool value) }
Y Z
[C#]
public bool ControlDomainPolicy { get; set; }
2631
Contents | Index
SecurityPermissionAttribute
System.Security.Permissions
ControlEvidence Property
Summary Gets or sets a value indicating whether permission to alter or manipulate domain security policy is declared. A B
Property Value
C
true if permission to alter or manipulate security policy in an application domain is declared; otherwise, false.
D E F
SecurityPermissionAttribute.ControlEvidence Property
G
[ILASM]
H
.property bool ControlEvidence { public hidebysig specialname instance bool get_ControlEvidence() public hidebysig specialname instance void set_ControlEvidence(bool value) }
I
[C#]
J
public bool ControlEvidence { get; set; }
K
Summary
L
Gets or sets a value indicating whether permission to alter or manipulate evidence is declared.
M N
Property Value
O
true if the ability to alter or manipulate evidence is declared; otherwise, false.
P Q R
SecurityPermissionAttribute.ControlPolicy Property
S
[ILASM]
.property bool ControlPolicy { public hidebysig specialname instance bool get_ControlPolicy() public hidebysig specialname instance void set_ControlPolicy(bool value) }
T U
[C#]
V
public bool ControlPolicy { get; set; }
W
Summary
X
Gets or sets a value indicating whether permission to view and manipulate security policy is declared.
Y Z
Property Value true if permission to manipulate security policy is declared; otherwise, false. 2632
Contents | Index
System.Security.Permissions
SecurityPermissionAttribute Execution Property
SecurityPermissionAttribute.ControlPrincipal Property [ILASM]
.property bool ControlPrincipal { public hidebysig specialname instance bool get_ControlPrincipal() public hidebysig specialname instance void set_ControlPrincipal(bool value) }
A B
[C#]
C
public bool ControlPrincipal { get; set; }
D
Summary
E
Gets or sets a value indicating whether permission to manipulate the current principal is declared.
F G
Property Value
H
true if permission to manipulate the current principal is declared; otherwise, false.
I J
SecurityPermissionAttribute.ControlThread Property
K
[ILASM]
L
.property bool ControlThread { public hidebysig specialname instance bool get_ControlThread() public hidebysig specialname instance void set_ControlThread(bool value) }
M N
[C#]
public bool ControlThread { get; set; }
O P
Summary
Q
Gets or sets a value indicating whether permission to manipulate threads is declared.
R
Property Value
S
true if permission to manipulate threads is declared; otherwise, false.
T
Description
U
For more information, see System.Threading.Thread.
V W X
SecurityPermissionAttribute.Execution Property
Y
[ILASM]
.property bool Execution { public hidebysig specialname instance bool get_Execution() public hidebysig specialname instance void set_Execution(bool value) }
Z
[C#]
public bool Execution { get; set; }
2633
Contents | Index
SecurityPermissionAttribute
System.Security.Permissions
Flags Property
Summary Gets or sets a value indicating whether permission to execute code is declared. A
Property Value
B
true if permission to execute code is declared; otherwise, false.
C D
SecurityPermissionAttribute.Flags Property
E [ILASM]
F
.property valuetype System.Security.Permissions.SecurityPermissionFlag Flags { public hidebysig specialname instance valuetype System.Security.Permissions.SecurityPermissionFlag get_Flags() public hidebysig specialname instance void set_Flags(valuetype System.Security.Permissions.SecurityPermissionFlag value) }
G H I
[C#]
public SecurityPermissionFlag Flags { get; set; }
J K
Summary
L
Gets or sets values that define the permissions declared by the current instance.
M N
Property Value
O
One or more System.Security.Permissions.SecurityPermissionFlag values. To specify multiple values in a set operation, use the bitwise OR operator.
P Q
SecurityPermissionAttribute.Infrastructure Property
R
[ILASM]
S
.property bool Infrastructure { public hidebysig specialname instance bool get_Infrastructure() public hidebysig specialname instance void set_Infrastructure(bool value) }
T U
[C#]
public bool Infrastructure { get; set; }
V W
Summary
X
Gets or sets a value indicating whether code can plug into the common language runtime infrastructure, such as adding Remoting Context Sinks, Envoy Sinks, and Dynamic Sinks.
Y Z
Property Value true if code can plug into the common language runtime infrastructure; otherwise, false. 2634
Contents | Index
System.Security.Permissions
SecurityPermissionAttribute SkipVerification Property
SecurityPermissionAttribute.RemotingConfiguration Property [ILASM]
.property bool RemotingConfiguration { public hidebysig specialname instance bool get_RemotingConfiguration() public hidebysig specialname instance void set_RemotingConfiguration(bool value) }
A B
[C#]
C
public bool RemotingConfiguration { get; set; }
D
Summary
E
Gets or sets a value indicating whether code can configure remoting types and channels.
F
Property Value
G
true if code can configure remoting types and channels; otherwise, false.
H I J
SecurityPermissionAttribute.SerializationFormatter Property
K
[ILASM]
.property bool SerializationFormatter { public hidebysig specialname instance bool get_SerializationFormatter() public hidebysig specialname instance void set_SerializationFormatter(bool value) }
L M
[C#]
N
public bool SerializationFormatter { get; set; }
O
Summary
P
Gets or sets a value indicating whether code can use a serialization formatter to serialize or deserialize an object.
Q
Property Value
S
true if code can use a serialization formatter to serialize or deserialize an object; otherwise, false.
T
R
U V
SecurityPermissionAttribute.SkipVerification Property
W
[ILASM]
X
.property bool SkipVerification { public hidebysig specialname instance bool get_SkipVerification() public hidebysig specialname instance void set_SkipVerification(bool value) }
Y Z
[C#]
public bool SkipVerification { get; set; }
2635
Contents | Index
SecurityPermissionAttribute
System.Security.Permissions
UnmanagedCode Property
Summary Gets or sets a value indicating whether permission to bypass code verification is declared. A
Property Value
B
true if permission to bypass code verification is declared; otherwise, false.
C
Description
D
This is a powerful permission that should be granted only to highly trusted code.
E F G
SecurityPermissionAttribute.UnmanagedCode Property
H
[ILASM]
I
.property bool UnmanagedCode { public hidebysig specialname instance bool get_UnmanagedCode() public hidebysig specialname instance void set_UnmanagedCode(bool value) }
J
[C#]
public bool UnmanagedCode { get; set; }
K L
Summary
M
Gets or sets a value indicating whether permission to call unmanaged code is declared.
N
Property Value
O
true if permission to call unmanaged code is declared; otherwise, false.
P Q R
SecurityPermissionAttribute.CreatePermission() Method
S
[ILASM]
T
.method public hidebysig virtual class System.Security.IPermission CreatePermission()
U
[C#]
public override IPermission CreatePermission()
V W
Summary
X
Returns a new System.Security.Permissions.SecurityPermission object that contains the security information of the current instance.
Y Z
2636
Contents | Index
System.Security.Permissions
SecurityPermissionAttribute CreatePermission() Method
Description [Note: Applications typically do not call this method; it is intended for use by the system. The security information declared by a security attribute is stored in the metadata of the attribute target, and is accessed by the system at runtime. The system uses the object returned by this method to convert the security information of the current instance into the form stored in metadata. This method overrides System.Security.Permissions.SecurityAttribute.CreatePermission.]
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
2637
Contents | Index
System.Security.Permissions SecurityPermissionFlag Enum
BCL
Object
A
IComparable
ValueType
B
Enum
IFormattable SecurityPermissionFlag
C
IConvertible
NotStandardized
D
Summary
E
Specifies a set of security permissions applied to a System.Security.Permissions.SecurityPermission instance.
F G
Type Summary
H
CF public enum SecurityPermissionFlag { MS CF AllFlags = Assertion | UnmanagedCode | SkipVerification | Execution | ControlThread | ControlEvidence | ControlPolicy | SerializationFormatter | ControlDomainPolicy | ControlPrincipal | ControlAppDomain | RemotingConfiguration | Infrastructure | BindingRedirects, CF Assertion = 0x1, MS CF BindingRedirects = 0x2000, MS CF ControlAppDomain = 0x400, MS CF ControlDomainPolicy = 0x100, MS CF ControlEvidence = 0x20, MS CF ControlPolicy = 0x40, MS CF ControlPrincipal = 0x200, CF ControlThread = 0x10, CF Execution = 0x8, MS CF Infrastructure = 0x1000, CF NoFlags = 0x0, MS CF RemotingConfiguration = 0x800, MS CF SerializationFormatter = 0x80, CF SkipVerification = 0x4, CF UnmanagedCode= 0x2, }
I J K L M N O P Q R S T U V W
Description
X
This enumeration is used by System.Security.Permissions.SecurityPermission. System.Security.Permissions.SecurityPermissionFlag is a bit-field; specify multiple values using the bitwise OR operator. For information on security, see Partition II of the CLI Specification. [Note: Many of these flags are powerful and should only be granted to highly trusted code.]
Y Z
2638
Contents | Index
System.Security.Permissions
SecurityPermissionFlag Enum AllFlags Field
Example using System.Security; using System.Security.Permissions;
A
namespace Samples { public class SecurityPermissionFlagSample { public static void Main() { SecurityPermission sp1 = new SecurityPermission( SecurityPermissionFlag.Assertion); SecurityPermission sp2 = new SecurityPermission( SecurityPermissionFlag.ControlEvidence); SecurityPermission sp3 = new SecurityPermission( SecurityPermissionFlag.Execution); SecurityPermission sp4 = new SecurityPermission( SecurityPermissionFlag.SkipVerification); IPermission ip = sp1.Union(sp2); ip = ip.Union(sp3); ip = ip.Union(sp4); Console.WriteLine(ip); } } }
B C D E F G H I J K L M N O P
The output is:
Q
R S T U
SecurityPermissionFlag.AllFlags Field
V
[ILASM]
W
.field public static literal valuetype System.Security.Permissions.SecurityPermissionFlag AllFlags
X
[C#]
Y
AllFlags = Assertion | UnmanagedCode | SkipVerification | Execution | ControlThread | ControlEvidence | ControlPolicy | SerializationFormatter | ControlDomainPolicy | ControlPrincipal | ControlAppDomain | RemotingConfiguration | Infrastructure | BindingRedirects
Z
2639
Contents | Index
SecurityPermissionFlag Enum
System.Security.Permissions
Assertion Field
Summary The unrestricted state of the permission. A B
SecurityPermissionFlag.Assertion Field
C
[ILASM]
D
.field public static literal valuetype System.Security.Permissions.SecurityPermissionFlag Assertion [C#]
E
Assertion = 0x1
F
Summary
G
Specifies the ability to assert that all of the callers of the code granted this permission will pass the check for a specific permission or permission set. The ability to assert a specific permission or permission set allows code to ensure that its callers do not fail with a security exception for lack of the specific permission or permission set asserted. [Note: Asserting a permission is often used when writing library code that accesses protected resources but itself does not expose these resources in any exploitable way to the calling code.]
H I J K L M N
SecurityPermissionFlag.BindingRedirects Field
O
[ILASM]
P
.field public static literal valuetype System.Security.Permissions.SecurityPermissionFlag BindingRedirects
Q
[C#]
R
BindingRedirects = 0x2000
S
Summary
T
Permission to perform explicit binding redirection in the application configuration file. This includes redirection of .NET Framework assemblies that have been unified as well as other assemblies found outside the .NET Framework.
U V W X
SecurityPermissionFlag.ControlAppDomain Field
Y
[ILASM]
.field public static literal valuetype System.Security.Permissions.SecurityPermissionFlag ControlAppDomain
Z
[C#]
ControlAppDomain = 0x400
2640
Contents | Index
System.Security.Permissions
SecurityPermissionFlag Enum ControlPolicy Field
Summary Ability to create and manipulate a System.AppDomain. A
SecurityPermissionFlag.ControlDomainPolicy Field
B
[ILASM]
C
.field public static literal valuetype System.Security.Permissions.SecurityPermissionFlag ControlDomainPolicy
D
[C#]
E
ControlDomainPolicy = 0x100
F
Summary
G
Ability to specify domain policy.
H I J
SecurityPermissionFlag.ControlEvidence Field
K
[ILASM]
.field public static literal valuetype System.Security.Permissions.SecurityPermissionFlag ControlEvidence
L M
[C#]
ControlEvidence = 0x20
N O
Summary
P
Ability to provide evidence, including the ability to alter the evidence provided by the common language runtime. This is a powerful permission that should only be granted to highly trusted code.
Q R S
SecurityPermissionFlag.ControlPolicy Field
T
[ILASM]
U
.field public static literal valuetype System.Security.Permissions.SecurityPermissionFlag ControlPolicy
V
[C#]
W
ControlPolicy = 0x40
X
Summary
Y
Ability to view and modify policy. This is a powerful permission that should only be granted to highly trusted code.
Z
2641
Contents | Index
SecurityPermissionFlag Enum
System.Security.Permissions
ControlPrincipal Field
SecurityPermissionFlag.ControlPrincipal Field [ILASM]
A
.field public static literal valuetype System.Security.Permissions.SecurityPermissionFlag ControlPrincipal
B
[C#]
ControlPrincipal = 0x200
C D
Summary
E
Ability to manipulate the principal object.
F G
SecurityPermissionFlag.ControlThread Field
H
[ILASM]
I
.field public static literal valuetype System.Security.Permissions.SecurityPermissionFlag ControlThread
J
[C#]
ControlThread = 0x10
K L
Summary
M
Specifies the ability to control thread behavior. The operations protected include System.Threading.Thread.Abort and System.Threading.Thread.ResetAbort.
N O P Q
SecurityPermissionFlag.Execution Field
R
[ILASM]
S
.field public static literal valuetype System.Security.Permissions.SecurityPermissionFlag Execution
T
[C#]
Execution = 0x8
U V
Summary
W
Specifies permission for the code to run. Without this permission managed code cannot execute.
X Y Z
2642
Contents | Index
System.Security.Permissions
SecurityPermissionFlag Enum SerializationFormatter Field
SecurityPermissionFlag.Infrastructure Field [ILASM]
.field public static literal valuetype System.Security.Permissions.SecurityPermissionFlag Infrastructure
A
[C#]
B
Infrastructure = 0x1000
C
Summary
D
Permission to plug code into the common language runtime infrastructure, such as adding Remoting Context Sinks, Envoy Sinks, and Dynamic Sinks.
E F G
SecurityPermissionFlag.NoFlags Field
H
[ILASM]
I
.field public static literal valuetype System.Security.Permissions.SecurityPermissionFlag NoFlags
J
[C#]
K
NoFlags = 0x0
L
Summary
M
Specifies that none of the permissions in this enumeration is available.
N O
SecurityPermissionFlag.RemotingConfiguration Field
P
[ILASM]
Q
.field public static literal valuetype System.Security.Permissions.SecurityPermissionFlag RemotingConfiguration
R
[C#]
S
RemotingConfiguration = 0x800
T
Summary
U
Permission to configure Remoting types and channels.
V W
SecurityPermissionFlag.SerializationFormatter Field
X
[ILASM]
Y
.field public static literal valuetype System.Security.Permissions.SecurityPermissionFlag SerializationFormatter
Z
[C#]
SerializationFormatter = 0x80
2643
Contents | Index
SecurityPermissionFlag Enum
System.Security.Permissions
SkipVerification Field
Summary Ability to provide serialization services. Used by serialization formatters. A B
SecurityPermissionFlag.SkipVerification Field
C
[ILASM]
D
.field public static literal valuetype System.Security.Permissions.SecurityPermissionFlag SkipVerification
E
[C#]
SkipVerification = 0x4
F G
Summary
H
Specifies the right to skip the verification checks that ensure type safety and metadata correctness in an assembly. If an assembly has been granted this permission it will not fail with a System.Security.VerificationException even if the assembly contains unverifiable constructs. [Note: Code that is unverifiable can execute without causing a System.Security.VerificationException if this permission is granted.]
I J K L M N
SecurityPermissionFlag.UnmanagedCode Field
O
[ILASM]
P
.field public static literal valuetype System.Security.Permissions.SecurityPermissionFlag UnmanagedCode [C#]
Q
UnmanagedCode = 0x2
R
Summary
S
Specifies the ability to call unmanaged code. [Note: Because unmanaged code potentially allows other permissions to be bypassed, this permission should be used with caution. It is used for applications calling native code using PInvoke.]
T U V W X Y Z
2644
Contents | Index
System.IO SeekOrigin Enum
BCL
Object
A
IComparable
ValueType Enum
B
IFormattable SeekOrigin
IConvertible
NotStandardized
C D
Summary
E
Defines the seek reference positions.
F G
Type Summary public enum SeekOrigin Begin = 0, Current = 1, End = 2, }
{
H I J K
Description
L
The System.IO.SeekOrigin enumeration is used by the overrides of the System.IO.Stream.Seek method to set the seek reference point in a stream, which allows you to specify an offset from the reference point.
M N O
Example
P
using System; using System.IO; using System.Text;
Q R S
namespace Samples { public class SeekOriginSample { public static void Main() { string s = "filestream.txt"; FileStream fs = new FileStream(s, FileMode.OpenOrCreate, FileAccess.Write); fs.Seek(0, SeekOrigin.Begin); Console.WriteLine("Position: {0}", fs.Position); fs.Seek(1, SeekOrigin.Current); Console.WriteLine("Position: {0}",
T U V W X Y Z
2645
Contents | Index
SeekOrigin Enum
System.IO
Begin Field
fs.Position); fs.Seek(0, SeekOrigin.End); Console.WriteLine("Position: {0}", fs.Position); fs.Seek(-1, SeekOrigin.End); Console.WriteLine("Position: {0}", fs.Position); fs.Close();
A B C }
D
} }
E F
The output is:
G Position: Position: Position: Position:
H I
0 1 35 34
J K
SeekOrigin.Begin Field
L
[ILASM]
M
.field public static literal valuetype System.IO.SeekOrigin Begin [C#]
N
Begin = 0
O P
Summary
Q
Indicates that the seek reference point is the beginning of a stream.
R S
SeekOrigin.Current Field
T
[ILASM]
.field public static literal valuetype System.IO.SeekOrigin Current
U
[C#]
V
Current = 1
W
Summary
X
Indicates that the seek reference point is the current position within a stream.
Y Z
2646
Contents | Index
System.IO
SeekOrigin Enum End Field
SeekOrigin.End Field [ILASM]
.field public static literal valuetype System.IO.SeekOrigin End [C#]
A
End = 2
B C
Summary
D
Indicates that the seek reference point is the first byte beyond the end of a stream.
E F G H I J K L M N O P Q R S T U V W X Y Z
2647
Contents | Index
System Single Structure
Extended Numerics
Object
A
IComparable
ValueType
B
Single
ExtendedNumerics
C
IFormattable IConvertible
NotStandardized
D
Summary
E
Represents a 32-bit single-precision floating-point number.
F
Type Summary
G
public struct Single : IComparable, IFormattable, IConvertible { // Fields public const float Epsilon = (float)1.4e-45; public const float MaxValue = (float)3.40282346638528859e+38; public const float MinValue = (float)-3.40282346638528859e+38; public const float NaN = (float)0.0 / (float)0.0; public const float NegativeInfinity = (float)-1.0 / (float)0.0; public const float PositiveInfinity = (float)1.0 / (float)0.0;
H I J K L M N
// Methods public int CompareTo (object value); public override bool Equals (object obj); public override int GetHashCode (); MS public TypeCode GetTypeCode (); public static bool IsInfinity (float f); public static bool IsNaN (float f); public static bool IsNegativeInfinity (float f); public static bool IsPositiveInfinity (float f); public static float Parse (string s); public static float Parse (string s, NumberStyles style); public static float Parse (string s, NumberStyles style, IFormatProvider provider); public static float Parse (string s, IFormatProvider provider); public override string ToString (); public string ToString (string format); public string ToString (string format, IFormatProvider provider); public string ToString (IFormatProvider provider);
O P Q R S T U V W X Y Z
// Explicit Interface Members MS bool IConvertible.ToBoolean(IFormatProvider provider); MS byte IConvertible.ToByte(IFormatProvider provider);
2648
Contents | Index
System
Single Structure Single Structure
MS MS MS MS MS MS MS MS MS MS MS MS MS
char IConvertible.ToChar(IFormatProvider provider); DateTime IConvertible.ToDateTime(IFormatProvider provider); decimal IConvertible.ToDecimal(IFormatProvider provider); double IConvertible.ToDouble(IFormatProvider provider); short IConvertible.ToInt16(IFormatProvider provider); int IConvertible.ToInt32(IFormatProvider provider); long IConvertible.ToInt64(IFormatProvider provider); sbyte IConvertible.ToSByte(IFormatProvider provider); float IConvertible.ToSingle(IFormatProvider provider); object IConvertible.ToType(Type type,IFormatProvider provider); ushort IConvertible.ToUInt16(IFormatProvider provider); uint IConvertible.ToUInt32(IFormatProvider provider); ulong IConvertible.ToUInt64(IFormatProvider provider);
A B C D E F
}
G H
BG See my comments for Double.
I J
Description
K
System.Single is a 32-bit single precision floating-point type that represents values ranging from approximately 1.5E–45 to 3.4E+38 and from approximately –1.5E–45 to –3.4E+38 with a precision of 7 decimal digits. The System.Single type conforms to standard IEC 60559:1989, Binary Floating-Point Arithmetic for Microprocessor Systems. A System.Single can represent the following values:
L
• •
•
M N O P
The finite set of non-zero values of the form s * m * 2e, where s is 1 or –1, and 0 < m < 224 and –149 <= e <= 104. Positive infinity and negative infinity. Infinities are produced by operations that produce results with a magnitude greater than that which can be represented by a System.Single, such as dividing a non-zero number by zero. For example, using System.Single operands, 1.0 / 0.0 yields positive infinity, and –1.0 / 0.0 yields negative infinity. Operations include passing parameters and returning values. The Not-a-Number value (NaN). NaN values are produced by invalid floating-point operations, such as dividing zero by zero.
Q R S T U V W
When performing binary operations, if one of the operands is a floating-point type (System.Double or System.Single), then the other operand is required to be an integral type or a floating-point type and the operation is evaluated as follows: •
X Y Z
If one of the operands is of an integral type, then that operand is converted to the floating-point type of the other operand.
2649
Contents | Index
Single Structure
System
Single Structure
•
A
•
B C
Then, if either of the operands is of type System.Double, the other operand is converted to System.Double, and the operation is performed using at least the range and precision of the System.Double type. For numeric operations, the type of the result is System.Double. Otherwise, the operation is performed using at least the range and precision of the System.Single type and, for numeric operations, the type of the result is System.Single.
D
The floating-point operators, including the assignment operators, do not throw exceptions. Instead, in exceptional situations, the result of a floating-point operation is zero, infinity, or NaN, as described below:
E F G
•
H
•
I J
• •
K L M
If the result of a floating-point operation is too small for the destination format, the result of the operation is zero. If the magnitude of the result of a floating-point operation is too large for the destination format, the result of the operation is positive infinity or negative infinity. If a floating-point operation is invalid, the result of the operation is NaN. If one or both operands of a floating-point operation are NaN, the result of the operation is NaN.
Conforming implementations of the CLI are permitted to perform floating-point operations using a precision that is higher than that required by the System.Single type. For example, hardware architectures that support an “extended” or “long double” floating-point type with greater range and precision than the System.Single type could implicitly perform all floating-point operations using this higher precision type. Expressions evaluated using a higher precision may cause a finite result to be produced instead of an infinity.
N O P Q R
Example
S
using System;
T namespace Samples { public class SingleSample { public static void Main() { Single max = Single.MaxValue, epsilon = Single.Epsilon, nan = Single.NaN, negativeInfinity = Single.NegativeInfinity, positiveInfinity = Single.PositiveInfinity, min = Single.MinValue;
U V W X Y Z
2650
Contents | Index
System
Single Structure Epsilon Field
Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("Epsilon: {0}", epsilon); Console.WriteLine("Nan: {0}", nan); Console.WriteLine("NegativeInfinity: {0}", negativeInfinity); Console.WriteLine("PositiveInfinity: {0}", positiveInfinity); Console.WriteLine("MinValue: {0}", min); string s = Single.MaxValue.ToString("R"); Console.WriteLine("From String {0} yields {1}", s, Single.Parse(s)); string[] formats = {"C","E","e4","F","G","N","P","R"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\") yields {2}", epsilon, f, epsilon.ToString(f));
A B C D E F
}
G
}
H
}
I
The output is
J MaxValue: 1.79769313486232E+308 Epsilon: 4.94065645841247E-324 Nan: NaN NegativeInfinity: -Infinity PositiveInfinity: Infinity MinValue: -1.79769313486232E+308 From String 1.7976931348623157E+308 yields 1.79769313486232E+308 4.94065645841247E-324.ToString("C") yields $0.00 4.94065645841247E-324.ToString("E") yields 4.940656E-324 4.94065645841247E-324.ToString("e4") yields 4.9407e-324 4.94065645841247E-324.ToString("F") yields 0.00 4.94065645841247E-324.ToString("G") yields 4.94065645841247E-324 4.94065645841247E-324.ToString("N") yields 0.00 4.94065645841247E-324.ToString("P") yields 0.00 % 4.94065645841247E-324.ToString("R") yields 4.94065645841247E-324
K L M N O P Q R S T U
Single.Epsilon Field
V [ILASM]
W
.field public static literal float32 Epsilon [C#]
X
public const float Epsilon = (float)1.4e-45;
Y
Summary
Z
Represents the smallest positive System.Single value greater than zero.
2651
Contents | Index
Single Structure
System
MaxValue Field
Description The value of this constant is 1.401298E–45. A
Example
B
using System;
C
namespace Samples { public class SingleEpsilon { public static void Main() { Single max = Single.MaxValue, epsilon = Single.Epsilon, nan = Single.NaN, negativeInfinity = Single.NegativeInfinity, positiveInfinity = Single.PositiveInfinity, min = Single.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("Epsilon: {0}", epsilon); Console.WriteLine("Nan: {0}", nan); Console.WriteLine("NegativeInfinity: {0}", negativeInfinity); Console.WriteLine("PositiveInfinity: {0}", positiveInfinity); Console.WriteLine("MinValue: {0}", min); } } }
D E F G H I J K L M N O P
The output is
Q R
MaxValue: 3.402823E+38 Epsilon: 1.401298E-45 Nan: NaN NegativeInfinity: -Infinity PositiveInfinity: Infinity MinValue: -3.402823E+38
S T U V W
Single.MaxValue Field
X [ILASM]
Y
.field public static literal float32 MaxValue [C#]
Z
public const float MaxValue = (float)3.40282346638528859e+38
2652
Contents | Index
System
Single Structure MinValue Field
Summary Contains the maximum positive value for the System.Single type.
Description
A
The value of this constant is 3.40282346638528859E+38 converted to System.Single.
B C
Example
D
using System;
E namespace Samples { public class SingleMaxValue { public static void Main() { Single max = Single.MaxValue, epsilon = Single.Epsilon, nan = Single.NaN, negativeInfinity = Single.NegativeInfinity, positiveInfinity = Single.PositiveInfinity, min = Single.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("Epsilon: {0}", epsilon); Console.WriteLine("Nan: {0}", nan); Console.WriteLine("NegativeInfinity: {0}", negativeInfinity); Console.WriteLine("PositiveInfinity: {0}", positiveInfinity); Console.WriteLine("MinValue: {0}", min); } } }
F G H I J K L M N O P Q R
The output is
S MaxValue: 3.402823E+38 Epsilon: 1.401298E-45 Nan: NaN NegativeInfinity: -Infinity PositiveInfinity: Infinity MinValue: -3.402823E+38
T U V W X
Single.MinValue Field
Y
[ILASM]
Z
.field public static literal float32 MinValue [C#]
public const float MinValue = (float)-3.40282346638528859e+38
2653
Contents | Index
Single Structure
System
NaN Field
Summary Contains the minimum (most negative) value for the System.Single type. A
Description
B
The value of this constant is –3.40282346638528859E+38 converted to System.Single.
C
Example
D
using System;
E namespace Samples { public class SingleMinValue { public static void Main() { Single max = Single.MaxValue, epsilon = Single.Epsilon, nan = Single.NaN, negativeInfinity = Single.NegativeInfinity, positiveInfinity = Single.PositiveInfinity, min = Single.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("Epsilon: {0}", epsilon); Console.WriteLine("Nan: {0}", nan); Console.WriteLine("NegativeInfinity: {0}", negativeInfinity); Console.WriteLine("PositiveInfinity: {0}", positiveInfinity); Console.WriteLine("MinValue: {0}", min); } } }
F G H I J K L M N O P Q R
The output is
S MaxValue: 3.402823E+38 Epsilon: 1.401298E-45 Nan: NaN NegativeInfinity: -Infinity PositiveInfinity: Infinity MinValue: -3.402823E+38
T U V W X
Single.NaN Field
Y
[ILASM]
Z
.field public static literal float32 NaN [C#]
public const float NaN = (float)0.0 / (float)0.0
2654
Contents | Index
System
Single Structure NaN Field
Summary Represents an undefined result of operations involving System.Single.
Description
A
Not-a-Number (NaN) values are returned when the result of a System.Single operation is undefined. A NaN value is not equal to any other value, including another NaN value. The value of this field is obtained by dividing System.Single zero by zero. [Note: System.Single.NaN represents one of many possible NaN values. To test whether a System.Single value is a NaN, use the System.Single.IsNaN method.]
B C D E F G
Example
H
using System;
I
namespace Samples { public class SingleNaN { public static void Main() { Single max = Single.MaxValue, epsilon = Single.Epsilon, nan = Single.NaN, negativeInfinity = Single.NegativeInfinity, positiveInfinity = Single.PositiveInfinity, min = Single.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("Epsilon: {0}", epsilon); Console.WriteLine("Nan: {0}", nan); Console.WriteLine("NegativeInfinity: {0}", negativeInfinity); Console.WriteLine("PositiveInfinity: {0}", positiveInfinity); Console.WriteLine("MinValue: {0}", min); } } }
J K L M N O P Q R S T U V
The output is
W X
MaxValue: 3.402823E+38 Epsilon: 1.401298E-45 Nan: NaN NegativeInfinity: -Infinity PositiveInfinity: Infinity MinValue: -3.402823E+38
Y Z
2655
Contents | Index
Single Structure
System
NegativeInfinity Field
Single.NegativeInfinity Field [ILASM]
.field public static literal float32 NegativeInfinity
A
[C#]
public const float NegativeInfinity = (float)-1.0 / (float)0.0
B C
Summary
D
Represents a negative infinity of type System.Single.
E
Description
F
The value of this constant can be obtained by dividing a negative System.Single by zero. [Note: To test whether a System.Single value is a negative infinity value, use the System.Single.IsNegativeInfinity method.]
G H I
Example
J
using System;
K namespace Samples { public class SingleNegativeInfinity { public static void Main() { Single max = Single.MaxValue, epsilon = Single.Epsilon, nan = Single.NaN, negativeInfinity = Single.NegativeInfinity, positiveInfinity = Single.PositiveInfinity, min = Single.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("Epsilon: {0}", epsilon); Console.WriteLine("Nan: {0}", nan); Console.WriteLine("NegativeInfinity: {0}", negativeInfinity); Console.WriteLine("PositiveInfinity: {0}", positiveInfinity); Console.WriteLine("MinValue: {0}", min); } } }
L M N O P Q R S T U V W X Y
The output is
Z MaxValue: 3.402823E+38 Epsilon: 1.401298E-45 Nan: NaN
2656
Contents | Index
System
Single Structure PositiveInfinity Field
NegativeInfinity: -Infinity PositiveInfinity: Infinity MinValue: -3.402823E+38
A B
Single.PositiveInfinity Field
C
[ILASM]
D
.field public static literal float32 PositiveInfinity [C#]
E
public const float PositiveInfinity = (float)1.0 / (float)0.0
F
Summary
G
Represents a positive infinity of type System.Single.
H
Description
I
The value of this constant can be obtained by dividing a positive System.Single by zero. [Note: To test whether a System.Single value is a positive infinity value, use the System.Single.IsPositiveInfinity method.]
J K L
Example
M
using System;
N
namespace Samples { public class SinglePositiveInfinity { public static void Main() { Single max = Single.MaxValue, epsilon = Single.Epsilon, nan = Single.NaN, negativeInfinity = Single.NegativeInfinity, positiveInfinity = Single.PositiveInfinity, min = Single.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("Epsilon: {0}", epsilon); Console.WriteLine("Nan: {0}", nan); Console.WriteLine("NegativeInfinity: {0}", negativeInfinity); Console.WriteLine("PositiveInfinity: {0}", positiveInfinity); Console.WriteLine("MinValue: {0}", min); } } }
O P Q R S T U V W X Y Z
2657
Contents | Index
Single Structure
System
CompareTo() Method
The output is MaxValue: 3.402823E+38 Epsilon: 1.401298E-45 Nan: NaN NegativeInfinity: -Infinity PositiveInfinity: Infinity MinValue: -3.402823E+38
A B C D E
Single.CompareTo(System.Object) Method
F
[ILASM]
.method public final hidebysig virtual int32 CompareTo(object value)
G
[C#]
H
public int CompareTo(object value)
I
Summary
J
Returns the sort order of the current instance compared to the specified System.Object.
K
Parameters
L M
Parameter
Description
N
value
The System.Object to compare to the current instance.
O P
Return Value
Q
A System.Int32 containing a value that reflects the sort order of the current instance as compared to value. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number.
R S T U V W X
Return Value
Description
any negative number
Current instance < value. Current instance is a NaN and value is not a NaN and is not a null reference.
zero
Current instance == value. Current instance and value are both NaN, positive infinity, or negative infinity.
any positive number
Current instance > value. value is a null reference. Current instance is not a NaN and value is a NaN.
Y Z
2658
Contents | Index
System
Single Structure CompareTo() Method
Description [Note: This method is implemented to support the System.IComparable interface. Note that, although a NaN is not considered to be equal to another NaN (even itself), the System.IComparable interface requires that A.CompareTo(A) return zero.]
A B
Exceptions
C
Exception
Condition
System.ArgumentException
value is not a null reference and is not of type System.Single.
D E F G H
Example
I
using System;
J
namespace Samples { public class SingleCompareTo { private static string CompareSingles(Single d1, Single d2) { int i = d1.CompareTo(d2); if(0 == i) return String.Format("{0} is equal to {1}", d1, d2); if(i > 0) return String.Format("{0} is greater than {1}", d1, d2); else return String.Format("{0} is less than {1}", d1, d2); } public static void Main() { Single max = Single.MaxValue, min = Single.MinValue; Console.WriteLine(CompareSingles(min, min)); Console.WriteLine(CompareSingles(max, min)); Console.WriteLine(CompareSingles(min, max)); } } }
K L M N O P Q R S T U V W X Y
The output is
Z -3.402823E+38 is equal to -3.402823E+38 3.402823E+38 is greater than -3.402823E+38 -3.402823E+38 is less than 3.402823E+38
2659
Contents | Index
Single Structure
System
Equals() Method
Single.Equals(System.Object) Method [ILASM]
.method public hidebysig virtual bool Equals(object obj)
A
[C#]
public override bool Equals(object obj)
B C
Summary
D
Determines whether the current instance and the specified System.Object represent the same type and value.
E F
Parameters
G H
Parameter
Description
obj
The System.Object to compare to the current instance.
I J K
Return Value
L
true if obj represents the same type and value as the current instance; otherwise, false. If obj is a null reference or is not an instance of System.Single, returns false. If either obj or the current instance is a NaN and the other is not, returns false. If obj and the current instance are both NaN, positive infinity, or negative infinity, returns true.
M N O P
Description
Q
[Note: This method overrides System.Object.Equals.]
R
Example
S
using System;
T namespace Samples { public class SingleEquals { public static void Main() { Single max = Single.MaxValue, min = Single.MinValue; Console.WriteLine("Is {0} equal to {1}: {2}", max, max, max.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", max, min, max.Equals(min));
U V W X Y Z
2660
Contents | Index
System
Single Structure GetHashCode() Method
Console.WriteLine("Is {0} equal to {1}: {2}", min, max, min.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", min, min, min.Equals(min));
A
} }
B
}
C
The output is Is Is Is Is
D E
3.402823E+38 equal to 3.402823E+38: True 3.402823E+38 equal to -3.402823E+38: False -3.402823E+38 equal to 3.402823E+38: False -3.402823E+38 equal to -3.402823E+38: True
F G H
Single.GetHashCode() Method
I
[ILASM]
J
.method public hidebysig virtual int32 GetHashCode()
K
[C#]
L
public override int GetHashCode()
M
Summary
N
Generates a hash code for the current instance.
O
Return Value
P
A System.Int32 containing the hash code for this instance.
Q R
Description
S
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
T U
Example
V
using System;
W namespace Samples { public class SingleGetHashCode { public static void Main() { Single max = Single.MaxValue,
X Y Z
2661
Contents | Index
Single Structure
System
GetTypeCode() Method
zero = 0, min = Single.MinValue; Console.WriteLine("{0} has hashcode of: {1}", max, max.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", zero, zero.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", min, min.GetHashCode());
A B C }
D
} }
E F
The output is
G 3.402823E+38 has hashcode of: 2139095039 0 has hashcode of: 0 -3.402823E+38 has hashcode of: -8388609
H I J K
Single.GetTypeCode() Method
L
[ILASM]
.method public final hidebysig virtual valuetype System.TypeCode GetTypeCode()
M
[C#]
public TypeCode GetTypeCode()
N O
Summary
P
Returns the System.TypeCode for value type System.Single.
Q R
Single.IsInfinity(System.Single) Method
S
[ILASM]
T
.method public hidebysig static bool IsInfinity(float32 f) [C#]
U
public static bool IsInfinity(float f)
V W
Summary
X
Determines whether the specified System.Single represents an infinity, which can be either positive or negative.
Y Z
2662
Contents | Index
System
Single Structure IsInfinity() Method
Parameters Parameter
Description
f
The System.Single to be checked.
A B C
Return Value
D
true if f represents a positive or negative infinity value; otherwise, false.
E F
Description
G
[Note: Floating-point operations return positive or negative infinity values to signal an overflow condition.]
H I
Example
J
using System;
K namespace Samples { public class SingleIsInfinity { public static void Main() { Single nan = Single.NaN, negativeInfinity = Single.NegativeInfinity, positiveInfinity = Single.PositiveInfinity; Console.WriteLine("{0} IsInfinity: {1}", nan, Single.IsInfinity(nan)); Console.WriteLine("{0} IsInfinity: {1}", negativeInfinity, Single.IsInfinity(negativeInfinity)); Console.WriteLine("{0} IsInfinity: {1}", positiveInfinity, Single.IsInfinity(positiveInfinity)); Console.WriteLine("{0} IsNaN: {1}", nan, Single.IsNaN(nan)); Console.WriteLine("{0} IsNaN: {1}", positiveInfinity, Single.IsNaN(positiveInfinity)); } } }
L M N O P Q R S T U V W X Y Z
2663
Contents | Index
Single Structure
System
IsNaN() Method
The output is NaN IsInfinity: False -Infinity IsInfinity: True Infinity IsInfinity: True NaN IsNaN: True Infinity IsNaN: False
A B C D E
Single.IsNaN(System.Single) Method
F
[ILASM]
.method public hidebysig static bool IsNaN(float32 f)
G
[C#]
public static bool IsNaN(float f)
H I
Summary
J
Determines whether the value of the specified System.Single is undefined (Not-aNumber).
K L
Parameters
M N O
Parameter
Description
f
The System.Single to be checked.
P Q
Return Value
R
true if f represents a NaN value; otherwise, false.
S T
Description
U
[Note: Floating-point operations return NaN values to signal that the result of the operation is undefined. For example, dividing (Single) 0.0 by 0.0 results in a NaN value.]
V W
Example
X
using System;
Y
namespace Samples { public class SingleIsNan { public static void Main()
Z
2664
Contents | Index
System
Single Structure IsNegativeInfinity() Method
{ Single nan = Single.NaN, negativeInfinity = Single.NegativeInfinity, positiveInfinity = Single.PositiveInfinity; Console.WriteLine("{0} IsInfinity: {1}", nan, Single.IsInfinity(nan)); Console.WriteLine("{0} IsInfinity: {1}", negativeInfinity, Single.IsInfinity(negativeInfinity)); Console.WriteLine("{0} IsInfinity: {1}", positiveInfinity, Single.IsInfinity(positiveInfinity)); Console.WriteLine("{0} IsNaN: {1}", nan, Single.IsNaN(nan)); Console.WriteLine("{0} IsNaN: {1}", positiveInfinity, Single.IsNaN(positiveInfinity));
A B C D E F G
}
H
} }
I
The output is
J K
NaN IsInfinity: False -Infinity IsInfinity: True Infinity IsInfinity: True NaN IsNaN: True Infinity IsNaN: False
L M N O
Single.IsNegativeInfinity(System.Single) Method
P
[ILASM]
Q
.method public hidebysig static bool IsNegativeInfinity(float32 f)
R
[C#]
public static bool IsNegativeInfinity(float f)
S
Summary
T
Determines whether the specified System.Single represents a negative infinity value.
U V
Parameters
W
Parameter
Description
f
The System.Single to be checked.
X Y Z
2665
Contents | Index
Single Structure
System
IsNegativeInfinity() Method
Return Value true if f represents a negative infinity value; otherwise, false. A
Description
B
[Note: Floating-point operations return negative infinity values to signal an overflow condition.]
C D
Example
E
using System;
F namespace Samples { public class SingleIsNegativeInfinity { public static void Main() { Single nan = Single.NaN, negativeInfinity = Single.NegativeInfinity, positiveInfinity = Single.PositiveInfinity; Console.WriteLine("{0} IsInfinity: {1}", nan, Single.IsInfinity(nan)); Console.WriteLine("{0} IsInfinity: {1}", negativeInfinity, Single.IsInfinity(negativeInfinity)); Console.WriteLine("{0} IsInfinity: {1}", positiveInfinity, Single.IsInfinity(positiveInfinity)); Console.WriteLine("{0} IsNegativeInfinity: {1}", negativeInfinity, Single.IsNegativeInfinity(negativeInfinity)); Console.WriteLine("{0} IsNegativeInfinity: {1}", positiveInfinity, Single.IsNegativeInfinity(positiveInfinity)); } } }
G H I J K L M N O P Q R S T U
The output is
V NaN IsInfinity: False -Infinity IsInfinity: True Infinity IsInfinity: True -Infinity IsNegativeInfinity: True Infinity IsNegativeInfinity: False
W X Y Z
2666
Contents | Index
System
Single Structure IsPositiveInfinity() Method
Single.IsPositiveInfinity(System.Single) Method [ILASM]
.method public hidebysig static bool IsPositiveInfinity(float32 f) [C#]
A
public static bool IsPositiveInfinity(float f)
B C
Summary
D
Determines whether the specified System.Single represents a positive infinity value.
E
Parameters
F
Parameter
Description
f
The System.Single to be checked.
G H I J
Return Value
K
true if f represents a positive infinity value; otherwise, false.
L M
Description
N
[Note: Floating-point operations return positive infinity values to signal an overflow condition.]
O P
Example
Q
using System;
R namespace Samples { public class SingleIsPositiveInfinity { public static void Main() { Single nan = Single.NaN, negativeInfinity = Single.NegativeInfinity, positiveInfinity = Single.PositiveInfinity; Console.WriteLine("{0} IsInfinity: {1}", nan, Single.IsInfinity(nan)); Console.WriteLine("{0} IsInfinity: {1}", negativeInfinity, Single.IsInfinity(negativeInfinity)); Console.WriteLine("{0} IsInfinity: {1}", positiveInfinity, Single.IsInfinity(positiveInfinity)); Console.WriteLine("{0} IsPositiveInfinity: {1}",
S T U V W X Y Z
2667
Contents | Index
Single Structure
System
Parse() Method
negativeInfinity, Single.IsPositiveInfinity(negativeInfinity)); Console.WriteLine("{0} IsPositiveInfinity: {1}", positiveInfinity, Single.IsPositiveInfinity(positiveInfinity));
A }
B }
C
}
D
The output is
E NaN IsInfinity: False -Infinity IsInfinity: True Infinity IsInfinity: True -Infinity IsPositiveInfinity: False Infinity IsPositiveInfinity: True
F G H I J
Single.Parse(System.String) Method
K [ILASM]
L
.method public hidebysig static float32 Parse(string s) [C#]
M
public static float Parse(string s)
N
Summary
O
Returns the specified System.String converted to a System.Single value.
P Q
Parameters
R S
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Float and/or System.Globalization.NumberStyles.AllowThousands style.
T U V W
Return Value
X
The System.Single value obtained from s. If the parsed value is less than System.Single.MinValue, this method returns System.Single.NegativeInfinity. If the parsed value is greater than System.Single.MaxValue, this method returns System.Single.PositiveInfinity. If s equals System.Globalization.NumberFormatInfo.NaNSymbol, this method returns System.Single.NaN.
Y Z
2668
Contents | Index
System
Single Structure Parse() Method
Description This version of System.Single.Parse is equivalent to System.Single.Parse(s, System.Globalization.NumberStyles.Float| System.Globalization.NumberStyles.AllowThousands, null). The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.]
A B C D
Exceptions
E F
Exception
Condition
System.ArgumentNullException
s is a null reference.
H
System.FormatException
s is not in the correct style.
I
G
J
Example
K
using System;
L
namespace Samples { public class SingleParse { public static void Main() { string s; try { s = Single.MaxValue.ToString("R"); Console.WriteLine("From String {0} yields s, Single.Parse(s)); s = "0"; Console.WriteLine("From String {0} yields s, Single.Parse(s)); s = Single.MinValue.ToString("R"); Console.WriteLine("From String {0} yields s, Single.Parse(s)); s = String.Empty; Console.WriteLine("From String {0} yields s, Single.Parse(s)); } catch(FormatException e) {
M N O P Q R S
{1}",
T U
{1}",
V W
{1}",
X {1}",
Y Z
2669
Contents | Index
Single Structure
System
Parse() Method
Console.WriteLine("Exception: {0}", e); } try { s = Double.MaxValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Single.Parse(s)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E F
} }
G
}
H
The output is
I
From String 3.40282347E+38 yields 3.402823E+38 From String 0 yields 0 From String -3.40282347E+38 yields -3.402823E+38 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseSingle(String s, NumberStyles style, NumberFormatInfo info) at System.Single.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Single.Parse(String s) at Samples.SingleParse.Main() in C:\Books\BCL\Samples\System\Single\ Parse(System.String)\Single.cs:line 22 Exception: System.OverflowException: Value was either too large or too small for a Single. at System.Number.ParseSingle(String s, NumberStyles style, NumberFormatInfo info) at System.Single.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Single.Parse(String s) at Samples.SingleParse.Main() in C:\Books\BCL\Samples\System\Single\ Parse(System.String)\Single.cs:line 32
J K L M N O P Q R S T U
Single.Parse(System.String, System.Globalization.NumberStyles) Method
V [ILASM]
W
.method public hidebysig static float32 Parse(string s, valuetype System.Globalization.NumberStyles style)
X
[C#]
public static float Parse(string s, NumberStyles style)
Y Z
Summary Returns the specified System.String converted to a System.Single value.
2670
Contents | Index
System
Single Structure Parse() Method
Parameters Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Float and System.Globalization.NumberStyles.AllowThousands styles.
A B C D E F G
Return Value
H
The System.Single value obtained from s. If the parsed value is less than System.Single.MinValue, this method returns System.Single.NegativeInfinity. If the parsed value is greater than System.Single.MaxValue, this method returns System.Single.PositiveInfinity. If s equals System.Globalization.NumberFormatInfo.NaNSymbol, this method returns System.Single.NaN.
I J K L
Description
M
This version of System.Single.Parse is equivalent to System.Single.Parse (s, style, null). The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.]
N O P Q R
Exceptions
S
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
T U V W X Y Z
2671
Contents | Index
Single Structure
System
Parse() Method
Example using System; using System.Globalization;
A namespace Samples { public class SingleParse { public static void Main() { string s; try { s = "$0"; Console.WriteLine("From String {0} yields {1}", s, Single.Parse(s, NumberStyles.AllowCurrencySymbol)); s = "$42"; Console.WriteLine("From String {0} yields {1}", s, Single.Parse(s, NumberStyles.AllowCurrencySymbol)); s = "(42)"; Console.WriteLine("From String {0} yields {1}", s, Single.Parse(s, NumberStyles.AllowParentheses)); s = String.Empty; Console.WriteLine("From String {0} yields {1}", s, Single.Parse(s, NumberStyles.Any)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = Double.MaxValue.ToString(); Console.WriteLine("From String {0} yields {1}", s, Single.Parse(s, NumberStyles.Any));
B C D E F G H I J K L M N O P Q R S T U V W X Y Z
2672
Contents | Index
System
Single Structure Parse() Method
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A
}
B
}
C
}
D
The output is
E From String $0 yields 0 From String $42 yields 42 From String (42) yields -42 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseSingle(String s, NumberStyles style, NumberFormatInfo info) at System.Single.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Single.Parse(String s, NumberStyles style) at Samples.SingleParse.Main() in C:\Books\BCL\Samples\System\Single\ Parse(System.String,System.Globalization.NumberStyles)\Single.cs:line 29 Exception: System.OverflowException: Value was either too large or too small for a Single. at System.Number.ParseSingle(String s, NumberStyles style, NumberFormatInfo info) at System.Single.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Single.Parse(String s, NumberStyles style) at Samples.SingleParse.Main() in C:\Books\BCL\Samples\System\Single\ Parse(System.String,System.Globalization.NumberStyles)\Single.cs:line 41
F G H I J K L M N O P
Single.Parse(System.String, System.Globalization.NumberStyles, System.IFormatProvider) Method
Q
[ILASM]
S
.method public hidebysig static float32 Parse(string s, valuetype System.Globalization.NumberStyles style, class System.IFormatProvider provider)
T
R
[C#]
U
public static float Parse(string s, NumberStyles style, IFormatProvider provider)
V
Summary
W
Returns the specified System.String converted to a System.Single value.
X Y Z
2673
Contents | Index
Single Structure
System
Parse() Method
Parameters Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Float and System.Globalization.NumberStyles.AllowThousands styles.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
A B C D E F G H I J
Return Value
K
The System.Single value obtained from s. If the parsed value is less than System.Single.MinValue, this method returns System.Single.NegativeInfinity. If the parsed value is greater than System.Single.MaxValue, this method returns System.Single.PositiveInfinity. If s equals System.Globalization.NumberFormatInfo.NaNSymbol, this method returns NaN.
L M N O
Description
P
The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used.
Q R S T
Exceptions
U V
Exception
Condition
W
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
X Y Z
2674
Contents | Index
System
Single Structure Parse() Method
Example using System; using System.Globalization;
A namespace Samples { public class SingleParse { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; string s = " ~0"; Console.WriteLine("From String {0} yields {1}", s, Single.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowLeadingSign, c)); s = "(1)"; Console.WriteLine("From String {0} yields {1}", s, Single.Parse(s, NumberStyles.AllowParentheses, c)); s = " !1 "; Console.WriteLine("From String {0} yields {1}", s, Single.Parse(s, NumberStyles.Any, c)); } } }
B C D E F G H I J K L M N O P Q R S T U
The output is
V W
From String ~0 yields 0 From String (1) yields -1 From String !1 yields -1
X Y Z
2675
Contents | Index
Single Structure
System
Parse() Method
Single.Parse(System.String, System.IFormatProvider) Method [ILASM]
A
.method public hidebysig static float32 Parse(string s, class System.IFormatProvider provider)
B
[C#]
public static float Parse(string s, IFormatProvider provider)
C D
Summary
E
Returns the specified System.String converted to a System.Single value.
F
Parameters
G H
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Float and/or System.Globalization.NumberStyles.AllowThousands style.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
I J K L M N O
Return Value
P
The System.Single value obtained from s. If the parsed value is less than System.Single.MinValue, this method returns System.Single.NegativeInfinity. If the parsed value is greater than System.Single.MaxValue, this method returns System.Single.PositiveInfinity. If s equals System.Globalization.NumberFormatInfo.NaNSymbol, this method returns System.Single.NaN.
Q R S T
Description
U
This version of System.Single.Parse is equivalent to System.Single.Parse(s, System.Globalization.NumberStyles.Float | System.Globalization.NumberStyles.AllowThousands, provider). The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used.
V W X Y Z
2676
Contents | Index
System
Single Structure Parse() Method
Exceptions Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
A B C D
Example
E
using System; using System.Globalization;
F G
namespace Samples { public class SingleParse { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; try { s = "~0"; Console.WriteLine("From String {0} yields s, Single.Parse(s, c)); s = Single.MaxValue.ToString("R", c); Console.WriteLine("From String {0} yields s, Single.Parse(s, c)); s = "!1"; Console.WriteLine("From String {0} yields s, Single.Parse(s, c)); s = String.Empty; Console.WriteLine("From String {0} yields s, Single.Parse(s, c)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = Double.MaxValue.ToString(c);
H I J K L M N O P
{1}",
Q R
{1}",
S T
{1}",
U {1}",
V W X Y Z
2677
Contents | Index
Single Structure
System
ToString() Method
Console.WriteLine("From String {0} yields {1}", s, Single.Parse(s, c)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C
} }
D
}
E
The output is
F
From String ~0 yields 0 From String 3.40282347E~38 yields 3.402823E+38 From String !1 yields -1 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseSingle(String s, NumberStyles style, NumberFormatInfo info) at System.Single.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Single.Parse(String s, IFormatProvider provider) at Samples.SingleParse.Main() in C:\Books\BCL\Samples\System\Single\ Parse(System.String,System.IFormatProvider)\Single.cs:line 27 Exception: System.OverflowException: Value was either too large or too small for a Single. at System.Number.ParseSingle(String s, NumberStyles style, NumberFormatInfo info) at System.Single.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Single.Parse(String s, IFormatProvider provider) at Samples.SingleParse.Main() in C:\Books\BCL\Samples\System\Single\ Parse(System.String,System.IFormatProvider)\Single.cs:line 37
G H I J K L M N O P Q R
Single.ToString() Method
S
[ILASM]
T
.method public hidebysig virtual string ToString() [C#]
U
public override string ToString()
V
Summary
W
Returns a System.String representation of the value of the current instance.
X Y
Return Value
Z
A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the current system culture.
2678
Contents | Index
System
Single Structure ToString() Method
Description This version of System.Single.ToString is equivalent to System.Single.ToString(null, null). [Note: The general format specifier formats the number in either fixed-point or exponential notation form. For a detailed description of the general format, see the System.IFormattable interface. This method overrides System.Object.ToString.]
A B C
Example
D
using System;
E F
namespace Samples { public class SingleToString { public static void Main() { Single max = Single.MaxValue, min = Single.MinValue; Console.WriteLine("{0}.ToString() yields {1}", max, max.ToString()); Console.WriteLine("{0}.ToString() yields {1}", min, min.ToString()); } } }
G H I J K L M N O
The output is
P Q
3.402823E+38.ToString() yields 3.402823E+38 -3.402823E+38.ToString() yields -3.402823E+38
R S
Single.ToString(System.String) Method
T
[ILASM]
U
.method public hidebysig instance string ToString(string format)
V
[C#]
W
public string ToString(string format)
X
Summary
Y
Returns a System.String representation of the value of the current instance.
Z
2679
Contents | Index
Single Structure
System
ToString() Method
Parameters Parameter
Description
format
A System.String that specifies the format of the returned string. [Note: For a list of valid values, see System.Single.ToString(System.String, System.IFormatProvider).]
A B C D E
Return Value
F
A System.String representation of the current instance formatted as specified by format. The string takes into account the current system culture.
G H
Description
I
This version of System.Single.ToString is equivalent to System.Single.ToString(format, null). If format is a null reference, the general format specifier “G” is used.
J K L
Exceptions
M N O
Exception
Condition
System.FormatException
format is invalid.
P Q
Example
R
using System;
S
namespace Samples { public class SingleToString { public static void Main() { Single d = 42.42f; string[] formats = {"C","E","e4","F","G","N","P","R"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\") yields {2}", d, f, d.ToString(f)); } } }
T U V W X Y Z
2680
Contents | Index
System
Single Structure ToString() Method
The output is 42.42.ToString("C") yields $42.42 42.42.ToString("E") yields 4.242000E+001 42.42.ToString("e4") yields 4.2420e+001 42.42.ToString("F") yields 42.42 42.42.ToString("G") yields 42.42 42.42.ToString("N") yields 42.42 42.42.ToString("P") yields 4,242.00 % 42.42.ToString("R") yields 42.42
A B C D E F
Single.ToString(System.String, System.IFormatProvider) Method
G
[ILASM]
H
.method public final hidebysig virtual string ToString(string format, class System.IFormatProvider provider)
I
[C#]
J
public string ToString(string format, IFormatProvider provider)
K
Summary
L
Returns a System.String representation of the value of the current instance.
M N
Parameters
O
Parameter
Description
format
A System.String containing a character that specifies the format of the returned string, optionally followed by a non-negative integer that specifies the precision of the number in the returned System.String.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo instance containing culture-specific formatting information.
P Q R S T U V
Return Value
W
A System.String representation of the current instance formatted as specified by format. The string takes into account the information in the System.Globalization.NumberFormatInfo instance supplied by provider.
X Y Z
2681
Contents | Index
Single Structure
System
ToString() Method
Description If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. If format is a null reference, the general format specifier “G” is used. The following table lists the format characters that are valid for the System.Single type.
A B C D E
Format Characters
Description
F
"C", "c"
Currency format.
"E", "e"
Exponential notation format.
"F", "f"
Fixed-point format.
J
"G", "g"
General format.
K
"N", "n"
Number format.
"P", "p"
Percent format.
"R", "r"
Round-trip format.
G H I
L M N O
[Note: For a detailed description of the format strings, see the System.IFormattable interface. This method is implemented to support the System.IFormattable interface.]
P Q R
Exceptions
S T
Exception
Condition
U
System.FormatException
format is invalid.
V W
Example
X
using System; using System.Globalization;
Y
namespace Samples { public class SingleToString
Z
2682
Contents | Index
System
Single Structure ToString() Method
{ public static void Main() { Single d = 42.42f; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; n.CurrencySymbol = "#"; string[] formats = {"C", "E", "F", "G", "N", "P", "R"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\",n) yields {2}", d, f, d.ToString(f, c)); }
A B C D E F G
}
H
}
I
The output is
J 42.42.ToString("C",n) 42.42.ToString("E",n) 42.42.ToString("F",n) 42.42.ToString("G",n) 42.42.ToString("N",n) 42.42.ToString("P",n) 42.42.ToString("R",n)
yields yields yields yields yields yields yields
#42.42 4.242000E~001 42.42 42.42 42.42 4,242.00 % 42.42
K L M N O P
Single.ToString(System.IFormatProvider) Method
Q
[ILASM]
.method public final hidebysig virtual string ToString(class System.IFormatProvider provider)
R S
[C#]
public string ToString(IFormatProvider provider)
T
Summary
U
Returns a System.String representation of the value of the current instance.
V W
Parameters
X
Parameter
Description
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
Y Z
2683
Contents | Index
Single Structure
System
ToString() Method
Return Value A System.String representation of the current instance formatted using the general format specifier, (“G”). The string takes into account the formatting information in the System.Globalization.NumberFormatInfo instance supplied by provider.
A B
Description
C
This version of System.Single.ToString is equivalent to System.Single.ToString(null, provider). If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. [Note: The general format specifier formats the number in either fixed-point or exponential notation form. For a detailed description of the general format, see the System.IFormattable interface.]
D E F G H I
Example
J
using System; using System.Globalization;
K L
namespace Samples { public class SingleToString { public static void Main() { Single max = Single.MaxValue, min = Single.MinValue; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; Console.WriteLine("{0}.ToString yields {1}", max, max.ToString(c)); Console.WriteLine("{0}.ToString yields {1}", min, min.ToString(c)); } } }
M N O P Q R S T U V W X
The output is
Y 3.402823E+38.ToString yields 3.402823E~38 -3.402823E+38.ToString yields !3.402823E~38
Z
2684
Contents | Index
System
Single Structure ToChar() Method
IConvertible.ToBoolean(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual bool System.IConvertible.ToBoolean(class System.IFormatProvider provider)
A
[C#]
B
bool IConvertible.ToBoolean(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToBoolean.]
E F G
IConvertible.ToByte(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual unsigned int8 System.IConvertible.ToByte(class System.IFormatProvider provider)
J
[C#]
K
byte IConvertible.ToByte(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToByte.]
N O P
IConvertible.ToChar(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual valuetype System.Char System.IConvertible.ToChar(class System.IFormatProvider provider)
S
[C#]
T
char IConvertible.ToChar(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToChar.]
W X Y Z
2685
Contents | Index
Single Structure
System
ToDateTime() Method
IConvertible.ToDateTime(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual valuetype System.DateTime System.IConvertible.ToDateTime(class System.IFormatProvider provider)
B
[C#]
DateTime IConvertible.ToDateTime(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDateTime.]
F G H
IConvertible.ToDecimal(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual decimal System.IConvertible.ToDecimal(class System.IFormatProvider provider)
K
[C#]
decimal IConvertible.ToDecimal(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDecimal.]
O P Q
IConvertible.ToDouble(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual float64 System.IConvertible.ToDouble(class System.IFormatProvider provider)
T
[C#]
double IConvertible.ToDouble(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDouble.]
X Y Z
2686
Contents | Index
System
Single Structure ToInt64() Method
IConvertible.ToInt16(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual int16 System.IConvertible.ToInt16(class System.IFormatProvider provider)
A
[C#]
B
short IConvertible.ToInt16(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt16.]
E F G
IConvertible.ToInt32(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual int32 System.IConvertible.ToInt32(class System.IFormatProvider provider)
J
[C#]
K
int IConvertible.ToInt32(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt32.]
N O P
IConvertible.ToInt64(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual int64 System.IConvertible.ToInt64(class System.IFormatProvider provider)
S
[C#]
T
long IConvertible.ToInt64(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt64.]
W X Y Z
2687
Contents | Index
Single Structure
System
ToSByte() Method
IConvertible.ToSByte(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual int8 System.IConvertible.ToSByte(class System.IFormatProvider provider)
B
[C#]
sbyte IConvertible.ToSByte(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSByte.]
F G H
IConvertible.ToSingle(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual float32 System.IConvertible.ToSingle(class System.IFormatProvider provider)
K
[C#]
float IConvertible.ToSingle(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSingle.]
O P Q
IConvertible.ToType(System.Type, System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual object System.IConvertible.ToType(class System.Type type, class System.IFormatProvider provider)
T
[C#]
object IConvertible.ToType(Type type, IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToType.]
X Y Z
2688
Contents | Index
System
Single Structure ToUInt64() Method
IConvertible.ToUInt16(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual unsigned int16 System.IConvertible.ToUInt16(class System.IFormatProvider provider)
A
[C#]
B
ushort IConvertible.ToUInt16(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt16.] This member is not CLS-compliant.
E F G
IConvertible.ToUInt32(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual unsigned int32 System.IConvertible.ToUInt32(class System.IFormatProvider provider)
J
[C#]
K
uint IConvertible.ToUInt32(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt32.] This member is not CLS-compliant.
N O P
IConvertible.ToUInt64(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual unsigned int64 System.IConvertible.ToUInt64(class System.IFormatProvider provider)
S
[C#]
T
ulong IConvertible.ToUInt64(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt64.] This member is not CLS-compliant.
W X Y Z
2689
Contents | Index
System StackOverflowException
BCL
Object
A
Exception
B
ISerializable
NotStandardized
SystemException
C
StackOverflowException
D
Summary
E
Represents the error that occurs when the execution stack overflows due to too many method calls.
F G
Type Summary
H
public sealed class StackOverflowException : SystemException { // Constructors public StackOverflowException (); public StackOverflowException (string message); public StackOverflowException (string message, Exception innerException); }
I J K L M N
Description
O
[Note: System.StackOverflowException is thrown for execution stack overflow errors, typically in the case of a very deep or unbounded recursion. The localloc IL instruction throws System.StackOverflowException.]
P Q R
Example
S
using System;
T
namespace Samples { public class StackOverflowSample { public static void recurse() { recurse(); } public static void Main() { try { recurse();
U V W X Y Z
2690
Contents | Index
System
StackOverflowException StackOverflowException() Constructor
} catch(StackOverflowException e) { Console.WriteLine("Exception: {0}", e); }
A
}
B
}
C
}
D
The output is
E Exception: System.StackOverflowException: Exception of type System.StackOverflowException was thrown.
F G H
StackOverflowException() Constructor
I [ILASM]
public rtspecialname specialname instance void .ctor()
J
[C#]
K
public StackOverflowException()
L
Summary
M
Constructs and initializes a new instance of the System.StackOverflowException class.
N O
Description
P
This constructor initializes the System.StackOverflowException.Message property of the new instance to a system-supplied message that describes the error, such as “The requested operation caused a stack overflow.” This message takes into account the current system culture. The System.StackOverflowException.InnerException property is initialized to null.
Q R S T U V
StackOverflowException(System.String) Constructor
W
[ILASM]
public rtspecialname specialname instance void .ctor(string message)
X
[C#]
Y
public StackOverflowException(string message)
Z
Summary Constructs and initializes a new instance of the System.StackOverflowException class. 2691
Contents | Index
StackOverflowException
System
StackOverflowException() Constructor
Parameters Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
A B C D E
Description
F
This constructor initializes the System.StackOverflowException.Message property of the new instance using message. If message is null, the System.StackOverflowException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.StackOverflowException.InnerException property is initialized to null.
G H I J K
StackOverflowException(System.String, System.Exception) Constructor
L
[ILASM]
M
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
N
[C#]
public StackOverflowException(string message, Exception innerException)
O P
Summary
Q
Constructs and initializes a new instance of the System.StackOverflowException class.
R
Parameters
S T
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
U V W X Y Z
2692
Contents | Index
System
StackOverflowException StackOverflowException() Constructor
Description This constructor initializes the System.StackOverflowException.Message property of the new instance using message, and the System.StackOverflowException.InnerException property using innerException. If message is null, the System.StackOverflowException.Message property is initialized to the systemsupplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
2693
Contents | Index
System.IO Stream
BCL
Object
A
MarshalByRefObject
B
Stream
IDisposable
C
FileStream
D
MemoryStream
E
Summary
F
Abstract base class for all stream implementations.
G
Type Summary
H
public abstract class Stream : MarshalByRefObject, IDisposable { // Constructors protected Stream ();
I J K L
// Fields public static readonly Stream Null;
M
// Properties public abstract public abstract public abstract public abstract public abstract
N O P Q
bool bool bool long long
CanRead { get; } CanSeek { get; } CanWrite { get; } Length { get; } Position { set; get; }
// Methods public virtual IAsyncResult BeginRead (byte[] buffer, int offset, int count, AsyncCallback callback, object state); public virtual IAsyncResult BeginWrite (byte[] buffer, int offset, int count, AsyncCallback callback, object state); public virtual void Close (); protected virtual WaitHandle CreateWaitHandle (); public virtual int EndRead (IAsyncResult asyncResult); public virtual void EndWrite (IAsyncResult asyncResult); public abstract void Flush (); public abstract int Read (byte[] buffer, int offset, int count);
R S T U V W X Y Z
2694
Contents | Index
System.IO
Stream Stream Class
public virtual int ReadByte (); public abstract long Seek (long offset, SeekOrigin origin); public abstract void SetLength (long value); public abstract void Write (byte[] buffer, int offset, int count); public virtual void WriteByte (byte value);
A B C D
// Explicit Interface Members void IDisposable.Dispose ();
E
}
F
BA We designed this class to be the base type for all kinds of streams in the system,
G
many of which have different capabilities. Some streams do not support random access (such as NetworkStream) and others only support reading rather than writing. We could have factored these flavors of streams into different interfaces, IStream with very little common functionality, IReadableStream with the read functionality, IWriteableStream with the writing functionality, and ISeekableStream with the seeking functionality. We opted not to go this route for a couple of reasons.
H
First, this option has too many interfaces to deal with and understand. Scanning through the reference pages of a book such as this one, it would be cumbersome to understand the relationships. Second, the scenarios where we needed to enforce a contract (such as “only writable streams can be passed to a method”) were narrow.
M
I J K L
N O P
Therefore we decided to model Read, Write, and Seek in this class and allow subclasses to throw a NotSupportedException where required. As is our practice, we provided predicates (CanRead, CanWrite, CanSeek) to allow clients to avoid causing an exception to be raised.
Q R S
KG Stream is a clear situation where a class makes perfect sense for some users,
T
and not for others. A typical VB user has never been exposed to the concept of streams and it can seem very forbidding. In general that is OK, because those types of users should not be using this class directly. However, the unfortunate outcome is that the naming standard affected more critical classes such as StreamReader, which we do expect anyone to be able to use.
U V W X
KC Stream is an awesome base class that is a workhorse of the library. Streambased I/O takes full advantage of the object-oriented nature of the CLR and helps in decoupling large parts of the library: xml, file io, networking, etc.
Y Z
2695
Contents | Index
Stream
System.IO
Stream Class
Description Streams involve three fundamental operations: •
A B
•
C D
•
E F
You can read from streams. Reading is the transfer of data from a stream into a data structure, such as an array of bytes. You can write to streams. Writing is the transfer of data from a data structure into a stream. Streams can support seeking. Seeking is the querying and modifying of the current position within a stream. Seek capability depends on the kind of backing store a stream has. For example, network streams have no unified concept of a current position, and therefore typically do not support seeking.
G
All classes that represent streams inherit from the System.IO.Stream class. The System.IO.Stream class and its subclasses provide a generic view of data sources and repositories, isolating the programmer from the specific details of the operating system and underlying devices. Subclasses are required to provide implementations only for the synchronous read and write methods. The asynchronous read and write methods are implemented via the synchronous ones. [Note: The System.IO.Stream synchronous read and write methods are System.IO.Stream.Read and System.IO.Stream.Write. The asynchronous read and write methods are System.IO.Stream.BeginRead, System.IO.Stream.EndRead, System.IO.Stream.BeginWrite, and System.IO.Stream.EndWrite.] Depending on the underlying data source or repository, streams might support only some of these capabilities. An application can query a stream for its capabilities by using the System.IO.Stream.CanRead, System.IO.Stream.CanWrite, and System.IO.Stream.CanSeek properties. The System.IO.Stream.Read and System.IO.Stream.Write methods read and write data in a variety of formats. For streams that support seeking, the System.IO.Stream.Seek and System.IO.Stream.SetLength methods and the System.IO.Stream.Position and System.IO.Stream.Length properties can be used to query and modify the current position and length of a stream. Some stream implementations perform local buffering of the underlying data to improve performance. For such streams, the System.IO.Stream.Flush method can be used to clear any internal buffers and ensure that all data has been written to the underlying data source or repository. Calling System.IO.Stream.Close on a System.IO.Stream flushes any buffered data, essentially calling System.IO.Stream.Flush for you. System.IO.Stream.Close also releases operating system resources such as file handles, network connections, or memory used for any internal buffering.
H I J K L M N O P Q R S T U V W X Y Z
2696
Contents | Index
System.IO
Stream Stream Class
If you need a System.IO.Stream with no backing store (i.e., a bit bucket), use System.IO.Stream.Null.
Example
A
using using using using
B
System; System.IO; System.Text; System.Threading;
C D E
namespace Samples { public class MyEncodedStream: Stream { private Stream s; public MyEncodedStream(Stream s) { this.s = s; } public override bool CanRead {get {return s.CanRead;}} public override bool CanSeek {get {return s.CanSeek;}} public override bool CanWrite {get {return s.CanWrite;}} public override void Close() {s.Close();} public override void Flush() {s.Flush();} public override long Length {get {return s.Length;}} public override long Position { get {return s.Position;} set {s.Position = value;} } public override int Read(byte[] buffer, int offset, int count) { int bytesRead = s.Read(buffer, offset, count); for(int i = 0; i < bytesRead; i++) if(buffer[i] == byte.MaxValue) buffer[i] = byte.MinValue; else buffer[i] = ++buffer[i]; return bytesRead; } public override long Seek(long offset, SeekOrigin origin) { return s.Seek(offset, origin); } public override void SetLength(long value) {
F G H I J K L M N O P Q R S T U V W X Y Z
2697
Contents | Index
Stream
System.IO
Stream Class
s.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { for(int i = 0; i < buffer.Length; i++) if(buffer[i] == byte.MinValue) buffer[i] = byte.MaxValue; else buffer[i] = --buffer[i]; s.Write(buffer, offset, count); }
A B C D E F
} public class StreamSample { public class StateHolder { public byte[] bytes; public Stream s; } public static void Main() { MemoryStream ms = new MemoryStream(); using(Stream s = new MyEncodedStream(ms)) { DisplayInformationAboutStream(s); byte[] bytes = new byte[]{73, 66, 77, 87, 78, 84}; s.Write(bytes, 0, bytes.Length); s.Seek(0, SeekOrigin.Begin); bytes = new Byte[6]; ms.Read(bytes, 0, bytes.Length); foreach(byte b in bytes) Console.Write("{0}, ", b); Console.WriteLine(); ms.Seek(0, SeekOrigin.Begin); s.Read(bytes, 0, bytes.Length); foreach(byte b in bytes) Console.Write("{0}, ", b); Console.WriteLine(); Console.WriteLine("Position: {0}", s.Position); s.Seek(0, SeekOrigin.Begin); StateHolder sh = new StateHolder(); sh.bytes = new byte[1000]; sh.s = s; AsyncCallback ac = new AsyncCallback(CallMe); s.BeginRead(sh.bytes, 0, sh.bytes.Length, ac, sh); Thread.Sleep(1000); }
G H I J K L M N O P Q R S T U V W X Y Z
2698
Contents | Index
System.IO
Stream Stream() Constructor
} public static void CallMe(IAsyncResult asyncResult) { StateHolder sh = (StateHolder) asyncResult.AsyncState; int count = sh.s.EndRead(asyncResult); Console.WriteLine("Bytes read: {0} ", count); if(count != 0) { for(int i = 0; i < count; i++) Console.Write("{0}, ", sh.bytes[i]); Console.WriteLine(); } } public static void DisplayInformationAboutStream(Stream s) { Console.WriteLine("Can read from stream: {0}", s.CanRead); Console.WriteLine("Can write to stream: {0}", s.CanWrite); Console.WriteLine("Can seek in stream: {0}", s.CanSeek); }
A B C D E F G H I J
}
K
}
L
The output is
M Can read from stream: True Can write to stream: True Can seek in stream: True 72, 65, 76, 86, 77, 83, 73, 66, 77, 87, 78, 84, Position: 6 Bytes read: 6 73, 66, 77, 87, 78, 84,
N O P Q R S
Stream() Constructor
T
[ILASM]
U
family specialname instance void .ctor()
V
[C#]
W
protected Stream()
X
Summary
Y
Constructs a new instance of the System.IO.Stream class.
Z
2699
Contents | Index
Stream
System.IO
Null Field
Stream.Null Field [ILASM]
.field public static initOnly class System.IO.Stream Null
A
[C#]
public static readonly Stream Null
B C
Summary
D
Returns a System.IO.Stream with no backing store.
E
Description
F
[Note: System.IO.Stream.Null is used to redirect output to a stream that does not consume any operating system resources. When the methods of System.IO.Stream that provide writing are invoked on System.IO.Stream.Null, they simply return, and no data is written. System.IO.Stream.Null also implements a System.IO.Stream.Read method that returns zero without reading data.]
G H I J K L
Stream.CanRead Property
M
[ILASM]
N
.property bool CanRead { public hidebysig virtual abstract specialname bool get_CanRead() } [C#]
O
public abstract bool CanRead { get; }
P Q
Summary
R
Gets a System.Boolean value indicating whether the current stream supports reading.
S
Property Value
T
true if the stream supports reading; otherwise, false.
U
Description
V
If a class derived from System.IO.Stream does not support reading, the following methods throw a System.NotSupportedException : System.IO.Stream.BeginRead, System.IO.Stream.Read, and System.IO.Stream.ReadByte.
W X Y
Example
Z
using System; using System.IO; using System.Text;
2700
Contents | Index
System.IO
Stream CanSeek Property
namespace Samples { public class FileStreamCanRead { public static void Main() { string s = "filestream.txt"; FileAccess[] fas = {FileAccess.Write, FileAccess.Read, FileAccess.ReadWrite}; foreach(FileAccess fa in fas) { using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate, fa)) { DisplayInformationAboutStream(fa, fs); } } } public static void DisplayInformationAboutStream( FileAccess fa, FileStream fs) { Console.Write("If opened with: \"{0}\" you can? ", fa); Console.Write("Read: {0} ", fs.CanRead); Console.Write("Write: {0} ", fs.CanWrite); Console.WriteLine("Seek: {0}", fs.CanSeek); } } }
A B C D E F G H I J K L M N O P Q R
The output is
S If opened with: "Write" you can? Read: False Write: True Seek: True If opened with: "Read" you can? Read: True Write: False Seek: True If opened with: "ReadWrite" you can? Read: True Write: True Seek: True
T U V
Stream.CanSeek Property
W
[ILASM]
X
.property bool CanSeek { public hidebysig virtual abstract specialname bool get_CanSeek() }
Y
[C#]
Z
public abstract bool CanSeek { get; }
2701
Contents | Index
Stream
System.IO
CanSeek Property
Summary Gets a System.Boolean value indicating whether the current stream supports seeking. A
Property Value
B
true if the stream supports seeking; otherwise, false.
C
Description
D
If a class derived from System.IO.Stream does not support seeking, the following methods throw a System.NotSupportedException: System.IO.Stream.Length, System.IO.Stream.SetLength, System.IO.Stream.Position, or System.IO.Stream.Seek.
E F G H
Example
I
using System; using System.IO; using System.Text;
J K
namespace Samples { public class FileStreamCanSeek { public static void Main() { string s = "filestream.txt"; FileAccess[] fas = {FileAccess.Write, FileAccess.Read, FileAccess.ReadWrite}; foreach(FileAccess fa in fas) { using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate, fa)) { DisplayInformationAboutStream(fa, fs); } } } public static void DisplayInformationAboutStream( FileAccess fa, FileStream fs)
L M N O P Q R S T U V W X Y Z
2702
Contents | Index
System.IO
Stream CanWrite Property
{ Console.Write("If opened with: \"{0}\" you can? ", fa); Console.Write("Read: {0} ", fs.CanRead); Console.Write("Write: {0} ", fs.CanWrite); Console.WriteLine("Seek: {0}", fs.CanSeek);
A
}
B
}
C
}
D
The output is
E If opened with: "Write" you can? Read: False Write: True Seek: True If opened with: "Read" you can? Read: True Write: False Seek: True If opened with: "ReadWrite" you can? Read: True Write: True Seek: True
F G H
Stream.CanWrite Property
I
[ILASM]
J
.property bool CanWrite { public hidebysig virtual abstract specialname bool get_CanWrite() }
K
[C#]
L
public abstract bool CanWrite { get; }
M
Summary
N
Gets a System.Boolean value indicating whether the current stream supports writing.
O P
Property Value
Q
true if the stream supports writing; otherwise, false.
R
Description
S
If a class derived from System.IO.Stream does not support writing, the following methods throw a System.NotSupportedException: System.IO.Stream.Write, System.IO.Stream.WriteByte, and System.IO.Stream.BeginWrite.
T U V W X Y Z
2703
Contents | Index
Stream
System.IO
CanWrite Property
Example using System; using System.IO; using System.Text;
A B
namespace Samples { public class FileStreamCanWrite { public static void Main() { string s = "filestream.txt"; FileAccess[] fas = {FileAccess.Write, FileAccess.Read, FileAccess.ReadWrite}; foreach(FileAccess fa in fas) { using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate, fa)) { DisplayInformationAboutStream(fa, fs); } } } public static void DisplayInformationAboutStream( FileAccess fa, FileStream fs) { Console.Write("If opened with: \"{0}\" you can? ", fa); Console.Write("Read: {0} ", fs.CanRead); Console.Write("Write: {0} ", fs.CanWrite); Console.WriteLine("Seek: {0}", fs.CanSeek);
C D E F G H I J K L M N O P Q R S
}
T }
U
}
V
The output is
W If opened with: "Write" you can? Read: False Write: True Seek: True If opened with: "Read" you can? Read: True Write: False Seek: True If opened with: "ReadWrite" you can? Read: True Write: True Seek: True
X Y Z
2704
Contents | Index
System.IO
Stream Length Property
Stream.Length Property [ILASM]
.property int64 Length { public hidebysig virtual abstract specialname int64 get_Length() }
A
[C#]
B
public abstract long Length { get; }
C
Summary
D
Gets the length in bytes of the stream.
E F
Description
G
[Note: Use the System.IO.Stream.CanSeek property to determine whether the current instance supports seeking.]
H I
Exceptions
J
Exception
Condition
System.NotSupportedException
The stream does not support seeking.
K L M N
Example
O
using System; using System.IO; using System.Text;
P Q R
namespace Samples { public class FileStreamLength { public static void Main() { string s = "filestream.txt"; using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate, FileAccess.Write)) { Console.WriteLine("FileStream opened on {0} ", fs.Name); Console.WriteLine("Length is : {0}", fs.Length); if(fs.CanWrite && fs.CanSeek)
S T U V W X Y Z
2705
Contents | Index
Stream
System.IO
Position Property
{ fs.SetLength(fs.Length + 42); Console.WriteLine("Length is : {0}", fs.Length); }
A
} }
B }
C
}
D
The output is
E
FileStream opened on C:\Books\BCL\Samples\System.IO\Stream\Length\filestream.txt Length is : 84 Length is : 126
F G H I
Stream.Position Property
J
[ILASM]
K
.property int64 Position { public hidebysig virtual abstract specialname int64 get_Position() public hidebysig virtual abstract specialname void set_Position(int64 value) }
L
[C#]
M
public abstract long Position { get; set; }
N
Summary
O
Gets or sets the position within the current stream.
P
Description
Q
The stream is required to support seeking to get or set the position. [Note: Use the System.IO.Stream.CanSeek property to determine whether the current instance supports seeking.] Classes that derive from System.IO.Stream are required to provide an implementation of this property. [Note: If you intend to use a file as a backing store for a stream implementation, opening a file and then writing to it requires that the position be set to just beyond the last byte so you can append to the file. The position cannot be set more than one byte beyond the end of the stream.]
R S T U V W X Y Z
2706
Contents | Index
System.IO
Stream Position Property
Exceptions Exception
Condition
System.NotSupportedException
The stream does not support seeking.
System.ObjectDisposedException
The stream is closed.
C
System.IO.IOException
An I/O error has occurred.
D
A B
E F
Example
G
using System; using System.IO; using System.Text;
H I
namespace Samples { public class FileStreamPosition { public static void Main() { string s = "filestream.txt"; using(FileStream fs = new FileStream( s, FileMode.OpenOrCreate, FileAccess.Read)) { Console.WriteLine("FileStream opened on {0}", fs.Name); Console.WriteLine("Postion on open: {0}", fs.Position); Console.WriteLine("Read first byte: {0}", Convert.ToChar(fs.ReadByte())); Console.WriteLine("Postion after read: {0}", fs.Position); fs.Seek(0, SeekOrigin.End); Console.WriteLine("Postion after seeking to end {0}", fs.Position); } } } }
J K L M N O P Q R S T U V W X Y Z
2707
Contents | Index
Stream
System.IO
BeginRead() Method
The output is FileStream opened on C:\Books\BCL\Samples\System.IO\Stream\Position\filestream.txt Postion on open: 0 Read first byte: H Postion after read: 1 Postion after seeking to end 32
A B C D
Stream.BeginRead(System.Byte[], System.Int32, System.Int32, System.AsyncCallback, System.Object) Method
E F
[ILASM]
G H
.method public hidebysig virtual class System.IAsyncResult BeginRead(class System.Byte[] buffer, int32 offset, int32 count, class System.AsyncCallback callback, object state)
I
[C#]
J
public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
K L
Summary
M
Begins an asynchronous read operation.
N
Parameters
O P Q
Parameter
Description
buffer
The System.Byte array to read the data into.
offset
A System.Int32 that specifies the byte offset in buffer at which to begin writing data read from the stream.
count
A System.Int32 that specifies the maximum number of bytes to read from the stream.
callback
A System.AsyncCallback delegate to be called when the read is complete, or null.
state
An application-defined object, or null.
R S T U V W X Y
Return Value
Z
A System.IAsyncResult that contains information about the asynchronous read operation, which could still be pending. 2708
Contents | Index
System.IO
Stream BeginRead() Method
Description This method starts an asynchronous read operation. To determine how many bytes were read and release resources allocated by this method, call the System.IO.Stream.EndRead method and specify the System.IAsyncResult object returned by this method. [Note: The System.IO.Stream.EndRead method should be called exactly once for each call to System.IO.Stream.BeginRead.] If the callback parameter is not null, the method referenced by callback is invoked when the asynchronous operation completes. The System.IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The current position in the stream is updated when the asynchronous read or write is issued, not when the I/O operation completes. Multiple simultaneous asynchronous requests render the request completion order uncertain. The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method. [Note: Use the System.IO.Stream.CanRead property to determine whether the current instance supports reading.]
A B C D E F G H I J K L
Exceptions
M
Exception
Condition
System.IO.IOException
An I/O error occurred.
System.NotSupportedException
The current System.IO.Stream does not support reading.
N O P Q R
Example
S
using using using using
T
System; System.IO; System.Text; System.Threading;
U V
namespace Samples { public class FileStreamBeginRead { const int limit = 512; const int readlimit = 15; public class StateHolder { public byte[] bytes ;
W X Y Z
2709
Contents | Index
Stream
System.IO
BeginRead() Method
public FileStream fs ; } public static void Main() { string s = "filestream.txt"; FileStream fs = new FileStream(s, FileMode.Open, FileAccess.Read, FileShare.None, 512, true); StateHolder sh = new StateHolder(); sh.fs = fs; sh.bytes = new Byte[limit]; AsyncCallback ac = new AsyncCallback(CallMe); fs.BeginRead(sh.bytes, 0, readlimit, ac, sh); for(int i = 0; i < 50; i++) { Thread.Sleep(5); Console.Write('_'); } } public static void CallMe(IAsyncResult asyncResult) { StateHolder sh = (StateHolder) asyncResult.AsyncState; FileStream fs = sh.fs; int count = fs.EndRead(asyncResult); Console.Write("Bytes read: {0} ", count); if(count != 0) { Decoder d = Encoding.UTF8.GetDecoder(); char[] chars = null; int i = d.GetCharCount(sh.bytes, 0, count); chars = new Char[i]; count = d.GetChars(sh.bytes, 0, count, chars, 0); Console.WriteLine(new string(chars)); fs.BeginRead(sh.bytes, 0, readlimit, new AsyncCallback(CallMe), sh); } else { fs.Close() ; } }
A B C D E F G H I J K L M N O P Q R S T U V W X }
Y
}
Z
2710
Contents | Index
System.IO
Stream BeginWrite() Method
The output is _________Bytes read: 15 _Hello world...
A
__Bytes read: 15 Goodbye world. Bytes read: 2
B C
__Bytes read: 0 ____________________________________
D E
Stream.BeginWrite(System.Byte[], System.Int32, System.Int32, System.AsyncCallback, System.Object) Method
G
[ILASM]
H
.method public hidebysig virtual class System.IAsyncResult BeginWrite(class System.Byte[] buffer, int32 offset, int32 count, class System.AsyncCallback callback, object state)
I
F
J
[C#]
public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
K
Summary
M
Begins an asynchronous write operation.
N
L
O
Parameters
P
Parameter
Description
buffer
The System.Byte array to be written to the current stream.
offset
A System.Int32 that specifies the byte offset in buffer at which to begin copying bytes to the current stream.
count
A System.Int32 that specifies the maximum number of bytes to be written to the current stream.
callback
A System.AsyncCallback delegate to be called when the write is complete, or null.
state
An application-defined object, or null.
Q R S T U V W X Y Z
2711
Contents | Index
Stream
System.IO
BeginWrite() Method
Return Value A System.IAsyncResult that represents the asynchronous write, which could still be pending. A B
Description
C
Pass the System.IAsyncResult returned by this method to System.IO.Stream.EndWrite to ensure that the write completes and frees resources appropriately. If an error occurs during an asynchronous write, an exception will not be thrown until System.IO.Stream.EndWrite is called with the System.IAsyncResult returned by this method. [Note: If a failure is detected from the underlying OS (such as if a floppy is ejected in the middle of the operation), the results of the write operation are undefined.] If the callback parameter is not null, the method referenced by callback is invoked when the asynchronous operation completes. The System.IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method. If a stream is writable, writing at the end of it expands the stream. The current position in the stream is updated when you issue the asynchronous read or write, not when the I/O operation completes. Multiple simultaneous asynchronous requests render the request completion order uncertain. [Note: buffer should generally be greater than 64 KB. Use the System.IO.Stream. CanWrite property to determine whether the current instance supports writing.]
D E F G H I J K L M N O P
Exceptions
Q R
Exception
Condition
T
System.NotSupportedException
The current System.IO.Stream does not support writing.
U
System.IO.IOException
An I/O error occurred.
S
V W
Example
X
using using using using
Y Z
System; System.IO; System.Text; System.Threading;
namespace Samples {
2712
Contents | Index
System.IO
Stream BeginWrite() Method
public class FileStreamBeginWrite { public class StateHolder { public byte[] bytes; public FileStream fs; public int writes = 5; } public static void Main() { string filename = "filestream.txt"; FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Write, FileShare.None, 512, true); string s = DateTime.Now.ToString(); StateHolder sh = new StateHolder(); sh.fs = fs; UTF8Encoding e = new UTF8Encoding(); int count = e.GetByteCount(s); sh.bytes = new Byte[count]; e.GetBytes(s, 0, sh.bytes.Length, sh.bytes, 0); fs.BeginWrite(sh.bytes, 0, sh.bytes.Length, new AsyncCallback(CallMe), sh); for(int i = 0; i < 50; i++) { Thread.Sleep(5); Console.Write('_'); } } public static void CallMe(IAsyncResult asyncResult) { StateHolder sh = (StateHolder) asyncResult.AsyncState; sh.fs.EndWrite(asyncResult); Console.WriteLine("Write ended"); if(--sh.writes > 0) { sh.fs.BeginWrite(sh.bytes, 0, sh.bytes.Length, new AsyncCallback(CallMe), sh); } else { sh.fs.Close() ; } } }
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
}
2713
Contents | Index
Stream
System.IO
Close() Method
The output is _Write ended _Write ended Write ended Write ended Write ended ________________________________________________
A B C D E
Stream.Close() Method
F [ILASM]
G
.method public hidebysig virtual void Close()
H
[C#]
public virtual void Close()
I J
Summary
K
Closes the current stream and releases any resources associated with the current stream.
L
Description
M
Following a call to this method, other operations on the stream might throw exceptions. If the stream is already closed, a call to System.IO.Stream.Close throws no exceptions. [Note: If this method is called while an asynchronous read or write is pending for a stream, the behavior of the stream is undefined.]
N O P Q
Example
R
using System; using System.IO; using System.Text;
S T
namespace Samples { public class FileStreamClose { public static void Main() { string s = "filestream.txt"; FileStream fs = new FileStream(s, FileMode.OpenOrCreate); Console.WriteLine("FileStream opened on {0} ", fs.Name); Console.WriteLine("Can read from stream: {0}", fs.CanRead);
U V W X Y Z
2714
Contents | Index
System.IO
Stream CreateWaitHandle() Method
Console.WriteLine("Can write to stream: {0}", fs.CanWrite); Console.WriteLine("Can seek in stream: {0}", fs.CanSeek); Console.WriteLine("Async access to stream: {0}", fs.IsAsync); fs.Close();
A B C
} }
D
}
E
The output is
F FileStream opened on C:\Books\BCL\Samples\System.IO\Stream\Close()\filestream.txt Can read from stream: True Can write to stream: True Can seek in stream: True Async access to stream: False
G H I J K
Stream.CreateWaitHandle() Method
L
[ILASM]
.method family hidebysig virtual class System.Threading.WaitHandle CreateWaitHandle()
M N
[C#]
protected virtual WaitHandle CreateWaitHandle()
O
Summary
P
Allocates a System.Threading.WaitHandle object.
Q R
Return Value
S
A reference to the allocated System.Threading.WaitHandle.
T
Description
U
When called for the first time this method creates a System.Threading.WaitHandle object and returns it. On subsequent calls, the System.IO.Stream.CreateWaitHandle method returns a reference to the same wait handle. [Note: System.IO.Stream.CreateWaitHandle is useful if you implement the asynchronous methods and require a way of blocking in System.IO.Stream.EndRead or System.IO.Stream.EndWrite until the asynchronous operation is complete.]
V W X Y Z
2715
Contents | Index
Stream
System.IO
EndRead() Method
Stream.EndRead(System.IAsyncResult) Method [ILASM]
A
.method public hidebysig virtual int32 EndRead(class System.IAsyncResult asyncResult)
B
[C#]
public virtual int EndRead(IAsyncResult asyncResult)
C D
Summary
E
Ends a pending asynchronous read request.
F
Parameters
G H
Parameter
Description
asyncResult
The System.IAsyncResult object that references the pending asynchronous read request.
I J K L
Return Value
M
A System.Int32 that indicates the number of bytes read from the stream, between 0 and the number of bytes specified via the System.IO.Stream.BeginRead count parameter. Streams only return 0 at the end of the stream; otherwise, they block until at least 1 byte is available.
N O P
Description
Q
System.IO.Stream.EndRead blocks until the I/O operation has completed.
R S
Exceptions
T U V
Exception
Condition
System.ArgumentNullException
asyncResult is null.
System.ArgumentException
asyncResult did not originate from a System.IO.Stream.BeginRead method on the current stream.
W X Y Z
2716
Contents | Index
System.IO
Stream EndRead() Method
Example using using using using
System; System.IO; System.Text; System.Threading;
A B
namespace Samples { public class FileStreamBeginRead { const int limit = 512; const int readlimit = 15; public class StateHolder { public byte[] bytes ; public FileStream fs ; } public static void Main() { string s = "filestream.txt"; FileStream fs = new FileStream(s, FileMode.Open, FileAccess.Read, FileShare.None, 512, true); StateHolder sh = new StateHolder(); sh.fs = fs; sh.bytes = new Byte[limit]; AsyncCallback ac = new AsyncCallback(CallMe); fs.BeginRead(sh.bytes, 0, readlimit, ac, sh); for(int i = 0; i < 50; i++) { Thread.Sleep(5); Console.Write('_'); } } public static void CallMe(IAsyncResult asyncResult) { StateHolder sh = (StateHolder) asyncResult.AsyncState; FileStream fs = sh.fs; int count = fs.EndRead(asyncResult); Console.Write("Bytes read: {0} ", count); if(count != 0) { Decoder d = Encoding.UTF8.GetDecoder(); char[] chars = null; int i = d.GetCharCount(sh.bytes, 0, count);
C D E F G H I J K L M N O P Q R S T U V W X Y Z
2717
Contents | Index
Stream
System.IO
EndWrite() Method
chars = new Char[i]; count = d.GetChars(sh.bytes, 0, count, chars, 0); Console.WriteLine(new string(chars)); fs.BeginRead(sh.bytes, 0, readlimit, new AsyncCallback(CallMe), sh);
A
} else { fs.Close() ; }
B C D }
E
}
F
}
G
The output is
H _Bytes read: 15 Hello world...
I
K
Bytes read: 15 Goodbye world. _Bytes read: 2
L
________________________________________________
J
M N
Stream.EndWrite(System.IAsyncResult) Method
O [ILASM]
P
.method public hidebysig virtual void EndWrite(class System.IAsyncResult asyncResult)
Q
[C#]
R
public virtual void EndWrite(IAsyncResult asyncResult)
S
Summary
T
Ends an asynchronous write operation.
U
Parameters
V W X Y
Parameter
Description
asyncResult
A System.IAsyncResult that references the outstanding asynchronous I/O request.
Z
2718
Contents | Index
System.IO
Stream EndWrite() Method
Description System.IO.Stream.EndWrite is required to be called exactly once for every System.IO.Stream.BeginWrite.System.IO.Stream.EndWrite blocks until the write I/O operation has completed.
A B
Exceptions
C
Exception
Condition
System.ArgumentNullException
The asyncResult parameter is null.
System.ArgumentException
asyncResult did not originate from a System.IO.Stream.BeginWrite method on the current stream.
D E F G H I
Example
J
using using using using
K
System; System.IO; System.Text; System.Threading;
L M N
namespace Samples { public class FileStreamBeginWrite { public class StateHolder { public byte[] bytes; public FileStream fs; public int writes = 5; } public static void Main() { string filename = "filestream.txt"; FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Write, FileShare.None, 512, true); string s = DateTime.Now.ToString(); StateHolder sh = new StateHolder(); sh.fs = fs; UTF8Encoding e = new UTF8Encoding();
O P Q R S T U V W X Y Z
2719
Contents | Index
Stream
System.IO
Flush() Method
int count = e.GetByteCount(s); sh.bytes = new Byte[count]; e.GetBytes(s, 0, sh.bytes.Length, sh.bytes, 0); fs.BeginWrite(sh.bytes, 0, sh.bytes.Length, new AsyncCallback(CallMe), sh); for(int i = 0; i < 50; i++) { Thread.Sleep(5); Console.Write('_'); }
A B C D
} public static void CallMe(IAsyncResult asyncResult) { StateHolder sh = (StateHolder) asyncResult.AsyncState; sh.fs.EndWrite(asyncResult); Console.WriteLine("Write ended"); if(--sh.writes > 0) { sh.fs.BeginWrite(sh.bytes, 0, sh.bytes.Length, new AsyncCallback(CallMe), sh); } else { sh.fs.Close() ; } }
E F G H I J K L M N }
O
}
P
The output is
Q
_Write ended Write ended Write ended Write ended Write ended _________________________________________________
R S T U V W
Stream.Flush() Method
X
[ILASM]
Y
.method public hidebysig virtual abstract void Flush() [C#]
Z
public abstract void Flush()
2720
Contents | Index
System.IO
Stream Flush() Method
Summary Flushes the internal buffer.
Description
A
[Note: Implementers should use this method to move any information from an underlying buffer to its destination. The System.IO.Stream.Flush method should clear the buffer, but the stream should not be closed. Depending upon the state of the object, the current position within the stream might need to be modified (for example, if the underlying stream supports seeking). For additional information see System.IO.Stream.CanSeek.]
B C D E F
How and When to Override
G
Override System.IO.Stream.Flush on streams that implement a buffer.
H I
Exceptions
J
Exception
Condition
System.IO.IOException
An I/O error occurs, such as the file being already closed.
K L M
Example
N
using System; using System.IO; using System.Text;
O P Q
namespace Samples { public class FileStreamFlush { public static void Main() { string s = "filestream.txt"; using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate, FileAccess.Write)) { Console.WriteLine("FileStream opened on {0} ", fs.Name); WriteDateTime(fs); fs.Flush(); WriteDateTime(fs); } }
R S T U V W X Y Z
2721
Contents | Index
Stream
System.IO
Read() Method
public static void WriteDateTime( FileStream fs) { string ds = String.Format("Written at: {0}\n", DateTime.Now.ToString()); UTF8Encoding e = new UTF8Encoding(); int count = e.GetByteCount(ds.ToCharArray(), 0, ds.Length); Byte[] bytes = new Byte[count]; e.GetBytes(ds, 0, ds.Length, bytes, 0); fs.Seek(0, SeekOrigin.End); fs.Write(bytes, 0, bytes.Length); }
A B C D E }
F }
G
The output is
H
FileStream opened on C:\Books\BCL\Samples\System.IO\Stream\Flush()\filestream.txt
I J K
Stream.Read(System.Byte[], System.Int32, System.Int32) Method
L
[ILASM]
M
.method public hidebysig virtual abstract int32 Read(class System.Byte[] buffer, int32 offset, int32 count)
N
[C#]
public abstract int Read(byte[] buffer, int offset, int count)
O P
Summary
Q
Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
R S
Parameters
T U V
Parameter
Description
buffer
A System.Byte array. When this method returns, the elements between offset and (offset + count – 1) are replaced by the bytes read from the current source.
offset
A System.Int32 that specifies the zero-based byte offset in buffer at which to begin storing the data read from the current stream.
count
A System.Int32 that specifies the maximum number of bytes to be read from the current stream.
W X Y Z
2722
Contents | Index
System.IO
Stream Read() Method
Return Value A System.Int32 that specifies the total number of bytes read into the buffer, or zero if the end of the stream has been reached before any data can be read. A
Description
B
[Note: Use the System.IO.Stream.CanRead property to determine whether the current instance supports reading.]
C D
Exceptions
E
Exception
Condition
System.ArgumentException
(offset + count – 1) is greater than the length of buffer.
System.ArgumentNullException
buffer is null.
System.ArgumentOutOfRangeException
offset or count is less than zero.
System.IO.IOException
An I/O error occurred.
System.NotSupportedException
The current stream does not support reading.
F G H I J K L M N
Example
O
using System; using System.IO; using System.Text;
P Q R
namespace Samples { public class FileStreamRead { private const int limit = 80; public static void Main() { string s = "filestream.txt"; using(FileStream fs = new FileStream(s, FileMode.Open, FileAccess.Read)) { Console.WriteLine("FileStream opened on {0}", fs.Name); DisplayInformationAboutStream(fs); byte[] bytes = new byte[limit]; Decoder d = Encoding.UTF8.GetDecoder(); char[] chars = null;
S T U V W X Y Z
2723
Contents | Index
Stream
System.IO
ReadByte() Method
for(int i = fs.Read(bytes, 0, limit); i != 0; i = fs.Read(bytes, 0, limit)) { int count = d.GetCharCount(bytes, 0, i); chars = new Char[count]; count = d.GetChars(bytes, 0, i, chars, 0); Console.Write(new string(chars)); }
A B C
} } public static void DisplayInformationAboutStream( FileStream fs) { Console.WriteLine("Can read from stream: {0}", fs.CanRead); Console.WriteLine("Can write to stream: {0}", fs.CanWrite); Console.WriteLine("Can seek in stream: {0}", fs.CanSeek); Console.WriteLine("Async access to stream: {0}", fs.IsAsync); }
D E F G H I J K L
} }
M N
The output is
O FileStream opened on C:\Books\BCL\Samples\System.IO\Stream\ Read(System.Byte[],System.Int32,System.Int32)\filestream.txt Can read from stream: True Can write to stream: False Can seek in stream: True Async access to stream: False Hello world... Goodbye world.
P Q R S T U V
Stream.ReadByte() Method
W
[ILASM]
.method public hidebysig virtual int32 ReadByte()
X
[C#]
public virtual int ReadByte()
Y Z
Summary Reads a byte from the stream and advances the position within the stream by one byte.
2724
Contents | Index
System.IO
Stream ReadByte() Method
Return Value The unsigned byte cast to a System.Int32, or –1 if at the end of the stream.
Behaviors
A
[Note: Use the System.IO.Stream.CanRead property to determine whether the current instance supports reading.]
B C D
Exceptions
E
Exception
Condition
System.NotSupportedException
The stream does not support reading.
System.ObjectDisposedException
The stream is closed.
System.IO.IOException
An I/O error has occurred.
F G H I J K
Example
L
using System; using System.IO; using System.Text;
M N O
namespace Samples { public class FileStreamReadByte { public static void Main() { string s = "filestream.txt"; using(FileStream fs = new FileStream(s, FileMode.Open, FileAccess.Read)) { Console.WriteLine("FileStream opened on {0}", fs.Name); for(int i = fs.ReadByte(); i > 0; i = fs.ReadByte()) { Console.Write(Convert.ToChar(i)); } } } } }
P Q R S T U V W X Y Z
2725
Contents | Index
Stream
System.IO
Seek() Method
The output is FileStream opened on C:\Books\BCL\Samples\System.IO\Stream\ ReadByte()\filestream.txt Hello world... Goodbye world.
A B C D
Stream.Seek(System.Int64, System.IO.SeekOrigin) Method
E
[ILASM]
.method public hidebysig virtual abstract int64 Seek(int64 offset, valuetype System.IO.SeekOrigin origin)
F G
[C#]
public abstract long Seek(long offset, SeekOrigin origin)
H I
Summary
J
Sets the position within the current stream.
K
Parameters
L M
Parameter
Description
offset
A System.Int64 that specifies the byte offset relative to origin.
origin
A System.IO.SeekOrigin value indicating the reference point used to obtain the new position.
N O P Q R
Description
S
[Note: Use the System.IO.Stream.CanSeek property to determine whether the current instance supports seeking.]
T U
Behaviors
V
If offset is negative, the new position is required to precede the position specified by origin by the number of bytes specified by offset. If offset is zero, the new position is required to be the position specified by origin. If offset is positive, the new position is required to follow the position specified by origin by the number of bytes specified by offset.
W X Y
How and When to Override
Z
If you intend to use a file as a backing store for a stream implementation, you are required to override System.IO.Stream.Seek to set the System.IO.Stream.Position property 2726
Contents | Index
System.IO
Stream Seek() Method
one byte beyond the end of the stream. The position cannot be set to more than one byte beyond the end of the stream. Classes derived from System.IO.Stream that support seeking are required to override this method.
A B
Exceptions
C D
Exception
Condition
System.NotSupportedException
The stream does not support seeking, such as if the stream is constructed from a pipe or console output.
System.ObjectDisposedException
The current System.IO.Stream is closed.
G
System.IO.IOException
An I/O error has occurred.
H
E F
I J
Example
K
using System; using System.IO; using System.Text;
L M
namespace Samples { public class FileStreamSeek { public static void Main() { string s = "filestream.txt"; using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate, FileAccess.Write)) { Console.WriteLine("FileStream opened on {0} ", fs.Name); string ds = String.Format("Written at: {0}\n", DateTime.Now.ToString()); char[] chars = ds.ToCharArray(); UTF8Encoding e = (UTF8Encoding) Encoding.UTF8; int count = e.GetByteCount(chars, 0, chars.Length); Byte[] bytes = new Byte[count]; e.GetBytes(chars, 0, chars.Length, bytes, 0); fs.Seek(0, SeekOrigin.End); Console.WriteLine("Position: {0}", fs.Position); fs.Write(bytes, 0, bytes.Length); fs.Seek(0, SeekOrigin.Begin);
N O P Q R S T U V W X Y Z
2727
Contents | Index
Stream
System.IO
SetLength() Method
Console.WriteLine("Position: {0}", fs.Position); fs.Seek(0, SeekOrigin.End); Console.WriteLine("Position: {0}", fs.Position); }
A
} }
B }
C
The output is
D E
FileStream opened on C:\Books\BCL\Samples\System.IO\Stream\ Seek(System.Int32,System.IO.SeekOrigin)\filestream.txt Position: 137 Position: 0 Position: 171
F G H I
Stream.SetLength(System.Int64) Method
J
[ILASM]
K
.method public hidebysig virtual abstract void SetLength(int64 value)
L
[C#]
public abstract void SetLength(long value)
M N
Summary
O
Sets the length of the current stream.
P
Parameters
Q R
Parameter
Description
value
A System.Int64 that specifies the desired length of the current stream in bytes.
S T U V
Description
W
[Note: Use the System.IO.Stream.CanWrite property to determine whether the current instance supports writing, and the System.IO.Stream.CanSeek property to determine whether seeking is supported.]
X Y Z
2728
Contents | Index
System.IO
Stream SetLength() Method
Behaviors If the specified value is less than the current length of the stream, the stream is truncated. If the specified value is larger than the current length of the stream, the stream is expanded. If the stream is expanded, the contents of the stream between the old and the new length are initialized to zeros.
A B C
Default
D
There is no default implementation.
E
How and When to Override
F
Classes derived from System.IO.Stream are required to support both writing and seeking for System.IO.Stream.SetLength to work.
G H I
Exceptions
J
Exception
Condition
System.NotSupportedException
The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output.
System.ObjectDisposedException
The current System.IO.Stream is closed.
System.IO.IOException
An I/O error occurred.
K L M N O P Q
Example
R
using System; using System.IO; using System.Text;
S T U
namespace Samples { public class FileStreamSetLength { public static void Main() { string s = "filestream.txt"; using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate, FileAccess.Write)) { Console.WriteLine("FileStream opened on {0} ", fs.Name);
V W X Y Z
2729
Contents | Index
Stream
System.IO
Write() Method
if(fs.CanWrite && fs.CanSeek) { Console.WriteLine("Length is : {0}", fs.Length); fs.SetLength(fs.Length + 42); Console.WriteLine("Length is : {0}", fs.Length); }
A B }
C
} }
D
}
E
The output is
F FileStream opened on C:\Books\BCL\Samples\System.IO\Stream\ SetLength(System.Int64)\filestream.txt Length is : 42 Length is : 84
G H I J
Stream.Write(System.Byte[], System.Int32, System.Int32) Method
K
[ILASM]
L
.method public hidebysig virtual abstract void Write(class System.Byte[] buffer, int32 offset, int32 count)
M
[C#]
N
public abstract void Write(byte[] buffer, int offset, int count)
O P
Summary
Q
Writes a sequence of bytes to the current stream and advances the current position within the current stream by the number of bytes written.
R
Parameters
S T
Parameter
Description
buffer
A System.Byte array containing the data to write.
offset
A System.Int32 that specifies the zero-based byte offset in buffer at which to begin copying bytes to the current stream.
count
A System.Int32 that specifies the number of bytes to be written to the current stream.
U V W X Y Z
2730
Contents | Index
System.IO
Stream Write() Method
Description [Note: Use the System.IO.Stream.CanWrite property to determine whether the current instance supports writing.] A
Behaviors
B
If the write operation is successful, the position within the stream advances by the number of bytes written. If an exception occurs, the position within the stream remains unchanged.
C D E
Exceptions
F
Exception
Condition
System.ArgumentException
(offset + count ) is greater than the length of buffer.
H
System.ArgumentNullException
buffer is null.
J
System.ArgumentOutOfRangeException
offset or count is negative.
K
System.IO.IOException
An I/O error occurred.
System.NotSupportedException
The stream does not support writing.
G
I
L M N O
Example using using using using
P
System; System.IO; System.Text; System.Threading;
Q R S
namespace Samples { public class FileStreamWrite { public static void Main() { string filename = "filestream.txt"; using(FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write)) { string s = DateTime.Now.ToString(); UTF8Encoding e = new UTF8Encoding(); int count = e.GetByteCount(s);
T U V W X Y Z
2731
Contents | Index
Stream
System.IO
WriteByte() Method
Byte[] bytes = new Byte[count]; e.GetBytes(s, 0, bytes.Length, bytes, 0); fs.Write(bytes, 0, bytes.Length); }
A
} }
B }
C
The output is
D E
FileStream opened on C:\Books\BCL\Samples\System.IO\Stream\ Write(System.Byte[],System.Int32,System.Int32)\filestream.txt
F G H
Stream.WriteByte(System.Byte) Method
I
[ILASM]
.method public hidebysig virtual void WriteByte(unsigned int8 value)
J
[C#]
public virtual void WriteByte(byte value)
K L
Summary
M
Writes a System.Byte to the current position in the stream and advances the position within the stream by one byte.
N O
Parameters
P Q R
Parameter
Description
value
The System.Byte to write to the stream.
S T
Description
U
[Note: Use the System.IO.Stream.CanWrite property to determine whether the current instance supports writing.]
V W X Y Z
2732
Contents | Index
System.IO
Stream WriteByte() Method
Exceptions Exception
Condition
System.NotSupportedException
The stream does not support writing.
System.ObjectDisposedException
The stream is closed.
C
System.IO.IOException
An I/O error has occurred.
D
A B
E F
Example using using using using
G
System; System.IO; System.Text; System.Threading;
H I J
namespace Samples { public class FileStreamWrite { public static void Main() { string filename = "filestream.txt"; using(FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write)) { Console.WriteLine("FileStream opened on {0} ", fs.Name); string s = DateTime.Now.ToString(); foreach(char c in s) { fs.WriteByte(Convert.ToByte(c)); } } } } }
K L M N O P Q R S T U V W
The output is
X Y
FileStream opened on C:\Books\BCL\Samples\System.IO\Stream\ WriteByte(System.Byte)\filestream.txt
Z
2733
Contents | Index
Stream
System.IO
Dispose() Method
IDisposable.Dispose() Method [ILASM]
.method private final hidebysig virtual void System.IDisposable.Dispose()
A
[C#]
void IDisposable.Dispose()
B C
Summary
D
Implemented to support the System.IDisposable interface. [Note: For more information, see System.IDisposable.Dispose.]
E F G H I J K L M N O P Q R S T U V W X Y Z
2734
Contents | Index
System.IO StreamReader
BCL
Object
A
MarshalByRefObject TextReader
B
IDisposable
StreamReader
C D
Summary
E
Implements a System.IO.Stream that reads characters from a byte stream in a particular encoding.
F G
Type Summary
H
public class StreamReader : TextReader { // Constructors public StreamReader (string path); public StreamReader (string path, bool detectEncodingFromByteOrderMarks); public StreamReader (string path, Encoding encoding); public StreamReader (string path, Encoding encoding, bool detectEncodingFromByteOrderMarks); public StreamReader (string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize); public StreamReader (Stream stream); public StreamReader (Stream stream, bool detectEncodingFromByteOrderMarks); public StreamReader (Stream stream, Encoding encoding); public StreamReader (Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks); public StreamReader (Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize);
I J K L M N O P Q R S T U
// Fields MS public static readonly StreamReader Null;
V W
// Properties public virtual Stream BaseStream { get; } public virtual Encoding CurrentEncoding { get; }
X Y
// Methods public override void Close (); public void DiscardBufferedData (); protected override void Dispose (bool disposing);
Z
2735
Contents | Index
StreamReader
System.IO
StreamReader Class
public override int Peek (); public override int Read (); public override int Read (char[] buffer, int index, int count); public override string ReadLine (); public override string ReadToEnd ();
A B }
C D
KG One of the most useful I/O classes, with one of the most confusing names. FileReader would have helped users find this class a lot more easily.
E F G
Description
H
The System.IO.StreamReader class is designed for character input in a particular System.Text.Encoding, whereas subclasses of System.IO.Stream are designed for byte input and output. [Note: System.IO.StreamReader defaults to UTF-8 encoding unless specified otherwise, instead of defaulting to the ANSI code page for the current system. UTF-8 handles Unicode characters correctly and provides consistent results on localized versions of the operating system. When reading from a System.IO.Stream, it is more efficient to use a buffer that is the same size as the internal buffer of the stream. By default, a System.IO.StreamReader is not thread safe. For a thread-safe wrapper, see System.IO.TextReader.Synchronized.]
I J K L M N O P
Example
Q
using System; using System.IO; using System.Text;
R S
namespace Samples { public class StreamReaderSample { public static void Main() { string s = "streamreader.txt"; using(StreamReader sr = new StreamReader(s)) { DisplayInformationAboutStream(sr); Console.WriteLine(sr.ReadLine()); Console.WriteLine((Char)sr.Peek()); Console.WriteLine(sr.ReadLine()); }
T U V W X Y Z
2736
Contents | Index
System.IO
StreamReader StreamReader Class
Byte[] bytes = {72, 101, 108, 108, 111, (byte) '\n', 87, 111, 114, 108, 100}; MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length); using(StreamReader sr = new StreamReader(ms)) { DisplayInformationAboutStream(sr); Console.WriteLine(sr.ReadLine()); Console.WriteLine((Char)sr.Peek()); Console.WriteLine(sr.ReadLine()); }
A B C D E F
} public static void DisplayInformationAboutStream( StreamReader sr) { Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding); Console.WriteLine("Can read from stream: {0}", sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sr.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek); }
G H I J K L M N
} }
O
The output is
P Q
CurrentEncoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: False Can seek in stream: True Hello world! G Goodbye world! CurrentEncoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: True Can seek in stream: True Hello W World
R S T U V W X Y Z
2737
Contents | Index
StreamReader
System.IO
StreamReader() Constructor
StreamReader(System.String) Constructor [ILASM]
public rtspecialname specialname instance void .ctor(string path)
A
[C#]
public StreamReader(string path)
B C
Summary
D
Constructs and initializes a new instance of the System.IO.StreamReader class for the specified file name.
E F
Parameters
G H
Parameter
Description
path
A System.String that specifies the complete file path to read.
I J K
Description
L
This constructor initializes the System.IO.StreamReader.CurrentEncoding property to System.Text.UTF8Encoding, and the internal buffer to the default size. [Note: The default buffer size is implementation defined.] [Note: path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device. For information on the valid format and characters for path strings, see System.IO.Path.]
M N O P Q R
Exceptions
S T U
Exception
Condition
System.IO.IOException
path is in an invalid format or contains invalid characters.
System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
System.IO.FileNotFoundException
The file specified in path was not found.
System.ArgumentException
path is an empty string ("").
System.ArgumentNullException
path is null.
V W X Y Z
2738
Contents | Index
System.IO
StreamReader StreamReader() Constructor
Example using System; using System.IO; using System.Text;
A
namespace Samples { public class StreamReaderConstructor { public static void Main() { string s = "streamreader.txt"; using(StreamReader sr = new StreamReader(s)) { DisplayInformationAboutStream(sr); } } public static void DisplayInformationAboutStream( StreamReader sr) { Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding); Console.WriteLine("Can read from stream: {0}", sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sr.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek); } } }
B C D E F G H I J K L M N O P Q
The output is
R
CurrentEncoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: False Can seek in stream: True
S T U
StreamReader(System.String, System.Boolean) Constructor
V
[ILASM]
W
public rtspecialname specialname instance void .ctor(string path, bool detectEncodingFromByteOrderMarks)
X
[C#]
Y
public StreamReader(string path, bool detectEncodingFromByteOrderMarks)
Z
Summary Constructs and initializes a new instance of the System.IO.StreamReader class for the specified file name, with the specified byte order mark detection option. 2739
Contents | Index
StreamReader
System.IO
StreamReader() Constructor
Parameters Parameter
Description
path
A System.String that specifies the complete file path to read.
detectEncodingFromByteOrderMarks
A System.Boolean value that indicates whether the new System.IO.StreamReader is required to look for byte order marks at the beginning of the stream. Specify true to enable detection of byte order marks; otherwise, specify false.
A B C D E F
Description
G
This constructor initializes the System.IO.StreamReader.CurrentEncoding property to System.Text.UTF8Encoding, and the internal buffer to the default size. [Note: The default buffer size is implementation defined.] If requested, the current constructor detects the encoding by examining the first three bytes of the stream. The constructor automatically recognizes UTF-8, little-endian Unicode, and big-endian Unicode text if the file starts with the appropriate byte order marks. Otherwise, UTF-8 encoding is used. See the System.Text.Encoding.GetPreamble method for more information. [Note: path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device. For information on the valid format and characters for path strings, see System.IO.Path.]
H I J K L M N O P Q
Exceptions
R
Exception
Condition
System.IO.IOException
path is in an invalid format or contains invalid characters.
System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
X
System.IO.FileNotFoundException
The file specified in path was not found.
Y
System.ArgumentException
path is an empty string ("").
Z
System.ArgumentNullException
path is null.
S T U V W
2740
Contents | Index
System.IO
StreamReader StreamReader() Constructor
Example using System; using System.IO; using System.Text;
A B
namespace Samples { public class StreamReaderConstructor { public static void Main() { string s = "streamreader.txt"; using(StreamReader sr = new StreamReader(s, false)) { DisplayInformationAboutStream(sr); } } public static void DisplayInformationAboutStream( StreamReader sr) { Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding); Console.WriteLine("Can read from stream: {0}", sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sr.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek); } } }
C D E F G H I J K L M N O P Q R
The output is
S
CurrentEncoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: False Can seek in stream: True
T U V W
StreamReader(System.String, System.Text.Encoding) Constructor
X
[ILASM]
Y
public rtspecialname specialname instance void .ctor(string path, class System.Text.Encoding encoding)
Z
[C#]
public StreamReader(string path, Encoding encoding)
2741
Contents | Index
StreamReader
System.IO
StreamReader() Constructor
Summary Constructs and initializes a new instance of the System.IO.StreamReader class for the specified file name and with the specified character encoding. A
Parameters
B C
Parameter
Description
E
path
A System.String that specifies the complete file path to read.
F
encoding
A System.Text.Encoding that specifies the character encoding to use.
D
G H
Description
I
This constructor initializes the System.IO.StreamReader.CurrentEncoding property using encoding, and the internal buffer to the default size. [Note: The default buffer size is implementation defined.] [Note: path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device. For information on the valid format and characters for path strings, see System.IO.Path.]
J K L M N O
Exceptions
P
Exception
Condition
System.IO.IOException
path is in an invalid format or contains invalid characters.
System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
System.IO.FileNotFoundException
The file specified in path was not found.
W
System.ArgumentException
path is an empty string ("").
X
System.ArgumentNullException
path or encoding is null.
Q R S T U V
Y Z
2742
Contents | Index
System.IO
StreamReader StreamReader() Constructor
Example using System; using System.IO; using System.Text;
A
namespace Samples { public class StreamReaderConstructor { public static void Main() { string s = "streamreader.txt"; using(StreamReader sr = new StreamReader(s, System.Text.Encoding.ASCII)) { DisplayInformationAboutStream(sr); } } public static void DisplayInformationAboutStream( StreamReader sr) { Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding); Console.WriteLine("Can read from stream: {0}", sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sr.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek); } } }
B C D E F G H I J K L M N O P Q
The output is
R S
CurrentEncoding: System.Text.ASCIIEncoding Can read from stream: True Can write to stream: False Can seek in stream: True
T U V
StreamReader(System.String, System.Text.Encoding, System.Boolean) Constructor
W X
[ILASM]
Y
public rtspecialname specialname instance void .ctor(string path, class System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks)
Z
[C#]
public StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks)
2743
Contents | Index
StreamReader
System.IO
StreamReader() Constructor
Summary Constructs and initializes a new instance of the System.IO.StreamReader class for the specified file name, with the specified character encoding and byte order mark detection option.
A B
Parameters
C D
Parameter
Description
path
A System.String that specifies the complete file path to read.
encoding
A System.Text.Encoding that specifies the character encoding to use.
detectEncodingFromByteOrderMarks
A System.Boolean value that indicates whether the new System.IO.StreamReader is required to look for byte order marks at the beginning of the stream. Specify true to enable detection of byte order marks; otherwise, specify false.
E F G H I J K L
Description
M
This constructor initializes the System.IO.StreamReader.CurrentEncoding property using encoding, and the internal buffer to the default size. [Note: The default buffer size is implementation defined.] If requested, the current constructor detects the encoding by examining the first three bytes of the stream. The constructor automatically recognizes UTF-8, little-endian Unicode, and big-endian Unicode text if the file starts with the appropriate byte order marks. Otherwise, the user-provided encoding is used. See the System.Text.Encoding.GetPreamble method for more information. [Note: path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device. For information on the valid format and characters for path strings, see System.IO.Path.]
N O P Q R S T U V W X Y Z
2744
Contents | Index
System.IO
StreamReader StreamReader() Constructor
Exceptions Exception
Condition
System.IO.IOException
path is in an invalid format or contains invalid characters.
System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
D
System.IO.FileNotFoundException
The file specified in path was not found.
E
System.ArgumentException
path is an empty string ("").
F
System.ArgumentNullException
path or encoding is null.
G
A B C
H
Example
I
using System; using System.IO; using System.Text;
J K L
namespace Samples { public class StreamReaderConstructor { public static void Main() { string s = "streamreader.txt"; using(StreamReader sr = new StreamReader(s, System.Text.Encoding.ASCII, false)) { DisplayInformationAboutStream(sr); } } public static void DisplayInformationAboutStream( StreamReader sr) { Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding); Console.WriteLine("Can read from stream: {0}", sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sr.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek); } } }
M N O P Q R S T U V W X Y Z
2745
Contents | Index
StreamReader
System.IO
StreamReader() Constructor
The output is CurrentEncoding: System.Text.ASCIIEncoding Can read from stream: True Can write to stream: False Can seek in stream: True
A B C D E
StreamReader(System.String, System.Text.Encoding, System.Boolean, System.Int32) Constructor
F
[ILASM]
public rtspecialname specialname instance void .ctor(string path, class System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks, int32 bufferSize)
G H
[C#]
I
public StreamReader(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
J K
Summary
L
Constructs and initializes a new instance of the System.IO.StreamReader class for the specified file name, with the specified character encoding, byte order mark detection option, and buffer size.
M N O
Parameters
P Q R S
Parameter
Description
path
A System.String that specifies the complete file path to read.
encoding
A System.Text.Encoding that specifies the character encoding to use.
detectEncodingFromByteOrderMarks
A System.Boolean value that indicates whether the new System.IO.StreamReader is required to look for byte order marks at the beginning of the stream. Specify true to enable detection of byte order marks; otherwise, specify false.
bufferSize
A System.Int32 that specifies the minimum buffer size, in number of 16-bit characters. If less than the minimum allowable size (128 characters), the minimum allowable size is used.
T U V W X Y Z
2746
Contents | Index
System.IO
StreamReader StreamReader() Constructor
Description This constructor initializes the System.IO.StreamReader.CurrentEncoding property using encoding. If requested, the current constructor detects the encoding by examining the first three bytes of the stream. The constructor automatically recognizes UTF-8, little-endian Unicode, and big-endian Unicode text if the file starts with the appropriate byte order marks. Otherwise, the user-provided encoding is used. See the System.Text.Encoding.GetPreamble method for more information. [Note: path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device. When reading from a System.IO.Stream, it is more efficient to use a buffer that is the same size as the internal buffer of the stream. For information on the valid format and characters for path strings, see System.IO.Path.]
A B C D E F G H I
Exceptions
J
Exception
Condition
K
path is in an invalid format or contains invalid characters.
L
System.IO.IOException
M
System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
System.IO.FileNotFoundException
The file specified in path was not found.
System.ArgumentException
path is an empty string ("").
Q
System.ArgumentNullException
path or encoding is null.
R
System.ArgumentOutOfRangeException
buffersize is less than or equal to zero.
N O P
S T U
Example
V
using System; using System.IO; using System.Text;
W X Y
namespace Samples { public class StreamReaderConstructor {
Z
2747
Contents | Index
StreamReader
System.IO
StreamReader() Constructor
public static void Main() { string s = "streamreader.txt"; using(StreamReader sr = new StreamReader(s, System.Text.Encoding.ASCII, false, 512)) { DisplayInformationAboutStream(sr); } } public static void DisplayInformationAboutStream( StreamReader sr) { Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding); Console.WriteLine("Can read from stream: {0}", sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sr.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek); }
A B C D E F G H I J K L
} }
M N
The output is
O CurrentEncoding: System.Text.ASCIIEncoding Can read from stream: True Can write to stream: False Can seek in stream: True
P Q R S
StreamReader(System.IO.Stream) Constructor
T [ILASM]
U
public rtspecialname specialname instance void .ctor(class System.IO.Stream stream)
V
[C#]
W
public StreamReader(Stream stream)
X
Summary
Y
Constructs and initializes a new instance of the System.IO.StreamReader class for the specified stream.
Z
2748
Contents | Index
System.IO
StreamReader StreamReader() Constructor
Parameters Parameter
Description
stream
The System.IO.Stream to read.
A B C
Description
D
This constructor initializes the System.IO.StreamReader.CurrentEncoding property to System.Text.UTF8Encoding, the System.IO.StreamReader.BaseStream property using stream, and the internal buffer to the default size. [Note: The default buffer size is implementation dependent.]
E F G H
Exceptions
I
Exception
Condition
System.ArgumentException
stream does not support reading.
System.ArgumentNullException
stream is null.
J K L M N
Example
O
using System; using System.IO; using System.Text;
P Q R
namespace Samples { public class StreamReaderConstructor { public static void Main() { string s = "filestream.txt"; FileStream fs = new FileStream(s, FileMode.OpenOrCreate); using(StreamReader sr = new StreamReader(fs)) { DisplayInformationAboutStream(sr); Console.WriteLine(sr.ReadLine()); } } public static void DisplayInformationAboutStream( StreamReader sr)
S T U V W X Y Z
2749
Contents | Index
StreamReader
System.IO
StreamReader() Constructor
{ Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding); Console.WriteLine("Can read from stream: {0}", sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sr.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek);
A B C D
} }
E }
F
The output is
G H
CurrentEncoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: True Can seek in stream: True Hello world!
I J K L M
StreamReader(System.IO.Stream, System.Boolean) Constructor
N
[ILASM]
O
public rtspecialname specialname instance void .ctor(class System.IO.Stream stream, bool detectEncodingFromByteOrderMarks) [C#]
P
public StreamReader(Stream stream, bool detectEncodingFromByteOrderMarks)
Q R
Summary
S
Constructs and initializes a new instance of the System.IO.StreamReader class for the specified stream, with the specified byte order mark detection option.
T
Parameters
U V W X
Parameter
Description
stream
The stream to read.
detectEncodingFromByteOrderMarks
A System.Boolean value that indicates whether the new System.IO.StreamReader is required to look for byte order marks at the beginning of the stream. Specify true to enable detection of byte order marks; otherwise, specify false.
Y Z
2750
Contents | Index
System.IO
StreamReader StreamReader() Constructor
Description This constructor initializes the System.IO.StreamReader.CurrentEncoding property to System.Text.UTF8Encoding, the System.IO.StreamReader.BaseStream property using stream, and the internal buffer to the default size. [Note: The default buffer size is implementation defined.] If requested, the current constructor detects the encoding by examining the first three bytes of the stream. The constructor automatically recognizes UTF-8, little-endian Unicode, and bigendian Unicode text if the file starts with the appropriate byte order marks. Otherwise, UTF-8 encoding is used. For more information, see the System.Text.Encoding.GetPreamble method.
A B C D E F G
Exceptions
H
Exception
Condition
System.ArgumentException
stream does not support reading.
J
System.ArgumentNullException
stream is null.
K
I
L M
Example
N
using System; using System.IO; using System.Text;
O P
namespace Samples { public class StreamReaderConstructor { public static void Main() { string s = "filestream.txt"; FileStream fs = new FileStream(s, FileMode.OpenOrCreate); using(StreamReader sr = new StreamReader(fs, false)) { DisplayInformationAboutStream(sr); Console.WriteLine(sr.ReadLine()); } } public static void DisplayInformationAboutStream( StreamReader sr) { Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding);
Q R S T U V W X Y Z
2751
Contents | Index
StreamReader
System.IO
StreamReader() Constructor
Console.WriteLine("Can read from stream: {0}", sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sr.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek);
A B }
C
} }
D
The output is
E F
CurrentEncoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: True Can seek in stream: True Hello world!
G H I J K
StreamReader(System.IO.Stream, System.Text.Encoding) Constructor
L
[ILASM]
M
public rtspecialname specialname instance void .ctor(class System.IO.Stream stream, class System.Text.Encoding encoding)
N
[C#]
public StreamReader(Stream stream, Encoding encoding)
O P
Summary
Q
Constructs and initializes a new instance of the System.IO.StreamReader class for the specified stream with the specified character encoding.
R S
Parameters
T U V W
Parameter
Description
stream
The System.IO.Stream to read.
encoding
A System.Text.Encoding that specifies the character encoding to use.
X Y
Description
Z
This constructor initializes the System.IO.StreamReader.CurrentEncoding property using encoding, the System.IO.StreamReader.BaseStream property using
2752
Contents | Index
System.IO
StreamReader StreamReader() Constructor
stream, and the internal buffer to the default size. [Note: The default buffer size is implementation defined.] A
Exceptions
B
Exception
Condition
System.ArgumentException
stream does not support reading.
System.ArgumentNullException
stream or encoding is null.
C D E F G
Example
H
using System; using System.IO; using System.Text;
I J
namespace Samples { public class StreamReaderConstructor { public static void Main() { string s = "filestream.txt"; FileStream fs = new FileStream(s, FileMode.OpenOrCreate); using(StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8)) { DisplayInformationAboutStream(sr); Console.WriteLine(sr.ReadLine()); } } public static void DisplayInformationAboutStream( StreamReader sr) { Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding); Console.WriteLine("Can read from stream: {0}", sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sr.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek); } } }
K L M N O P Q R S T U V W X Y Z
2753
Contents | Index
StreamReader
System.IO
StreamReader() Constructor
The output is CurrentEncoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: True Can seek in stream: True Hello world!
A B C D
StreamReader(System.IO.Stream, System.Text.Encoding, System.Boolean) Constructor
E F
[ILASM]
G
public rtspecialname specialname instance void .ctor(class System.IO.Stream stream, class System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks)
H
[C#]
I
public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks)
J K
Summary
L
Constructs and initializes a new instance of the System.IO.StreamReader class for the specified stream, with the specified character encoding and byte order mark detection option.
M N O
Parameters
P Q R S
Parameter
Description
stream
The System.IO.Stream to read.
encoding
A System.Text.Encoding that specifies the character encoding to use.
detectEncodingFromByteOrderMarks
A System.Boolean value that indicates whether the new System.IO.StreamReader is required to look for byte order marks at the beginning of the stream. Specify true to enable detection of byte order marks; otherwise, specify false.
T U V W X
Description
Y
This constructor initializes the System.IO.StreamReader.CurrentEncoding property using encoding, the System.IO.StreamReader.BaseStream property using stream, and the internal buffer to the default size. [Note: The default buffer size is implementation defined.]
Z
2754
Contents | Index
System.IO
StreamReader StreamReader() Constructor
If requested, this constructor detects the encoding by examining the first three bytes of stream. This constructor automatically recognizes UTF-8, little-endian Unicode, and bigendian Unicode text if the stream starts with the appropriate byte order marks. Otherwise, the user-provided encoding is used. See the System.Text.Encoding.GetPreamble method for more information.
A B C
Exceptions
D
Exception
Condition
E
System.ArgumentException
stream does not support reading.
F
System.ArgumentNullException
stream or encoding is null.
G H I
Example
J
using System; using System.IO; using System.Text;
K L
namespace Samples { public class StreamReaderConstructor { public static void Main() { string s = "filestream.txt"; FileStream fs = new FileStream(s, FileMode.OpenOrCreate); using(StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8, false)) { DisplayInformationAboutStream(sr); Console.WriteLine(sr.ReadLine()); } } public static void DisplayInformationAboutStream( StreamReader sr) { Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding); Console.WriteLine("Can read from stream: {0}", sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sr.BaseStream.CanWrite);
M N O P Q R S T U V W X Y Z
2755
Contents | Index
StreamReader
System.IO
StreamReader() Constructor
Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek); } }
A
}
B
The output is
C CurrentEncoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: True Can seek in stream: True Hello world!
D E F G
StreamReader(System.IO.Stream, System.Text.Encoding, System.Boolean, System.Int32) Constructor
H I
[ILASM]
J K
public rtspecialname specialname instance void .ctor(class System.IO.Stream stream, class System.Text.Encoding encoding, bool detectEncodingFromByteOrderMarks, int32 bufferSize)
L
[C#]
M
public StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)
N
Summary
O
Constructs and initializes a new instance of the System.IO.StreamReader class for the specified stream, with the specified character encoding, byte order mark detection option, and buffer size.
P Q R
Parameters
S T U V
Parameter
Description
stream
The System.IO.Stream to read.
encoding
A System.Text.Encoding that specifies the character encoding to use.
detectEncodingFromByteOrderMarks
A System.Boolean value that indicates whether the new System.IO.StreamReader is required to look for byte order marks at the beginning of the stream. Specify true to enable detection of byte order marks; otherwise, specify false.
bufferSize
A System.Int32 that specifies the minimum buffer size, in number of 16-bit characters. If bufferSize is less than the minimum allowable size (128 characters), the minimum allowable size is used.
W X Y Z
2756
Contents | Index
System.IO
StreamReader StreamReader() Constructor
Description This constructor initializes the System.IO.StreamReader.CurrentEncoding property using the encoding parameter and the System.IO.StreamReader.BaseStream property using the stream parameter. If requested, this constructor detects the encoding by examining the first three bytes of the stream. The constructor automatically recognizes UTF-8, little-endian Unicode, and big-endian Unicode text if the file starts with the appropriate byte order marks. Otherwise, the user-provided encoding is used. For more information, see the System.Text.Encoding.GetPreamble method. [Note: When reading from a System.IO.Stream, it is more efficient to use a buffer that is the same size as the internal buffer of the stream.]
A B C D E F G
Exceptions
H
Exception
Condition
System.ArgumentException
stream does not support reading.
System.ArgumentNullException
stream or encoding is null.
System.ArgumentOutOfRangeException
bufferSize is less than or equal to zero.
I J K L M N
Example
O
using System; using System.IO; using System.Text;
P Q R
namespace Samples { public class StreamReaderConstructor { public static void Main() { string s = "filestream.txt"; FileStream fs = new FileStream(s, FileMode.OpenOrCreate); using(StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8, false, 512)) { DisplayInformationAboutStream(sr); Console.WriteLine(sr.ReadLine()); } }
S T U V W X Y Z
2757
Contents | Index
StreamReader
System.IO
Null Field
public static void DisplayInformationAboutStream( StreamReader sr) { Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding); Console.WriteLine("Can read from stream: {0}", sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sr.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek); }
A B C D E }
F
}
G
The output is
H
CurrentEncoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: True Can seek in stream: True Hello world!
I J K L M
StreamReader.Null Field
N
[ILASM]
O
.field public static initOnly class System.IO.StreamReader Null
P
public static readonly StreamReader Null
[C#]
Q
Summary
R
A StreamReader around an empty stream.
S
Description
T
When read methods are invoked on StreamReader.Null, zero is always returned. When System.IO.StreamReader.ReadLine is invoked on StreamReader.Null, null is returned.
U V W X
StreamReader.BaseStream Property
Y
[ILASM]
Z
.property class System.IO.Stream BaseStream { public hidebysig virtual specialname class System.IO.Stream get_BaseStream() } [C#]
public virtual Stream BaseStream { get; }
2758
Contents | Index
System.IO
StreamReader BaseStream Property
Summary Gets the underlying stream.
Property Value
A
The underlying System.IO.Stream which the current System.IO.StreamReader instance is reading.
B C D
Example
E
using System; using System.IO; using System.Text;
F G
namespace Samples { public class StreamReaderBaseStream { public static void Main() { string s = "streamreader.txt"; using(StreamReader sr = new StreamReader(s)) { DisplayInformationAboutStream(sr); Console.WriteLine(sr.ReadLine()); sr.BaseStream.Seek(0, SeekOrigin.End); Console.WriteLine(sr.ReadLine()); sr.BaseStream.Seek(0, SeekOrigin.Begin); Console.WriteLine(sr.ReadLine()); sr.BaseStream.Seek(0, SeekOrigin.End); sr.DiscardBufferedData(); Console.WriteLine(sr.ReadLine()); } } public static void DisplayInformationAboutStream( StreamReader sr) { Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding); Console.WriteLine("Can read from stream: {0}", sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sr.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek); } } }
H I J K L M N O P Q R S T U V W X Y Z
2759
Contents | Index
StreamReader
System.IO
CurrentEncoding Property
The output is CurrentEncoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: False Can seek in stream: True Hello world! Goodbye world! Hello world!
A B C D E F
StreamReader.CurrentEncoding Property
G
[ILASM]
H
.property class System.Text.Encoding CurrentEncoding { public hidebysig virtual specialname class System.Text.Encoding get_CurrentEncoding() }
I
[C#]
public virtual Encoding CurrentEncoding { get; }
J K
Summary
L
Gets the current character encoding that the current System.IO.StreamReader is using.
M
Description
N
The value returned by this property might change after the first call to a System.IO.StreamReader.Read method if encoding auto detection was specified to the constructor for the current instance.
O P Q
Example
R
using System; using System.IO; using System.Text;
S T
namespace Samples { public class StreamReaderCurrentEncoding { public static void Main() { string s = "streamreader.txt"; using(StreamReader sr = new StreamReader(s)) { DisplayInformationAboutStream(sr); } }
U V W X Y Z
2760
Contents | Index
System.IO
StreamReader Close() Method
public static void DisplayInformationAboutStream( StreamReader sr) { Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding); Console.WriteLine("Can read from stream: {0}", sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sr.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek); }
A B C D E F
} }
G
The output is
H I
CurrentEncoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: False Can seek in stream: True
J K L M
StreamReader.Close() Method
N [ILASM]
O
.method public hidebysig virtual void Close() [C#]
P
public override void Close()
Q
Summary
R
Closes the current instance of System.IO.StreamReader, releasing any system resources associated with it.
S T
Description
U
Following a call to this method, operations on the current instance might raise exceptions. [Note: This version of System.IO.StreamReader.Close is equivalent to System.IO.StreamReader.Dispose(true). This method overrides System.IO.TextReader.Close.]
V W X Y Z
2761
Contents | Index
StreamReader
System.IO
DiscardBufferedData() Method
Example using System; using System.IO; using System.Text;
A B
namespace Samples { public class StreamReaderClose { public static void Main() { string s = "streamreader.txt"; StreamReader sr = new StreamReader(s); DisplayInformationAboutStream(sr); sr.Close(); } public static void DisplayInformationAboutStream( StreamReader sr) { Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding); Console.WriteLine("Can read from stream: {0}", sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sr.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek); } } }
C D E F G H I J K L M N O P Q
The output is
R S
CurrentEncoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: False Can seek in stream: True
T U V W
StreamReader.DiscardBufferedData() Method
X [ILASM]
Y
.method public hidebysig instance void DiscardBufferedData() [C#]
Z
public void DiscardBufferedData()
2762
Contents | Index
System.IO
StreamReader DiscardBufferedData() Method
Summary Allows a System.IO.StreamReader to discard its buffered data.
Description
A
[Note: This method is useful when reading from a stream after seeking to a new position. If this method is not called and the internal buffer is not empty, a read attempt at the new location will first return data that is in the buffer before returning the text at the current position in the stream.]
B C D E
Example
F
using System; using System.IO; using System.Text;
G H
namespace Samples { public class StreamReaderDiscardBufferedData { public static void Main() { string s = "streamreader.txt"; using(StreamReader sr = new StreamReader(s)) { DisplayInformationAboutStream(sr); Console.WriteLine(sr.ReadLine()); sr.BaseStream.Seek(0, SeekOrigin.End); Console.WriteLine(sr.ReadLine()); sr.BaseStream.Seek(0, SeekOrigin.Begin); Console.WriteLine(sr.ReadLine()); sr.BaseStream.Seek(0, SeekOrigin.End); sr.DiscardBufferedData(); Console.WriteLine(sr.ReadLine()); } } public static void DisplayInformationAboutStream( StreamReader sr) { Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding); Console.WriteLine("Can read from stream: {0}", sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sr.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek); } } }
I J K L M N O P Q R S T U V W X Y Z
2763
Contents | Index
StreamReader
System.IO
Dispose() Method
The output is CurrentEncoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: False Can seek in stream: True Hello world! Goodbye world! Hello world!
A B C D E F
StreamReader.Dispose(System.Boolean) Method
G
[ILASM]
H
.method family hidebysig virtual void Dispose(bool disposing)
I
protected override void Dispose(bool disposing)
[C#]
J
Summary
K
Releases the unmanaged resources used by the System.IO.StreamReader and optionally releases the managed resources.
L M
Parameters
N O
Parameter
Description
disposing
true to release both managed and unmanaged resources; false to release only unmanaged resources.
P Q R S
Description
T
When the disposing parameter is true, this method releases all resources held by any managed objects that this System.IO.StreamReader references. This method invokes the Dispose() method of each referenced object. [Note: System.IO.StreamReader.Dispose may be called multiple times by other objects. When overriding System.IO.StreamReader.Dispose(System.Boolean), be careful not to reference objects that have been previously disposed in an earlier call to System.IO.StreamReader.Dispose. This method calls the dispose method of the base class, System.IO.TextReader.Dispose(disposing).]
U V W X Y Z
2764
Contents | Index
System.IO
StreamReader Peek() Method
StreamReader.Peek() Method [ILASM]
.method public hidebysig virtual int32 Peek() [C#]
A
public override int Peek()
B C
Summary
D
Returns the next character in the underlying stream without advancing the position of the System.IO.StreamReader in the stream.
E F
Return Value
G
The next character from the character source as a System.Int32, or –1 if at the end of the stream.
H I
Description
J
[Note: This method returns –1 when the end of the underlying stream is reached because a Unicode character can contain only values between hexadecimal 0x0000 to 0xFFFF (0 to 65535). This method overrides System.IO.TextReader.Peek.]
K L M
Exceptions
N
Exception
Condition
System.IO.IOException
An I/O error occurred.
O P Q R
Example
S
using System; using System.IO; using System.Text;
T U V
namespace Samples { public class StreamReaderPeek { public static void Main() { string s = "streamreader.txt"; using(StreamReader sr = new StreamReader(s)) { DisplayInformationAboutStream(sr);
W X Y Z
2765
Contents | Index
StreamReader
System.IO
Read() Method
Console.WriteLine(sr.ReadLine()); Console.WriteLine((Char)sr.Peek()); Console.WriteLine((Char)sr.Peek()); Console.WriteLine((Char)sr.Peek()); Console.WriteLine(sr.ReadLine());
A
} } public static void DisplayInformationAboutStream( StreamReader sr) { Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding); Console.WriteLine("Can read from stream: {0}", sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sr.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek); }
B C D E F G H I J }
K
}
L
The output is
M CurrentEncoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: False Can seek in stream: True Hello world! G G G Goodbye world!
N O P Q R S T
StreamReader.Read() Method
U
[ILASM]
V
.method public hidebysig virtual int32 Read()
W
[C#]
public override int Read()
X Y
Summary
Z
Reads the next character from the input stream and advances the character position by one character.
2766
Contents | Index
System.IO
StreamReader Read() Method
Return Value The next character from the character source represented as a System.Int32, or –1 if at the end of the stream. A
Description
B
[Note: This method returns –1 when the end of the underlying stream is reached because a Unicode character can contain only values between hexadecimal 0x0000 to 0xFFFF (0 to 65535). This method overrides System.IO.TextReader.Read.]
C D E
Exceptions Exception
F G
Condition
H System.IO.IOException
An I/O error occurred.
I J
Example
K
using System; using System.IO; using System.Text;
L M N
namespace Samples { public class StreamReaderRead { public static void Main() { string s = "streamreader.txt"; using(StreamReader sr = new StreamReader(s)) { DisplayInformationAboutStream(sr); Console.WriteLine(sr.ReadLine()); Console.WriteLine((Char)sr.Read()); Console.WriteLine((Char)sr.Read()); Console.WriteLine((Char)sr.Read()); Console.WriteLine(sr.ReadLine()); } } public static void DisplayInformationAboutStream( StreamReader sr) { Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding); Console.WriteLine("Can read from stream: {0}",
O P Q R S T U V W X Y Z
2767
Contents | Index
StreamReader
System.IO
Read() Method
sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sr.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek);
A }
B }
C
}
D
The output is
E CurrentEncoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: False Can seek in stream: True Hello world! G o o dbye world!
F G H I J K L
StreamReader.Read(System.Char[], System.Int32, System.Int32) Method
M
[ILASM]
N
.method public hidebysig virtual int32 Read(class System.Char[] buffer, int32 index, int32 count)
O
[C#]
P
public override int Read(char[] buffer, int index, int count)
Q
Summary
R
Reads a maximum of count characters from the current stream into buffer, beginning at index.
S T
Parameters
U V
Parameter
Description
buffer
A System.Char array. When this method returns, contains the specified character array with the values between index and (index + count – 1) replaced by the characters read from the current instance.
index
A System.Int32 that specifies the index of buffer at which to begin writing.
count
A System.Int32 that specifies the maximum number of characters to read.
W X Y Z
2768
Contents | Index
System.IO
StreamReader Read() Method
Return Value A System.Int32 containing the number of characters that have been read, or zero if there are no more characters left to read. Can be less than count if the end of the stream has been reached.
A B
Description
C
[Note: This method returns after either count characters are read, or the end of the file is reached. System.IO.TextReader.ReadBlock is a blocking version of System.IO.StreamReader.Read. This method overrides System.IO.TextReader.Read.]
D E F
Exceptions
G H
Exception
Condition
System.ArgumentException
buffer.Length – index < count.
System.ArgumentNullException
buffer is null.
K
System.ArgumentOutOfRangeException
index or count is negative.
L
An I/O error occurred.
M
-or-
N
The current stream is closed.
O
System.IO.IOException
I J
P
Example
Q
using System; using System.IO; using System.Text;
R S T
namespace Samples { public class StreamReaderRead { public static void Main() { string s = "streamreader.txt"; using(StreamReader sr = new StreamReader(s)) { DisplayInformationAboutStream(sr); Char[] chars = new Char[10]; while(sr.Read(chars, 0, chars.Length) != 0) {
U V W X Y Z
2769
Contents | Index
StreamReader
System.IO
ReadLine() Method
foreach(char c in chars) Console.Write(c); } }
A
} public static void DisplayInformationAboutStream( StreamReader sr) { Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding); Console.WriteLine("Can read from stream: {0}", sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sr.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek); }
B C D E F G H I
} }
J K
The output is
L
CurrentEncoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: False Can seek in stream: True Hello world! Goodbye world!
M N O P Q
StreamReader.ReadLine() Method
R S
[ILASM]
T
[C#]
.method public hidebysig virtual string ReadLine() public override string ReadLine()
U V
Summary
W
Reads a line of characters from the current stream and returns the data as a string.
X
Return Value
Y
A System.String containing the next line from the input stream, or null if the end of the input stream is reached.
Z
2770
Contents | Index
System.IO
StreamReader ReadLine() Method
Description [Note: This method defines a line as a sequence of characters followed by a carriage return (hexadecimal 0x000d), a line feed (hexadecimal 0x000a), or System.Environment.NewLine. The returned string does not contain the terminating character(s). This method overrides System.IO.TextReader.ReadLine.]
A B C
Exceptions
D
Exception
Condition
E
System.IO.IOException
An I/O error occurred.
F
There is insufficient memory to allocate a buffer for the returned string.
G
System.OutOfMemoryException
H I
Example
J
using System; using System.IO; using System.Text;
K L M
namespace Samples { public class StreamReaderReadLine { public static void Main() { string s = "streamreader.txt"; using(StreamReader sr = new StreamReader(s)) { DisplayInformationAboutStream(sr); s = sr.ReadLine(); while(s!=null) { Console.WriteLine(s); s = sr.ReadLine(); } } } public static void DisplayInformationAboutStream( StreamReader sr) { Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding); Console.WriteLine("Can read from stream: {0}", sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}",
N O P Q R S T U V W X Y Z
2771
Contents | Index
StreamReader
System.IO
ReadToEnd() Method
sr.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek); }
A
} }
B
The output is
C D
CurrentEncoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: False Can seek in stream: True Hello world! Goodbye world!
E F G H I
StreamReader.ReadToEnd() Method
J
[ILASM]
K
.method public hidebysig virtual string ReadToEnd() [C#]
L
public override string ReadToEnd()
M N
Summary
O
Reads the stream from the current position to the end of the stream.
P
Return Value
Q
A System.Int32 containing the rest of the stream as a string, from the current position to the end. If the current position is at the end of the stream, returns the empty string ("").
R S
Description
T
[Note: This method overrides System.IO.TextReader.ReadToEnd.]
U V
Exceptions
W X Y
Exception
Condition
System.IO.IOException
An I/O error occurred.
System.OutOfMemoryException
There is insufficient memory to allocate a buffer for the returned string.
Z
2772
Contents | Index
System.IO
StreamReader ReadToEnd() Method
Example using System; using System.IO; using System.Text;
A B
namespace Samples { public class StreamReaderReadToEnd { public static void Main() { string s = "streamreader.txt"; using(StreamReader sr = new StreamReader(s)) { DisplayInformationAboutStream(sr); Console.WriteLine(sr.ReadToEnd()); } } public static void DisplayInformationAboutStream( StreamReader sr) { Console.WriteLine("CurrentEncoding: {0}", sr.CurrentEncoding); Console.WriteLine("Can read from stream: {0}", sr.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sr.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sr.BaseStream.CanSeek); } } }
C D E F G H I J K L M N O P Q R S
The output is
T CurrentEncoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: False Can seek in stream: True Hello world! Goodbye world!
U V W X Y Z
2773
Contents | Index
System.IO StreamWriter
BCL
Object
A
MarshalByRefObject
B
TextWriter
IDisposable
StreamWriter
C D
Summary
E
Implements a System.IO.Stream wrapper that writes characters to a stream in a particular encoding.
F G
Type Summary
H
public class StreamWriter : TextWriter { // Constructors public StreamWriter (string path); public StreamWriter (string path, bool append); public StreamWriter (string path, bool append, Encoding encoding); public StreamWriter (string path, bool append, Encoding encoding, int bufferSize); public StreamWriter (Stream stream); public StreamWriter (Stream stream, Encoding encoding); public StreamWriter (Stream stream, Encoding encoding, int bufferSize);
I J K L M N O P Q
// Fields MS public static readonly StreamWriter Null;
R
// Properties public virtual bool AutoFlush { set; get; } public virtual Stream BaseStream { get; } public override Encoding Encoding { get; }
S T U
// Methods public override void Close (); protected override void Dispose (bool disposing); CF ~StreamWriter () {} public override void Flush (); public override void Write (char value); public override void Write (char[] buffer); public override void Write (char[] buffer, int index, int count); public override void Write (string value);
V W X Y Z }
2774
Contents | Index
System.IO
StreamWriter StreamWriter Class
KG See my comments on the StreamReader class. A
Description
B
The System.IO.StreamWriter class is designed for character output in a particular System.Text.Encoding, whereas subclasses of System.IO.Stream are designed for byte input and output. System.IO.StreamWriter defaults to using an instance of System.Text.UTF8Encoding unless specified otherwise. This instance of System.Text.UTF8Encoding is constructed such that the System.Text.Encoding.GetPreamble method returns the Unicode byte order mark written in UTF-8. The preamble of the encoding is added to a stream when you are not appending to an existing stream. This means any text file you create with System.IO.StreamWriter has three byte order marks at its beginning. UTF-8 handles all Unicode characters correctly and gives consistent results on localized versions of the operating system. [Note: By default, System.IO.StreamWriter is not thread safe. For a thread-safe wrapper, see System.IO.TextWriter.Synchronized.]
C D E F G H I J K L
Example
M
using System; using System.IO; using System.Text;
N O
namespace Samples { public class StreamWriterSample { public static void Main() { string s = "streamwriter.txt"; using(StreamWriter sw = new StreamWriter(s)) { DisplayInformationAboutStream(sw); sw.WriteLine(DateTime.Now.ToString()); } MemoryStream ms = new MemoryStream(); using(StreamWriter sw = new StreamWriter(ms)) { DisplayInformationAboutStream(sw); sw.WriteLine(DateTime.Now.ToString()); Byte[] bytes = ((MemoryStream)sw.BaseStream).ToArray(); foreach(Byte b in bytes) Console.Write((char)b);
P Q R S T U V W X Y Z
2775
Contents | Index
StreamWriter
System.IO
StreamWriter() Constructor
} } public static void DisplayInformationAboutStream( StreamWriter sw) { Console.WriteLine("Encoding: {0}", sw.Encoding); Console.WriteLine("Can read from stream: {0}", sw.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sw.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sw.BaseStream.CanSeek); }
A B C D E F G
} }
H
The output is
I J
Encoding: System.Text.UTF8Encoding Can read from stream: False Can write to stream: True Can seek in stream: True Encoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: True Can seek in stream: True
K L M N O P
StreamWriter(System.String) Constructor
Q
[ILASM]
R
public rtspecialname specialname instance void .ctor(string path) [C#]
S
public StreamWriter(string path)
T U
Summary
V
Constructs and initializes a new instance of the System.IO.StreamWriter class for the specified file on the specified path, using the default encoding and buffer size.
W X
Parameters
Y Z
Parameter
Description
path
A System.String that specifies the complete file path to write to.
2776
Contents | Index
System.IO
StreamWriter StreamWriter() Constructor
Description This constructor initializes the System.IO.StreamWriter.Encoding property to a System.Text.UTF8Encoding whose System.Text.Encoding.GetPreamble method returns an empty byte array. For additional information, see System.IO.TextWriter.Encoding. [Note: path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device. For information on the valid format and characters for path strings, see System.IO.Path. The default buffer size may typically be around 4 KB.]
A B C D E F
Exceptions
G
Exception
Condition
H
path is in an invalid format or contains invalid characters.
I
System.IO.IOException System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
K
System.UnauthorizedAccessException
Access to path is denied.
M
System.ArgumentException
path is an empty string ("").
N
System.ArgumentNullException
path is null.
System.Security.SecurityException
The caller does not have the required permission.
J
L
O P Q R S
Permissions
T
Permission
Description
U
Requires permission for reading and writing files. See System.Security.Permissions.FileIOPermissionAccess.Read, System.Security.Permissions.FileIOPermissionAccess.Write.
V
System.Security.Permissions.FileIOPermission
W X Y Z
2777
Contents | Index
StreamWriter
System.IO
StreamWriter() Constructor
Example using System; using System.IO; using System.Text;
A B
namespace Samples { public class StreamWriterConstructor { public static void Main() { string s = "streamwriter.txt"; using(StreamWriter sw = new StreamWriter(s)) { DisplayInformationAboutStream(sw); sw.WriteLine(DateTime.Now.ToString()); } } public static void DisplayInformationAboutStream( StreamWriter sw) { Console.WriteLine("Encoding: {0}", sw.Encoding); Console.WriteLine("Can read from stream: {0}", sw.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sw.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sw.BaseStream.CanSeek); } } }
C D E F G H I J K L M N O P Q R
The output is
S
Encoding: System.Text.UTF8Encoding Can read from stream: False Can write to stream: True Can seek in stream: True
T U V W X
StreamWriter(System.String, System.Boolean) Constructor
Y
[ILASM]
public rtspecialname specialname instance void .ctor(string path, bool append)
Z
[C#]
public StreamWriter(string path, bool append)
2778
Contents | Index
System.IO
StreamWriter StreamWriter() Constructor
Summary Constructs and initializes a new instance of the System.IO.StreamWriter class for the specified file on the specified path, using the default encoding and buffer size. A
Parameters
B C
Parameter
Description
path
A System.String that specifies the complete file path to write to.
E F
append
A System.Boolean value that determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created.
D
G H I
Description
J
This constructor initializes the System.IO.StreamWriter.Encoding property to System.Text.UTF8Encoding whose System.Text.Encoding.GetPreamble method returns an empty byte array. For additional information, see System.IO.TextWriter.Encoding. If the specified file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file. [Note: path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device. For information on the valid format and characters for path strings, see System.IO.Path. The default buffer size may typically be around 4 KB.]
K L M N O P Q R S T U V W X Y Z
2779
Contents | Index
StreamWriter
System.IO
StreamWriter() Constructor
Exceptions Exception
Condition
System.IO.IOException
path is in an invalid format or contains invalid characters.
System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
F
System.UnauthorizedAccessException
Access to path is denied.
G
System.ArgumentException
path is an empty string (“”).
System.ArgumentNullException
path is null.
System.Security.SecurityException
The caller does not have the required permission.
A B C D E
H I J K
Permissions
L M
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission for reading and writing files. See System.Security.Permissions.FileIOPermission-Access.Read, System.Security.Permissions.File-IOPermissionAccess.Write.
N O P Q R
Example
S
using System; using System.IO; using System.Text;
T U
namespace Samples { public class StreamWriterConstructor { public static void Main() { string s = "streamwriter.txt"; using(StreamWriter sw = new StreamWriter(s, true)) { DisplayInformationAboutStream(sw); sw.WriteLine(DateTime.Now.ToString());
V W X Y Z
2780
Contents | Index
System.IO
StreamWriter StreamWriter() Constructor
} } public static void DisplayInformationAboutStream( StreamWriter sw) { Console.WriteLine("Encoding: {0}", sw.Encoding); Console.WriteLine("Can read from stream: {0}", sw.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sw.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sw.BaseStream.CanSeek); }
A B C D E F G
} }
H
The output is
I
Encoding: System.Text.UTF8Encoding Can read from stream: False Can write to stream: True Can seek in stream: True
J K L M
StreamWriter(System.String, System.Boolean, System.Text.Encoding) Constructor
N O
[ILASM]
P
public rtspecialname specialname instance void .ctor(string path, bool append, class System.Text.Encoding encoding)
Q
[C#]
R
public StreamWriter(string path, bool append, Encoding encoding)
S
Summary
T
Constructs and initializes a new instance of the System.IO.StreamWriter class for the specified file on the specified path, using the specified encoding and default buffer size.
U V W X Y Z
2781
Contents | Index
StreamWriter
System.IO
StreamWriter() Constructor
Parameters Parameter
Description
path
A System.String that specifies the complete file path to write to.
append
A System.Boolean value that determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created.
encoding
A System.Text.Encoding that specifies the character encoding to use.
A B C D E F G H
Description
I
If the specified file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file. This constructor initializes the System.IO.StreamWriter.Encoding property using encoding. For additional information, see System.IO.TextWriter.Encoding. [Note: path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able to access a physical device. For information on the valid format and characters for path strings, see System.IO.Path. The default buffer size may typically be around 4 KB.]
J K L M N O
Exceptions
P Q
Exception
Condition
System.IO.IOException
path is in an invalid format or contains invalid characters.
U
System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
V
System.UnauthorizedAccessException
Access to path is denied.
System.ArgumentException
path is an empty string ("").
System.ArgumentNullException
path is null.
System.Security.SecurityException
The caller does not have the required permission.
R S T
W X Y Z
2782
Contents | Index
System.IO
StreamWriter StreamWriter() Constructor
Permissions Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission for reading and writing files. See System.Security.Permissions.FileIOPermissionAccess.Read, System.Security.Permissions.FileIOPermissionAccess.Write.
A B C D E
Example
F
using System; using System.IO; using System.Text;
G H
namespace Samples { public class StreamWriterConstructor { public static void Main() { string s = "streamwriter.txt"; using(StreamWriter sw = new StreamWriter(s, true, System.Text.Encoding.UTF8)) { DisplayInformationAboutStream(sw); sw.WriteLine(DateTime.Now.ToString()); } } public static void DisplayInformationAboutStream( StreamWriter sw) { Console.WriteLine("Encoding: {0}", sw.Encoding); Console.WriteLine("Can read from stream: {0}", sw.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sw.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sw.BaseStream.CanSeek); } } }
I J K L M N O P Q R S T U V W X Y Z
2783
Contents | Index
StreamWriter
System.IO
StreamWriter() Constructor
The output is Encoding: System.Text.UTF8Encoding Can read from stream: False Can write to stream: True Can seek in stream: True
A B C D E
StreamWriter(System.String, System.Boolean, System.Text.Encoding, System.Int32) Constructor
F
[ILASM]
G
public rtspecialname specialname instance void .ctor(string path, bool append, class System.Text.Encoding encoding, int32 bufferSize)
H
[C#]
public StreamWriter(string path, bool append, Encoding encoding, int bufferSize)
I J
Summary
K
Constructs and initializes a new instance of the System.IO.StreamWriter class for the specified file on the specified path, using the specified encoding and buffer size.
L M
Parameters
N O P
Parameter
Description
path
A System.String that specifies the complete file path to write to.
append
A System.Boolean value that determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created.
encoding
A System.Text.Encoding that specifies the character encoding to use.
bufferSize
A System.Int32 that specifies the buffer size.
Q R S T U V
Description
W
If the specified file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file. This constructor initializes the System.IO.StreamWriter.Encoding property using encoding. For additional information, see System.IO.TextWriter.Encoding. [Note: path is not required to be a file stored on disk; it can be any part of a system that supports access via streams. For example, depending on the system, this class may be able
X Y Z
2784
Contents | Index
System.IO
StreamWriter StreamWriter() Constructor
to access a physical device. For information on the valid format and characters for path strings, see System.IO.Path.] A
Exceptions
B
Exception
Condition
System.IO.IOException
path is in an invalid format or contains invalid characters.
System.IO.DirectoryNotFoundException
The directory information specified in path was not found.
System.ArgumentException
path is an empty string ("").
System.ArgumentNullException
path or encoding is null.
System.ArgumentOutOfRangeException
bufferSize is negative.
System.Security.SecurityException
The caller does not have the required permission.
System.UnauthorizedAccessException
Access to path is denied.
C D E F G H I J K L M N
Permissions
O
Permission
Description
System.Security.Permissions.FileIOPermission
Requires permission for reading and writing files. See System.Security.Permissions.FileIOPermissionAccess.Read, System.Security.Permissions.FileIOPermissionAccess.Write.
P Q R S T U
Example
V
using System; using System.IO; using System.Text;
W X
namespace Samples { public class StreamWriterConstructor { public static void Main() {
Y Z
2785
Contents | Index
StreamWriter
System.IO
StreamWriter() Constructor
string s = "streamwriter.txt"; using(StreamWriter sw = new StreamWriter(s, true, System.Text.Encoding.Default, 512)) { DisplayInformationAboutStream(sw); sw.WriteLine(DateTime.Now.ToString()); }
A B C D
} public static void DisplayInformationAboutStream( StreamWriter sw) { Console.WriteLine("Encoding: {0}", sw.Encoding); Console.WriteLine("Can read from stream: {0}", sw.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sw.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sw.BaseStream.CanSeek); }
E F G H I J K L
} }
M N
The output is
O
Encoding: System.Text.CodePageEncoding Can read from stream: False Can write to stream: True Can seek in stream: True
P Q R S
StreamWriter(System.IO.Stream) Constructor
T
[ILASM]
public rtspecialname specialname instance void .ctor(class System.IO.Stream stream)
U V
[C#]
W
public StreamWriter(Stream stream)
X
Summary
Y
Constructs and initializes a new instance of the System.IO.StreamWriter class for the specified stream, using the default encoding and buffer size.
Z
2786
Contents | Index
System.IO
StreamWriter StreamWriter() Constructor
Parameters Parameter
Description
stream
The System.IO.Stream to write to.
A B C
Description
D
This constructor initializes the System.IO.StreamWriter.Encoding property to a System.Text.UTF8Encoding whose System.Text.Encoding.GetPreamble method returns an empty byte array. For additional information, see System.IO.TextWriter.Encoding. The System.IO.StreamWriter.BaseStream property is initialized using stream. [Note: The default buffer size may typically be around 4 KB.]
E F G H I
Exceptions
J K
Exception
Condition
System.ArgumentException
stream does not support writing.
M
System.ArgumentNullException
stream is null.
N
L
O
Example
P
using System; using System.IO; using System.Text;
Q R S
namespace Samples { public class StreamWriterConstructor { public static void Main() { string s = "streamwriter.txt"; using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate)) { StreamWriter sw = new StreamWriter(fs); DisplayInformationAboutStream(sw); sw.WriteLine(DateTime.Now.ToString()); }
T U V W X Y Z
2787
Contents | Index
StreamWriter
System.IO
StreamWriter() Constructor
} public static void DisplayInformationAboutStream( StreamWriter sw) { Console.WriteLine("Encoding: {0}", sw.Encoding); Console.WriteLine("Can read from stream: {0}", sw.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sw.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sw.BaseStream.CanSeek); }
A B C D E F }
G
}
H
The output is
I
Encoding: System.Text.UTF8Encoding Can read from stream: True Can write to stream: True Can seek in stream: True
J K L M N
StreamWriter(System.IO.Stream, System.Text.Encoding) Constructor
O
[ILASM]
P
public rtspecialname specialname instance void .ctor(class System.IO.Stream stream, class System.Text.Encoding encoding)
Q
[C#]
public StreamWriter(Stream stream, Encoding encoding)
R S
Summary
T
Constructs and initializes a new instance of the System.IO.StreamWriter class for the specified stream, using the specified encoding and the default buffer size.
U V
Parameters
W X
Parameter
Description
Y
stream
The System.IO.Stream to write to.
encoding
A System.Text.Encoding that specifies the character encoding to use.
Z
2788
Contents | Index
System.IO
StreamWriter StreamWriter() Constructor
Description This constructor initializes the System.IO.StreamWriter.Encoding property using encoding, and the System.IO.StreamWriter.BaseStream property using stream. For additional information, see System.IO.TextWriter.Encoding. [Note: The default buffer size may typically be around 4 KB.]
A B C
Exceptions
D
Exception
Condition
System.ArgumentNullException
stream or encoding is null.
System.ArgumentException
stream does not support writing.
E F G H I
Example
J
using System; using System.IO; using System.Text;
K L M
namespace Samples { public class StreamWriterConstructor { public static void Main() { string s = "streamwriter.txt"; using(FileStream fs = new FileStream(s, FileMode.OpenOrCreate)) { StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default); DisplayInformationAboutStream(sw); sw.WriteLine(DateTime.Now.ToString()); } } public static void DisplayInformationAboutStream( StreamWriter sw) { Console.WriteLine("Encoding: {0}", sw.Encoding); Console.WriteLine("Can read from stream: {0}", sw.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sw.BaseStream.CanWrite);
N O P Q R S T U V W X Y Z
2789
Contents | Index
StreamWriter
System.IO
StreamWriter() Constructor
Console.WriteLine("Can seek in stream: {0}", sw.BaseStream.CanSeek); } }
A
}
B
The output is
C
Encoding: System.Text.CodePageEncoding Can read from stream: True Can write to stream: True Can seek in stream: True
D E F G
StreamWriter(System.IO.Stream, System.Text.Encoding, System.Int32) Constructor
H I
[ILASM]
J
public rtspecialname specialname instance void .ctor(class System.IO.Stream stream, class System.Text.Encoding encoding, int32 bufferSize)
K
[C#]
L
public StreamWriter(Stream stream, Encoding encoding, int bufferSize)
M N
Summary
O
Constructs and initializes a new instance of the System.IO.StreamWriter class for the specified stream, using the specified encoding and buffer size.
P
Parameters
Q R
Parameter
Description
T
stream
The System.IO.Stream to write to.
U
encoding
A System.Text.Encoding that specifies the character encoding to use.
bufferSize
A System.Int32 that specifies the buffer size.
S
V W X
Description
Y
This constructor initializes the System.IO.StreamWriter.Encoding property using encoding, and the System.IO.StreamWriter.BaseStream property using stream. For additional information, see System.IO.TextWriter.Encoding.
Z
2790
Contents | Index
System.IO
StreamWriter StreamWriter() Constructor
Exceptions Exception
Condition
System.ArgumentNullException
stream or encoding is null.
System.ArgumentOutOfRangeException
bufferSize is negative.
C
System.ArgumentException
stream does not support writing.
D
A B
E F
Example
G
using System; using System.IO; using System.Text;
H I
namespace Samples { public class StreamWriterConstructor { public static void Main() { string s = "streamwriter.txt"; FileStream fs = new FileStream(s, FileMode.OpenOrCreate); using(StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default, 512)) { DisplayInformationAboutStream(sw); sw.WriteLine(DateTime.Now.ToString()); } } public static void DisplayInformationAboutStream( StreamWriter sw) { Console.WriteLine("Encoding: {0}", sw.Encoding); Console.WriteLine("Can read from stream: {0}", sw.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sw.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sw.BaseStream.CanSeek); } } }
J K L M N O P Q R S T U V W X Y Z
2791
Contents | Index
StreamWriter
System.IO
Null Field
The output is Encoding: System.Text.CodePageEncoding Can read from stream: True Can write to stream: True Can seek in stream: True
A B C D
StreamWriter.Null Field
E
[ILASM]
.field public static initOnly class System.IO.StreamWriter Null
F
[C#]
G
public static readonly StreamWriter Null
H
Summary
I
Provides a StreamWriter with no backing store that can be written to, but not read from.
J K
Description
L
Use Null to redirect output to a StreamWriter that will not consume any operating system resources. When the StreamWriter.Write methods are invoked on Null, the call simply returns, and no data is actually written to any backing store.
M N O
StreamWriter.AutoFlush Property
P
[ILASM]
Q
.property bool AutoFlush { public hidebysig virtual specialname bool get_AutoFlush() public hidebysig virtual specialname void set_AutoFlush(bool value) }
R
[C#]
S
public virtual bool AutoFlush { get; set; }
T
Summary
U
Gets or sets a System.Boolean value indicating whether the current System.IO.StreamWriter will flush its buffer to the underlying stream after every call to System.IO.StreamWriter.Write.
V W X
Property Value
Y
true to force System.IO.StreamWriter to flush its buffer; otherwise, false.
Z
2792
Contents | Index
System.IO
StreamWriter AutoFlush Property
Description The System.IO.StreamWriter will do a limited amount of buffering, both internally and potentially in the encoder from the encoding you passed in. If System.IO.StreamWriter.AutoFlush is set to false, the data will be flushed into the underlying stream only when the buffer is full, or when System.IO.StreamWriter.Dispose(true) or System.IO.StreamWriter.Close is called. Setting System.IO.StreamWriter.AutoFlush to true forces System.IO.StreamWriter to flush the buffered data out of the encoder and call System.IO.StreamWriter.Flush on the stream every time System.IO.StreamWriter.Write is called.
A B C D E F
Example
G
using System; using System.IO; using System.Text;
H I
namespace Samples { public class StreamWriterAutoFlush { public static void Main() { string s = "streamwriter.txt"; using(StreamWriter sw = new StreamWriter(s)) { DisplayInformationAboutStream(sw); sw.WriteLine(DateTime.Now.ToString()); sw.Flush(); sw.AutoFlush = true; Console.WriteLine("AutoFlush: {0}", sw.AutoFlush); sw.WriteLine(DateTime.Now.ToString()); } } public static void DisplayInformationAboutStream( StreamWriter sw) { Console.WriteLine("Encoding: {0}", sw.Encoding); Console.WriteLine("AutoFlush: {0}", sw.AutoFlush); Console.WriteLine("Can read from stream: {0}", sw.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sw.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sw.BaseStream.CanSeek); } } }
J K L M N O P Q R S T U V W X Y Z
2793
Contents | Index
StreamWriter
System.IO
BaseStream Property
The output is Encoding: System.Text.UTF8Encoding AutoFlush: False Can read from stream: False Can write to stream: True Can seek in stream: True AutoFlush: True
A B C D E
StreamWriter.BaseStream Property
F [ILASM]
G
.property class System.IO.Stream BaseStream { public hidebysig virtual specialname class System.IO.Stream get_BaseStream() }
H
[C#]
I
public virtual Stream BaseStream { get; }
J
Summary
K
Gets the underlying stream.
L M
Property Value
N
The System.IO.Stream the current System.IO.StreamWriter instance is writing to.
O
Example
P
using System; using System.IO; using System.Text;
Q R
namespace Samples { public class StreamWriterBaseStream { public static void Main() { string s = "streamwriter.txt"; using(StreamWriter sw = new StreamWriter(s)) { DisplayInformationAboutStream(sw); } } public static void DisplayInformationAboutStream( StreamWriter sw) { Console.WriteLine("Encoding: {0}", sw.Encoding); Console.WriteLine("AutoFlush: {0}", sw.AutoFlush);
S T U V W X Y Z
2794
Contents | Index
System.IO
StreamWriter Encoding Property
Console.WriteLine("Can read from stream: {0}", sw.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sw.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sw.BaseStream.CanSeek);
A B
} }
C
}
D
The output is
E
Encoding: System.Text.UTF8Encoding AutoFlush: False Can read from stream: False Can write to stream: True Can seek in stream: True
F G H I J
StreamWriter.Encoding Property
K [ILASM]
L
.property class System.Text.Encoding Encoding { public hidebysig virtual specialname class System.Text.Encoding get_Encoding() } [C#]
M
public override Encoding Encoding { get; }
N O
Summary
P
Gets the System.Text.Encoding in which the output is written.
Q
Property Value
R
The System.Text.Encoding specified in the constructor for the current instance, or System.Text.UTF8Encoding if an encoding was not specified.
S T
Description
U
[Note: This property overrides the System.IO.TextWriter.Encoding property.]
V W
Usage
X
This property is required in some XML scenarios where a header must be written containing the encoding used by the System.IO.StreamWriter. This allows XML code to consume an arbitrary System.IO.StreamWriter and generate a correct XML header.
Y Z
2795
Contents | Index
StreamWriter
System.IO
Close() Method
Example using System; using System.IO; using System.Text;
A B
namespace Samples { public class StreamWriterEncoding { public static void Main() { string s = "streamwriter.txt"; using(StreamWriter sw = new StreamWriter(s)) { DisplayInformationAboutStream(sw); } } public static void DisplayInformationAboutStream( StreamWriter sw) { Console.WriteLine("Encoding: {0}", sw.Encoding); Console.WriteLine("AutoFlush: {0}", sw.AutoFlush); Console.WriteLine("Can read from stream: {0}", sw.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sw.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sw.BaseStream.CanSeek); } } }
C D E F G H I J K L M N O P Q R
The output is
S
Encoding: System.Text.UTF8Encoding AutoFlush: False Can read from stream: False Can write to stream: True Can seek in stream: True
T U V W X
StreamWriter.Close() Method
Y
[ILASM]
Z
.method public hidebysig virtual void Close() [C#]
public override void Close()
2796
Contents | Index
System.IO
StreamWriter Close() Method
Summary Closes the current System.IO.StreamWriter and the underlying stream.
Description
A
This method calls System.IO.StreamWriter.Flush, writing buffered data to the underlying stream. Following a call to System.IO.StreamWriter.Close, any operations on the current instance might raise exceptions. [Note: This version of System.IO.StreamWriter.Close is equivalent to System.IO.StreamWriter.Dispose(true). This method overrides System.IO.Stream.Close.]
B C D E F G
Example
H
using System; using System.IO; using System.Text;
I J
namespace Samples { public class StreamWriterConstructor { public static void Main() { string s = "streamwriter.txt"; using(StreamWriter sw = new StreamWriter(s)) { DisplayInformationAboutStream(sw); sw.WriteLine(DateTime.Now.ToString()); } } public static void DisplayInformationAboutStream( StreamWriter sw) { Console.WriteLine("Encoding: {0}", sw.Encoding); Console.WriteLine("Can read from stream: {0}", sw.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sw.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sw.BaseStream.CanSeek); } } }
K L M N O P Q R S T U V W X Y Z
2797
Contents | Index
StreamWriter
System.IO
Dispose() Method
The output is Encoding: System.Text.UTF8Encoding Can read from stream: False Can write to stream: True Can seek in stream: True
A B C D
StreamWriter.Dispose(System.Boolean) Method
E
[ILASM]
.method family hidebysig virtual void Dispose(bool disposing)
F
[C#]
G
protected override void Dispose(bool disposing)
H
Summary
I
Releases the unmanaged resources used by the System.IO.StreamWriter and optionally releases the managed resources.
J K
Parameters
L M
Parameter
Description
disposing
true to release both managed and unmanaged resources; false to release only unmanaged resources.
N O P Q
Description
R
When the disposing parameter is true, this method releases all resources held by any managed objects that this System.IO.StreamWriter references. This method invokes the Dispose() method of each referenced object. [Note: System.IO.StreamWriter.Dispose may be called multiple times by other objects. When overriding System.IO.StreamWriter.Dispose(System.Boolean), be careful not to reference objects that have been previously disposed in an earlier call to System.IO.StreamWriter.Dispose. This method calls the dispose method of the base class, System.IO.TextWriter.Dispose(disposing).]
S T U V W X Y Z
2798
Contents | Index
System.IO
StreamWriter Flush() Method
StreamWriter.Finalize() Method [ILASM]
.method family hidebysig virtual void Finalize() [C#]
A
~StreamWriter()
B C
Summary
D
Releases resources held by the current instance.
E
Description
F
[Note: Application code does not call this method; it is automatically invoked during garbage collection unless finalization by the garbage collector has been disabled. For more information, see System.GC.SuppressFinalize, and System.Object.Finalize. This method overrides System.Object.Finalize.]
G H I J K
StreamWriter.Flush() Method
L
[ILASM]
public override void Flush()
M
[C#]
N
.method public hidebysig virtual void Flush()
O
Summary
P
Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.
Q R
Description
S
[Note: This method overrides System.IO.TextWriter.Flush.]
T U
Exceptions
V
Exception
Condition
W
System.ObjectDisposedException
The current writer is closed.
X
System.IO.IOException
An I/O error occurred.
Y Z
2799
Contents | Index
StreamWriter
System.IO
Write() Method
Example using System; using System.IO; using System.Text;
A B
namespace Samples { public class StreamWriterFlush { public static void Main() { string s = "streamwriter.txt"; using(StreamWriter sw = new StreamWriter(s)) { DisplayInformationAboutStream(sw); sw.WriteLine(DateTime.Now.ToString()); sw.Flush(); sw.WriteLine(DateTime.Now.ToString()); } } public static void DisplayInformationAboutStream( StreamWriter sw) { Console.WriteLine("Encoding: {0}", sw.Encoding); Console.WriteLine("Can read from stream: {0}", sw.BaseStream.CanRead); Console.WriteLine("Can write to stream: {0}", sw.BaseStream.CanWrite); Console.WriteLine("Can seek in stream: {0}", sw.BaseStream.CanSeek); } } }
C D E F G H I J K L M N O P Q R S
The output is
T
Encoding: System.Text.UTF8Encoding Can read from stream: False Can write to stream: True Can seek in stream: True
U V W X
StreamWriter.Write(System.Char) Method
Y
[ILASM]
Z
.method public hidebysig virtual void Write(valuetype System.Char value) [C#]
public override void Write(char value)
2800
Contents | Index
System.IO
StreamWriter Write() Method
Summary Writes a character to the stream. A
Parameters
B
Parameter
Description
C
value
The System.Char to write to the underlying stream.
D E F
Description
G
The specified character is written to the underlying stream unless the end of the stream is reached prematurely. If System.IO.StreamWriter.AutoFlush is true, System.IO.StreamWriter.Flush is invoked automatically. [Note: This method overrides System.IO.TextWriter.Write.]
H I J K
Exceptions
L
Exception
Condition
System.NotSupportedException
System.IO.StreamWriter.AutoFlush is true or the System.IO.StreamWriter buffer is full, and the contents of the buffer cannot be written to the underlying fixed size stream because the System.IO.StreamWriter is at the end of the stream.
M N O P Q R
System.ObjectDisposedException
The current writer is closed.
System.IO.IOException
An I/O error occurred.
S T U
Example
V
using System; using System.IO; using System.Text;
W X Y
namespace Samples { public class StreamWriterWrite { public static void Main()
Z
2801
Contents | Index
StreamWriter
System.IO
Write() Method
{ string s = "streamwriter.txt"; using(StreamWriter sw = new StreamWriter(s)) { s = DateTime.Now.ToString(); foreach(char c in s) sw.Write(c); }
A B C }
D
} }
E F
This program produces no console output.
G H
StreamWriter.Write(System.Char[]) Method
I [ILASM]
J
.method public hidebysig virtual void Write(class System.Char[] buffer)
K
[C#]
public override void Write(char[] buffer)
L M
Summary
N
Writes a character array to the underlying stream.
O
Parameters
P Q
Parameter
Description
buffer
A System.Char array containing the data to write. If buffer is null, nothing is written.
R S T U
Description
V
The specified characters are written to the underlying stream unless the end of the stream is reached prematurely. If System.IO.StreamWriter.AutoFlush is true, System.IO.StreamWriter.Flush is invoked automatically. [Note: This method overrides System.IO.TextWriter.Write.]
W X Y Z
2802
Contents | Index
System.IO
StreamWriter Write() Method
Exceptions Exception
Condition
System.NotSupportedException
System.IO.StreamWriter.AutoFlush is true or the System.IO.StreamWriter buffer is full, and the contents of the buffer cannot be written to the underlying fixed size stream because the System.IO.StreamWriter is at the end of the stream.
A B C D E System.ObjectDisposedException
The current writer is closed.
System.IO.IOException
An I/O error occurred.
F G H
Example
I
using System; using System.IO; using System.Text;
J K
namespace Samples { public class StreamWriterWrite { public static void Main() { string s = "streamwriter.txt"; using(StreamWriter sw = new StreamWriter(s)) { char[] chars = {'H', 'e', 'l', 'l', 'o', ' ','w','o','r','l', 'd'}; sw.Write(chars); } } } }
L M N O P Q R S T U
This program produces no console output.
V W
StreamWriter.Write(System.Char[], System.Int32, System.Int32) Method
X
[ILASM]
Y
.method public hidebysig virtual void Write(class System.Char[] buffer, int32 index, int32 count)
Z
[C#]
public override void Write(char[] buffer, int index, int count)
2803
Contents | Index
StreamWriter
System.IO
Write() Method
Summary Writes a sub-array of characters to the underlying stream. A
Parameters
B C
Parameter
Description
D
buffer
A System.Char array containing the data to write.
index
A System.Int32 that specifies the index into buffer at which to begin writing.
count
A System.Int32 that specifies the number of characters to read from buffer.
E F G H
Description
I
The specified characters are written to the underlying stream unless the end of the stream is reached prematurely. If System.IO.StreamWriter.AutoFlush is true, System.IO.StreamWriter.Flush is invoked automatically. [Note: This method overrides System.IO.TextWriter.Write.]
J K L M N
Exceptions
O
Exception
Condition
System.ArgumentException
buffer.Length – index < count.
System.ArgumentNullException
buffer is null.
System.ArgumentOutOfRangeException
index or count is negative.
System.NotSupportedException
System.IO.StreamWriter.AutoFlush is true or the System.IO.StreamWriter buffer is full, and the contents of the buffer cannot be written to the underlying fixed size stream because the System.IO.StreamWriter is at the end the stream.
Y
System.ObjectDisposedException
The current writer is closed.
Z
System.IO.IOException
An I/O error occurred.
P Q R S T U V W X
2804
Contents | Index
System.IO
StreamWriter Write() Method
Example using System; using System.IO; using System.Text;
A B
namespace Samples { public class StreamWriterWrite { public static void Main() { string s = "streamwriter.txt"; using(StreamWriter sw = new StreamWriter(s)) { char[] chars = {'H', 'e', 'l', 'l', 'o', ' ','w','o','r','l', 'd'}; sw.Write(chars, 0, 5); } } } }
C D E F G H I J K L
This program produces no console output.
M N
StreamWriter.Write(System.String) Method
O
[ILASM]
P
.method public hidebysig virtual void Write(string value)
Q
[C#]
public override void Write(string value)
R
Summary
S
Writes a string to the stream.
T U
Parameters
V
Parameter
Description
value
The System.String to write to the stream. If value is null, nothing is written.
W X Y Z
2805
Contents | Index
StreamWriter
System.IO
Write() Method
Description The specified System.String is written to the underlying stream unless the end of the stream is reached prematurely. If System.IO.StreamWriter.AutoFlush is true, System.IO.StreamWriter.Flush is invoked automatically. [Note: This method overrides System.IO.TextWriter.Write.]
A B C D
Exceptions
E F
Exception
Condition
System.NotSupportedException
System.IO.StreamWriter.AutoFlush is true or the System.IO.StreamWriter buffer is full, and the contents of the buffer cannot be written to the underlying fixed size stream because the System.IO.StreamWriter is at the end the stream.
System.ObjectDisposedException
The current writer is closed.
System.IO.IOException
An I/O error occurred.
G H I J K L M N
Example
O
using System; using System.IO; using System.Text;
P Q
namespace Samples { public class StreamWriterWrite { public static void Main() { string s = "streamwriter.txt"; using(StreamWriter sw = new StreamWriter(s)) { sw.Write(DateTime.Now.ToString()); } } } }
R S T U V W X Y Z
This program produces no console output.
2806
Contents | Index
System String
BCL
IComparable Object ICloneable
A
IEnumerable
B
String
IConvertible
C
NotStandardized
D
Summary
E
Represents an immutable series of characters.
F
Type Summary
G
public sealed class String : IComparable, ICloneable, IConvertible, IEnumerable { // Constructors unsafe public String (char* value); unsafe public String (char* value, int startIndex, int length); public String (char c, int count); public String (char[] value); public String (char[] value, int startIndex, int length); MS unsafe public String (sbyte* value); MS CF unsafe public String (sbyte* value, int startIndex, int length); CF unsafe public String (sbyte* value, int startIndex, int length, Encoding enc);
H I J K L M N O P Q
// Fields public static readonly string Empty = “”;
R S
// Properties public char this[int index] { get; } public int Length { get; }
T U
// Methods public object Clone (); public static int Compare (string strA, int indexA, string strB, int indexB, int length); public static int Compare (string strA, int indexA, string strB, int indexB, int length, bool ignoreCase); MS public static int Compare (string strA, int indexA, string strB,
V W X Y Z
2807
Contents | Index
String
System
String Class
public
A public
B C
MS public
D E public
F G H I
public
J
L
public MS public MS public public
M
public
K
N MS CF public
O P Q
public public
R S
public
T MS public
U V W
public public public
X Y Z
public public MS public
int indexB, int length, bool ignoreCase, CultureInfo culture); static int Compare (string strA, string strB); static int Compare (string strA, string strB, bool ignoreCase); static int Compare (string strA, string strB, bool ignoreCase, CultureInfo culture); static int CompareOrdinal (string strA, int indexA, string strB, int indexB, int length); static int CompareOrdinal (string strA, string strB); int CompareTo (object value); int CompareTo (string strB); static string Concat (object arg0); static string Concat (object arg0, object arg1); static string Concat (object arg0, object arg1, object arg2); static string Concat (object arg0, object arg1, object arg2, object arg3); static string Concat (params object[] args); static string Concat (string str0, string str1); static string Concat (string str0, string str1, string str2); static string Concat (string str0, string str1, string str2, string str3); static string Concat (params string[] values); static string Copy (string str); void CopyTo (int sourceIndex, char[] destination, int destinationIndex, int count); bool EndsWith (string value); override bool Equals (object obj); bool Equals (string value);
2808
Contents | Index
System
String String Class
public static bool Equals (string a, string b); public static string Format (string format, object arg0); public static string Format (string format, object arg0, object arg1); public static string Format (string format, object arg0, object arg1, object arg2); public static string Format (string format, params object[] args); public static string Format (IFormatProvider provider, string format, params object[] args); CF public CharEnumerator GetEnumerator(); public override int GetHashCode (); MS public TypeCode GetTypeCode (); public int IndexOf (char value); public int IndexOf (char value, int startIndex); public int IndexOf (char value, int startIndex, int count); public int IndexOf (string value); public int IndexOf (string value, int startIndex); public int IndexOf (string value, int startIndex, int count); public int IndexOfAny (char[] anyOf); public int IndexOfAny (char[] anyOf, int startIndex); public int IndexOfAny (char[] anyOf, int startIndex, int count); public string Insert (int startIndex, string value); public static string Intern (string str); public static string IsInterned (string str); public static string Join (string separator, string[] value); public static string Join (string separator, string[] value, int startIndex, int count); public int LastIndexOf (char value); public int LastIndexOf (char value, int startIndex); public int LastIndexOf (char value, int startIndex, int count); public int LastIndexOf (string value); public int LastIndexOf (string value, int startIndex); public int LastIndexOf (string value, int startIndex, int count); public int LastIndexOfAny (char[] anyOf); public int LastIndexOfAny (char[] anyOf,
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
2809
Contents | Index
String
System
String Class
A B C D E F G H I CF
J K L M CF
N O
MS
P Q MS
R S T U
// CF MS MS MS MS MS MS MS MS MS
V W X Y Z
int startIndex); public int LastIndexOfAny (char[] value, int startIndex, int count); public static bool operator ==(string a, string b); public static bool operator !=(string a, string b); public string PadLeft (int totalWidth); public string PadLeft (int totalWidth, char paddingChar); public string PadRight (int totalWidth); public string PadRight (int totalWidth, char paddingChar); public string Remove (int startIndex, int count); public string Replace (char oldChar, char newChar); public string Replace (string oldValue, string newValue); public string[] Split (params char[] separator); public string[] Split (char[] separator, int count); public bool StartsWith (string value); public string Substring (int startIndex); public string Substring (int startIndex, int length); public char[] ToCharArray (); public char[] ToCharArray (int startIndex, int length); public string ToLower (); public string ToLower (CultureInfo culture); public override string ToString (); public string ToString (IFormatProvider provider); public string ToUpper (); public string ToUpper (CultureInfo culture); public string Trim (); public string Trim (params char[] trimChars); public string TrimEnd (params char[] trimChars); public string TrimStart (params char[] trimChars); Explicit Interface Members IEnumerator IEnumerable.GetEnumerator(); bool IConvertible.ToBoolean(IFormatProvider provider); byte IConvertible.ToByte(IFormatProvider provider); char IConvertible.ToChar(IFormatProvider provider); DateTime IConvertible.ToDateTime(IFormatProvider provider); decimal IConvertible.ToDecimal(IFormatProvider provider); double IConvertible.ToDouble(IFormatProvider provider); short IConvertible.ToInt16(IFormatProvider provider); int IConvertible.ToInt32(IFormatProvider provider); long IConvertible.ToInt64(IFormatProvider provider);
2810
Contents | Index
System
String String Class
MS MS MS MS MS MS
sbyte IConvertible.ToSByte(IFormatProvider provider); float IConvertible.ToSingle(IFormatProvider provider); object IConvertible.ToType(Type type,IFormatProvider provider); ushort IConvertible.ToUInt16(IFormatProvider provider); uint IConvertible.ToUInt32(IFormatProvider provider); ulong IConvertible.ToUInt64(IFormatProvider provider);
A B
}
C D
AH While it may seem obvious, one of the big advantages of .NET is that it defines
E
a single representation for strings. During its evolution, the Windows platform has accrued quite a collection of string representations: ANSI strings, Unicode strings, null terminated strings, length prefixed strings, etc. Unifying all of those has made .NET a much simpler and safer place to program.
F G H
BA Why did we seal the String class? This is one of the most common questions
I
about the BCL. In general I am not a big fan of sealing classes arbitrarily. As a general rule we designed classes in the BCL with extensibility in mind. However, from a pragmatic standpoint that is not always possible. Because a fully extensible design is not always practical, we use non-virtual members by default and only use virtual members where they have been designed for extensibility. This limits the number of places in the implementation of the class that may be calling into user code. However, in the case of String it was necessary to seal it because the JIT needs to understand the exact physical layout of the string to perform optimizations.
J K L M N O
String being immutable is a very nice thing for the type system. It means you do not have to worry about ownership issues. You can pass a reference to a string in your internal implementation to clients without a worry that they will modify your data. However, when building up a string this immutability frequently means lots of copies of the string are being made. For example, in the following code snippet each line creates a new copy of the string: string s = "As "; s+=" You "; s = s.Append ("wish s = s.ToUpper(); s = s.Trim();
P Q R S T U V
");
W X
In general this is not a problem. The GC is tuned to take care of small short-lived allocations like this. But in performance-sensitive parts of your application (such as a tight loop) it could be an issue. In such cases, we recommend using StringBuilder.
Y Z
continued
2811
Contents | Index
String
System
String Class
BG String has three different ways to test for equality. The first is the Compare family of methods, which are generally case-sensitive and use the current thread’s culture for the comparison rules, but the comparison is always linguistically correct. By this, I mean we handle somewhat obscure Unicode concepts like combining characters and diacritics in the manner required by the Unicode specification. The second is CompareOrdinal and Equals, which do bitwise comparisons in memory, similar to C’s memcmp or strcmp methods. A memory comparison such as this works consistently on all machines, independent of their culture. The third way to do string comparison with the .NET Framework is by using the CompareInfo class, which can be culture-sensitive or not, can be case-insensitive, and can special-case certain language aspects, such as kana handling in Japanese or specifying string sorting instead of word sorting.
A B C D E F G H
KG We get more requests to add functionality to the String class than any other. You can see that it already has a plethora of operations: we therefore consider all new functionality carefully before adding it. String is one of the hardest classes to modify since even the smallest and most innocuous change will have effects that we do not even consider. Expect String to grow over time and for any APIs to be long-lived.
I J K L
JR Note that a String is really a set of UTF-16 code points, which will be a character unless the code point represents a high or low surrogate value. To properly traverse the characters of a string, you should use the System.Globalization.StringInfo class’s methods.
M N O P Q
Description
R
An index is the position of a character within a string. The first character in the string is at index 0. The length of a string is the number of characters it is made up of. The last accessible index of a string instance is System.String.Length-1. Strings are immutable; once created, the contents of a System.String do not change. Combining operations, such as System.String.Replace, cannot alter existing strings. Instead, such operations return a new string that contains the results of the operation, an unchanged string, or the null value. To perform modifications to a System.String use the System.Text.StringBuilder. Implementations of System.String are required to contain a variable-length character buffer positioned a fixed number of bytes after the beginning of the String object. [Note: The System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData method returns the number of bytes between the start of the String object and the character buffer. This information is intended primarily for use by compilers, not applica-
S T U V W X Y Z
2812
Contents | Index
System
String String Class
tion programmers. For additional information, see System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.] [Note: Comparisons and searches are case-sensitive by default and unless otherwise specified, use the culture defined for the current thread to determine the order of the alphabet used by the strings. This information is then used to compare the two strings on a character-by-character basis. Uppercase letters evaluate greater than their lower case equivalents. The following characters are considered white space when present in a System.String instance: 0x9, 0xA, 0xB, 0xC, 0xD, 0x20, 0xA0, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x200B, 0x3000, and 0xFEFF. The null character is defined as hexadecimal 0x00. The System.String(System.String) constructor is omitted for performance reasons. If you need a copy of a System.String, consider using System.String.Copy or the System.Text.StringBuilder class. To insert a formatted string representation of an object into a string use the System.String.Format methods. These methods take one or more arguments to be formatted and a format string. The format string contains literals and zero or more format specifications in the form { N [, M][: formatSpecifier]}, where: If an object referenced in the format string implements System.IFormattable, then the System.IFormattable.ToString method of the object provides the formatting. If the argument does not implement System.IFormattable, then the System.Object.ToString method of the object provides default formatting, and formatSpecifier, if present, is ignored. For an example that demonstrates this, see Example 2. To include a curly bracket in a formatted string, specify the bracket twice; for example, specify “{{” to include “{” in the formatted string. See Example 1. The System.Console class exposes the same functionality as the System.String.Format methods via System.Console.Write and System.Console.WriteLine. The primary difference is that the System.String.Format methods return the formatted string, while the System.Console methods write the formatted string to a stream.]
A B C D E F G H I J K L M N O P Q R
Examples
S
Example 1
T
using System;
U namespace Samples { public class StringSample { public static void Main() { string s = "Hello World!"; Console.WriteLine("\"{0}\".Length: {1}", s, s.Length); Console.WriteLine("\"{0}\".ToUpper(): {1}",
V W X Y Z
2813
Contents | Index
String
System
String Class
s, s.ToUpper()); Console.WriteLine("\"{0}\".ToLower(): {1}", s, s.ToLower()); char c = 'l'; Console.WriteLine("\"{0}\".IndexOf({1}): {2}", s, c, s.IndexOf(c)); int i = 5; Console.WriteLine("\"{0}\".IndexOf({1}, {2}): {3}", s, c, i, s.IndexOf(c,i)); Console.WriteLine("\"{0}\".LastIndexOf({1}): {2}", s, c, s.LastIndexOf(c));
A B C D E }
F
} }
G
The output is
H I
"Hello "Hello "Hello "Hello "Hello "Hello
J K L
World!".Length: 12 World!".ToUpper(): HELLO WORLD! World!".ToLower(): hello world! World!".IndexOf(l): 2 World!".IndexOf(l, 5): 9 World!".LastIndexOf(l): 9
M
Example 2
N
using System;
O namespace Samples { public class StringFormatSample { public class FortyTwoNotFormattable { public override string ToString() { return "*42"; } } public class FortyTwoFormattable: IFormattable { public override string ToString() { return "#42"; } public string ToString(string format, IFormatProvider formatProvider)
P Q R S T U V W X Y Z
2814
Contents | Index
System
String String() Constructor
{ return 42.ToString(format, formatProvider); } } public static void Main() { FortyTwoNotFormattable noFormatting = new FortyTwoNotFormattable(); FortyTwoFormattable formatting = new FortyTwoFormattable(); Console.WriteLine("object"); Console.WriteLine(noFormatting); Console.WriteLine(formatting); Console.WriteLine("object.ToString()"); Console.WriteLine(noFormatting.ToString()); Console.WriteLine(formatting.ToString()); Console.WriteLine("String.Format(\"{0}\", object)"); Console.WriteLine(String.Format("{0}", noFormatting)); Console.WriteLine(String.Format("{0}", formatting)); Console.WriteLine("String.Format(\"{0,15:P}\", object)"); Console.WriteLine(String.Format("{0,15:P}", noFormatting)); Console.WriteLine(String.Format("{0,15:P}", formatting)); }
A B C D E F G H I J K L
} }
M N
The output is
O object *42 42 object.ToString() *42 #42 String.Format("{0}", object) *42 42 String.Format("{0,15:P}", object) *42 4,200.00 %
P Q R S T U V W X
String(System.Char*) Constructor
Y [ILASM]
Z
public rtspecialname specialname instance void .ctor(class System.Char* value) [C#]
unsafe public String(char* value)
2815
Contents | Index
String
System
String() Constructor
Summary Constructs and initializes a new instance of System.String using a specified pointer to a sequence of Unicode characters. A
Parameters
B C D E
Parameter
Description
value
A pointer to a null-terminated array of Unicode characters. If value is a null pointer, System.String.Empty is created.
F G
Description
H
This member is not CLS-compliant. For a CLS-compliant alternative, use the System.String(System.Char) constructor. This constructor copies the sequence of Unicode characters at the specified pointer until a null character (hexadecimal 0x00) is reached. If the specified array is not null-terminated, the behavior of this constructor is system dependent. For example, such a situation might cause an access violation. [Note: In C# this constructor is defined only in the context of unmanaged code.]
I J K L M N
Example
O
using System;
P namespace Samples { public class StringConstructor { public unsafe static void Main() { char[] chars = {'H', 'e', 'l', 'l', 'o', }; string s; fixed(char* pc = chars) { s = new string(pc); } Console.WriteLine(s); Console.WriteLine("\"{0}\".Length: {1}", s, s.Length); } } }
Q R S T U V W X Y Z
2816
Contents | Index
System
String String() Constructor
The output is Hello "Hello".Length: 5
A B
String(System.Char*, System.Int32, System.Int32) Constructor
C
[ILASM]
D
public rtspecialname specialname instance void .ctor(class System.Char* value, int32 startIndex, int32 length)
E
[C#]
F
unsafe public String(char* value, int startIndex, int length)
G
Summary
H
Constructs and initializes a new instance of System.String using a specified pointer to a sequence of Unicode characters, the index within that sequence at which to start copying characters, and the number of characters to be copied to construct the System.String.
I J K
Parameters
L M
Parameter
Description N
value
A pointer to an array of Unicode characters.
O
startIndex
A System.Int32 containing the index within the array referenced by value from which to start copying.
P
length
Q
A System.Int32 containing the number of characters to copy from value to the new System.String. If length is zero, System.String.Empty is created.
R S T
Description
U
This member is not CLS-compliant. For a CLS-compliant alternative, use the System.String(System.Char, System.Int32, System.Int32) constructor. This constructor copies Unicode characters from value, starting at startIndex and ending at (startIndex + length – 1). If the specified range is outside of the memory allocated for the sequence of characters, the behavior of this constructor is system dependent. For example, such a situation might cause an access violation. [Note: In C# this constructor is defined only in the context of unmanaged code.]
V W X Y Z
2817
Contents | Index
String
System
String() Constructor
Exceptions Exception
Condition
A
startIndex or length is less than zero.
B System.ArgumentOutOfRangeException
C
-orvalue is a null pointer and length is not zero.
D E
Example
F
using System;
G namespace Samples { public class StringConstructor { public unsafe static void Main() { char[] chars = {'H', 'e', 'l', 'l', 'o', }; string s; fixed(char* pc = chars) { s = new string(pc, 3, 2); } Console.WriteLine(s); Console.WriteLine("\"{0}\".Length: {1}", s, s.Length); } } }
H I J K L M N O P Q R S
The output is
T lo "lo".Length: 2
U V W
String(System.Char, System.Int32) Constructor
X [ILASM]
Y
public rtspecialname specialname instance void .ctor(valuetype System.Char c, int32 count)
Z
[C#]
public String(char c, int count)
2818
Contents | Index
System
String String() Constructor
Summary Constructs and initializes a new instance of System.String. A
Parameters
B
Parameter
Description
C
c
A System.Char.
D
count
A System.Int32 containing the number of occurrences of c.
E F G
Description
H
If the specified number is 0, System.String.Empty is created.
I
Exceptions
J K
Exception
Condition
System.ArgumentOutOfRangeException
count is less than zero.
L M N
Example
O
using System;
P
namespace Samples { public class StringConstructor { public static void Main() { string s = new string('A', 9); Console.WriteLine(s); Console.WriteLine("\"{0}\".Length: {1}", s, s.Length); } } }
Q R S T U V W X Y
The output is
Z
AAAAAAAAA "AAAAAAAAA".Length: 9
2819
Contents | Index
String
System
String() Constructor
String(System.Char[]) Constructor [ILASM]
public rtspecialname specialname instance void .ctor(class System.Char[] value)
A
[C#]
public String(char[] value)
B C
Summary
D
Constructs and initializes a new instance of System.String by copying the specified array of Unicode characters.
E F
Parameters
G H I
Parameter
Description
value
An array of Unicode characters.
J K
Description
L
If the specified array is a null reference or contains no elements, System.String.Empty is created.
M N
Example
O
using System;
P namespace Samples { public class StringConstructor { public static void Main() { char[] chars = {'H', 'e', 'l', 'l', 'o', }; string s = new string(chars); Console.WriteLine(s); Console.WriteLine("\"{0}\".Length: {1}", s, s.Length); } } }
Q R S T U V W X Y
The output is
Z
Hello "Hello".Length: 5
2820
Contents | Index
System
String String() Constructor
String(System.Char[], System.Int32, System.Int32) Constructor [ILASM]
public rtspecialname specialname instance void .ctor(class System.Char[] value, int32 startIndex, int32 length)
A
[C#]
B
public String(char[] value, int startIndex, int length)
C
Summary
D
Constructs and initializes a new instance of System.String using an array of Unicode characters, the index within the array at which to start copying characters, and the number of characters to be copied.
E F G
Parameters Parameter
H I
Description
J
value
An array of Unicode characters.
K
startIndex
A System.Int32 containing the index within the array referenced by value from which to start copying.
L
length
A System.Int32 containing the number of characters to copy from the value array. If length is zero, System.String.Empty is created.
M N O P
Description
Q
This constructor copies the sequence Unicode characters found at value between indexes startIndex and startIndex + length – 1.
R S
Exceptions
T
Exception
Condition
System.ArgumentNullException
value is a null reference.
U V W
startIndex or length is less than zero. System.ArgumentOutOfRangeException
X
-or-
Y
The sum of startIndex and length is greater than the number of elements in value.
Z
2821
Contents | Index
String
System
String() Constructor
Example using System; namespace Samples { public class StringConstructor { public static void Main() { char[] chars = {'H', 'e', 'l', 'l', 'o', }; string s = new string(chars, 3, 2); Console.WriteLine(s); Console.WriteLine("\"{0}\".Length: {1}", s, s.Length); } } }
A B C D E F G H I J
The output is
K
lo "lo".Length: 2
L M N
String(System.SByte*) Constructor
O
[ILASM]
public rtspecialname specialname instance void .ctor(class System.SByte* value)
P
[C#]
Q
unsafe public String(sbyte* value)
R
Summary
S
Initializes a new instance of the System.String class to the value indicated by a pointer to an array of 8-bit signed integers.
T U
Parameters
V W
Parameter
Description
value
A pointer to a null-terminated array of 8-bit signed integers.
X Y Z
2822
Contents | Index
System
String String() Constructor
Description If value is a null pointer, the new instance is initialized to the empty string (""). This constructor copies the sequence of characters at the specified pointer until a null character (hexadecimal 0x00) is reached. If the specified array is not null-terminated, the behavior of this constructor is system dependent. For example, such a situation might cause an access violation. In C#, this constructor is defined only in the context of unmanaged code. This member is not CLS-compliant.
A B C D
Exceptions
E
Exception
Condition
System.ArgumentException
A new instance of System.String could not be initialized using value and the current code page.
F G H I J
String(System.SByte*, System.Int32, System.Int32) Constructor
K
[ILASM]
L
public rtspecialname specialname instance void .ctor(class System.SByte* value, int32 startIndex, int32 length)
M
[C#]
N
unsafe public String(sbyte* value, int startIndex, int length)
O
Summary
P
Initializes a new instance of the System.String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting character position within that array, and a length.
Q
Parameters
T
R S
U
Parameter
Description
value
A pointer to an array of 8-bit signed integers.
W
startIndex
The starting position within value.
X
length
The number of characters within value to use.
V
Y Z
2823
Contents | Index
String
System
String() Constructor
Description If value is a null pointer or length is zero, the new instance is initialized to the empty string (""). This constructor copies Unicode characters from value, starting at startIndex and ending at (startIndex + length – 1). If the specified range is outside of the memory allocated for the sequence of characters, the behavior of this constructor is system dependent. For example, such a situation might cause an access violation. In C#, this constructor is defined only in the context of unmanaged code. This member is not CLS-compliant.
A B C D E
Exceptions
F G
Exception
Condition
System.ArgumentOutOfRangeException
startIndex or length is less than zero.
H I
value + startIndex is less than 64K.
J System.ArgumentException
K
-orA new instance of System.String could not be initialized using value and the current code page.
L M N
String(System.SByte*, System.Int32, System.Int32, System.Text.Encoding) Constructor
O P
[ILASM]
Q
public rtspecialname specialname instance void .ctor(class System.SByte* value, int32 startIndex, int32 length, class System.Text.Encoding enc)
R
[C#]
S
unsafe public String(sbyte* value, int startIndex, int length, Encoding enc)
T
Summary
U
Constructs and initializes a new instance of the String class to the value indicated by a specified pointer to an array of 8-bit signed integers, a starting character position within that array, a length, and an Encoding object.
V W X Y Z
2824
Contents | Index
System
String String() Constructor
Parameters Parameter
Description
value
A pointer to a System.SByte array.
startIndex
A System.Int32 containing the starting position within value.
C
A System.Int32 containing the number of characters within value to use. If length is zero, System.String.Empty is created.
D
length
A System.Text.Encoding object that specifies how the array referenced by value is encoded.
F
A
enc
B
E
G H
Description
I
If value is a null pointer, a System.String.Empty instance is constructed. This member must be implemented if the Runtime Infrastructure Library is present in the implementation.
J K
Exceptions Exception
L M
Condition
N
startIndex or length is less than zero. System.ArgumentOutOfRangeException
O
-or-
P
value is a null pointer and length is not zero.
Q R
Example
S
using System;
T namespace Samples { public class StringConstructor { public unsafe static void Main() { SByte[] sbytes = {72, 101, 108, 108, 111}; string s; fixed(SByte* psb = sbytes) { s = new string(psb, 3, 2, System.Text.Encoding.UTF8);
U V W X Y Z
2825
Contents | Index
String
System
Empty Field
} Console.WriteLine(s); Console.WriteLine("\"{0}\".Length: {1}", s, s.Length);
A
} }
B }
C
The output is
D E
lo "lo".Length: 2
F G H
String.Empty Field
I
[ILASM]
.field public static initOnly string Empty
J
[C#]
public static readonly string Empty = ""
K L
Summary
M
A constant string representing the empty string.
N
Description
O
This field is a string of length zero, "".
P Q
Example
R
using System;
S
namespace Samples { public class StringEmpty { public static void Main() { Console.WriteLine("String.Empty == \"\": {0}", String.Empty == ""); Console.WriteLine("String.Empty == new string('a', 0): {0}", String.Empty == new string('a', 0)); Console.WriteLine("\"{0}\".Length: {1}", String.Empty, String.Empty.Length); } } }
T U V W X Y Z
2826
Contents | Index
System
String Chars Property
The output is String.Empty == "": True String.Empty == new string('a', 0): True "".Length: 0
A B C
String.Chars Property
D
[ILASM]
E
.property valuetype System.Char Chars[int32 index] { public hidebysig specialname instance valuetype System.Char get_Chars(int32 index) }
F
[C#]
G
public char this[int index] { get; }
H
Summary
I
Gets the character at a specified position in the current instance.
J
Description
K
index is the position of a character within a string. The first character in the string is at index 0. The length of a string is the number of characters it is made up of. The last accessible index of a string instance is its length – 1.
L M N
Exceptions
O P
Exception
Condition
System.IndexOutOfRangeException
index is greater than or equal to the length of the current instance or less than zero.
Q R S T
Example
U
using System;
V namespace Samples { public class StringChars { public static void Main() { string s = "Hello world!"; for(int i = 0; i < s.Length; i++)
W X Y Z
2827
Contents | Index
String
System
Length Property
Console.WriteLine(s[i]); } } }
A
The output is
B C
H e l l o
D E F
w o r l d !
G H I J K
String.Length Property
L
[ILASM]
M
.property int32 Length { public hidebysig specialname instance int32 get_Length() }
N
[C#]
O
public int Length { get; }
P
Summary
Q
Gets the number of characters in the current instance.
R S
Example
T
using System;
U
namespace Samples { public class StringLength { public static void Main() { string s = "Hello world!"; Console.WriteLine("Length of \"{0}\" is: {1}", s, s.Length); } } }
V W X Y Z
2828
Contents | Index
System
String Clone() Method
The output is Length of "Hello world!" is: 12
A B
String.Clone() Method
C [ILASM]
D
.method public final hidebysig virtual object Clone() [C#]
E
public object Clone()
F
Summary
G
Returns a reference to the current instance of System.String.
H
Description
I
[Note: System.String.Clone does not generate a new System.String instance. Use the System.String.Copy or System.String.CopyTo method to create a separate System.String object with the same value as the current instance. This method is implemented to support the System.ICloneable interface.]
J K L M
Example
N
using System;
O
namespace Samples { public class StringClone { public static void Main() { string s = "Hello world!"; Console.WriteLine("Interned: {0}", String.IsInterned(s) != null); string clone = (string)s.Clone(); Console.WriteLine("Interned: {0}", String.IsInterned(clone) != null); Console.WriteLine("s.Equals(clone): {0}", s.Equals(clone)); Console.WriteLine( "Object.ReferenceEquals(s, clone): {0}", Object.ReferenceEquals(s, clone)); s = DateTime.Now.ToString(); Console.WriteLine("Interned: {0}", String.IsInterned(s) != null);
P Q R S T U V W X Y Z
2829
Contents | Index
String
System
Compare() Method
clone = (string)s.Clone(); Console.WriteLine("Interned: {0}", String.IsInterned(clone) != null); Console.WriteLine("s.Equals(clone): {0}", s.Equals(clone)); Console.WriteLine( "Object.ReferenceEquals(s, clone): {0}", Object.ReferenceEquals(s, clone));
A B C }
D
} }
E F
The output is
G Interned: True Interned: True s.Equals(clone): True Object.ReferenceEquals(s, clone): True Interned: False Interned: False s.Equals(clone): True Object.ReferenceEquals(s, clone): True
H I J K L M
O
String.Compare(System.String, System.Int32, System.String, System.Int32, System.Int32) Method
P
[ILASM]
Q
.method public hidebysig static int32 Compare(string strA, int32 indexA, string strB, int32 indexB, int32 length)
N
[C#]
R
public static int Compare(string strA, int indexA, string strB, int indexB, int length)
S T
Summary
U
Compares substrings of two strings.
V W X Y Z
2830
Contents | Index
System
String Compare() Method
Parameters Parameter
Description
strA
The first System.String to compare.
indexA
A System.Int32 containing the starting index of the substring within strA.
C
strB
The second System.String to compare.
D
indexB
A System.Int32 containing the starting index of the substring within strB.
E
A System.Int32 containing the number of characters in the substrings to compare. If length is zero, then zero is returned.
F
length
A B
G H
Return Value
I
A System.Int32 containing a value that reflects the sort order of substrings of the two specified strings. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number.
J K L
Value
Meaning
M
The substring in strA is < the substring in strB, or strA is a null reference.
N
any negative number zero
The substring in strA == the substring in strB, or both strA and strB are null references.
any positive number
The substring in strA is > the substring in strB, or strB is a null reference.
O P Q R S T
Description
U
When either of the String arguments is the null reference a System.ArgumentOutOfRangeException shall be thrown if the corresponding index is non-zero. [Note: The result of comparing any System.String (including the empty string) to a null reference is greater than zero. The result of comparing two null references is zero. Uppercase letters evaluate greater than their lowercase equivalents. The method uses the culture of the current thread to determine the ordering of individual characters. The two strings are compared on a character-by-character basis.]
V W X Y Z
2831
Contents | Index
String
System
Compare() Method
Exceptions Exception
Condition
A
The sum of indexA and length is greater than strA.Length.
B
-or-
C
The sum of indexB and length is greater than strB.Length.
D
-orSystem.ArgumentOutOfRangeException
E
indexA, indexB, or length is negative. -or-
F
strA is null and indexA is non-zero.
G
-or-
H
strB is null and indexB is non-zero.
I J
Example
K
using System;
L
namespace Samples { public class StringCompare { public static void Main() { string s1 = "Hello world!"; string s2 = "Hello World!"; Console.WriteLine("Compare {0} to {1}: {2}", s1, s2, String.Compare(s1, 0, s2, 0, s2.Length)); int i = 6; Console.WriteLine( "Compare first {0} chars in {1} to {2}: {3}", i, s1, s2, String.Compare(s1, 0, s2, 0, i, true)); Console.WriteLine( "Compare last {0} chars in {1} to {2}: {3}", i, s1, s2, String.Compare(s1, s1.Length - i, s2, s2.Length - i, i)); } } }
M N O P Q R S T U V W X Y Z
2832
Contents | Index
System
String Compare() Method
The output is Compare Hello world! to Hello World!: -1 Compare first 6 chars in Hello world! to Hello World!: 0 Compare last 6 chars in Hello world! to Hello World!: -1
A B C
String.Compare(System.String, System.Int32, System.String, System.Int32, System.Int32, System.Boolean) Method
D E
[ILASM]
F
.method public hidebysig static int32 Compare(string strA, int32 indexA, string strB, int32 indexB, int32 length, bool ignoreCase)
G
[C#]
public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase)
H I
Summary
J
Compares substrings of two strings.
K L
Parameters
M
Parameter
Description
strA
The first System.String containing a substring to compare.
indexA
A System.Int32 containing the starting index of the substring within strA.
strB
The second System.String containing a substring to compare.
indexB
A System.Int32 containing the starting index of the substring within strB.
length
A System.Int32 containing the number of characters in the substrings to compare. If length is zero, then zero is returned.
ignoreCase
A System.Boolean indicating if the comparison is case-insensitive. If ignoreCase is true, the comparison is case-insensitive. If ignoreCase is false, the comparison is case-sensitive, and uppercase letters evaluate greater than their lowercase equivalents.
N O P Q R S T U V W X
Return Value
Y
A System.Int32 containing a value that reflects the sort order of substrings of the two specified strings. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number.
Z
2833
Contents | Index
String
System
Compare() Method
A B
Value Type
Condition
any negative number
The substring in strA is < the substring in strB, or strA is a null reference.
zero
The substring in strA == the substring in strB, or both strA and strB are null references.
any positive number
The substring in strA is > the substring in strB, or strB is a null reference.
C D E
Description
F
When either of the String arguments is the null reference a System.ArgumentOutOfRangeException shall be thrown if the corresponding index is non-zero. [Note: The result of comparing any System.String (including the empty string) to a null reference is greater than zero. The result of comparing two null references is zero. Uppercase letters evaluate greater than their lowercase equivalents. The method uses the culture of the current thread to determine the ordering of individual characters. The two strings are compared on a character-by-character basis.]
G H I J K L
Exceptions
M N
Exception
Condition
System.ArgumentOutOfRangeException
The sum of indexA and length is greater than strA.Length. -orThe sum of indexB and length is greater than strB.Length. -orindexA, indexB, or length is negative. -orstrA is null and indexA is non-zero. -orstrB is null and indexB is non-zero.
O P Q R S T U V W
Example
X
using System;
Y namespace Samples { public class StringCompare {
Z
2834
Contents | Index
System
String Compare() Method
public static void Main() { string s1 = "Hello world!"; string s2 = "Hello World!"; Console.WriteLine( "Compare {0} to {1} check case: {2}", s1, s2, String.Compare(s1, 0, s2, 0, s2.Length, false)); Console.WriteLine( "Compare {0} to {1} ignore case: {2}", s1, s2, String.Compare(s1, 0, s2, 0, s2.Length, true)); int i = 5; Console.WriteLine( "Compare first {0} chars in {1} to {2}: {3}", i, s1, s2, String.Compare(s1, 0, s2, 0, i, true)); }
A B C D E F G H I J K
}
L
}
M
The output is
N Compare Hello world! to Hello World! check case: -1 Compare Hello world! to Hello World! ignore case: 0 Compare first 5 chars in Hello world! to Hello World!: 0
O P Q
String.Compare(System.String, System.Int32, System.String, System.Int32, System.Int32, System.Boolean, System.Globalization.CultureInfo) Method
R
[ILASM]
T
.method public hidebysig static int32 Compare(string strA, int32 indexA, string strB, int32 indexB, int32 length, bool ignoreCase, class System.Globalization.CultureInfo culture)
U
S
V
[C#]
W
public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase, CultureInfo culture)
X
Summary
Y
Compares substrings of two specified System.String objects, ignoring or honoring their case, and using culture-specific information to influence the comparison.
Z
2835
Contents | Index
String
System
Compare() Method
Parameters Parameter
Description
strA
The first System.String.
C
indexA
The position of the substring within strA.
D
strB
The second System.String.
indexB
The position of the substring within the strB.
length
The maximum number of characters in the substrings to compare.
ignoreCase
A System.Boolean indicating a case-sensitive or insensitive comparison. (true indicates a case-insensitive comparison.)
culture
A System.Globalization.CultureInfo object that supplies culturespecific comparison information.
A B
E F G H I J K L
Return Value
M
An integer indicating the lexical relationship between the two comparands.
N O
Value Type
Condition
Q
less than zero
The substring in strA is less than the substring in strB.
R
zero
The substrings are equal, or length is zero.
greater than zero
The substring in strA is greater than the substring in strB.
P
S T U
Description
V
The substrings to compare start at strA plus indexA, and strB plus indexB. The length of the first substring is the length of strA minus indexA, and the length of the second substring is the length of strB minus indexB. The number of characters to compare is the lesser of the lengths of the two substrings, and length. The indexA, indexB, and length parameters must be nonnegative. The comparison uses the culture parameter to obtain culture-specific information such as casing rules and the alphabetic order of individual characters. For example, a culture could specify that certain combinations of characters be treated as a single character, or
W X Y Z
2836
Contents | Index
System
String Compare() Method
uppercase and lowercase characters be compared in a particular way, or that the sorting order of a character depends on the characters that precede or follow it. The comparison is performed using word sort rules. For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions. One or both comparands can be null. By definition, any string, including the empty string (""), compares greater than a null reference, and two null references compare equal to each other. The comparison terminates when an inequality is discovered or both substrings have been compared. However, if the two strings compare equal to the end of one string, and other string has characters remaining, then the string with remaining characters is considered greater. The return value is the result of the last comparison performed. Unexpected results can occur when comparisons are affected by culture-specific casing rules. For example, in Turkish, the following example yields the wrong results because the file system in Turkish does not use linguistic casing rules for the letter i in file.
A B C D E F G H I
static String IsFileURI(String path) { return (String.Compare(path, 0, "file:", 0, 5, true)== 0); }
J K
The path name needs to be compared in an invariant manner. The correct code to do this is as follows.
L M
static String IsFileURI(String path) { return (String.Compare(path, 0, "file:", 0, 5, true, CultureInfo.InvariantCulture)== 0); }
N O P
Exceptions
Q
Exception
System.ArgumentOutOfRangeException
Condition
R
indexA is greater than strA.Length.
S
-or-
T
indexB is greater than strB.Length.
U
-or-
V
indexA, indexB, or length is negative.
W System.ArgumentNullException
culture is null.
X Y Z
2837
Contents | Index
String
System
Compare() Method
String.Compare(System.String, System.String) Method [ILASM]
.method public hidebysig static int32 Compare(string strA, string strB)
A
[C#]
public static int Compare(string strA, string strB)
B C
Summary
D
Compares two System.String objects in a case-sensitive manner.
E
Parameters
F G
Parameter
Description
I
strA
The first System.String to compare. Can be a null reference.
J
strB
The second System.String to compare. Can be a null reference.
H
K L
Return Value
M
A System.Int32 containing a value that reflects the sort order of the two specified strings. The following table defines conditions under which the returned value is a negative number, zero, or a positive number.
N O P Q
Value
Meaning
R
any negative number
strA is lexicographically < strB, or strA is a null reference.
zero
strA is lexicographically == strB, or both strA and strB are null references.
any positive number
strA is lexicographically > strB, or strB is a null reference.
S T U V
Description
W
This method performs a case-sensitive operation. [Note: The result of comparing any System.String (including the empty string) to a null reference is greater than zero. The result of comparing two null references is zero. Uppercase letters evaluate greater than their lowercase equivalents. The method uses the culture of the current thread to determine the ordering of individual characters. The two strings are compared on a character-by-character basis.]
X Y Z
2838
Contents | Index
System
String Compare() Method
Example using System; namespace Samples { public class StringCompare { public static void Main() { string s1 = "Hello world!"; string s2 = "Hello World!"; Console.WriteLine( "Compare {0} to {1} check case: {2}", s1, s2, String.Compare(s1, s2)); Console.WriteLine( "Compare {0} to {1} check case: {2}", s2, s1, String.Compare(s2, s1)); Console.WriteLine( "Compare {0} to {1} check case: {2}", s1, s2, String.Compare(s1, s1)); } } }
A B C D E F G H I J K L M
The output is
N O
Compare Hello world! to Hello World! check case: -1 Compare Hello World! to Hello world! check case: 1 Compare Hello world! to Hello World! check case: 0
P Q R
String.Compare(System.String, System.String, System.Boolean) Method
S [ILASM]
T
.method public hidebysig static int32 Compare(string strA, string strB, bool ignoreCase)
U
[C#]
V
public static int Compare(string strA, string strB, bool ignoreCase)
W
Summary
X
Returns sort order of two System.String objects.
Y Z
2839
Contents | Index
String
System
Compare() Method
Parameters Parameter
Description
strA
The first System.String to compare. Can be a null reference.
strB
The second System.String to compare. Can be a null reference.
ignoreCase
A System.Boolean indicating whether the comparison is case-insensitive. If ignoreCase is true, the comparison is case-insensitive. If ignoreCase is false, the comparison is case-sensitive, and uppercase letters evaluate greater than their lowercase equivalents.
A B C D E F G H
Return Value
I
A System.Int32 containing a value that reflects the sort order of the two specified strings. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number.
J K L M N O
Value
Meaning
any negative number
strA is < strB, or strA is a null reference.
zero
strA == strB, or both strA and strB are null references.
any positive number
strA is > strB, or strB is a null reference.
P Q R
Description
S
[Note: The result of comparing any System.String (including the empty string) to a null reference is greater than zero. The result of comparing two null references is zero. Uppercase letters evaluate greater than their lowercase equivalents. The method uses the culture of the current thread to determine the ordering of individual characters. The two strings are compared on a character-by-character basis. String.Compare(strA, strB, false) is equivalent to String.Compare(strA, strB).]
T U V W X Y Z
2840
Contents | Index
System
String Compare() Method
Example using System; namespace Samples { public class StringCompare { public static void Main() { string s1 = "Hello world!"; string s2 = "Hello World!"; Console.WriteLine( "Compare {0} to {1} check case: {2}", s1, s2, String.Compare(s1, s2, false)); Console.WriteLine( "Compare {0} to {1} ignore case: {2}", s1, s2, String.Compare(s1, s2, true)); } } }
A B C D E F G H I J K
The output is
L M
Compare Hello world! to Hello World! check case: -1 Compare Hello world! to Hello World! ignore case: 0
N O
String.Compare(System.String, System.String, System.Boolean, System.Globalization.CultureInfo) Method
Q
[ILASM]
R
.method public hidebysig static int32 Compare(string strA, string strB, bool ignoreCase, class System.Globalization.CultureInfo culture)
S
P
[C#]
T
public static int Compare(string strA, string strB, bool ignoreCase, CultureInfo culture)
U V
Summary
W
Compares two specified System.String objects, ignoring or honoring their case, and using culture-specific information to influence the comparison.
X Y Z
2841
Contents | Index
String
System
Compare() Method
Parameters Parameter
Description
strA
The first System.String.
strB
The second System.String.
ignoreCase
A System.Boolean indicating a case-sensitive or insensitive comparison. (true indicates a case-insensitive comparison.)
culture
A System.Globalization.CultureInfo object that supplies culturespecific comparison information.
A B C D E F G H
Return Value
I
A 32-bit signed integer indicating the lexical relationship between the two comparands.
J K L M
Value
Meaning
less than zero
strA is less than strB.
zero
strA equals strB.
greater than zero
strA is greater than strB.
N O P Q R
Description
S
The comparison uses the culture parameter to obtain culture-specific information such as casing rules and the alphabetic order of individual characters. For example, a culture could specify that certain combinations of characters be treated as a single character, or uppercase and lowercase characters be compared in a particular way, or that the sorting order of a character depends on the characters that precede or follow it. The comparison is performed using word sort rules. For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions. One or both comparands can be null. By definition, any string, including the empty string (""), compares greater than a null reference, and two null references compare equal to each other. The comparison terminates when an inequality is discovered or both strings have been compared. However, if the two strings compare equal to the end of one string, and other
T U V W X Y Z
2842
Contents | Index
System
String CompareOrdinal() Method
string has characters remaining, then the string with remaining characters is considered greater. The return value is the result of the last comparison performed. Unexpected results can occur when comparisons are affected by culture-specific casing rules. For example, in Turkish, the following example yields the wrong results because the file system in Turkish does not use linguistic casing rules for the letter ‘i’ in “file”.
A B C
static String IsFileURI(String path) { return (String.Compare(path, 0, "file:", 0, 5, true)== 0); }
D
The path name needs to be compared in an invariant manner. The correct code to do this is as follows.
E
static String IsFileURI(String path) { return (String.Compare(path, 0, "file:", 0, 5, true, CultureInfo.InvariantCulture)== 0); }
G
F
H I
Exceptions
J
Exception
Condition
System.ArgumentNullException
culture is null.
K L M N
Example
O
The following example demonstrates how culture can affect a comparison. In Czech Czech Republic culture, ‘ch’ is a single character that is greater than ‘d’. However, in English - United States culture, “ch” consists of two characters, and ‘c’ is less than ‘d’.
P Q R S
String.CompareOrdinal(System.String, System.Int32, System.String, System.Int32, System.Int32) Method
T U
[ILASM]
.method public hidebysig static int32 CompareOrdinal(string strA, int32 indexA, string strB, int32 indexB, int32 length)
V
[C#]
W
public static int CompareOrdinal(string strA, int indexA, string strB, int indexB, int length)
X Y
Summary
Z
Compares substrings of two specified System.String objects based on the code points of the contained Unicode characters. 2843
Contents | Index
String
System
CompareOrdinal() Method
Parameters Parameter
Description
strA
The first System.String to compare.
C
indexA
A System.Int32 containing the starting index of the substring in strA.
D
strB
The second System.String to compare.
E
indexB
A System.Int32 containing the starting index of the substring in strB.
length
A System.Int32 containing the number of characters in the substrings to compare.
A B
F G H
Return Value
I
A System.Int32 containing a value that reflects the sort order of the two specified strings. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number.
J K L M N
Value Type
Condition
any negative number
The substring in strA is < the substring in strB, or strA is a null reference.
zero
The substring in strA == the substring in strB, or both strA and strB are null references.
any positive number
The substring in strA is > the substring in strB, or strB is a null reference.
O P Q R S
Description
T
When either of the String arguments is the null reference a System.ArgumentOutOfRangeException shall be thrown if the corresponding index is non-zero. [Note: The result of comparing any System.String (including the empty string) to a null reference is greater than zero. The result of comparing two null references is zero. Upper case letters evaluate greater than their lowercase equivalents. The method uses the culture of the current thread to determine the ordering of individual characters. The two strings are compared on a character-by-character basis.]
U V W X Y Z
2844
Contents | Index
System
String CompareOrdinal() Method
Exceptions Exception
Condition A
The sum of indexA and length is greater than strA.Length.
B
-or-
System.ArgumentOutOfRangeException
The sum of indexB and length is greater than strB.Length.
C
-or-
D
indexA, indexB, or length is negative.
E
-orstrA is null and indexA is non-zero.
F
-or-
G
strB is null and indexB is non-zero.
H I
Example
J
using System;
K
namespace Samples { public class StringCompareOrdinal { public static void Main() { string s1 = "Hello world!"; string s2 = "Hello World!"; Console.WriteLine( "CompareOrdinal {0} to {1}: {2}", s1, s2, String.CompareOrdinal(s1, 0, s2, 0, s2.Length)); int i = 6; Console.WriteLine( "CompareOrdinal first {0} chars " + "in {1} to {2}: {3}", i, s1, s2, String.CompareOrdinal(s1, 0, s2, 0, i)); Console.WriteLine( "CompareOrdinal last {0} chars " + "in {1} to {2}: {3}", i, s1, s2, String.CompareOrdinal(s1, s1.Length - i, s2, s2.Length - i, i)); } } }
L M N O P Q R S T U V W X Y Z
2845
Contents | Index
String
System
CompareOrdinal() Method
The output is CompareOrdinal Hello world! to Hello World!: 32 CompareOrdinal first 6 chars in Hello world! to Hello World!: 0 CompareOrdinal last 6 chars in Hello world! to Hello World!: 32
A B C
String.CompareOrdinal(System.String, System.String) Method
D
[ILASM]
E
.method public hidebysig static int32 CompareOrdinal(string strA, string strB)
F
[C#]
public static int CompareOrdinal(string strA, string strB)
G H
Summary
I
Compares two specified System.String objects based on the code points of the contained Unicode characters.
J K
Parameters
L M
Parameter
Description
N
strA
The first System.String to compare.
strB
The second System.String to compare.
O P Q
Return Value
R
A System.Int32 containing a value that reflects the sort order of the two specified strings. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number.
S T U V
Permission
Description
any negative number
strA is < strB, or strA is a null reference.
Y
zero
strA == strB, or both strA and strB are null references.
Z
any positive number
strA is > strB, or strB is a null reference.
W X
2846
Contents | Index
System
String CompareTo() Method
Description [Note: The result of comparing any System.String (including the empty string) to a null reference is greater than zero. The result of comparing two null references is zero. Uppercase letters evaluate greater than their lowercase equivalents. The method uses the culture of the current thread to determine the ordering of individual characters. The two strings are compared on a character-by-character basis.]
A B C
Example
D
using System;
E
namespace Samples { public class StringCompareOrdinal { public static void Main() { string s1 = "Hello world!"; string s2 = "Hello World!"; Console.WriteLine( "CompareOrdinal {0} to {1}: {2}", s1, s2, String.CompareOrdinal(s1, s2)); Console.WriteLine( "CompareOrdinal {0} to {1}: {2}", s1, s1, String.CompareOrdinal(s1, s1)); Console.WriteLine( "CompareOrdinal {0} to {1}: {2}", s2, s1, String.CompareOrdinal(s2, s1)); } } }
F G H I J K L M N O P Q R S T
The output is
U CompareOrdinal Hello world! to Hello World!: 32 CompareOrdinal Hello world! to Hello world!: 0 CompareOrdinal Hello World! to Hello world!: -32
V W X
String.CompareTo(System.Object) Method
Y
[ILASM]
Z
.method public final hidebysig virtual int32 CompareTo(object value) [C#]
public int CompareTo(object value)
2847
Contents | Index
String
System
CompareTo() Method
Summary Returns the sort order of the current instance compared to the specified object. A
Parameters
B C
Parameter
Description
D
value
The System.Object to compare to the current instance.
E F
Return Value
G
A System.Int32 containing a value that reflects the sort order of the current instance as compared to value. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number.
H I J K
Value
Condition
L
any negative number
The current instance is lexicographically < value.
zero
The current instance is lexicographically == value.
any positive number
The current instance is lexicographically > value, or value is a null reference.
M N O P Q
Description
R
value is required to be a System.String object. [Note: The result of comparing any System.String (including the empty string) to a null reference is greater than zero. The result of comparing two null references is zero. Uppercase letters evaluate greater than their lowercase equivalents. The method uses the culture of the current thread to determine the ordering of individual characters. The two strings are compared on a character-by-character basis. This method is implemented to support the System.IComparable interface.]
S T U V W X
Exceptions
Y Z
Exception
Condition
System.ArgumentException
value is not a System.String.
2848
Contents | Index
System
String CompareTo() Method
Example using System; namespace Samples { public class StringCompareTo { private static string CompareStrings(string s1, string s2) { int i = s1.CompareTo(s2); if(0 == i) return String.Format("{0} is equal to {1}", s1, s2); if(i > 0) return String.Format("{0} is greater than {1}", s1, s2); else return String.Format("{0} is less than {1}", s1, s2); }
A B C D E F G H I J
public static void Main() { string s1 = "damien"; string s2 = "brad"; Console.WriteLine(CompareStrings(s1, s1)); Console.WriteLine(CompareStrings(s1, s2)); Console.WriteLine(CompareStrings(s2, s1)); }
K L M N
}
O
}
P
The output is
Q R
damien is equal to damien damien is greater than brad brad is less than damien
S T U
String.CompareTo(System.String) Method
V
[ILASM]
.method public hidebysig instance int32 CompareTo(string strB)
W
[C#]
X
public int CompareTo(string strB)
Y
Summary
Z
Compares this instance with a specified System.String object.
2849
Contents | Index
String
System
Concat() Method
Parameters Parameter
Description
strB
A System.String.
A B C D
Return Value
E
A 32-bit signed integer indicating the lexical relationship between the two comparands.
F G H
Value
Condition
less than zero
This instance is less than strB.
aero
This instance is equal to strB.
I J
This instance is greater than strB.
K
greater than zero
L
-orstrB is null.
M N
Description
O
This method performs a word (case-sensitive and culture-sensitive) comparison using the current culture. For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions. For more information about the behavior of this method, see the System.String.Compare method.
P Q R S T U
String.Concat(System.Object) Method
V
[ILASM]
.method public hidebysig static string Concat(object arg0)
W
[C#]
public static string Concat(object arg0)
X Y
Summary
Z
Creates the System.String representation of a specified object.
2850
Contents | Index
System
String Concat() Method
Parameters Parameter
Description
arg0
A System.Object or null.
A B C
Return Value
D
System.String representation of the value of arg0.
E F
Description
G
A System.String.Empty string is used in place of any null argument.
H I
String.Concat(System.Object, System.Object) Method
J
[ILASM]
K
.method public hidebysig static string Concat(object arg0, object arg1) [C#]
L
public static string Concat(object arg0, object arg1)
M
Summary
N
Concatenates the System.String representations of two specified objects.
O P
Parameters
Q
Parameter
Description
arg0
The first System.Object to concatenate.
arg1
The second System.Object to concatenate.
R S T U V
Return Value
W
The concatenated System.String representation of the values of arg0 and arg1.
X
Description
Y
System.String.Empty is used in place of any null argument. This version of System.String.Concat is equivalent to System.String.Concat(arg0.ToString(), arg1.ToString()).
Z
2851
Contents | Index
String
System
Concat() Method
[Note: If either of the arguments is an array reference, the method concatenates a string representing that array, instead of its members (for example, System.String[]).] A
Example
B
using System;
C
namespace Samples { public class StringConcat { public static void Main() { object o = new Object(); int i = 42; string s = "Hello world!"; Console.WriteLine( "String.Concat({0}, {1}) yields: {2}", o, i, String.Concat(o, i)); Console.WriteLine( "String.Concat({0}, {1}) yields: {2}", i, s, String.Concat(i, s)); Console.WriteLine( "String.Concat({0}, {1}) yields: {2}", s, o, String.Concat(s, o)); } } }
D E F G H I J K L M N O P
The output is
Q R
String.Concat(System.Object, 42) yields: System.Object42 String.Concat(42, Hello world!) yields: 42Hello world! String.Concat(Hello world!, System.Object) yields: Hello world!System.Object
S T U
String.Concat(System.Object, System.Object, System.Object) Method
V [ILASM]
W
.method public hidebysig static string Concat(object arg0, object arg1, object arg2)
X
[C#]
public static string Concat(object arg0, object arg1, object arg2)
Y
Summary
Z
Concatenates the System.String representations of three specified objects, in order provided. 2852
Contents | Index
System
String Concat() Method
Parameters Parameter
Description
arg0
The first System.Object to concatenate.
arg1
The second System.Object to concatenate.
C
arg2
The third System.Object to concatenate.
D
A B
E F
Return Value
G
The concatenated System.String representations of the values of arg0, arg1, and arg2.
H
Description
I
This method concatenates the values returned by the System.String.ToString methods on every argument. System.String.Empty is used in place of any null argument. This version of System.String.Concat is equivalent to String.Concat(arg0.ToString(), arg1.ToString(), arg2.ToString()).
J K L M
Example
N
using System;
O namespace Samples { public class StringConcat { public static void Main() { object o = new Object(); int i = 42; string s = "Hello world!"; Console.WriteLine( "String.Concat({0}, {1}, {2}) yields: {3}", o, i, s, String.Concat(o, i, s)); Console.WriteLine( "String.Concat({0}, {1}, {2}) yields: {3}", s, i, o, String.Concat(s, i, o)); Console.WriteLine( "String.Concat({0}, {1}, {2}) yields: {3}", o, o, o, String.Concat(o, o, o)); } } }
P Q R S T U V W X Y Z
2853
Contents | Index
String
System
Concat() Method
The output is String.Concat(System.Object, 42, Hello world!) yields: System.Object42Hello world! String.Concat(Hello world!, 42, System.Object) yields: Hello world!42System.Object String.Concat(System.Object, System.Object, System.Object) yields: System.ObjectSystem.ObjectSystem.Object
A B C
E
String.Concat(System.Object, System.Object, System.Object, System.Object) Method
F
[ILASM]
G
.method public hidebysig static string Concat(object arg0, object arg1, object arg2, object arg3)
D
[C#]
H
public static string Concat(object arg0, object arg1, object arg2, object arg3)
I
Summary
J
This member is not CLS-compliant.
K L M
String.Concat(System.Object[]) Method
N
[ILASM]
.method public hidebysig static string Concat(class System.Object[] args)
O
[C#]
public static string Concat(params object[] args)
P Q
Sumary
R
Concatenates the System.String representations of the elements in an array of System.Object instances.
S T
Parameters
U V
Parameter
Description
W
args
An array of System.Object instances to concatenate.
X Y
Description
Z
This method concatenates the values returned by the System.String.ToString methods on every object in the args array. System.String.Empty is used in place of any null reference in the array. 2854
Contents | Index
System
String Concat() Method
Exceptions Exception
Condition
System.ArgumentNullException
args is a null reference.
A B C
Example
D
using System;
E
namespace Samples { public class StringConcat { public static void Main() { object[] objects = {new Object(), 42, "Hello world!"}; Console.WriteLine("String.Concat(objects):"); Console.WriteLine(String.Concat(objects)); Console.WriteLine("String.Concat(42, \"Dave\", " + "DateTime.Now, new object()"); Console.WriteLine(String.Concat(42, "Dave", DateTime.Now, new object())); } } }
F G H I J K L M N O P Q R
The output is
S
String.Concat(objects): System.Object42Hello world! String.Concat(42, "Dave", DateTime.Now, new object() 42Dave20/06/2003 8:08:34 PMSystem.Object
T U V W
String.Concat(System.String, System.String) Method
X
[ILASM]
Y
.method public hidebysig static string Concat(string str0, string str1)
Z
[C#]
public static string Concat(string str0, string str1)
2855
Contents | Index
String
System
Concat() Method
Summary Concatenates two specified instances of System.String. A
Parameters
B C
Parameter
Description
D
str0
The first System.String to concatenate.
str1
The second System.String to concatenate.
E F G
Description
H
System.String.Empty is used in place of any null argument.
I J
Example
K
using System;
L
namespace Samples { public class StringConcat { public static void Main() { string s1 = "one ", s2 = "two"; Console.WriteLine( "String.Concat({0}, {1}) yields: {2}", s1, s2, String.Concat(s1, s2)); } } }
M N O P Q R S T
The output is
U String.Concat(one, two) yields: one two
V W X
String.Concat(System.String, System.String, System.String) Method
Y
[ILASM]
.method public hidebysig static string Concat(string str0, string str1, string str2)
Z
[C#]
public static string Concat(string str0, string str1, string str2)
2856
Contents | Index
System
String Concat() Method
Summary Concatenates three specified instances of System.String. A
Parameters
B
Parameter
Description
str0
The first System.String to concatenate.
str1
The second System.String to concatenate.
str2
The third System.String to concatenate.
C D E F G H
Description
I
System.String.Empty is used in place of any null argument.
J
Example
K
using System;
L M
namespace Samples { public class StringConcat { public static void Main() { string s1 = "one ", s2 = "two ", s3 = "three"; Console.WriteLine( "String.Concat({0}, {1}, {2}) yields: {3}", s1, s2, s3, String.Concat(s1, s2, s3)); } } }
N O P Q R S T U V
The output is
W String.Concat(one, two, three) yields: one two three
X Y Z
2857
Contents | Index
String
System
Concat() Method
String.Concat(System.String, System.String, System.String, System.String) Method [ILASM]
A
.method public hidebysig static string Concat(string str0, string str1, string str2, string str3)
B
[C#]
C
public static string Concat(string str0, string str1, string str2, string str3)
D
Summary
E
Concatenates four specified instances of System.String.
F G
Parameters
H I
Parameter
Description
J
str0
The first System.String.
str1
The second System.String.
str2
The third System.String.
str3
The fourth System.String.
K L M N O P
Description
Q
A System.String.Empty string is used in place of any null object in the array.
R S
String.Concat(System.String[]) Method
T
[ILASM]
.method public hidebysig static string Concat(class System.String[] values)
U
[C#]
V
public static string Concat(params string[] values)
W
Summary
X
Concatenates the elements of a specified array.
Y Z
2858
Contents | Index
System
String Concat() Method
Parameters Parameter
Description
values
An array of System.String instances to concatenate.
A B C
Description
D
System.String.Empty is used in place of any null reference in the array.
E F
Exceptions
G
Exception
Condition
System.ArgumentNullException
values is a null reference.
H I J K
Example
L
using System;
M namespace Samples { public class StringConcat { public static void Main() { string[] strings = {"one ", "two ", "three"}; Console.WriteLine("String.Concat(strings): {0}", String.Concat(strings)); Console.WriteLine("String.Concat(\"1\", \"2\", \"3\", " + "\"4\", \"5\") : {0}", String.Concat("1", "2", "3", "4", "5")); } } }
N O P Q R S T U V W
The output is
X String.Concat(strings): one two three String.Concat("1", "2", "3", "4", "5"): 12345
Y Z
2859
Contents | Index
String
System
Copy() Method
String.Copy(System.String) Method [ILASM]
.method public hidebysig static string Copy(string str)
A
[C#]
public static string Copy(string str)
B C
Summary
D
Creates a new instance of System.String with the same value as a specified instance of System.String.
E F
Parameters
G H
Parameter
Description
str
The System.String to be copied.
I J K
Exceptions
L M
Exception
Condition
System.ArgumentNullException
str is a null reference.
N O P
Example
Q
using System;
R namespace Samples { public class StringCopy { public static void Main() { string s = "Hello world!"; Console.WriteLine("Interned: {0}", String.IsInterned(s) != null); string copy = String.Copy(s); Console.WriteLine("Interned: {0}", String.IsInterned(copy) != null); Console.WriteLine("s.Equals(copy): {0}", s.Equals(copy)); Console.WriteLine(
S T U V W X Y Z
2860
Contents | Index
System
String CopyTo() Method
"Object.ReferenceEquals(s, copy): {0}", Object.ReferenceEquals(s, copy)); s = DateTime.Now.ToString(); Console.WriteLine("Interned: {0}", String.IsInterned(s) != null); copy = String.Copy(s); Console.WriteLine("Interned: {0}", String.IsInterned(copy) != null); Console.WriteLine("s.Equals(copy): {0}", s.Equals(copy)); Console.WriteLine( "Object.ReferenceEquals(s, copy): {0}", Object.ReferenceEquals(s, copy));
A B C D E F
}
G
}
H
}
I
The output is
J Interned: True Interned: True s.Equals(copy): True Object.ReferenceEquals(s, copy): False Interned: False Interned: False s.Equals(copy): True Object.ReferenceEquals(s, copy): False
K L M N O P
String.CopyTo(System.Int32, System.Char[], System.Int32, System.Int32) Method
Q
[ILASM]
S
.method public hidebysig instance void CopyTo(int32 sourceIndex, class System.Char[] destination, int32 destinationIndex, int32 count)
T
R
[C#]
U
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
V W
Summary
X
Copies a specified number of characters from a specified position in the current System.String instance to a specified position in a specified array of Unicode characters.
Y Z
2861
Contents | Index
String
System
CopyTo() Method
Parameters Parameter
Description
sourceIndex
A System.Int32 containing the index of the current instance from which to copy.
destination
An array of Unicode characters.
destinationIndex
A System.Int32 containing the index of an array element in destination to copy.
count
A System.Int32 containing the number of characters in the current instance to copy to destination.
A B C D E F G H I
Exceptions
J K L
Exception
Condition
System.ArgumentNullException
destination is a null reference.
M
sourceIndex, destinationIndex, or count is negative.
N
-or-
O
System.ArgumentOutOfRangeException
P
count is greater than the length of the substring from startIndex to the end of the current instance. -or-
Q
count is greater than the length of the subarray from destinationIndex to the end of destination.
R S
Example
T
using System;
U
namespace Samples { public class StringCopyTo { public static void Main() { string s = "Hello world!"; char[] chars = new char[s.Length]; s.CopyTo(0, chars, 0, chars.Length); foreach(char c in chars)
V W X Y Z
2862
Contents | Index
System
String EndsWith() Method
Console.Write(c); Console.WriteLine(); int i = 6; s.CopyTo(0, chars, i, chars.Length - i); foreach(char c in chars) Console.Write(c); Console.WriteLine();
A B C
} }
D
}
E
The output is
F
Hello world! Hello Hello
G H I
String.EndsWith(System.String) Method
J
[ILASM]
K
.method public hidebysig instance bool EndsWith(string value)
L
[C#]
public bool EndsWith(string value)
M
Summary
N
Returns a System.Boolean value that indicates whether the ending characters of the current instance match the specified System.String.
O P Q
Parameters
R
Parameter
Description
value
A System.String to match.
S T U V
Return Value
W
true if the end of the current instance is equal to value; false if value is not equal to the end of the current instance or is longer than the current instance.
X Y
Description
Z
This method compares value with the substring at the end of the current instance that has the same length as value.
2863
Contents | Index
String
System
EndsWith() Method
The comparison is case-sensitive.
Exceptions
A B C
Exception
Condition
System.ArgumentNullException
value is a null reference.
D E
Example
F
using System;
G namespace Samples { public class StringEndsWith { public static void Main() { string s = "Hello world!"; for(int i = 0; i <= s.Length; i++) { string end = s.Substring(s.Length - i, i); Console.WriteLine( "Does \"{0}\" end with \"{1}\": {2}", s, end, s.EndsWith(end)); } } } }
H I J K L M N O P Q R
The output is
S T
Does Does Does Does Does Does Does Does Does Does Does Does Does
U V W X Y Z
"Hello "Hello "Hello "Hello "Hello "Hello "Hello "Hello "Hello "Hello "Hello "Hello "Hello
world!" world!" world!" world!" world!" world!" world!" world!" world!" world!" world!" world!" world!"
end end end end end end end end end end end end end
with with with with with with with with with with with with with
"": True "!": True "d!": True "ld!": True "rld!": True "orld!": True "world!": True " world!": True "o world!": True "lo world!": True "llo world!": True "ello world!": True "Hello world!": True
2864
Contents | Index
System
String Equals() Method
String.Equals(System.Object) Method [ILASM]
.method public hidebysig virtual bool Equals(object obj) [C#]
A
public override bool Equals(object obj)
B C
Summary
D
Determines whether the current instance and the specified object have the same value.
E
Parameters
F
Parameter
Description
obj
A System.Object.
G H I J
Return Value
K
true if obj is a System.String and its value is the same as the value of the current instance; otherwise, false.
L M
Description
N
This method checks for value equality. This comparison is case-sensitive. [Note: This method overrides System.Object.Equals.]
O
Exceptions
Q
P
R
Exception
Condition
S
System.NullReferenceException
The current instance is a null reference.
T U V
Example
W
using System;
X
namespace Samples { public class StringEquals { public static void Main() {
Y Z
2865
Contents | Index
String
System
Equals() Method
string s = "Hello World!"; string upper = s.ToUpper(); Console.WriteLine("s.Equals(upper): {0}", s.Equals(upper)); Console.WriteLine("s.ToUpper().Equals(upper): {0}", s.ToUpper().Equals(upper)); string copy = String.Copy(s); Console.WriteLine("s.Equals(copy): {0}", s.Equals(copy)); Console.WriteLine( "Object.ReferenceEquals(s, copy): {0}", Object.ReferenceEquals(s, copy));
A B C D E F
} }
G
}
H
The output is
I
s.Equals(upper): False s.ToUpper().Equals(upper): True s.Equals(copy): True Object.ReferenceEquals(s, copy): False
J K L M N
String.Equals(System.String) Method
O
[ILASM]
.method public hidebysig instance bool Equals(string value)
P
[C#]
public bool Equals(string value)
Q R
Summary
S
Determines whether this instance and a specified System.String have the same value.
T
Parameters
U V
Parameter
Description
value
A System.String.
W X Y
Return Value
Z
true if the value of value is the same as this instance; otherwise, false.
2866
Contents | Index
System
String Equals() Method
Description This method performs an ordinal (case-sensitive and culture-insensitive) comparison. A
Exceptions
B
Exception
Condition
C
System.NullReferenceException
This instance is null.
D E F
String.Equals(System.String, System.String) Method
G
[ILASM]
H
.method public hidebysig static bool Equals(string a, string b)
I
[C#]
public static bool Equals(string a, string b)
J K
Summary
L
Determines whether two specified System.String objects have the same value.
M
Parameters Parameter
N O
Description
P
a
A System.String or a null reference.
Q
b
A System.String or a null reference.
R S
Return Value
T
true if the value of a is the same as the value of b; otherwise, false.
U V
Description
W
The comparison is case-sensitive.
X Y Z
2867
Contents | Index
String
System
Format() Method
Example using System; namespace Samples { public class StringEquals { public static void Main() { string s = "Hello world!"; string clone = (string) s.Clone(); Console.WriteLine( "String.Equals(s, clone): {0}", String.Equals(s, clone)); string copy = String.Copy(s); Console.WriteLine( "String.Equals(s, copy) : {0}", String.Equals(s, copy)); Console.WriteLine( "Object.ReferenceEquals(s, clone): {0}", Object.ReferenceEquals(s, clone)); Console.WriteLine( "Object.ReferenceEquals(s, copy): {0}", Object.ReferenceEquals(s, copy)); } } }
A B C D E F G H I J K L M N O P
The output is
Q String.Equals(s, clone): True String.Equals(s, copy) : True Object.ReferenceEquals(s, clone): True Object.ReferenceEquals(s, copy): False
R S T U
String.Format(System.String, System.Object) Method
V
[ILASM]
W
.method public hidebysig static string Format(string format, object arg0) [C#]
X
public static string Format(string format, object arg0)
Y
Summary
Z
Replaces the format specification in a provided System.String with a specified textual equivalent of the value of a specified System.Object instance. 2868
Contents | Index
System
String Format() Method
Parameters Parameter
Description
format
A System.String containing zero or more format specifications.
arg0
A System.Object to be formatted.
A B C D
Return Value
E
A copy of format in which the first format specification has been replaced by the formatted System.String equivalent of the arg0.
F G H
Description
I
[Note: This version of System.String.Format is equivalent to String.Format(null, format, new Object[]{arg0}). For more information on the format specification see the System.String class overview.]
J K L
Exceptions
M
Exception
Condition
System.ArgumentNullException
format is a null reference.
N O P
The format specification in format is invalid.
Q
-orSystem.FormatException
R
The number indicating an argument to be formatted is less than zero, or greater than or equal to the number of provided objects to be formatted (1).
S T U
Example
V
using System;
W
namespace Samples { public class StringFormat { public static void Main() { Console.WriteLine(
X Y Z
2869
Contents | Index
String
System
Format() Method
String.Format("{0:0000}", 42)); Console.WriteLine( String.Format("{0:####}", 42)); Console.Write(String.Format("{0, -10}", 42)); Console.Write(String.Format("{0, -10}", 42)); Console.WriteLine( String.Format("{0, -10}", 42)); Console.WriteLine( String.Format("{0:dddd dd MMMM yyyy}", DateTime.Now));
A B C D }
E }
F
}
G
The output is
H 0042 42 42 42 42 Friday 20 June 2003
I J K L M
String.Format(System.String, System.Object, System.Object) Method
N
[ILASM]
O
.method public hidebysig static string Format(string format, object arg0, object arg1) [C#]
P
public static string Format(string format, object arg0, object arg1)
Q R
Summary
S
Replaces the format specification in a specified System.String with the textual equivalent of the value of two specified System.Object instances.
T
Parameters
U V
Parameter
Description
X
format
A System.String containing zero or more format specifications.
Y
arg0
A System.Object to be formatted. Can be a null reference.
arg1
A System.Object to be formatted. Can be a null reference.
W
Z
2870
Contents | Index
System
String Format() Method
Return Value A System.String containing a copy of format in which the format specifications have been replaced by the System.String equivalent of arg0 and arg1. A
Description
B
If an object referenced in the format string is a null reference, an empty string is used in its place. [Note: This version of System.String.Format is equivalent to String.Format(null, format, new Object[]{arg0, arg1}). For more information on the format specification see the System.String class overview.]
C D E F G
Exceptions
H
Exception
Condition
System.ArgumentNullException
format is a null reference.
System.FormatException
I J K
format is invalid.
L
-or-
M
The number indicating an argument to be formatted is less than zero, or greater than or equal to the number of provided objects to be formatted (2).
N O P
Example
Q
using System;
R
namespace Samples { public class StringFormat { public static void Main() { Console.WriteLine( String.Format("1:{0:0000} 2:{0:####}", 42, 42)); Console.WriteLine( String.Format("1: {0, -10} 2: {0, -10}", 42, 42)); Console.WriteLine( String.Format(
S T U V W X Y Z
2871
Contents | Index
String
System
Format() Method
"Date: {0:dd MMMM yyyy} Day: {1:dddd}", DateTime.Now, DateTime.Now)); } }
A
}
B
The output is
C
1:0042 2:42 1: 42 2: 42 Date: 20 June 2003 Day: Friday
D E F G H
String.Format(System.String, System.Object, System.Object, System.Object) Method
I
[ILASM]
J
.method public hidebysig static string Format(string format, object arg0, object arg1, object arg2)
K
[C#]
public static string Format(string format, object arg0, object arg1, object arg2)
L M
Summary
N
Replaces the format specification in a specified System.String with the textual equivalent of the value of three specified System.Object instances.
O P
Parameters
Q R
Parameter
Description
S
format
A System.String containing zero or more format specifications.
arg0
The first System.Object to be formatted. Can be a null reference.
arg1
The second System.Object to be formatted. Can be a null reference.
arg2
The third System.Object to be formatted. Can be a null reference.
T U V W X Y
Return Value
Z
A System.String containing a copy of format in which the first, second, and third format specifications have been replaced by the System.String equivalent of arg0, arg1, and arg2.
2872
Contents | Index
System
String Format() Method
Description If an object referenced in the format string is a null reference, an empty string is used in its place. [Note: This version of System.String.Format is equivalent to String.Format(null, format, new Object[]{arg0, arg1, arg2}). For more information on the format specification see the System.String class overview.]
A B C D
Exceptions
E
Exception
Condition
System.ArgumentNullException
format is a null reference.
F G H
format is invalid.
I
-orSystem.FormatException
J
The number indicating an argument to be formatted is less than zero, or greater than or equal to the number of provided objects to be formatted (3).
K L M
Example
N
using System;
O namespace Samples { public class StringFormat { public static void Main() { Console.WriteLine( String.Format( "1:{0, 10} 2:{1, -10} 3:{2:0000}", 42, 42, 42)); DateTime d = DateTime.Now; Console.WriteLine( String.Format( "Date: {0:dd MMMM yyyy} " + "Day: {1:dddd} Time: {2: hh mm}", d, d, d)); } } }
P Q R S T U V W X Y Z
2873
Contents | Index
String
System
Format() Method
The output is 1: 42 2:42 3:0042 Date: 20 June 2003 Day: Friday Time:
A
08 22
B C
String.Format(System.String, System.Object[]) Method
D
[ILASM]
E
.method public hidebysig static string Format(string format, class System.Object[] args)
F
[C#]
public static string Format(string format, params object[] args)
G H
Summary
I
Replaces the format specification in a specified System.String with the textual equivalent of the value of a corresponding System.Object instance in a specified array.
J K
Parameters
L M
Parameter
Description
N
format
A System.String containing zero or more format specifications.
args
A System.Object array containing the objects to be formatted.
O P Q
Return Value
R
A System.String containing a copy of format in which the format specifications have been replaced by the System.String equivalent of the corresponding instances of System.Object in args.
S T U
Description
V
If an object referenced in the format string is a null reference, an empty string is used in its place. [Note: This version of System.String.Format is equivalent to System.String.Format(null, format, args). For more information on the format specification see the System.String class overview.]
W X Y Z
2874
Contents | Index
System
String Format() Method
Exceptions Exception
Condition A
System.ArgumentNullException
format or args is a null reference.
B C
format is invalid. System.FormatException
D
-or-
E
The number indicating an argument to be formatted is less than zero, or greater than or equal to the length of the args array.
F G
Example
H
using System;
I
namespace Samples { public class StringFormat { public static void Main() { object[] objects = {new Object(), 42, "Hello world!"}; Console.WriteLine( "Object: {0} Integer: {1} String: {2}", objects); } } }
J K L M N O P Q R S
The output is
T Object: System.Object Integer: 42 String: Hello world!
U V
String.Format(System.IFormatProvider, System.String, System.Object[]) Method
W X
[ILASM]
Y
.method public hidebysig static string Format(class System.IFormatProvider provider, string format, class System.Object[] args)
Z
[C#]
public static string Format(IFormatProvider provider, string format, params object[] args)
2875
Contents | Index
String
System
Format() Method
Summary Replaces the format specification in a specified System.String with the culture-specific textual equivalent of the value of a corresponding System.Object instance in a specified array. A
Parameters
B C
Parameter
Description
provider
A System.IFormatProvider interface that supplies an object that provides culture-specific formatting information. Can be a null reference.
format
A System.String containing zero or more format specifications.
args
A System.Object array to be formatted.
D E F G H I
Return Value
J
A System.String containing a copy of format in which the format specifications have been replaced by the System.String equivalent of the corresponding instances of System.Object in args.
K L M
Description
N
If an object referenced in the format string is a null reference, an empty string is used in its place. The format parameter string is embedded with zero or more format specifications of the form, {N [, M][: formatString]}, where N is a zero-based integer indicating the argument to be formatted, M is an optional integer indicating the width of the region to contain the formatted value, and formatString is an optional string of formatting codes. [Note: For more information on the format specification see the System.String class overview.]
O P Q R S T
Exceptions
U V
Exception
Condition
W
System.ArgumentNullException
format or args is a null reference.
X
format is invalid.
Y System.FormatException
Z
-orThe number indicating an argument to be formatted (N) is less than zero, or greater than or equal to the length of the args array.
2876
Contents | Index
System
String GetEnumerator() Method
Example using System; using System.Globalization;
A namespace Samples { public class StringFormat { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.NegativeSign = "minus"; Object[] objects = { -42, -42, -42}; Console.WriteLine(String.Format( c, "{0:0000}*{1, -20}*{2, 20}.", objects)); } } }
B C D E F G H I J K L
The output is minus0042*minus42
M *
minus42.
N O
String.GetEnumerator() Method
P
[ILASM]
Q
.method public hidebysig instance class System.CharEnumerator GetEnumerator()
R
[C#]
S
public CharEnumerator GetEnumerator()
T
Summary
U
Retrieves an object that can iterate through the individual characters in the current instance.
V W
Description
X
This method is required by programming languages that support the System.Collections.IEnumerator interface to iterate through members of a collection.
Y Z
2877
Contents | Index
String
System
GetHashCode() Method
Example using System; namespace Samples { public class StringGetEnumerator { public static void Main() { string s = "Hello World!"; CharEnumerator ce = s.GetEnumerator(); while(ce.MoveNext()) Console.WriteLine(ce.Current); } } }
A B C D E F G H I
The output is
J
H e l l o
K L M N
W o r l d !
O P Q R S
String.GetHashCode() Method
T
[ILASM]
.method public hidebysig virtual int32 GetHashCode()
U
[C#]
V
public override int GetHashCode()
W
Summary
X
Generates a hash code for the current instance.
Y Z
Description The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.] 2878
Contents | Index
System
String IndexOf() Method
Example using System; namespace Samples { public class StringGetHashCode { public static void Main() { string[] strings = {"one", "two", "three", String.Empty}; foreach(string s in strings) Console.WriteLine( "\"{0}\".GetHashCode(): {1}", s, s.GetHashCode()); } } }
A B C D E F G H I J
The output is
K L
"one".GetHashCode(): 193420161 "two".GetHashCode(): 193421353 "three".GetHashCode(): 183191147 "".GetHashCode(): 5381
M N O
String.GetTypeCode() Method
P
[ILASM]
Q
.method public final hidebysig virtual valuetype System.TypeCode GetTypeCode()
R
[C#]
S
public TypeCode GetTypeCode()
T
Summary
U
Returns the System.TypeCode for class System.String.
V W
String.IndexOf(System.Char) Method
X
[ILASM]
Y
.method public hidebysig instance int32 IndexOf(valuetype System.Char value)
Z
[C#]
public int IndexOf(char value)
2879
Contents | Index
String
System
IndexOf() Method
Summary Returns the index of the first occurrence of a specified Unicode character in the current instance. A
Parameters
B C
Parameter
Description
value
A Unicode character.
D E F G
Return Value
H
A System.Int32 containing a positive value equal to the index of the first occurrence of value character in the current instance; otherwise, –1 if value was not found.
I J
Description
K
This method is case-sensitive.
L
Example
M
using System;
N
namespace Samples { public class StringIndexOf { public static void Main() { string s = "Hello world!"; for(int i = 0; i < s.Length; i++) { char c = s[i]; Console.WriteLine("Char {0} is first found at {1}", c, s.IndexOf(c)); } } } }
O P Q R S T U V W X
The output is
Y Char Char Char Char
Z
H e l l
is is is is
first first first first
found found found found
at at at at
0 1 2 2
2880
Contents | Index
System
String IndexOf() Method
Char Char Char Char Char Char Char Char
o is is w is o is r is l is d is ! is
first first first first first first first first
found found found found found found found found
at at at at at at at at
4 5 6 4 8 2 10 11
A B C D E
String.IndexOf(System.Char, System.Int32) Method
F [ILASM]
G
.method public hidebysig instance int32 IndexOf(valuetype System.Char value, int32 startIndex) [C#]
H
public int IndexOf(char value, int startIndex)
I
Summary
J
Returns the index of the first occurrence of a specified Unicode character in the current instance, with the search starting from a specified index.
K L M
Parameters
N
Parameter
Description
O
value
A Unicode character.
P
startIndex
A System.Int32 containing the index of the current instance from which to start searching.
Q R S
Return Value
T
A System.Int32 containing a positive value equal to the index of the first occurrence of value in the current instance; otherwise, –1 if value was not found.
U
Description
W
This method is case-sensitive.
X
V
Y Z
2881
Contents | Index
String
System
IndexOf() Method
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
startIndex is less than zero or greater than the length of the current instance.
A B C D
Example
E
using System;
F namespace Samples { public class StringIndexOf { public static void Main() { string s = "Hello world!"; int start = 4; for(int i = 0; i < s.Length; i++) { char c = s[i]; Console.WriteLine("When starting at index {0} " + "Char {1} is first found at {2}", start, c, s.IndexOf(c, start)); } } } }
G H I J K L M N O P Q R
The output is
S When When When When When When When When When When When When
T U V W X Y Z
starting starting starting starting starting starting starting starting starting starting starting starting
at at at at at at at at at at at at
index index index index index index index index index index index index
4 4 4 4 4 4 4 4 4 4 4 4
Char Char Char Char Char Char Char Char Char Char Char Char
H e l l o w o r l d !
is is is is is is is is is is is is
first first first first first first first first first first first first
found found found found found found found found found found found found
at at at at at at at at at at at at
-1 -1 9 9 4 5 6 4 8 9 10 11
2882
Contents | Index
System
String IndexOf() Method
String.IndexOf(System.Char, System.Int32, System.Int32) Method [ILASM]
.method public hidebysig instance int32 IndexOf(valuetype System.Char value, int32 startIndex, int32 count)
A
[C#]
B
public int IndexOf(char value, int startIndex, int count)
C
Summary
D
Returns the index of the first occurrence of a specified Unicode character in the current instance, with the search over the specified range starting at the provided index.
E F
Parameters
G H
Parameter
Description
value
A Unicode character.
J
startIndex
A System.Int32 containing the index of the current instance from which to start searching.
K
count
A System.Int32 containing the range of the current instance at which to end searching.
I
L M N
Return Value
O
A System.Int32 containing a positive value equal to the index of the first occurrence of value in the current instance; otherwise, –1 if value was not found.
P Q R
Description
S
The search begins at startIndex and continues until startIndex + count – 1 is reached. The character at startIndex + count is not included in the search. This method is case-sensitive.
T U V
Exceptions
W
Exception
System.ArgumentOutOfRangeException
Condition
X
startIndex or count is negative.
Y
-or-
Z
startIndex + count is greater than the length of the current instance.
2883
Contents | Index
String
System
IndexOf() Method
Example using System; namespace Samples { public class StringIndexOf { public static void Main() { string s = "Hello world!"; int start = 3, count = 6; for(int i = 0; i < s.Length; i++) { char c = s[i]; Console.WriteLine("Start at {0} for {1} positions " + "and Char {2} is first found at {3}", start, count, c, s.IndexOf(c, start, count)); } } } }
A B C D E F G H I J K L M
The output is
N Start Start Start Start Start Start Start Start Start Start Start Start
O P Q R S T U
at at at at at at at at at at at at
3 3 3 3 3 3 3 3 3 3 3 3
for for for for for for for for for for for for
6 6 6 6 6 6 6 6 6 6 6 6
positions positions positions positions positions positions positions positions positions positions positions positions
and and and and and and and and and and and and
Char Char Char Char Char Char Char Char Char Char Char Char
H e l l o w o r l d !
is is is is is is is is is is is is
first first first first first first first first first first first first
found found found found found found found found found found found found
at at at at at at at at at at at at
-1 -1 3 3 4 5 6 4 8 3 -1 -1
V W
String.IndexOf(System.String) Method
X [ILASM]
Y
.method public hidebysig instance int32 IndexOf(string value) [C#]
Z
public int IndexOf(string value)
2884
Contents | Index
System
String IndexOf() Method
Summary Returns the index of the first occurrence of a specified System.String in the current instance. A
Parameters
B C
Parameter
Description
value
The System.String to seek.
D E F
Return Value
G
A System.Int32 that indicates the result of the search for value in the current instance as follows:
H I J
Return Value
Description
K L
A positive number equal to the index of the start of the first substring in the current instance that is equal to value.
value was found.
0
value is equal to System.String.Empty.
–1
value was not found.
M N O P Q
Description
R
The search begins at the first character of the current instance. The search is case-sensitive, culture-sensitive, and the culture of the current thread is used.
S T U
Exceptions
V
Exception
Condition
W
System.ArgumentNullException
value is a null reference.
X Y Z
2885
Contents | Index
String
System
IndexOf() Method
Example using System; namespace Samples { public class StringIndexOf { public static void Main() { string[] strings = {"one", "two", "three", String.Empty}; string s = String.Concat(strings); strings[1] = "TWO"; foreach(string s1 in strings) { Console.WriteLine( "String \"{0}\" is first found at {1}", s1, s.IndexOf(s1)); } } } }
A B C D E F G H I J K L M
The output is
N String String String String
O P
"one" is first found at 0 "TWO" is first found at -1 "three" is first found at 6 "" is first found at 0
Q R
String.IndexOf(System.String, System.Int32) Method
S [ILASM]
T
.method public hidebysig instance int32 IndexOf(string value, int32 startIndex)
U
[C#]
public int IndexOf(string value, int startIndex)
V W
Summary
X
Returns the index of the first occurrence of a specified System.String in the current instance, with the search starting from a specified index.
Y Z
2886
Contents | Index
System
String IndexOf() Method
Parameters Parameter
Description
value
The System.String to seek.
startIndex
A System.Int32 containing the index of the current instance from which to start searching.
A B C D E
Return Value
F
A System.Int32 that indicates the result of the search for value in the current instance as follows:
G H I
Return Value
Description
A positive number equal to the index of the start of the first substring in the current instance that is equal to value.
value was found.
startIndex
value is Empty.
–1
value was not found.
J K L M N O
Description
P
This method is case-sensitive.
Q R
Exceptions
S
Exception
Condition
System.ArgumentNullException
value is a null reference.
System.ArgumentOutOfRangeException
startIndex is greater than the length of the current instance.
T U V W X Y Z
2887
Contents | Index
String
System
IndexOf() Method
Example using System; namespace Samples { public class StringIndexOf { public static void Main() { string[] strings = {"one", "two", "three", String.Empty}; string s = String.Concat(strings); int start = 3; Console.WriteLine( "Searching from index {0}", start); foreach(string s1 in strings) { Console.WriteLine( "String \"{0}\" is first found at {1}", s1, s.IndexOf(s1, start)); } } } }
A B C D E F G H I J K L M N
The output is
O Searching from index 3 String "one" is first found at -1 String "two" is first found at 3 String "three" is first found at 6 String "" is first found at 3
P Q R S T
String.IndexOf(System.String, System.Int32, System.Int32) Method
U [ILASM]
V
.method public hidebysig instance int32 IndexOf(string value, int32 startIndex, int32 count)
W
[C#]
public int IndexOf(string value, int startIndex, int count)
X Y
Summary
Z
Returns the index of the first occurrence of a specified System.String in the current instance, with the search over the specified range starting at the provided index.
2888
Contents | Index
System
String IndexOf() Method
Parameters Parameter
Description
value
The System.String to seek.
startIndex
A System.Int32 containing the index of the current instance from which to start searching.
count
A System.Int32 containing the range of the current instance at which to end searching.
A B C D E F G
Return Value
H
A System.Int32 that indicates the result of the search for value in the current instance as follows: Return Value
I J
Description
K
A positive number equal to the index of the start of the first substring in the current instance that is equal to value.
value was found.
startIndex
value is Empty.
–1
value was not found.
L M N O P
Description
Q
The search begins at startIndex and continues until startIndex + count – 1 is reached. The character at startIndex + count is not included in the search. This method is case-sensitive.
R S T
Exceptions
U
Exception
Condition
System.ArgumentNullException
value is a null reference.
V W X
startIndex or count is negative. System.ArgumentOutOfRangeException
Y
-or-
Z
startIndex + count is greater than the length of the current instance.
2889
Contents | Index
String
System
IndexOfAny() Method
Example using System; namespace Samples { public class StringIndexOf { public static void Main() { string[] strings = {"one", "two", "three", String.Empty}; string s = String.Concat(strings); int start = 3, count = 10; Console.WriteLine( "Searching from index {0}", start); Console.WriteLine( "for {0} positions", count); foreach(string s1 in strings) { Console.WriteLine( "String \"{0}\" is first found at {1}", s1, s.IndexOf(s1, start)); } } } }
A B C D E F G H I J K L M N O
The output is
P
Searching from index 3 for 10 positions String "one" is first found at -1 String "two" is first found at 3 String "three" is first found at 6 String "" is first found at 3
Q R S T U
String.IndexOfAny(System.Char[]) Method
V [ILASM]
W
.method public hidebysig instance int32 IndexOfAny(class System.Char[] anyOf)
X
[C#]
public int IndexOfAny(char[] anyOf)
Y
Summary
Z
Reports the index of the first occurrence in the current instance of any character in a specified array of Unicode characters. 2890
Contents | Index
System
String IndexOfAny() Method
Parameters Parameter
Description
anyOf
An array of Unicode characters.
A B C
Return Value
D
The index of the first occurrence of an element of anyOf in the current instance; otherwise, –1 if no element of anyOf was found.
E
Description
G
This method is case-sensitive.
H
F
I
Exceptions
J
Exception
Condition
System.ArgumentNullException
anyOf is a null reference.
K L M N
Example
O
using System;
P namespace Samples { public class StringIndexOfAny { public static void Main() { string s = "Hello world!"; char[] chars = {'l', 'o'}; Console.WriteLine("A match found at {0}", s.IndexOfAny(chars)); chars[0] = 'L'; chars[1] = 'O'; Console.WriteLine("A match found at {0}", s.IndexOfAny(chars)); } } }
Q R S T U V W X Y Z
2891
Contents | Index
String
System
IndexOfAny() Method
The output is A match found at 2 A match found at -1
A B
String.IndexOfAny(System.Char[], System.Int32) Method
C
[ILASM]
D
.method public hidebysig instance int32 IndexOfAny(class System.Char[] anyOf, int32 startIndex)
E
[C#]
F
public int IndexOfAny(char[] anyOf, int startIndex)
G
Summary
H
Returns the index of the first occurrence of any element in a specified array of Unicode characters in the current instance, with the search starting from a specified index.
I J
Parameters
K L
Parameter
Description
anyOf
An array of Unicode characters.
startIndex
A System.Int32 containing the index of the current instance from which to start searching.
M N O P Q
Return Value
R
A System.Int32 containing a positive value equal to the index of the first occurrence of an element of anyOf in the current instance; otherwise, –1 if no element of anyOf was found.
S T
Description
U
This method is case-sensitive.
V
Exceptions
W X
Exception
Condition
System.ArgumentNullException
anyOf is a null reference.
System.ArgumentOutOfRangeException
startIndex is greater than the length of the current instance.
Y Z
2892
Contents | Index
System
String IndexOfAny() Method
Example using System; namespace Samples { public class StringIndexOfAny { public static void Main() { string s = "Hello world!"; char[] chars = {'l', 'o'}; int start = 5; Console.WriteLine("A match found at {0}", s.IndexOfAny(chars, start)); chars[0] = 'H'; chars[1] = 'd'; Console.WriteLine("A match found at {0}", s.IndexOfAny(chars, start)); } } }
A B C D E F G H I J K L
The output is
M
A match found at 7 A match found at 10
N O P
String.IndexOfAny(System.Char[], System.Int32, System.Int32) Method
Q
[ILASM]
R
.method public hidebysig instance int32 IndexOfAny(class System.Char[] anyOf, int32 startIndex, int32 count)
S
[C#]
T
public int IndexOfAny(char[] anyOf, int startIndex, int count)
U
Summary
V
Returns the index of the first occurrence of any element in a specified array of Unicode characters in the current instance, with the search over the specified range starting from the provided index.
W X Y Z
2893
Contents | Index
String
System
IndexOfAny() Method
Parameters Parameter
Description
anyOf
An array containing the Unicode characters to seek.
startIndex
A System.Int32 containing the index of the current instance from which to start searching.
count
A System.Int32 containing the range of the current instance at which to end searching.
A B C D E F G
Return Value
H
A System.Int32 containing a positive value equal to the index of the first occurrence of an element of anyOf in the current instance; otherwise, –1 if no element of anyOf was found.
I J
Description
K
The search begins at startIndex and continues until startIndex + count – 1. The character at startIndex + count is not included in the search. This method is case-sensitive.
L M N
Exceptions
O P
Exception
Condition
System.ArgumentNullException
anyOf is a null reference.
Q R
startIndex or count is negative.
S System.ArgumentOutOfRangeException
T
-orstartIndex + count is greater than the length of the current instance.
U V W
Example
X
using System;
Y
namespace Samples { public class StringIndexOfAny { public static void Main()
Z
2894
Contents | Index
System
String Insert() Method
{ string s = "Hello world!"; char[] chars = {'l', 'o'}; int start = 5, count = 5; Console.WriteLine("A match found at {0}", s.IndexOfAny(chars, start, count)); chars[0] = 'H'; chars[1] = 'd'; Console.WriteLine("A match found at {0}", s.IndexOfAny(chars, start, count));
A B C D
}
E
}
F
}
G
The output is
H A match found at 7 A match found at -1
I J K
String.Insert(System.Int32, System.String) Method
L
[ILASM]
.method public hidebysig instance string Insert(int32 startIndex, string value)
M
[C#]
N
public string Insert(int startIndex, string value)
O
Summary
P
Returns a System.String equivalent to the current instance with a specified System.String inserted at the specified position.
Q
Parameters
S
R
T
Parameter
Description
startIndex
A System.Int32 containing the index of the insertion.
value
The System.String to insert.
U V W X Y
Return Value
Z
A new System.String that is equivalent to the current string with value inserted at index startIndex.
2895
Contents | Index
String
System
Intern() Method
Description In the new string returned by this method, the first character of value is at startIndex, and all characters in the current string from startIndex to the end are inserted in the new string after the last character of value.
A B
Exceptions
C D
Exception
Condition
System.ArgumentNullException
value is a null reference.
System.ArgumentOutOfRangeException
startIndex is greater than the length of the current instance.
E F G H I
Example
J
using System;
K namespace Samples { public class StringInsert { public static void Main() { string s = "Hello!"; s = s.Insert(5, " world"); Console.WriteLine(s); } } }
L M N O P Q R S
The output is
T
Hello world!
U V W
String.Intern(System.String) Method
X
[ILASM]
Y
.method public hidebysig static string Intern(string str) [C#]
Z
public static string Intern(string str)
2896
Contents | Index
System
String Intern() Method
Summary Retrieves the system’s reference to a specified System.String. A
Parameters
B
Parameter
Description
C
str
A System.String.
D E F
Return Value
G
The System.String reference to str.
H
Description
I
Instances of each unique literal string constant declared in a program, as well as any unique instance of System.String you add programmatically, are kept in a table, called the “intern pool”. The intern pool conserves string storage. If a literal string constant is assigned to several variables, each variable is set to reference the same constant in the intern pool instead of referencing several different instances of System.String that have identical values. This method looks up a specified string in the intern pool. If the string exists, a reference to it is returned. If it does not exist, an instance equal to the specified string is added to the intern pool and a reference to that instance is returned.
J K L M N O P
Exceptions
Q R
Exception
Condition
System.ArgumentNullException
str is a null reference.
S T U
Example
V
using System;
W
namespace Samples { public class StringIntern { public static void Main() {
X Y Z
2897
Contents | Index
String
System
IsInterned() Method
string s1 = "one"; string s2 = String.IsInterned(s1); Console.WriteLine(s2==null? "null": s2); Char[] chars = new char[]{'t', 'w', 'o'}; s1 = new String(chars); s2 = String.IsInterned(s1); Console.WriteLine(s2==null? "null":s2); String.Intern(s1); s2 = String.IsInterned(s1); Console.WriteLine(s2==null? "null":s2);
A B C D }
E }
F
}
G
The output is
H one null two
I J K L
String.IsInterned(System.String) Method
M
[ILASM]
N
.method public hidebysig static string IsInterned(string str) [C#]
O
public static string IsInterned(string str)
P
Summary
Q
Retrieves a reference to a specified System.String.
R S
Parameters
T U V
Parameter
Description
str
A System.String.
W X
Return Value
Y
A System.String reference to str if it is in the system’s intern pool; otherwise, a null reference.
Z
2898
Contents | Index
System
String IsInterned() Method
Description Instances of each unique literal string constant declared in a program, as well as any unique instance of System.String you add programmatically, are kept in a table, called the “intern pool”. The intern pool conserves string storage. If a literal string constant is assigned to several variables, each variable is set to reference the same constant in the intern pool instead of referencing several different instances of System.String that have identical values. [Note: This method does not return a System.Boolean value, but can still be used where a System.Boolean is needed.]
A B C D E F
Exceptions
G
Exception
Condition
H
System.ArgumentNullException
str is a null reference.
I J K
Example
L
using System;
M namespace Samples { public class StringIsIntern { public static void Main() { string s1 = "one"; string s2 = String.IsInterned(s1); Console.WriteLine(s2==null? "null": s2); Char[] chars = new char[]{'t', 'w', 'o'}; s1 = new String(chars); s2 = String.IsInterned(s1); Console.WriteLine(s2==null? "null":s2); String.Intern(s1); s2 = String.IsInterned(s1); Console.WriteLine(s2==null? "null":s2); } } }
N O P Q R S T U V W X Y
The output is
Z one null two
2899
Contents | Index
String
System
Join() Method
String.Join(System.String, System.String[]) Method [ILASM]
A
.method public hidebysig static string Join(string separator, class System.String[] value)
B
[C#]
public static string Join(string separator, string[] value)
C D
Summary
E
Concatenates the elements of a specified System.String array, inserting a separator string between each element pair and yielding a single concatenated string.
F G
Parameters
H I J K
Parameter
Description
separator
A System.String.
value
A System.String array.
L M
Return Value
N
A System.String consisting of the elements of value separated by instances of the separator string.
O P
Exceptions
Q R
Exception
Condition
System.ArgumentNullException
value is a null reference.
S T U
Example
V
using System;
W namespace Samples { public class StringJoin { public static void Main() { string[] strings = {"one", "two", "three"};
X Y Z
2900
Contents | Index
System
String Join() Method
Console.WriteLine(String.Join(" + ", strings)); } } }
A
The output is
B C
one + two + three
D E
String.Join(System.String, System.String[], System.Int32, System.Int32) Method
F [ILASM]
G
.method public hidebysig static string Join(string separator, class System.String[] value, int32 startIndex, int32 count)
H
[C#]
public static string Join(string separator, string[] value, int startIndex, int count)
I
Summary
K
Concatenates a specified separator System.String between the elements of a specified System.String array, yielding a single concatenated string.
L
J
M N
Parameters
O
Parameter
Description
P
separator
A System.String.
Q
value
A System.String array.
startIndex
A System.Int32 containing the first array element in value to join.
count
A System.Int32 containing the number of elements in value to join.
R S T U V
Return Value
W
A System.String consisting of the strings in value joined by separator. Returns System.String.Empty if count is zero, value has no elements, or separator and all the elements of value are Empty.
X Y Z
2901
Contents | Index
String
System
LastIndexOf() Method
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
startIndex plus count is greater than the number of elements in value.
A B C D
Example
E
using System;
F
namespace Samples { public class StringJoin { public static void Main() { string[] strings = {"one", "two", "three", "four", "five", "six"}; Console.WriteLine(String.Join(" + ", strings, 1, 4)); } } }
G H I J K L M N
The output is
O
two + three + four + five
P Q
String.LastIndexOf(System.Char) Method
R S
[ILASM]
T
[C#]
.method public hidebysig instance int32 LastIndexOf(valuetype System.Char value) public int LastIndexOf(char value)
U V
Summary
W
Returns the index of the last occurrence of a specified character within the current instance.
X
Parameters
Y Z
Parameter
Description
value
The Unicode character to locate.
2902
Contents | Index
System
String LastIndexOf() Method
Return Value A System.Int32 containing the index of the last occurrence of value in the current instance, if found; otherwise, –1. A
Description
B
This method is case-sensitive.
C D
Example
E
using System;
F namespace Samples { public class StringLastIndexOf { public static void Main() { string s = "Hello world!"; for(int i = 0; i < s.Length; i++) { char c = s[i]; Console.WriteLine("Char {0} is last found at {1}", c, s.LastIndexOf(c)); } } } }
G H I J K L M N O P
The output is Char Char Char Char Char Char Char Char Char Char Char Char
H e l l o w o r l d !
is is is is is is is is is is is is
last last last last last last last last last last last last
found found found found found found found found found found found found
Q at at at at at at at at at at at at
R
0 1 9 9 7 5 6 7 8 9 10 11
S T U V W X Y Z
2903
Contents | Index
String
System
LastIndexOf() Method
String.LastIndexOf(System.Char, System.Int32) Method [ILASM]
A
.method public hidebysig instance int32 LastIndexOf(valuetype System.Char value, int32 startIndex)
B
[C#]
public int LastIndexOf(char value, int startIndex)
C D
Summary
E
Returns the index of the last occurrence of a specified character within the current instance.
F
Parameters
G H I
Parameter
Description
value
A Unicode character to locate.
startIndex
A System.Int32 containing the index in the current instance from which to begin searching.
J K L M
Return Value
N
A System.Int32 containing the index of the last occurrence of value in the current instance, if found; otherwise, –1.
O P
Description
Q
This method searches for the last occurrence of the specified character between the start of the string and the indicated index. This method is case-sensitive.
R S T
Exceptions
U V
Exception
Condition
W
System.ArgumentNullException
value is a null reference.
System.ArgumentOutOfRangeException
startIndex is less than zero or greater than the length of the current instance.
X Y Z
2904
Contents | Index
System
String LastIndexOf() Method
Example using System; namespace Samples { public class StringLastIndexOf { public static void Main() { string s = "Hello world!"; int start = 9; Console.WriteLine("Starting at index {0}", start); for(int i = 0; i < s.Length; i++) { char c = s[i]; Console.WriteLine("Char {0} is last found at {1}", c, s.LastIndexOf(c, start)); } } } }
A B C D E F G H I J K L
The output is Starting at index 9 Char H is last found Char e is last found Char l is last found Char l is last found Char o is last found Char is last found Char w is last found Char o is last found Char r is last found Char l is last found Char d is last found Char ! is last found
M N at at at at at at at at at at at at
0 1 9 9 7 5 6 7 8 9 -1 -1
O P Q R S T U V W
String.LastIndexOf(System.Char, System.Int32, System.Int32) Method
X [ILASM]
Y
.method public hidebysig instance int32 LastIndexOf(valuetype System.Char value, int32 startIndex, int32 count)
Z
[C#]
public int LastIndexOf(char value, int startIndex, int count)
2905
Contents | Index
String
System
LastIndexOf() Method
Summary Returns the index of the last occurrence of a specified character in the provided range of the current instance. A
Parameters
B C
Parameter
Description
value
A Unicode character to locate.
startIndex
A System.Int32 containing the index of the current instance from which to start searching.
count
A System.Int32 containing the range of the current instance at which to end searching.
D E F G H I J
Return Value
K
A System.Int32 containing the index of the last occurrence of value in the current instance if found between startIndex and (startIndex – count + 1); otherwise, –1.
L M
Description
N
This method is case-sensitive.
O P
Exceptions
Q R S
Exception
Condition
System.ArgumentNullException
value is a null reference.
T
startIndex or count is less than zero.
U
System.ArgumentOutOfRangeException
-orstartIndex – count is less than –1.
V W X Y Z
2906
Contents | Index
System
String LastIndexOf() Method
Example using System; namespace Samples { public class StringLastIndexOf { public static void Main() { string s = "Hello world!"; int start = 9, count = 8; Console.WriteLine("Starting at index {0} and" + "checking for {1} chars", start, count); for(int i = 0; i < s.Length; i++) { char c = s[i]; Console.WriteLine("Char {0} is last found at {1}", c, s.LastIndexOf(c, start, count)); } } } }
A B C D E F G H I J K L M
The output is Starting at index 9 and Char H is last found at Char e is last found at Char l is last found at Char l is last found at Char o is last found at Char is last found at Char w is last found at Char o is last found at Char r is last found at Char l is last found at Char d is last found at Char ! is last found at
N O
checking for 8 chars -1 -1 9 9 7 5 6 7 8 9 -1 -1
P Q R S T U V W X
String.LastIndexOf(System.String) Method
Y
[ILASM]
Z
.method public hidebysig instance int32 LastIndexOf(string value) [C#]
public int LastIndexOf(string value)
2907
Contents | Index
String
System
LastIndexOf() Method
Summary Returns the index of the last occurrence of a specified System.String within the current instance. A
Parameters
B C D E
Parameter
Description
value
A System.String.
F G
Return Value
H
A System.Int32 that indicates the result of the search for value in the current instance as follows:
I J
Return Value
Description
M
A positive number equal to the index of the start of the last substring in the current instance that is equal to value.
value was found.
N
0
value is Empty.
–1
value was not found.
K L
O P Q
Description
R
The search is case-sensitive.
S
Exceptions
T U V W
Exception
Condition
System.ArgumentNullException
value is a null reference.
X Y Z
2908
Contents | Index
System
String LastIndexOf() Method
Example using System; namespace Samples { public class StringLastIndexOf { public static void Main() { string[] strings = {String.Empty, "one", "two", "three"}; string s = String.Concat(strings); strings[2] = "TWO"; foreach(string s1 in strings) { Console.WriteLine( "String \"{0}\" is last found at {1}", s1, s.LastIndexOf(s1)); } } } }
A B C D E F G H I J K L M
The output is
N String String String String
"" is last found at 10 "one" is last found at 0 "TWO" is last found at -1 "three" is last found at 6
O P Q R
String.LastIndexOf(System.String, System.Int32) Method
S [ILASM]
T
.method public hidebysig instance int32 LastIndexOf(string value, int32 startIndex)
U
[C#]
V
public int LastIndexOf(string value, int startIndex)
W
Summary
X
Returns the index of the last occurrence of a specified System.String within the current instance.
Y Z
2909
Contents | Index
String
System
LastIndexOf() Method
Parameters Parameter
Description
value
A System.String.
startIndex
A System.Int32 containing the index of the current instance from which to start searching.
A B C D E
Return Value
F
A System.Int32 that indicates the result of the search for value in the current instance as follows:
G H I J K
Return Value
Description
A positive number equal to the index of the start of the last substring in the current instance that is equal to value.
value was found.
startIndex
value is Empty.
–1
value was not found.
L M N O P
Description
Q
This method searches for the last occurrence of the specified System.String between the start of the string and the indicated index. This method is case-sensitive.
R S T
Exceptions
U V W
Exception
Condition
System.ArgumentNullException
value is a null reference.
System.ArgumentOutOfRangeException
startIndex is less than zero or greater than or equal to the length of the current instance.
X Y Z
2910
Contents | Index
System
String LastIndexOf() Method
Example using System; namespace Samples { public class StringLastIndexOf { public static void Main() { string[] strings = {String.Empty, " one ", " two ", " three "}; string s = String.Concat(strings); int start = 14; Console.WriteLine("Searching from index {0}", start); foreach(string s1 in strings) { Console.WriteLine( "String \"{0}\" is last found at {1}", s1, s.LastIndexOf(s1, start)); } } } }
A B C D E F G H I J K L M
The output is
N O
Searching from index 14 String "" is last found at 14 String " one " is last found at 0 String " two " is last found at 5 String " three " is last found at -1
P Q R S
String.LastIndexOf(System.String, System.Int32, System.Int32) Method
T
[ILASM]
U
.method public hidebysig instance int32 LastIndexOf(string value, int32 startIndex, int32 count)
V
[C#]
W
public int LastIndexOf(string value, int startIndex, int count)
X
Summary
Y
Returns the index of the last occurrence of a specified System.String in the provided range of the current instance.
Z
2911
Contents | Index
String
System
LastIndexOf() Method
Parameters Parameter
Description
value
The substring to search for.
startIndex
A System.Int32 containing the index of the current instance from which to start searching.
count
A System.Int32 containing the range of the current instance at which to end searching.
A B C D E F G
Return Value
H
A System.Int32 that indicates the result of the search for value in the current instance as follows:
I J K
Return Value
Description
A positive number equal to the index of the start of the last substring in the current instance that is equal to value.
value was found.
startIndex
value is Empty.
–1
value was not found.
L M N O P Q R
Description
S
The search begins at startIndex and continues until startIndex - count + 1. This method is case-sensitive.
T U
Exceptions
V W X
Exception
Condition
System.ArgumentNullException
value is a null reference.
Y
startIndex or count is less than zero.
Z
System.ArgumentOutOfRangeException
-orstartIndex – count is smaller than –1.
2912
Contents | Index
System
String LastIndexOfAny() Method
Example using System; namespace Samples { public class StringLastIndexOf { public static void Main() { string[] strings = {String.Empty, " one ", " two ", " three "}; string s = String.Concat(strings); int start = 14, count = 10; Console.WriteLine("Searching from index {0}", start); Console.WriteLine("and searching for {0} positions", count); foreach(string s1 in strings) { Console.WriteLine( "String \"{0}\" is last found at {1}", s1, s.LastIndexOf(s1, start, count)); } } } }
A B C D E F G H I J K L M N
The output is
O Searching from index 14 and searching for 10 positions String "" is last found at 14 String " one " is last found at -1 String " two " is last found at 5 String " three " is last found at -1
P Q R S T
String.LastIndexOfAny(System.Char[]) Method
U
[ILASM]
V
.method public hidebysig instance int32 LastIndexOfAny(class System.Char[] anyOf) [C#]
W
public int LastIndexOfAny(char[] anyOf)
X Y
Summary
Z
Returns the index of the last occurrence of any element of a specified array of characters in the current instance.
2913
Contents | Index
String
System
LastIndexOfAny() Method
Parameters Parameter
Description
anyOf
An array of Unicode characters.
A B C D
Return Value
E
A System.Int32 containing the index of the last occurrence of any element of anyOf in the current instance, if found; otherwise, –1.
F G
Description
H
This method is case-sensitive.
I
Exceptions
J K
Exception
Condition
System.ArgumentNullException
anyOf is a null reference.
L M N
Example
O
using System;
P namespace Samples { public class StringLastIndexOfAny { public static void Main() { string s = "Hello world!"; char[] chars = {'l', 'o'}; Console.WriteLine("Last match found at {0}", s.LastIndexOfAny(chars)); chars[0] = 'L'; chars[1] = 'O'; Console.WriteLine("Last match found at {0}", s.LastIndexOfAny(chars)); } } }
Q R S T U V W X Y Z
2914
Contents | Index
System
String LastIndexOfAny() Method
The output is Last match found at 9 Last match found at -1
A B
String.LastIndexOfAny(System.Char[], System.Int32) Method
C
[ILASM]
D
.method public hidebysig instance int32 LastIndexOfAny(class System.Char[] anyOf, int32 startIndex)
E
[C#]
F
public int LastIndexOfAny(char[] anyOf, int startIndex)
G
Summary
H
Returns the index of the last occurrence of any element of a specified array of characters in the current instance.
I
Parameters
K
J
L
Parameter
Description
M
anyOf
An array of Unicode characters.
N
startIndex
A System.Int32 containing the index of the current instance from which to start searching.
O P Q
Return Value
R
A System.Int32 containing the index of the last occurrence of any element of anyOf in the current instance, if found; otherwise, –1.
S
Description
U
This method searches for the last occurrence of the specified characters between the start of the string and the indicated index. This method is case-sensitive.
V
T
W X Y Z
2915
Contents | Index
String
System
LastIndexOfAny() Method
Exceptions Exception
Condition
System.ArgumentNullException
anyOf is a null reference.
System.ArgumentOutOfRangeException
startIndex is less than zero or greater than or equal to the length of the current instance.
A B C D E
Example
F
using System;
G
namespace Samples { public class StringLastIndexOfAny { public static void Main() { string s = "Hello world!"; char[] chars = {'l', 'o'}; int start = 8; Console.WriteLine("Starting at index {0}", start); Console.WriteLine("Last match found at {0}", s.LastIndexOfAny(chars, start)); chars[0] = 'd'; chars[1] = '!'; Console.WriteLine("Last match found at {0}", s.LastIndexOfAny(chars, start)); } } }
H I J K L M N O P Q R S
The output is
T
Starting at index 8 Last match found at 7 Last match found at -1
U V W X
String.LastIndexOfAny(System.Char[], System.Int32, System.Int32) Method
Y
[ILASM]
.method public hidebysig instance int32 LastIndexOfAny(class System.Char[] anyOf, int32 startIndex, int32 count)
Z
[C#]
public int LastIndexOfAny(char[] anyOf, int startIndex, int count)
2916
Contents | Index
System
String LastIndexOfAny() Method
Summary Returns the index of the last occurrence of any of specified characters in the provided range of the current instance. A
Parameters
B C
Parameter
Description
anyOf
An array of Unicode characters.
E
startIndex
A System.Int32 containing the index of the current instance from which to start searching.
F
count
D
G
A System.Int32 containing the range of the current instance at which to end searching.
H I J
Return Value
K
A System.Int32 containing the index of the last occurrence of any element of anyOf if found between startIndex and (startIndex – count + 1); otherwise, –1.
L M
Description
N
The search begins at startIndex and continues until startIndex – count + 1. The character at startIndex – count is not included in the search. This method is case-sensitive.
O P Q
Exceptions
R
Exception
Condition
System.ArgumentNullException
anyOf is a null reference.
S T U
startIndex or count is less than zero. System.ArgumentOutOfRangeException
V
-or-
W
startIndex – count is smaller than –1. X Y Z
2917
Contents | Index
String
System
op_Equality() Method
Example using System; namespace Samples { public class StringLastIndexOfAny { public static void Main() { string s = "Hello world!"; char[] chars = {'l', 'o'}; int start = 8, count = 6; Console.WriteLine("Starting at index {0}" + " and checking for {1}", start, count); Console.WriteLine("Last match found at {0}", s.LastIndexOfAny(chars, start, count)); chars[0] = 'H'; chars[1] = '!'; Console.WriteLine("Last match found at {0}", s.LastIndexOfAny(chars, start, count)); } } }
A B C D E F G H I J K L M N
The output is
O Starting at index 8 and checking for 6 Last match found at 7 Last match found at -1
P Q R S
String.op_Equality(System.String, System.String) Method
T
[ILASM]
.method public hidebysig static specialname bool op_Equality(string a, string b)
U
[C#]
V
public static bool operator ==(String a, String b)
W
Summary
X
Returns a System.Boolean value indicating whether the two specified string values are equal to each other.
Y Z
2918
Contents | Index
System
String op_Equality() Method
Parameters Parameter
Description
a
The first System.String to compare.
b
The second System.String to compare.
A B C D
Return Value
E
true if a and b represent the same string value; otherwise, false.
F G
Example
H
using System;
I namespace Samples { public class StringOperatorEquality { public static void Main() { string s = "Hello world!"; string clone = (string) s.Clone(); string copy = String.Copy(s); Console.WriteLine("s == clone: {0}", s == clone); Console.WriteLine("s == copy : {0}", s == copy); Console.WriteLine("String.Equals(s, clone): {0}", String.Equals(s, clone)); Console.WriteLine("String.Equals(s, copy) : {0}", String.Equals(s, copy)); Console.WriteLine( "Object.ReferenceEquals(s, clone): {0}", Object.ReferenceEquals(s, clone)); Console.WriteLine( "Object.ReferenceEquals(s, copy): {0}", Object.ReferenceEquals(s, copy)); } } }
J K L M N O P Q R S T U V W X Y Z
2919
Contents | Index
String
System
op_Inequality() Method
The output is s == clone: True s == copy : True String.Equals(s, clone): True String.Equals(s, copy) : True Object.ReferenceEquals(s, clone): True Object.ReferenceEquals(s, copy): False
A B C D E
String.op_Inequality(System.String, System.String) Method
F [ILASM]
G
.method public hidebysig static specialname bool op_Inequality(string a, string b)
H
[C#]
public static bool operator !=(String a, String b)
I J
Summary
K
Returns a System.Boolean value indicating whether the two string values are not equal to each other.
L M
Parameters
N
Parameter
Description
P
a
The first System.String to compare.
Q
b
The second System.String to compare.
O
R S
Return Value
T
true if a and b do not represent the same string value; otherwise, false.
U
Example
V
using System;
W
namespace Samples { public class StringOperatorInequality { public static void Main() { string s = "Hello world!";
X Y Z
2920
Contents | Index
System
String PadLeft() Method
string clone = (string) s.Clone(); string copy = String.Copy(s); Console.WriteLine("s != s: {0}", s != s); Console.WriteLine("s != clone: {0}", s != clone); Console.WriteLine("s != copy : {0}", s != copy);
A B C
}
D
} }
E F
The output is
G s != s: False s != clone: False s != copy : False
H I J
String.PadLeft(System.Int32) Method
K
[ILASM]
L
.method public hidebysig instance string PadLeft(int32 totalWidth) [C#]
M
public string PadLeft(int totalWidth)
N O
Summary
P
Right-aligns the characters in the current instance, padding with spaces on the left, for a specified total length.
Q R
Parameters
S
Parameter
Description
totalWidth
A System.Int32 containing the number of characters in the resulting string.
T U V W
Return Value
X
A new System.String that is equivalent to the current instance right-aligned and padded on the left with as many spaces as needed to create a length of totalWidth. If totalWidth is less than the length of the current instance, returns a new System.String that is identical to the current instance.
Y Z
2921
Contents | Index
String
System
PadLeft() Method
Description [Note: A space in Unicode format is defined as the hexadecimal value 0x20.] A
Exceptions
B C
Exception
Condition
D
System.ArgumentException
totalWidth is less than zero.
E F
Example
G
using System;
H
namespace Samples { public class StringPadLeft { public static void Main() { string s = "Hello world!"; Console.WriteLine(s); s = s.PadLeft(20); Console.WriteLine(s); s = s.Trim(); Console.WriteLine(s); } } }
I J K L M N O P Q R
The output is
S Hello world! Hello world! Hello world!
T U V W
String.PadLeft(System.Int32, System.Char) Method
X
[ILASM]
Y
.method public hidebysig instance string PadLeft(int32 totalWidth, valuetype System.Char paddingChar)
Z
[C#]
public string PadLeft(int totalWidth, char paddingChar)
2922
Contents | Index
System
String PadLeft() Method
Summary Right-aligns the characters in the current instance, padding on the left with a specified Unicode character, for a specified total length. A
Parameters
B C
Parameter
Description
totalWidth
A System.Int32 containing the number of characters in the resulting string.
paddingChar
A System.Char that specifies the padding character to use.
D E F G
Return Value
H
A new System.String that is equivalent to the current instance right-aligned and padded on the left with as many paddingChar characters as needed to create a length of totalWidth. If totalWidth is less than the length of the current instance, returns a new System.String that is identical to the current instance.
I J K L
Exceptions
M
Exception
Condition
N
System.ArgumentException
totalWidth is less than zero.
O P
Example
Q
using System;
R S
namespace Samples { public class StringPadLeft { public static void Main() { string s = "Hello world!"; Console.WriteLine(s); s = s.PadLeft(20, '-'); Console.WriteLine(s); s = s.Trim('-'); Console.WriteLine(s); } } }
T U V W X Y Z
2923
Contents | Index
String
System
PadRight() Method
The output is Hello world! --------Hello world! Hello world!
A B C
String.PadRight(System.Int32) Method
D
[ILASM]
E
.method public hidebysig instance string PadRight(int32 totalWidth)
F
[C#]
public string PadRight(int totalWidth)
G H
Summary
I
Left-aligns the characters in the current instance, padding with spaces on the right, for a specified total number of characters.
J K
Parameters
L M
Parameter
Description
N
totalWidth
A System.Int32 containing the number of characters in the resulting string.
O P
Return Value
Q
A new System.String that is equivalent to this instance left aligned and padded on the right with as many spaces as needed to create a length of totalWidth. If totalWidth is less than the length of the current instance, returns a new System.String that is identical to the current instance.
R S T
Exceptions
U V
Exception
Condition
System.ArgumentException
totalWidth is less than zero.
W X Y Z
2924
Contents | Index
System
String PadRight() Method
Example using System; namespace Samples { public class StringPadRight { public static void Main() { string s = "Hello world"; Console.WriteLine("{0}.", s); s = s.PadRight(20); Console.WriteLine("{0}.", s); s = s.Trim(); Console.WriteLine("{0}.", s); } } }
A B C D E F G H I J
The output is
K L
Hello world. Hello world Hello world.
.
M N O
String.PadRight(System.Int32, System.Char) Method
P
[ILASM]
Q
.method public hidebysig instance string PadRight(int32 totalWidth, valuetype System.Char paddingChar)
R
[C#]
public string PadRight(int totalWidth, char paddingChar)
S
Summary
T
Left-aligns the characters in the current instance, padding on the right with a specified Unicode character, for a specified total number of characters.
U
Parameters
W
V
X
Parameter
Description
Y
totalWidth
A System.Int32 containing the number of characters in the resulting string.
Z
paddingChar
A System.Char that specifies the padding character to use.
2925
Contents | Index
String
System
Remove() Method
Return Value A new System.String that is equivalent to the current instance left aligned and padded on the right with as many paddingChar characters as needed to create a length of totalWidth. If totalWidth is less than the length of the current instance, returns a new System.String that is identical to the current instance.
A B C
Exceptions
D E F
Exception
Condition
System.ArgumentException
totalWidth is less than zero.
G H
Example
I
using System;
J
namespace Samples { public class StringPadRight { public static void Main() { string s = "Hello world!"; Console.WriteLine(s); s = s.PadRight(20, '-'); Console.WriteLine(s); s = s.Trim('-'); Console.WriteLine(s); } } }
K L M N O P Q R S T
The output is
U
Hello world! Hello world!-------Hello world!
V W X
String.Remove(System.Int32, System.Int32) Method
Y
[ILASM]
Z
.method public hidebysig instance string Remove(int32 startIndex, int32 count) [C#]
public string Remove(int startIndex, int count)
2926
Contents | Index
System
String Remove() Method
Summary Deletes a specified number of characters from the current instance beginning at a specified index. A
Parameters
B C
Parameter
Description
startIndex
A System.Int32 containing the index of the current instance from which to start deleting characters.
count
A System.Int32 containing the number of characters to delete.
D E F G H
Return Value
I
A new System.String that is equivalent to the current instance without the specified range characters.
J K
Exceptions Exception
L M
Condition
N
startIndex or count is less than zero. System.ArgumentOutOfRangeException
O
-or-
P
startIndex plus count is greater than the length of the current instance.
Q R
Example
S
using System;
T
namespace Samples { public class StringRemove { public static void Main() { string s = "Hello world!"; s = s.Remove(5, 6); Console.WriteLine(s); } } }
U V W X Y Z
2927
Contents | Index
String
System
Replace() Method
The output is Hello!
A B
String.Replace(System.Char, System.Char) Method
C
[ILASM]
D
.method public hidebysig instance string Replace(valuetype System.Char oldChar, valuetype System.Char newChar)
E
[C#]
public string Replace(char oldChar, char newChar)
F G
Summary
H
Replaces all instances of a specified Unicode character with another specified Unicode character.
I J
Parameters
K
Parameter
Description
M
oldChar
The Unicode character to be replaced.
N
newChar
The Unicode character to replace all occurrences of oldChar.
L
O P
Return Value
Q
A System.String equivalent to the current instance with all occurrences of oldChar replaced with newChar.
R S
Example
T
using System;
U
namespace Samples { public class StringReplace { public static void Main() { string s = "hello world!"; s = s.Replace('h', 'H'); Console.WriteLine(s); } } }
V W X Y Z
2928
Contents | Index
System
String Replace() Method
The output is Hello world!
A B
String.Replace(System.String, System.String) Method
C [ILASM]
D
.method public hidebysig instance string Replace(string oldValue, string newValue) [C#]
E
public string Replace(string oldValue, string newValue)
F
Summary
G
Replaces all instances of a specified substring within the current instance with another specified string.
H I
Parameters
J K
Parameter
Description
oldValue
A System.String containing the string value to be replaced.
M
newValue
A System.String containing the string value to replace all occurrences of oldValue. Can be a null reference.
N
L
O P
Return Value
Q
A System.String equivalent to the current instance with all occurrences of oldValue replaced with newValue. If the replacement value is a null reference, the specified substring is removed.
R S T
Example
U
using System;
V namespace Samples { public class StringReplace { public static void Main() { string s = "Hello world!"; s = s.Replace("world", "Australia");
W X Y Z
2929
Contents | Index
String
System
Split() Method
Console.WriteLine(s); } } }
A B
The output is
C
Hello Australia!
D E
String.Split(System.Char[]) Method
F [ILASM]
G
.method public hidebysig instance class System.String[] Split(class System.Char[] separator)
H
[C#]
public string[] Split(params char[] separator)
I J
Summary
K
Returns substrings of the current instance that are delimited by the specified characters.
L
Parameters
M N
Parameter
Description
separator
A System.Char array of delimiters. Can be a null reference.
O P Q
Return Value
R
A System.String array containing the results of the split operation as follows:
S T U V
Return Value
Description
a single-element array containing the current instance.
None of the elements of separator is contained in the current instance.
a multi-element System.String array, each element of which is a substring of the current instance that was delimited by one or more characters in separator.
At least one element of separator is contained in the current instance.
a multi-element System.String array, each element of which is a substring of the current instance that was delimited by white space characters.
The current instance contains white space characters and separator is a null reference or an empty array.
W X Y Z
2930
Contents | Index
System
String Split() Method
Description System.String.Empty is returned for any substring where two delimiters are adjacent or a delimiter is found at the beginning or end of the current instance. Delimiter characters are not included in the substrings.
A B
Example
C
using System;
D namespace Samples { public class StringSplit { public static void Main() { string names = "damien+maire-mark+sacha-brad+tamara"; char[] chars = {'-'}; string[] strings = names.Split(chars); foreach(string s in strings) Console.WriteLine(s); chars= new Char[]{'-', '+'}; strings = names.Split(chars); foreach(string s in strings) Console.WriteLine(s); } } }
E F G H I J K L M N O
The output is
P Q
damien+maire mark+sacha brad+tamara damien maire mark sacha brad tamara
R S T U V W
String.Split(System.Char[], System.Int32) Method
X
[ILASM]
Y
.method public hidebysig instance class System.String[] Split(class System.Char[] separator, int32 count)
Z
[C#]
public string[] Split(char[] separator, int count)
2931
Contents | Index
String
System
Split() Method
Summary Returns substrings of the current instance that are delimited by the specified characters. A
Parameters
B C
Parameter
Description
separator
An array of Unicode characters that delimit the substrings in the current instance, an empty array containing no delimiters, or a null reference.
count
A System.Int32 containing the maximum number of array elements to return.
D E F G H
Return Value
I
A System.String array containing the results of the split operation as follows:
J K
Return Value
Description
A single-element array containing the current instance.
None of the elements of separator are contained in the current instance.
A multi-element System.String array, each element of which is a substring of the current instance that was delimited by one or more characters in separator.
At least one element of separator is contained in the current instance.
A multi-element System.String array, each element of which is a substring of the current instance that was delimited by white space characters.
The current instance contains white space characters and separator is a null reference or an empty array.
L M N O P Q R S T
Description
U
System.String.Empty is returned for any substring where two delimiters are adjacent or a delimiter is found at the beginning or end of the current instance. Delimiter characters are not included in the substrings. If there are more substrings in the current instance than the maximum specified number, the first count –1 elements of the array contain the first count – 1 substrings. The remaining characters in the current instance are returned in the last element of the array.
V W X Y Z
2932
Contents | Index
System
String StartsWith() Method
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
count is negative.
A B C
Example
D
using System;
E
namespace Samples { public class StringSplit { public static void Main() { string names = "damien+maire-mark+sacha-brad+tamara"; char[] chars = {'-'}; string[] strings = names.Split(chars, 3); foreach(string s in strings) Console.WriteLine(s); chars= new Char[]{'-', '+'}; strings = names.Split(chars, 3); foreach(string s in strings) Console.WriteLine(s); } } }
F G H I J K L M N O P Q
The output is
R
damien+maire mark+sacha brad+tamara damien maire mark+sacha-brad+tamara
S T U V W X
String.StartsWith(System.String) Method
Y
[ILASM]
.method public hidebysig instance bool StartsWith(string value)
Z
[C#]
public bool StartsWith(string value)
2933
Contents | Index
String
System
StartsWith() Method
Summary Returns a System.Boolean value that indicates whether the start of the current instance matches the specified System.String. A
Parameters
B C D E
Parameter
Description
value
A System.String.
F G
Return Value
H
true if the start of the current instance is equal to value; false if value is not equal to the start of the current instance or is longer than the current instance.
I J
Description
K
This method compares value with the substring at the start of the current instance that has a length of value.Length. If value.Length is greater than the length of the current instance or the relevant substring of the current instance is not equal to value, this method returns false; otherwise, this method returns true. The comparison is case-sensitive.
L M N O
Exceptions
P Q
Exception
Condition
System.ArgumentNullException
value is a null reference.
R S T
Example
U
using System;
V namespace Samples { public class StringStartsWith { public static void Main() { string s = "Hello world!"; string start = s.Substring(0, 5); Console.WriteLine(
W X Y Z
2934
Contents | Index
System
String Substring() Method
"Does \"{0}\" start with \"{1}\": {2}", s, start, s.StartsWith(start)); start = start.ToLower(); Console.WriteLine( "Does \"{0}\" start with \"{1}\": {2}", s, start, s.StartsWith(start));
A B
}
C
} }
D
The output is
E F
Does "Hello world!" start with "Hello": True Does "Hello world!" start with "hello": False
G H
String.Substring(System.Int32) Method
I
[ILASM]
J
.method public hidebysig instance string Substring(int32 startIndex)
K
[C#]
L
public string Substring(int startIndex)
M
Summary
N
Retrieves a substring from the current instance, starting from a specified index.
O
Parameters
P Q
Parameter
Description
startIndex
A System.Int32 containing the index of the start of the substring in the current instance.
R S T U
Return Value
V
A System.String equivalent to the substring that begins at startIndex of the current instance. Returns System.String.Empty if startIndex is equal to the length of the current instance.
W X Y Z
2935
Contents | Index
String
System
Substring() Method
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
startIndex is less than zero or greater than the length of the current instance.
A B C D
Example
E
using System;
F namespace Samples { public class StringSubstring { public static void Main() { string s = "Hello world!"; string end = s.Substring(6); Console.WriteLine( "Does \"{0}\" end with \"{1}\": {2}", s, end, s.EndsWith(end)); end = end.ToUpper(); Console.WriteLine( "Does \"{0}\" end with \"{1}\": {2}", s, end, s.EndsWith(end)); } } }
G H I J K L M N O P Q R
The output is
S Does "Hello world!" end with "world!": True Does "Hello world!" end with "WORLD!": False
T U V
String.Substring(System.Int32, System.Int32) Method
W [ILASM]
X
.method public hidebysig instance string Substring(int32 startIndex, int32 length) [C#]
Y
public string Substring(int startIndex, int length)
Z
2936
Contents | Index
System
String Substring() Method
Summary Retrieves a substring from the current instance, starting from a specified index, continuing for a specified length. A
Parameters
B C
Parameter
Description
startIndex
A System.Int32 containing the index of the start of the substring in the current instance.
length
A System.Int32 containing the number of characters in the substring.
D E F G H
Return Value
I
A System.String containing the substring of the current instance with the specified length that begins at the specified position. Returns System.String.Empty if startIndex is equal to the length of the current instance and length is zero.
J K L
Exceptions Exception
System.ArgumentOutOfRangeException
M
Condition
N
length is greater than the length of the current instance.
O P
-or-
Q
startIndex or length is less than zero.
R S
Example
T
using System;
U namespace Samples { public class StringSubstring { public static void Main() { string s = "Hello world!"; string start = s.Substring(0, 5); Console.WriteLine( "Does \"{0}\" start with \"{1}\": {2}", s, start, s.StartsWith(start));
V W X Y Z
2937
Contents | Index
String
System
ToCharArray() Method
start = start.ToLower(); Console.WriteLine( "Does \"{0}\" start with \"{1}\": {2}", s, start, s.StartsWith(start));
A
} }
B }
C
The output is
D
Does "Hello world!" start with "Hello": True Does "Hello world!" start with "hello": False
E F G
String.ToCharArray() Method
H
[ILASM]
I
.method public hidebysig instance class System.Char[] ToCharArray() [C#]
J
public char[] ToCharArray()
K L
Summary
M
Copies the characters in the current instance to a Unicode character array.
N
Return Value
O
A System.Char array whose elements are the individual characters of the current instance. If the current instance is an empty string, the array returned by this method is empty and has a zero length.
P Q R
Example
S
using System;
T
namespace Samples { public class StringToCharArray { public static void Main() { string s = "Hello world!"; char[] chars = s.ToCharArray(); foreach(char c in chars ) Console.WriteLine(c); } } }
U V W X Y Z
2938
Contents | Index
System
String ToCharArray() Method
The output is H e l l o
A B C
w o r l d !
D E F G H
String.ToCharArray(System.Int32, System.Int32) Method
I
[ILASM]
J
.method public hidebysig instance class System.Char[] ToCharArray(int32 startIndex, int32 length)
K
[C#]
L
public char[] ToCharArray(int startIndex, int length)
M
Summary
N
Copies the characters in a specified substring in the current instance to a Unicode character array.
O
Parameters
Q
P
R
Parameter
Description
startIndex
A System.Int32 containing the index of the start of a substring in the current instance.
length
A System.Int32 containing the length of the substring in the current instance.
S T U V W
Return Value
X
A System.Char array whose elements are the length number of characters in the current instance, starting from the index startIndex in the current instance. If the specified length is zero, the entire string is copied starting from the beginning of the current instance, and ignoring the value of startIndex. If the current instance is an empty string, the returned array is empty and has a zero length.
Y Z
2939
Contents | Index
String
System
ToLower() Method
Exceptions Exception
Condition
A
startIndex or length is less than zero.
B System.ArgumentOutOfRangeException
C
-orstartIndex plus length is greater than the length of the current instance.
D E
Example
F
using System;
G
namespace Samples { public class StringToCharArray { public static void Main() { string s = "Hello world!"; char[] chars = s.ToCharArray(0, 5); foreach(char c in chars ) Console.WriteLine(c); } } }
H I J K L M N O P
The output is
Q H e l l o
R S T U V
String.ToLower() Method
W [ILASM]
X
.method public hidebysig instance string ToLower() [C#]
Y
public string ToLower()
Z
Summary Returns a copy of this System.String in lowercase. 2940
Contents | Index
System
String ToLower() Method
Description This method takes into account the culture of the current thread. A
Example
B
using System;
C
namespace Samples { public class StringToLower { public static void Main() { string s = "Hello World!"; Console.WriteLine(s); Console.WriteLine(s.ToLower()); Console.WriteLine(s); s = s.ToLower(); Console.WriteLine(s); } } }
D E F G H I J K L M
The output is
N Hello hello Hello hello
World! world! World! world!
O P Q R
String.ToLower(System.Globalization.CultureInfo) Method
S [ILASM]
T
.method public hidebysig instance string ToLower(class System.Globalization.CultureInfo culture)
U
[C#]
V
public string ToLower(CultureInfo culture)
W
Summary
X
Returns a copy of this System.String in lowercase, using the casing rules of the specified culture.
Y Z
2941
Contents | Index
String
System
ToString() Method
Parameters Parameter
Description
culture
A System.Globalization.CultureInfo object that supplies culturespecific casing rules.
A B C D
Description
E
I
The casing rules of the culture that is currently in effect determine the way the case of a string is changed. If your application depends on the case of a string changing in a predictable way, and the effective culture changes unexpectedly, then you can get invalid results. Consider the following lookup routine where the lookup key is a text string, the key is forced to a standard case to simplify comparisons, and the effective culture is the culture associated with the current thread.
J
static object LookupKey(string key) { return internalHashtable[key.ToLower()]; }
F G H
K
If it is possible for the current thread and its associated culture to change unexpectedly, it is advisable to specify the invariant culture instead of defaulting to the current thread culture. The following example demonstrates the preferred technique.
L M N
static object LookupKey(string key) { return internalHashtable[key.ToLower(CultureInfo.InvariantCulture)]; }
O P
Exceptions
Q R S
Exception
Condition
System.ArgumentNullException
culture is null.
T U V
String.ToString() Method
W
[ILASM]
X
.method public hidebysig virtual string ToString()
Y
public override string ToString()
[C#]
Z
Summary Returns a System.String representation of the value of the current instance.
2942
Contents | Index
System
String ToUpper() Method
Description [Note: This method overrides System.Object.ToString.] A
String.ToString(System.IFormatProvider) Method
B
[ILASM]
C
.method public final hidebysig virtual string ToString(class System.IFormatProvider provider)
D
[C#]
E
public string ToString(IFormatProvider provider)
F
Summary
G
Returns this instance of String; no actual conversion is performed.
H I
Parameters
J
Parameter
Description
provider
(Reserved) A System.IFormatProvider interface implementation which supplies culture-specific formatting information.
K L M N
Description
O
provider is reserved, and does not currently participate in this operation.
P Q
String.ToUpper() Method
R
[ILASM]
S
.method public hidebysig instance string ToUpper() [C#]
T
public string ToUpper()
U V
Summary
W
Returns a copy of the current instance with all elements converted to uppercase, using default properties.
X Y Z
2943
Contents | Index
String
System
ToUpper() Method
Example using System; namespace Samples { public class StringToUpper { public static void Main() { string s = "Hello World!"; Console.WriteLine(s); Console.WriteLine(s.ToUpper()); Console.WriteLine(s); s = s.ToUpper(); Console.WriteLine(s); } } }
A B C D E F G H I J
The output is
K
Hello HELLO Hello HELLO
L M
World! WORLD! World! WORLD!
N O
String.ToUpper(System.Globalization.CultureInfo) Method
P
[ILASM]
Q
.method public hidebysig instance string ToUpper(class System.Globalization.CultureInfo culture)
R
[C#]
S
public string ToUpper(CultureInfo culture)
T
Summary
U
Returns a copy of this System.String in uppercase, using the casing rules of the specified culture.
V W
Parameters
X Y
Parameter
Description
culture
A System.Globalization.CultureInfo object that supplies culturespecific casing rules.
Z
2944
Contents | Index
System
String Trim() Method
Description The casing rules of the culture that is currently in effect determines the way the case of a string is changed. If your application depends on the case of a string changing in a predictable way, and the effective culture changes unexpectedly, then you can get invalid results. Consider the following lookup routine where the lookup key is a text string, the key is forced to a standard case to simplify comparisons, and the effective culture is the culture associated with the current thread.
A B C D
static object LookupKey(string key) { return internalHashtable[key.ToUpper()]; }
E
If it is possible for the current thread and its associated culture to change unexpectedly, it is advisable to specify the invariant culture instead of defaulting to the current thread culture. The following example demonstrates the preferred technique.
F G H
static object LookupKey(string key) { return internalHashtable[key.ToUpper(CultureInfo.InvariantCulture)]; }
I J
Exceptions
K
Exception
Condition
System.ArgumentNullException
culture is null.
L M N O P
String.Trim() Method
Q [ILASM]
.method public hidebysig instance string Trim()
R
[C#]
S
public string Trim()
T
Summary
U
Removes all occurrences of white space characters from the beginning and end of the current instance.
V W X Y Z
2945
Contents | Index
String
System
Trim() Method
Example using System; namespace Samples { public class StringTrim { public static void Main() { string s = " \t\nHello\t\n "; s = s.Trim(); Console.WriteLine(s); } } }
A B C D E F G H
The output is
I J
Hello
K L
String.Trim(System.Char[]) Method
M [ILASM]
N
.method public hidebysig instance string Trim(class System.Char[] trimChars) [C#]
O
public string Trim(params char[] trimChars)
P Q
Summary
R
Removes all occurrences of a set of characters provided in a character System.Array from the beginning and end of the current instance.
S
Parameters
T U V W
Parameter
Description
trimChars
An array of Unicode characters. Can be a null reference.
X Y
Return Value
Z
A new System.String equivalent to the current instance with the characters in trimChars removed from its beginning and end. If trimChars is a null reference, all of the white space characters are removed from the beginning and end of the current instance. 2946
Contents | Index
System
String TrimEnd() Method
Example using System; namespace Samples { public class StringTrim { public static void Main() { string s = "%@Hello%@"; s = s.Trim(new Char[]{'&', '#', '%', '@'}); Console.WriteLine(s); } } }
A B C D E F G H
The output is
I J
Hello
K L
String.TrimEnd(System.Char[]) Method
M [ILASM]
N
.method public hidebysig instance string TrimEnd(class System.Char[] trimChars) [C#]
O
public string TrimEnd(params char[] trimChars)
P
Summary
Q
Removes all occurrences of a set of characters specified in a Unicode character System.Array from the end of the current instance.
R S
Parameters
T U
Parameter
Description
trimChars
An array of Unicode characters. Can be a null reference.
V W X
Return Value
Y
A new System.String equivalent to the current instance with characters in trimChars removed from its end. If trimChars is a null reference, white space characters are removed.
Z
2947
Contents | Index
String
System
TrimStart() Method
Example using System; namespace Samples { public class StringTrimEnd { public static void Main() { string s = "Hello%@"; s = s.TrimEnd(new Char[]{'&', '#', '%', '@'}); Console.WriteLine(s); } } }
A B C D E F G H
The output is
I J
Hello
K L
String.TrimStart(System.Char[]) Method
M [ILASM]
N
.method public hidebysig instance string TrimStart(class System.Char[] trimChars) [C#]
O
public string TrimStart(params char[] trimChars)
P Q
Summary
R
Removes all occurrences of a set of characters specified in a Unicode character array from the beginning of the current instance.
S
Parameters
T U V W
Parameter
Description
trimChars
An array of Unicode characters or a null reference.
X Y
Return Value
Z
A new System.String equivalent to the current instance with the characters in trimChars removed from its beginning. If trimChars is a null reference, white space characters are removed. 2948
Contents | Index
System
String ToBoolean() Method
Example using System; namespace Samples { public class StringTrimStart { public static void Main() { string s = "%@Hello"; s = s.TrimStart(new Char[]{'&', '#', '%', '@'}); Console.WriteLine(s); } } }
A B C D E F G H
The output is
I J
Hello
K L
IEnumerable.GetEnumerator() Method
M [ILASM]
N
.method private final hidebysig virtual class System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
O
[C#]
IEnumerator IEnumerable.GetEnumerator()
P Q
Summary
R
Implemented to support the System.Collections.IEnumerable interface. [Note: For more information, see System.Collections.IEnumerable.GetEnumerator.]
S T U
IConvertible.ToBoolean(System.IFormatProvider) Method
V
[ILASM]
W
.method private final hidebysig virtual bool System.IConvertible.ToBoolean(class System.IFormatProvider provider)
X
[C#]
bool IConvertible.ToBoolean(IFormatProvider provider)
Y Z
2949
Contents | Index
String
System
ToByte() Method
Summary Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToBoolean.] A B
IConvertible.ToByte(System.IFormatProvider) Method
C
[ILASM]
D
.method private final hidebysig virtual unsigned int8 System.IConvertible.ToByte(class System.IFormatProvider provider)
E
[C#]
F
byte IConvertible.ToByte(IFormatProvider provider)
G H
Summary
I
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToByte.]
J K
IConvertible.ToChar(System.IFormatProvider) Method
L
[ILASM]
M
.method private final hidebysig virtual valuetype System.Char System.IConvertible.ToChar(class System.IFormatProvider provider)
N
[C#]
O
char IConvertible.ToChar(IFormatProvider provider)
P Q
Summary
R
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToChar.]
S T
IConvertible.ToDateTime(System.IFormatProvider) Method
U
[ILASM]
V
.method private final hidebysig virtual valuetype System.DateTime System.IConvertible.ToDateTime(class System.IFormatProvider provider)
W
[C#]
X
DateTime IConvertible.ToDateTime(IFormatProvider provider)
Y
Summary
Z
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDateTime.]
2950
Contents | Index
System
String ToInt16() Method
IConvertible.ToDecimal(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual decimal System.IConvertible.ToDecimal(class System.IFormatProvider provider)
A
[C#]
B
decimal IConvertible.ToDecimal(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDecimal.]
E F G
IConvertible.ToDouble(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual float64 System.IConvertible.ToDouble(class System.IFormatProvider provider)
J
[C#]
K
double IConvertible.ToDouble(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDouble.]
N O P
IConvertible.ToInt16(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual int16 System.IConvertible.ToInt16(class System.IFormatProvider provider)
S
[C#]
T
short IConvertible.ToInt16(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt16.]
W X Y Z
2951
Contents | Index
String
System
ToInt32() Method
IConvertible.ToInt32(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual int32 System.IConvertible.ToInt32(class System.IFormatProvider provider)
B
[C#]
int IConvertible.ToInt32(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt32.]
F G H
IConvertible.ToInt64(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual int64 System.IConvertible.ToInt64(class System.IFormatProvider provider)
K
[C#]
long IConvertible.ToInt64(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt64.]
O P Q
IConvertible.ToSByte(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual int8 System.IConvertible.ToSByte(class System.IFormatProvider provider)
T
[C#]
sbyte IConvertible.ToSByte(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSByte.] This member is not CLS-compliant.
W X Y Z
2952
Contents | Index
System
String ToUInt16() Method
IConvertible.ToSingle(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual float32 System.IConvertible.ToSingle(class System.IFormatProvider provider)
A
[C#]
B
float IConvertible.ToSingle(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSingle.]
E F G
IConvertible.ToType(System.Type, System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual object System.IConvertible.ToType(class System.Type type, class System.IFormatProvider provider)
J
[C#]
K
object IConvertible.ToType(Type type, IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToType.]
N O P
IConvertible.ToUInt16(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual unsigned int16 System.IConvertible.ToUInt16(class System.IFormatProvider provider)
S
[C#]
T
ushort IConvertible.ToUInt16(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt16.] This member is not CLS-compliant.
W X Y Z
2953
Contents | Index
String
System
ToUInt32() Method
IConvertible.ToUInt32(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual unsigned int32 System.IConvertible.ToUInt32(class System.IFormatProvider provider)
B
[C#]
uint IConvertible.ToUInt32(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt32.] This member is not CLS-compliant.
F G H
IConvertible.ToUInt64(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual unsigned int64 System.IConvertible.ToUInt64(class System.IFormatProvider provider)
K
[C#]
L
ulong IConvertible.ToUInt64(IFormatProvider provider)
M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt64.] This member is not CLS-compliant.
O P Q R S T U V W X Y Z
2954
Contents | Index
System.Text StringBuilder
BCL
Object
A
StringBuilder
B
Summary
C
Represents a mutable string of characters.
D E
Type Summary public sealed class StringBuilder { // Constructors public StringBuilder (); public StringBuilder (int capacity); MS public StringBuilder (int capacity, int maxCapacity); public StringBuilder (string value); MS public StringBuilder (string value, int capacity); MS public StringBuilder (string value, int startIndex, int length, int capacity);
F G H I J K L
// Properties public int Capacity { set; get; } public char this[int index] { set; get; } public int Length { set; get; } MS public int MaxCapacity { get; } // Methods public StringBuilder public StringBuilder public StringBuilder public StringBuilder public StringBuilder public StringBuilder CF public StringBuilder public StringBuilder public StringBuilder public StringBuilder public StringBuilder public StringBuilder public StringBuilder public StringBuilder public StringBuilder public StringBuilder public StringBuilder public StringBuilder
M N O P
Append Append Append Append Append Append Append Append Append Append Append Append Append Append Append Append Append Append
(bool value); (byte value); (char value); (char value, int repeatCount); (char[] value); (char[] value, int startIndex, int charCount); (decimal value); (double value); (float value); (int value); (long value); (object value); (sbyte value); (short value); (string value); (string value, int startIndex, int count); (uint value); (ulong value);
Q R S T U V W X Y Z
2955
Contents | Index
StringBuilder
System.Text
StringBuilder Class
public StringBuilder Append (ushort value); CF public StringBuilder AppendFormat (string format, object arg0); CF public StringBuilder AppendFormat (string format, object arg0, object arg1); CF public StringBuilder AppendFormat (string format, object arg0, object arg1, object arg2); CF public StringBuilder AppendFormat (string format, object[] args); public StringBuilder AppendFormat (params IFormatProvider provider, string format, params object[] args); CF public int EnsureCapacity (int capacity); CF public bool Equals (StringBuilder sb); CF public StringBuilder Insert (int index, bool value); CF public StringBuilder Insert (int index, byte value); CF public StringBuilder Insert (int index, char value); public StringBuilder Insert (int index, char[] value); public StringBuilder Insert (int index, char[] value, int startIndex, int charCount); CF public StringBuilder Insert (int index, decimal value); CF public StringBuilder Insert (int index, double value); CF public StringBuilder Insert (int index, float value); CF public StringBuilder Insert (int index, int value); CF public StringBuilder Insert (int index, long value); CF public StringBuilder Insert (int index, object value); CF public StringBuilder Insert (int index, sbyte value); CF public StringBuilder Insert (int index, short value); public StringBuilder Insert (int index, string value); public StringBuilder Insert (int index, string value, int count); CF public StringBuilder Insert (int index, uint value); CF public StringBuilder Insert (int index, ulong value); CF public StringBuilder Insert (int index, ushort value); public StringBuilder Remove (int startIndex, int length); public StringBuilder Replace (char oldChar, char newChar); public StringBuilder Replace (char oldChar, char newChar, int startIndex, int count); public StringBuilder Replace (string oldValue, string newValue); public StringBuilder Replace (string oldValue, string newValue, int startIndex, int count); public override string ToString (); public string ToString (int startIndex, int length);
A B C D E F G H I J K L M N O P Q R S T U V W
}
X Y Z
2956
Contents | Index
System.Text
StringBuilder StringBuilder Class
BA Notice we overload several of the methods with all the base types (Insert, Append, etc). As a general rule this is not necessary. Because System.Object is the root of the inheritance hierarchy for all types in the system just having a single method that takes System.Object will work. One issue with doing that is casting a base type (or any value type for that matter) to an Object in order to call this method is a boxing operation that creates temporary memory on the GC heap. In general this is not a problem because the GC is tuned to handle small short-lived instances such as these. However, in a tight loop it could be an issue. Therefore, we provide these special cases that avoid the box.
A B C D E F
KG In retrospect, putting the StringBuilder class in the System.Text
G
namespace was a mistake. People cannot find it, even though they know what it is for. It should have been in the System namespace.
H
KC StringBuilder should be in the root System namespace. Any real-life appli-
I
cation has need for it and it’s more related to String than to other types in System.Text in which it resides. Namespace factoring is another tricky part of designing large reusable libraries. Too many types in one namespace make the namespace diffcult to understand. Too few types in a namespace make the namespace difficult to use. Namespaces should help in avoiding and resolving naming conflicts and to organize types in a logical hierarchy. The problem is that the namespace hierarchy is static and just as any static hierarchy, no matter how you design it, it is never perfect in every scenario.
J K L M N O P
JR You should use StringBuilder when doing several string manipulations.
Q
However, it is strange that String offers ToLower, ToUpper, EndsWith, PadLeft, and Trim methods, but StringBuilder does not. Hopefully, a future version of the BCL will give greater parity between these two classes.
R S T
Description
U
This class represents string-like objects that are mutable. After a System.Text.StringBuilder object has been created, it can be directly modified by removing, replacing, or inserting characters. This contrasts the System.String class, which represents an immutable string of characters. The System.Text.StringBuilder.Capacity of an instance of the System.Text.StringBuilder class is the maximum number of characters it can hold in the currently allocated space. The System.Text.StringBuilder will dynamically allocate more space when it is required.
V W X Y Z
2957
Contents | Index
StringBuilder
System.Text
StringBuilder Class
Unlike most types in the Base Class Library, the arguments to System.Text.StringBuilder members are assumed to be passed as in/out arguments (passed by reference). [Note: Normally arguments are in arguments (passed by value) unless explicitly declared as out or in/out.] [Note: An instance of System.String is said to be “immutable” because its value cannot be modified once it has been created. Methods on System.String that appear to modify a System.String instance actually return a new instance containing the modification. The System.Text.StringBuilder class provides methods that actually modify the contents of a string-like object. Relational operators only perform reference comparisons (unless overloaded by a particular language compiler). Despite this restriction, relational operators can be used to compare System.String objects that are assigned literal values. Their values are immutable and can’t change, so a reference comparison is sufficient. Because System.Text.StringBuilder instances are mutable, they should not be compared with relational operators. For performance reasons a System.Text.StringBuilder might allocate more memory than needed. The amount of memory allocated is implementation specific.]
A B C D E F G H I J
Example
K
using System; using System.Text;
L M
namespace Samples { public class StringBuilderSample { public static void Main() { StringBuilder sb = new StringBuilder("Hello"); Console.WriteLine("Capacity: {0}", sb.Capacity); Console.WriteLine("MaxCapacity: {0}", sb.MaxCapacity); Console.WriteLine("Length: {0}", sb.Length); sb.Append(" world! "); sb.Insert(11, " from DAMIEN"); sb.Replace("DAMIEN", "damien"); sb.AppendFormat("appended at {0:dd/MM/yy}", DateTime.Now); string s = sb.ToString(); sb.Remove(11, 13); Console.WriteLine(s); Console.WriteLine(sb); } } }
N O P Q R S T U V W X Y Z
2958
Contents | Index
System.Text
StringBuilder StringBuilder() Constructor
The output is Capacity: 16 MaxCapacity: 2147483647 Length: 5 Hello world from damien! appended at 23/06/03 Hello world appended at 23/06/03
A B C D
StringBuilder() Constructor
E
[ILASM]
F
public rtspecialname specialname instance void .ctor()
G
[C#]
public StringBuilder()
H
Summary
I
Constructs and initializes a new, empty instance of the System.Text.StringBuilder class.
J K L
Description
M
The new instance of System.Text.StringBuilder represents a string equal to System.String.Empty. The System.Text.StringBuilder.Capacity is set to the default capacity. [Note: The default value of the System.Text.StringBuilder.Capacity property is implementation dependent.]
N O P Q
Example
R
using System; using System.Text;
S T
namespace Samples { public class StringBuilderConstructor { public static void Main() { StringBuilder sb = new StringBuilder(); Console.WriteLine("Capacity: {0}", sb.Capacity); Console.WriteLine("MaxCapacity: {0}", sb.MaxCapacity); Console.WriteLine("Length: {0}", sb.Length);
U V W X Y Z
2959
Contents | Index
StringBuilder
System.Text
StringBuilder() Constructor
sb.Append("Hello world! "); sb.AppendFormat("appended at {0:dd/MM/yy}", DateTime.Now); Console.WriteLine(sb);
A
} }
B }
C
The output is
D E
Capacity: 16 MaxCapacity: 2147483647 Length: 0 Hello world! appended at 23/06/03
F G H I
StringBuilder(System.Int32) Constructor
J
[ILASM]
public rtspecialname specialname instance void .ctor(int32 capacity)
K
[C#]
L
public StringBuilder(int capacity)
M
Summary
N
Constructs and initializes a new, empty instance of the System.Text.StringBuilder class, with a specified System.Text.StringBuilder.Capacity.
O P
Parameters
Q R
Parameter
Description
capacity
A System.Int32 containing the starting number of characters allowed in the System.Text.StringBuilder.
S T U V
Description
W
If the specified capacity is less than the default capacity, the System.Text.StringBuilder.Capacity of the new instance of System.Text.StringBuilder is set to the default value. The System.Text.StringBuilder will dynamically allocate more space when it is required. The new System.Text.StringBuilder is initialized to represent an empty string. [Note: The default value of the System.Text.StringBuilder.Capacity property is implementation dependent.]
X Y Z
2960
Contents | Index
System.Text
StringBuilder StringBuilder() Constructor
Example using System; using System.Text;
A namespace Samples { public class StringBuilderConstructor { public static void Main() { StringBuilder sb = new StringBuilder(512); Console.WriteLine("Capacity: {0}", sb.Capacity); Console.WriteLine("MaxCapacity: {0}", sb.MaxCapacity); Console.WriteLine("Length: {0}", sb.Length); sb.Append("Hello world!"); Console.WriteLine(sb); } } }
B C D E F G H I J K L M
The output is
N Capacity: 512 MaxCapacity: 2147483647 Length: 0 Hello world!
O P Q R
StringBuilder(System.Int32, System.Int32) Constructor
S [ILASM]
T
public rtspecialname specialname instance void .ctor(int32 capacity, int32 maxCapacity)
U
[C#]
V
public StringBuilder(int capacity, int maxCapacity)
W
Summary
X
Initializes a new instance of the System.Text.StringBuilder class that starts with a specified capacity and can grow to a specified maximum.
Y Z
2961
Contents | Index
StringBuilder
System.Text
StringBuilder() Constructor
Parameters Parameter
Description
capacity
The suggested starting size of the System.Text.StringBuilder.
maxCapacity
The maximum number of characters the current string can contain.
A B C D E
Description
F
If capacity is zero, the implementation-specific default capacity is used.
G
Exceptions
H I
Exception
Condition
System.ArgumentOutOfRangeException
maxCapacity is less than one, capacity is less than zero, or capacity is greater than maxCapacity.
J K L M N
StringBuilder(System.String) Constructor
O
[ILASM]
public rtspecialname specialname instance void .ctor(string value)
P
[C#]
public StringBuilder(string value)
Q R
Summary
S
Constructs and initializes a new instance of the System.Text.StringBuilder class, with the specified System.String as its value.
T U
Parameters
V W
Parameter
Description
value
A System.String containing the string value of the new instance of System.Text.StringBuilder.
X Y Z
2962
Contents | Index
System.Text
StringBuilder StringBuilder() Constructor
Description [Note: The System.Text.StringBuilder.Capacity of the new instance is implementation defined.] A
Example
B
using System; using System.Text;
C D
namespace Samples { public class StringBuilderConstructor { public static void Main() { StringBuilder sb = new StringBuilder("Hello "); Console.WriteLine("Capacity: {0}", sb.Capacity); Console.WriteLine("MaxCapacity: {0}", sb.MaxCapacity); Console.WriteLine("Length: {0}", sb.Length); sb.Append("world! "); sb.AppendFormat("appended at {0:dd/MM/yy}", DateTime.Now); Console.WriteLine(sb); } } }
E F G H I J K L M N O P Q
The output is
R
Capacity: 16 MaxCapacity: 2147483647 Length: 6 Hello world! appended at 23/06/03
S T U V
StringBuilder(System.String, System.Int32) Constructor
W
[ILASM]
X
public rtspecialname specialname instance void .ctor(string value, int32 capacity)
Y
[C#]
public StringBuilder(string value, int capacity)
Z
2963
Contents | Index
StringBuilder
System.Text
StringBuilder() Constructor
Summary Initializes a new instance of the System.Text.StringBuilder class using the specified string and capacity. A
Parameters
B C D
Parameter
Description
value
The string used to initialize the value of the instance. If value is null, the new System.Text.StringBuilder will contain the empty string (that is, it contains System.String.Empty ).
capacity
The suggested starting size of the System.Text.StringBuilder.
E F G H I
Description
J
If capacity is zero, the implementation-specific default capacity is used.
K
Exceptions
L M
Exception
Condition
System.ArgumentOutOfRangeException
capacity is less than zero.
N O P Q
StringBuilder(System.String, System.Int32, System.Int32, System.Int32) Constructor
R S
[ILASM]
T
public rtspecialname specialname instance void .ctor(string value, int32 startIndex, int32 length, int32 capacity)
U
[C#]
public StringBuilder(string value, int startIndex, int length, int capacity)
V W
Summary
X
Initializes a new instance of the System.Text.StringBuilder class from the specified substring and capacity.
Y Z
2964
Contents | Index
System.Text
StringBuilder Capacity Property
Parameters Parameter
Description
value
The string that contains the substring used to initialize the value of the instance. If value is null, the new StringBuilder will contain the empty string (that is, it contains System.String.Empty ).
A
startIndex
The position where the substring begins.
length
The number of characters in the substring.
capacity
The suggested starting size of the System.Text.StringBuilder.
B C D E F G H
Description
I
If capacity is zero, the implementation-specific default capacity is used.
J K
Exceptions
L
Exception
System.ArgumentOutOfRangeException
Condition
M
capacity is less than zero.
N
-or-
O
startIndex plus length is not a position within value.
P Q R
StringBuilder.Capacity Property
S
[ILASM]
T
.property int32 Capacity { public hidebysig specialname instance int32 get_Capacity() public hidebysig specialname instance void set_Capacity(int32 value) }
U
[C#]
V
public int Capacity { get; set; }
W
Summary
X
Gets or sets the maximum number of characters that can be contained in the memory allocated by the current instance.
Y Z
2965
Contents | Index
StringBuilder
System.Text
Capacity Property
Description The System.Text.StringBuilder.Capacity property does not affect the string value of the current instance. The System.Text.StringBuilder will dynamically increase the System.Text.StringBuilder.Capacity and allocate more space when it is required. [Note: For performance reasons a System.Text.StringBuilder might allocate more memory than needed. The amount of memory allocated is implementation specific.]
A B C D
Exceptions
E F
Exception
Condition
System.ArgumentException
The value specified for a set operation is less than System.Text.StringBuilder.Length.
G H I J
Example
K
using System; using System.Text;
L M
namespace Samples { public class StringBuilderCapacity { public static void Main() { StringBuilder sb = new StringBuilder(); DisplayInformation(sb); sb.Append("Hello world! "); DisplayInformation(sb); sb.Capacity = 256; DisplayInformation(sb); } public static void DisplayInformation( StringBuilder sb) { Console.WriteLine("Capacity: {0}", sb.Capacity); Console.WriteLine("MaxCapacity: {0}", sb.MaxCapacity); Console.WriteLine("Length: {0}", sb.Length); } } }
N O P Q R S T U V W X Y Z
2966
Contents | Index
System.Text
StringBuilder Chars Property
The output is Capacity: 16 MaxCapacity: 2147483647 Length: 0 Capacity: 16 MaxCapacity: 2147483647 Length: 13 Capacity: 256 MaxCapacity: 2147483647 Length: 13
A B C D E F G
StringBuilder.Chars Property
H
[ILASM]
.property valuetype System.Char Chars[int32 index] { public hidebysig specialname instance valuetype System.Char get_Chars(int32 index) public hidebysig specialname instance void set_Chars(int32 index, valuetype System.Char value) }
I
[C#]
K
J
public char this[int index] { get; set; }
L
Summary
M
Gets or sets the character at a specified position in the current instance.
N O
Property Value
P
A System.Char containing the Unicode character at location index in the current instance.
Q
Description
R
index is the position of a character within the System.Text.StringBuilder. The first character in the string is at index 0. The length of a string is the number of characters it contains. The last accessible character of a System.Text.StringBuilder instance is at the index System.Text.StringBuilder.Length–1.
S T U V
Exceptions Exception
W X
Condition
Y
index is greater than or equal to the length of the current instance. System.IndexOutOfRangeException
Z
-orindex is less than zero.
2967
Contents | Index
StringBuilder
System.Text
Length Property
Example using System; using System.Text;
A namespace Samples { public class StringBuilderChars { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Hello world!"); for(int i = 0; i < sb.Length; i++) Console.WriteLine(sb[i]); } } }
B C D E F G H I J
The output is
K
H e l l o
L M N O
w o r l d !
P Q R S T
StringBuilder.Length Property
U [ILASM]
V
.property int32 Length { public hidebysig specialname instance int32 get_Length() public hidebysig specialname instance void set_Length(int32 value) }
W
[C#]
public int Length { get; set; }
X Y
Summary
Z
Gets or sets the length of the current instance.
2968
Contents | Index
System.Text
StringBuilder Length Property
Description If the specified length is less than the current length, the System.Text.StringBuilder is truncated to the specified length. If the specified length is greater than the current length, the end of the string value of the System.Text.StringBuilder is padded with spaces. If the specified length is greater than the current System.Text.StringBuilder.Capacity, System.Text.StringBuilder.Capacity is set to the specified length. [Note: A space in Unicode format is defined as the hexadecimal value 0x20.]
A B C D E
Exceptions
F
Exception
Condition
System.ArgumentOutOfRangeException
The value specified for a set operation is less than 0 or greater than System.Int32.MaxValue.
G H I J
Example
K
using System; using System.Text;
L M
namespace Samples { public class StringBuilderLength { public static void Main() { StringBuilder sb = new StringBuilder(); DisplayInformation(sb); sb.Append("Hello world! "); DisplayInformation(sb); sb.Capacity = 256; DisplayInformation(sb); } public static void DisplayInformation( StringBuilder sb) { Console.WriteLine("Capacity: {0}", sb.Capacity); Console.WriteLine("MaxCapacity: {0}", sb.MaxCapacity); Console.WriteLine("Length: {0}", sb.Length); } } }
N O P Q R S T U V W X Y Z
2969
Contents | Index
StringBuilder
System.Text
MaxCapacity Property
The output is Capacity: 16 MaxCapacity: 2147483647 Length: 0 Capacity: 16 MaxCapacity: 2147483647 Length: 13 Capacity: 256 MaxCapacity: 2147483647 Length: 13
A B C D E F G
StringBuilder.MaxCapacity Property
H
[ILASM]
I
.property int32 MaxCapacity { public hidebysig specialname instance int32 get_MaxCapacity() }
J
[C#]
public int MaxCapacity { get; }
K L
Summary
M
Gets the maximum capacity of this instance. The maximum capacity for this implementation is System.Int32.MaxValue. However, this value is implementation-specific and might be different in other or later implementations.
N O P Q
StringBuilder.Append(System.Boolean) Method
R
[ILASM]
S
.method public hidebysig instance class System.Text.StringBuilder Append(bool value)
T
[C#]
U
public StringBuilder Append(bool value)
V W
Summary
X
Appends the string representation of a System.Boolean to the end of the current instance.
Y Z
2970
Contents | Index
System.Text
StringBuilder Append() Method
Parameters Parameter
Description
value
A System.Boolean to be appended.
A B C
Description
D
This method appends value.ToString() to the current instance. The System.Text.StringBuilder.Capacity of the current instance is increased as necessary.
E F G
Example
H
using System; using System.Text;
I J
namespace Samples { public class StringBuilderAppend { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("true: "); sb.Append(true); sb.Append(" false: "); sb.Append(false); Console.WriteLine(sb); } } }
K L M N O P Q R S T
The output is
U true: True false: False
V W
StringBuilder.Append(System.Byte) Method
X
[ILASM]
Y
.method public hidebysig instance class System.Text.StringBuilder Append(unsigned int8 value)
Z
[C#]
public StringBuilder Append(byte value)
2971
Contents | Index
StringBuilder
System.Text
Append() Method
Summary Appends the string representation of a System.Byte to the end of the current instance. A
Parameters
B C
Parameter
Description
D
value
The System.Byte to be appended.
E F
Description
G
This method appends value.ToString() to the current instance. The System.Text.StringBuilder.Capacity of the current instance is increased as necessary.
H I J
Example
K
using System; using System.Text;
L
namespace Samples { public class StringBuilderAppend { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Byte.MaxValue: "); sb.Append(Byte.MaxValue); sb.Append(" Byte.MinValue: "); sb.Append(Byte.MinValue); Console.WriteLine(sb); } } }
M N O P Q R S T U V
The output is
W X
Byte.MaxValue: 255 Byte.MinValue: 0
Y Z
2972
Contents | Index
System.Text
StringBuilder Append() Method
StringBuilder.Append(System.Char) Method [ILASM]
.method public hidebysig instance class System.Text.StringBuilder Append(valuetype System.Char value)
A
[C#]
B
public StringBuilder Append(char value)
C
Summary
D
Appends the string representation of a Unicode character to the end of the current instance.
E
Parameters
G
F
H
Parameter
Description
value
The System.Char to be appended.
I J K
Description
L
This method appends the specified character to the current instance. The System.Text.StringBuilder.Capacity of the current instance is increased as necessary.
M
Example
P
using System; using System.Text;
Q
N O
R namespace Samples { public class StringBuilderAppend { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append('A'); sb.Append('-'); sb.Append('Z'); Console.WriteLine(sb); } } }
S T U V W X Y Z
2973
Contents | Index
StringBuilder
System.Text
Append() Method
The output is A-Z
A B
StringBuilder.Append(System.Char, System.Int32) Method
C [ILASM]
D
.method public hidebysig instance class System.Text.StringBuilder Append(valuetype System.Char value, int32 repeatCount)
E
[C#]
public StringBuilder Append(char value, int repeatCount)
F G
Summary
H
Appends multiple copies of a character to the end of the current System.Text.StringBuilder.
I J
Parameters
K L M
Parameter
Description
value
The System.Char to be appended.
repeatCount
A System.Int32 containing the number of times to append value.
N O P
Description
Q
This method appends repeatCount copies of the specified character to the current instance. The System.Text.StringBuilder.Capacity of the current instance is increased as necessary.
R S T
Exceptions
U V W
Exception
Condition
System.ArgumentOutOfRangeException
repeatCount is less than zero.
X Y Z
2974
Contents | Index
System.Text
StringBuilder Append() Method
Example using System; using System.Text;
A namespace Samples { public class StringBuilderAppend { public static void Main() { StringBuilder sb = new StringBuilder(); Console.WriteLine("Length: {0}", sb.Length); sb.Append('A', 42); Console.WriteLine("Length: {0}", sb.Length); Console.WriteLine(sb); } } }
B C D E F G H I J K
The output is
L
Length: 0 Length: 42 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
M N O P
StringBuilder.Append(System.Char[]) Method
Q
[ILASM]
R
.method public hidebysig instance class System.Text.StringBuilder Append(class System.Char[] value)
S
[C#]
public StringBuilder Append(char[] value)
T
Summary
U
Appends the string representation of all of the characters in a System.Array to the end of the current instance.
V W X
Parameters
Y
Parameter
Description
value
The array of System.Char to be appended.
Z
2975
Contents | Index
StringBuilder
System.Text
Append() Method
Description This method appends all of the characters in the specified array to the current instance in the same order as they appear in value. If value is a null reference no changes are made. The System.Text.StringBuilder.Capacity of the current instance is increased as necessary.
A B C
Example
D
using System; using System.Text;
E F
namespace Samples { public class StringBuilderAppend { public static void Main() { StringBuilder sb = new StringBuilder(); string s = "Hello world!"; Char[] chars = s.ToCharArray(); sb.Append(chars); Console.WriteLine("Length: {0}", sb.Length); Console.WriteLine(sb); } } }
G H I J K L M N O P
The output is
Q
Length: 12 Hello world!
R S T
StringBuilder.Append(System.Char[], System.Int32, System.Int32) Method
U
[ILASM]
V
.method public hidebysig instance class System.Text.StringBuilder Append(class System.Char[] value, int32 startIndex, int32 charCount)
W
[C#]
X
public StringBuilder Append(char[] value, int startIndex, int charCount)
Y
Summary
Z
Appends the string representation of an array of Unicode characters to the end of the current instance.
2976
Contents | Index
System.Text
StringBuilder Append() Method
Parameters Parameter
Description
value
The System.Char array to be appended.
startIndex
A System.Int32 containing the index in value at which the subarray starts.
C
charCount
A System.Int32 containing the number of characters to copy from value.
D
A B
E F
Description
G
This method appends with the specified range of characters from the value array to the current instance. If value is a null reference, and both startIndex and charCount are zero, no changes are made. The System.Text.StringBuilder.Capacity of the current instance is increased as necessary.
H I J K
Exceptions
L
Exception
Condition
System.ArgumentNullException
value is a null reference, and startIndex and charCount are not both zero.
M N O P
charCount or startIndex is less than zero. System.ArgumentOutOfRangeException
Q
-or-
R
The sum of startIndex and charCount is greater than the length of value.
S T
Example
U
using System; using System.Text;
V W
namespace Samples { public class StringBuilderAppend { public static void Main() { StringBuilder sb = new StringBuilder(); string s = "I say Hello world! to you all";
X Y Z
2977
Contents | Index
StringBuilder
System.Text
Append() Method
Char[] chars = s.ToCharArray(); sb.Append(chars, 6, 12); Console.WriteLine("Length: {0}", sb.Length); Console.WriteLine(sb);
A }
B }
C
}
D
The output is
E Length: 12 Hello world!
F G H
StringBuilder.Append(System.Decimal) Method
I [ILASM]
J
.method public hidebysig instance class System.Text.StringBuilder Append(decimal value)
K
[C#]
L
public StringBuilder Append(decimal value)
M
Summary
N
Appends the string representation of a System.Decimal to the end of the current instance.
O
Parameters
P Q R S
Parameter
Description
value
The System.Decimal to be appended.
T U
Description
V
This method appends value.ToString() to the current instance. The System.Text.StringBuilder.Capacity of the current instance is increased as necessary. This member must be implemented if the Extended Numerics Library is present in the implementation.
W X Y Z
2978
Contents | Index
System.Text
StringBuilder Append() Method
Example using System; using System.Text;
A namespace Samples { public class StringBuilderAppend { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Decimal.MaxValue: "); sb.Append(Decimal.MaxValue); sb.Append(" Decimal.MinValue: "); sb.Append(Decimal.MinValue); Console.WriteLine(sb); } } }
B C D E F G H I J
The output is
K L
Decimal.MaxValue: 79228162514264337593543950335 Decimal.MinValue: 79228162514264337593543950335
M N
StringBuilder.Append(System.Double) Method
O
[ILASM]
P
.method public hidebysig instance class System.Text.StringBuilder Append(float64 value)
Q
[C#]
R
public StringBuilder Append(double value)
S
Summary
T
Appends the string representation of a System.Double to the end of the current instance.
U V
Parameters
W
Parameter
Description
X
value
The System.Double to be appended.
Y Z
2979
Contents | Index
StringBuilder
System.Text
Append() Method
Description This method appends value.ToString() to the current instance. The System.Text.StringBuilder.Capacity of the current instance is increased as necessary. This member must be implemented if the Extended Numerics Library is present in the implementation.
A B C D
Example
E
using System; using System.Text;
F namespace Samples { public class StringBuilderAppend { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Double.MaxValue: "); sb.Append(Double.MaxValue); sb.Append(" Double.MinValue: "); sb.Append(Double.MinValue); Console.WriteLine(sb); } } }
G H I J K L M N O P
The output is
Q
Double.MaxValue: 1.79769313486232E+308 Double.MinValue: -1.79769313486232E+308
R S T
StringBuilder.Append(System.Single) Method
U
[ILASM]
V
.method public hidebysig instance class System.Text.StringBuilder Append(float32 value)
W
[C#]
public StringBuilder Append(float value)
X Y
Summary
Z
Appends the string representation of a System.Single to the end of the current instance.
2980
Contents | Index
System.Text
StringBuilder Append() Method
Parameters Parameter
Description
value
The System.Single to be appended.
A B C
Description
D
This method appends value.ToString() to the current instance. The System.Text.StringBuilder.Capacity of the current instance is increased as necessary. This member must be implemented if the Extended Numerics Library is present in the implementation.
E F G H
Example
I
using System; using System.Text;
J K
namespace Samples { public class StringBuilderAppend { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Single.MaxValue: "); sb.Append(Single.MaxValue); sb.Append(" Single.MinValue: "); sb.Append(Single.MinValue); Console.WriteLine(sb); } } }
L M N O P Q R S T
The output is
U V
Single.MaxValue: 3.402823E+38 Single.MinValue: -3.402823E+38
W
StringBuilder.Append(System.Int32) Method
X
[ILASM]
Y
.method public hidebysig instance class System.Text.StringBuilder Append(int32 value)
Z
[C#]
public StringBuilder Append(int value)
2981
Contents | Index
StringBuilder
System.Text
Append() Method
Summary Appends the string representation of a System.Int32 to the end of the current instance. A
Parameters
B C D
Parameter
Description
value
The System.Int32 to be appended.
E F
Description
G
This method appends value.ToString() to the current instance. The System.Text.StringBuilder.Capacity of the current instance is increased as necessary.
H I J
Example
K
using System; using System.Text;
L
namespace Samples { public class StringBuilderAppend { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Int32.MaxValue: "); sb.Append(Int32.MaxValue); sb.Append(" Int32.MinValue: "); sb.Append(Int32.MinValue); Console.WriteLine(sb); } } }
M N O P Q R S T U V
The output is
W
Int32.MaxValue: 2147483647 Int32.MinValue: -2147483648
X Y Z
2982
Contents | Index
System.Text
StringBuilder Append() Method
StringBuilder.Append(System.Int64) Method [ILASM]
.method public hidebysig instance class System.Text.StringBuilder Append(int64 value)
A
[C#]
B
public StringBuilder Append(long value)
C
Summary
D
Appends the string representation of a System.Int64 to the end of the current instance.
E F
Parameters
G
Parameter
Description
value
The System.Int64 to be appended.
H I J K
Description
L
This method appends value.ToString() to the current instance. The System.Text.StringBuilder.Capacity of the current instance is increased as necessary.
M N O
Example
P
using System; using System.Text;
Q R
namespace Samples { public class StringBuilderAppend { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Int64.MaxValue: "); sb.Append(Int64.MaxValue); sb.Append(" Int64.MinValue: "); sb.Append(Int64.MinValue); Console.WriteLine(sb); } } }
S T U V W X Y Z
2983
Contents | Index
StringBuilder
System.Text
Append() Method
The output is Int64.MaxValue: 9223372036854775807 Int64.MinValue: -9223372036854775808
A B
StringBuilder.Append(System.Object) Method
C [ILASM]
D
.method public hidebysig instance class System.Text.StringBuilder Append(object value)
E
[C#]
public StringBuilder Append(object value)
F G
Summary
H
Appends the string representation of an object to the end of the current instance.
I
Parameters
J K
Parameter
Description
value
The System.Object to be appended.
L M N O
Description
P
This method appends value.ToString() to the current instance. If value is a null reference, no changes are made. The System.Text.StringBuilder.Capacity of the current instance is increased as necessary.
Q R S
Example
T
using System; using System.Text;
U V
namespace Samples { public class StringBuilderAppend { public static void Main() { StringBuilder sb = new StringBuilder(); object o = new Object(); sb.Append("Object: "); sb.Append(o);
W X Y Z
2984
Contents | Index
System.Text
StringBuilder Append() Method
o = 42; sb.Append(" Integer: "); sb.Append(o); o = "Hello World!"; sb.Append(" String: "); sb.Append(o); Console.WriteLine(sb);
A B C
} }
D
}
E
The output is
F
Object: System.Object Integer: 42 String: Hello World!
G H
StringBuilder.Append(System.SByte) Method
I
[ILASM]
J
.method public hidebysig instance class System.Text.StringBuilder Append(int8 value)
K
[C#]
L
public StringBuilder Append(sbyte value)
M
Summary
N
Appends the string representation of a System.SByte to the end of the current instance.
O P
Parameters
Q
Parameter
Description
value
The System.SByte to be appended.
R S T U
Description
V
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Text.StringBuilder.Append(System.Int16). This method appends value.ToString() to the current instance. The System.Text.StringBuilder.Capacity of the current instance is increased as necessary.
W X Y Z
2985
Contents | Index
StringBuilder
System.Text
Append() Method
Example using System; using System.Text;
A namespace Samples { public class StringBuilderAppend { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("SByte.MaxValue: "); sb.Append(SByte.MaxValue); sb.Append(" SByte.MinValue: "); sb.Append(SByte.MinValue); Console.WriteLine(sb); } } }
B C D E F G H I J K
The output is
L SByte.MaxValue: 127 SByte.MinValue: -128
M N O
StringBuilder.Append(System.Int16) Method
P
[ILASM]
Q
.method public hidebysig instance class System.Text.StringBuilder Append(int16 value) [C#]
R
public StringBuilder Append(short value)
S
Summary
T
Appends the string representation of a System.Int16 to the end of the current instance.
U V
Parameters
W X Y
Parameter
Description
value
The System.Int16 to be appended.
Z
2986
Contents | Index
System.Text
StringBuilder Append() Method
Description This method appends value.ToString() to the current instance. The System.Text.StringBuilder.Capacity of the current instance is increased as necessary.
A B
Example
C
using System; using System.Text;
D E
namespace Samples { public class StringBuilderAppend { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Int16.MaxValue: "); sb.Append(Int16.MaxValue); sb.Append(" Int16.MinValue: "); sb.Append(Int16.MinValue); Console.WriteLine(sb); } } }
F G H I J K L M N
The output is
O
Int16.MaxValue: 32767 Int16.MinValue: -32768
P Q
StringBuilder.Append(System.String) Method
R
[ILASM]
S
.method public hidebysig instance class System.Text.StringBuilder Append(string value)
T
[C#]
U
public StringBuilder Append(string value)
V
Summary
W
Appends a copy of a string to the end of the current instance.
X Y Z
2987
Contents | Index
StringBuilder
System.Text
Append() Method
Parameters Parameter
Description
value
The System.String to be appended.
A B C
Description
D
This method appends the value string to the current instance. If value is a null reference, no changes are made. The System.Text.StringBuilder.Capacity of the current instance is increased as necessary.
E F G H
Example
I
using System; using System.Text;
J K
namespace Samples { public class StringBuilderAppend { public static void Main() { StringBuilder sb = new StringBuilder(); Console.WriteLine("Length: {0}", sb.Length); sb.Append("Hello world!"); Console.WriteLine("Length: {0}", sb.Length); Console.WriteLine(sb); } } }
L M N O P Q R S T U
The output is
V
Length: 0 Length: 12 Hello world!
W X Y Z
2988
Contents | Index
System.Text
StringBuilder Append() Method
StringBuilder.Append(System.String, System.Int32, System.Int32) Method [ILASM]
.method public hidebysig instance class System.Text.StringBuilder Append(string value, int32 startIndex, int32 count)
A
[C#]
B
public StringBuilder Append(string value, int startIndex, int count)
C
Summary
D
Appends a copy of an array of Unicode characters, specified by a starting index and length, of a specified System.String to the end of the current instance.
E
Parameters
G
F
H
Parameter
Description
value
The System.String from which the substring will be taken.
startIndex
A System.Int32 containing the index in value from which to start copying.
count
A System.Int32 containing the number of characters to copy from value.
I J K L M N
Description
O
This method appends the specified range of characters in the value string to the current instance. If value is a null reference and startIndex and count are both zero, no changes are made. The System.Text.StringBuilder.Capacity of the current instance is increased as necessary.
P Q R S T
Exceptions
U
Exception
Condition
System.ArgumentNullException
value is a null reference, and startIndex and count are not both zero.
V W X
charCount or startIndex is less than zero. System.ArgumentOutOfRangeException
Y
-or-
Z
The sum of startIndex and charCount is greater than the length of value.
2989
Contents | Index
StringBuilder
System.Text
Append() Method
Example using System; using System.Text;
A namespace Samples { public class StringBuilderAppend { public static void Main() { StringBuilder sb = new StringBuilder(); string s = "I say Hello world! to you all"; sb.Append(s, 6, 12); Console.WriteLine("Length: {0}", sb.Length); Console.WriteLine(sb); } } }
B C D E F G H I J K
The output is
L Length: 12 Hello world!
M N O
StringBuilder.Append(System.UInt32) Method
P [ILASM]
Q
.method public hidebysig instance class System.Text.StringBuilder Append(unsigned int32 value)
R
[C#]
S
public StringBuilder Append(uint value)
T
Summary
U
Appends the string representation of a System.UInt32 to the end of the current instance.
V
Parameters
W X
Parameter
Description
value
The System.UInt32 to be appended.
Y Z
2990
Contents | Index
System.Text
StringBuilder Append() Method
Description This member is not CLS-compliant. For a CLS-compliant alternative, use System.Text.StringBuilder.Append(System.Int64). This method appends value.ToString() to the current instance. The System.Text.StringBuilder.Capacity of the current instance is increased as necessary.
A B C
Example
D
using System; using System.Text;
E F
namespace Samples { public class StringBuilderAppend { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("UInt32.MaxValue: "); sb.Append(UInt32.MaxValue); sb.Append(" UInt32.MinValue: "); sb.Append(UInt32.MinValue); Console.WriteLine(sb); } } }
G H I J K L M N O P
The output is
Q
UInt32.MaxValue: 4294967295 UInt32.MinValue: 0
R S
StringBuilder.Append(System.UInt64) Method
T
[ILASM]
U
.method public hidebysig instance class System.Text.StringBuilder Append(unsigned int64 value)
V
[C#]
W
public StringBuilder Append(ulong value)
X
Summary
Y
Appends the string representation of a System.UInt64 to the end of the current instance.
Z
2991
Contents | Index
StringBuilder
System.Text
Append() Method
Parameters Parameter
Description
value
The System.UInt64 to be appended.
A B C
Description
D
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Text.StringBuilder.Append(System.Decimal). This method appends value.ToString() to the current instance. The System.Text.StringBuilder.Capacity of the current instance is increased as necessary.
E F G H I
Example
J
using System; using System.Text;
K
namespace Samples { public class StringBuilderAppend { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("UInt64.MaxValue: "); sb.Append(UInt64.MaxValue); sb.Append(" UInt64.MinValue: "); sb.Append(UInt64.MinValue); Console.WriteLine(sb); } } }
L M N O P Q R S T U
The output is
V W
UInt64.MaxValue: 18446744073709551615 UInt64.MinValue: 0
X Y Z
2992
Contents | Index
System.Text
StringBuilder Append() Method
StringBuilder.Append(System.UInt16) Method [ILASM]
.method public hidebysig instance class System.Text.StringBuilder Append(unsigned int16 value)
A
[C#]
B
public StringBuilder Append(ushort value)
C
Summary
D
Appends the string representation of a System.UInt16 to the end of the current instance.
E F
Parameters
G
Parameter
Description
H
value
The System.UInt16 to be appended.
I J K
Description
L
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Text.StringBuilder.Append(System.Int32). This method appends value.ToString() to the current instance. The System.Text.StringBuilder.Capacity of the current instance is increased as necessary.
M N O P
Example
Q
using System; using System.Text;
R S
namespace Samples { public class StringBuilderAppend { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("UInt16.MaxValue: "); sb.Append(UInt16.MaxValue); sb.Append(" UInt16.MinValue: "); sb.Append(UInt16.MinValue); Console.WriteLine(sb); } } }
T U V W X Y Z
2993
Contents | Index
StringBuilder
System.Text
AppendFormat() Method
The output is UInt16.MaxValue: 65535 UInt16.MinValue: 0
A B
StringBuilder.AppendFormat(System.String, System.Object) Method
C [ILASM]
D
.method public hidebysig instance class System.Text.StringBuilder AppendFormat(string format, object arg0)
E
[C#]
public StringBuilder AppendFormat(string format, object arg0)
F G
Summary
H
Appends the specified string to the current instance, with the format specifications in that string being replaced with the appropriately formatted string value of the specified object.
I J
Parameters
K L
Parameter
Description
format
A System.String containing zero or more format specifications.
arg0
A System.Object to be formatted.
M N O P Q
Description
R
This method appends the formatted copy of the specified string to the current instance. [Note: This version of System.Text.StringBuilder.AppendFormat is equivalent to System.Text.StringBuilder.AppendFormat(null, format, new Object[]{arg0}). For more information on the format specification, see the System.String class overview.]
S T U
Exceptions
V W
Exception
Condition
System.ArgumentNullException
format is a null reference.
System.FormatException
format is invalid.
X Y Z
2994
Contents | Index
System.Text
StringBuilder AppendFormat() Method
Example using System; using System.Text;
A namespace Samples { public class StringBuilderAppendFormat { public static void Main() { StringBuilder sb = new StringBuilder(); Object d = DateTime.Now; string f = "Date: {0:dd-MM-yyyy}"; sb.AppendFormat(f, d); Console.WriteLine("Length: {0}", sb.Length); Console.WriteLine(sb); } } }
B C D E F G H I J K
The output is
L M
Length: 16 Date: 23-06-2003
N O
StringBuilder.AppendFormat(System.String, System.Object, System.Object) Method
Q
[ILASM]
R
.method public hidebysig instance class System.Text.StringBuilder AppendFormat(string format, object arg0, object arg1)
S
P
[C#]
T
public StringBuilder AppendFormat(string format, object arg0, object arg1)
U
Summary
V
Appends the specified string to the current instance, with the format specifications in that string being replaced with the appropriately formatted string values of the specified objects.
W X Y Z
2995
Contents | Index
StringBuilder
System.Text
AppendFormat() Method
Parameters Parameter
Description
format
A System.String containing zero or more format specifications.
C
arg0
The first System.Object to be formatted. Can be a null reference.
D
arg1
The second System.Object to be formatted. Can be a null reference.
A B
E F
Description
G
This method appends the formatted copy of the specified string to the current instance. If an object referenced in the format string is null, an empty string is used in its place. [Note: This version of System.Text.StringBuilder.AppendFormat is equivalent to System.Text.StringBuilder.AppendFormat(null, format, new Object[]{arg0, arg1}). For more information on the format specification, see the System.String class overview.]
H I J K L
Exceptions
M N O
Exception
Condition
System.ArgumentNullException
format is a null reference.
System.FormatException
format is invalid.
P Q R S
Example
T
using System; using System.Text;
U
namespace Samples { public class StringBuilderAppendFormat { public static void Main() { StringBuilder sb = new StringBuilder(); Object i = 42; Object d = DateTime.Now; string f = "Integer: {0,10} " + " Date: {1:dd-MM-yyyy}";
V W X Y Z
2996
Contents | Index
System.Text
StringBuilder AppendFormat() Method
sb.AppendFormat(f, i, d); Console.WriteLine("Length: {0}", sb.Length); Console.WriteLine(sb);
A
} }
B
}
C
The output is Length: 37 Integer:
D E 42
Date: 23-06-2003
F G
StringBuilder.AppendFormat(System.String, System.Object, System.Object, System.Object) Method
H I
[ILASM]
J
.method public hidebysig instance class System.Text.StringBuilder AppendFormat(string format, object arg0, object arg1, object arg2)
K
[C#]
L
public StringBuilder AppendFormat(string format, object arg0, object arg1, object arg2)
M
Summary
N
Appends the specified string to the current instance, with the format specifications in that string being replaced with the appropriately formatted string values of the specified objects.
O
Parameters
Q
P
R
Parameter
Description
S
format
A System.String containing zero or more format specifications.
T
arg0
The first System.Object to be formatted. Can be a null reference.
arg1
The second System.Object to be formatted. Can be a null reference.
arg2
The third System.Object to be formatted. Can be a null reference.
U V W X Y Z
Description This method appends the formatted copy of the specified string to the current instance. If an object referenced in the format string is null, an empty string is used in its place. 2997
Contents | Index
StringBuilder
System.Text
AppendFormat() Method
[Note: This version of System.Text.StringBuilder.AppendFormat is equivalent to System.Text.StringBuilder.AppendFormat(null, format, new Object[]{arg0, arg1, arg2}). For more information on the format specification, see the System.String class overview.]
A B
Exceptions
C D
Exception
Condition
System.ArgumentNullException
format is a null reference.
System.FormatException
format is invalid.
E F G H I
Example
J
using System; using System.Text;
K namespace Samples { public class StringBuilderAppendFormat { public static void Main() { StringBuilder sb = new StringBuilder(); Object o = new Object(); Object i = 42; Object s = "Hello world"; string f = "Object: {0,-10} Integer: {1,4:X} " + " String: {2,15}"; sb.AppendFormat(f, o, i,s); Console.WriteLine("Length: {0}", sb.Length); Console.WriteLine(sb); } } }
L M N O P Q R S T U V W
The output is
X Y
Length: 60 Object: System.Object Integer:
Z
2A
String:
Hello world
2998
Contents | Index
System.Text
StringBuilder AppendFormat() Method
StringBuilder.AppendFormat(System.String, System.Object[]) Method [ILASM]
.method public hidebysig instance class System.Text.StringBuilder AppendFormat(string format, class System.Object[] args)
A
[C#]
B
public StringBuilder AppendFormat(string format, params object[] args)
C
Summary
D
Appends the specified string to the current instance, with the format specifications in that string being replaced with the appropriately formatted string values of the elements in the specified array.
E F G
Parameters Parameter
H I
Description
J
format
A System.String containing zero or more format specifications.
K
args
A System.Object array to be formatted.
L M
Description
N
This method appends the formatted copy of the specified string to the current instance. If an object referenced in the format string is null, an empty string is used in its place. [Note: This version of System.Text.StringBuilder.AppendFormat is equivalent to System.Text.StringBuilder.AppendFormat(null, format, args). For more information on the format specification see the System.String class overview.]
O P Q R S
Exceptions
T
Exception
Condition
System.ArgumentNullException
format or args is a null reference.
System.FormatException
format is invalid.
U V W X Y Z
2999
Contents | Index
StringBuilder
System.Text
AppendFormat() Method
Example using System; using System.Text; using System.Globalization;
A B
namespace Samples { public class StringBuilderAppendFormat { public static void Main() { StringBuilder sb = new StringBuilder(); Object[] objects = {DateTime.Now, -42, "Hello world"}; string f = "Date: {0: dd/MM/yy} " + "Integer: {1,10} " + " String: {2}"; sb.AppendFormat(f, objects); Console.WriteLine("Length: {0}", sb.Length); Console.WriteLine(sb); } } }
C D E F G H I J K L M N
The output is
O P
Length: 56 Date: 23/06/03 Integer:
Q
-42
String: Hello world
R
T
StringBuilder.AppendFormat(System.IFormatProvider, System.String, System.Object[]) Method
U
[ILASM]
V
.method public hidebysig instance class System.Text.StringBuilder AppendFormat(class System.IFormatProvider provider, string format, class System.Object[] args)
S
W
[C#]
X
public StringBuilder AppendFormat(IFormatProvider provider, string format, params object[] args)
Y Z
3000
Contents | Index
System.Text
StringBuilder AppendFormat() Method
Summary Appends the specified string to the current instance, with the format specifications in that string being replaced with the string values of the specified array of objects, formatted in accordance with the formatting object returned by the specified System.IFormatProvider.
A B C
Parameters
D
Parameter
Description
provider
A System.IFormatProvider that supplies a formatting object that provides culture specific formatting information. Can be a null reference.
G
format
A System.String containing zero or more format specifications.
H
args
A System.Object array to be formatted.
E F
I J K
Description
L
This method appends the formatted copy of the specified string to the current instance. If an object referenced in the format string is null, an empty string is used in its place. The format parameter is embedded with zero or more format specifications of the form, {N [, M][: formatString]}, where N is a zero-based integer indicating the argument to be formatted, M is an optional integer indicating the width of the region to contain the formatted value, and formatString is an optional string of formatting codes. [Note: For more information on the format specification see the System.String class overview.]
M N O P Q R
Exceptions
S
Exception
Condition
T
System.ArgumentNullException
format or args is a null reference.
U
System.FormatException
format is invalid.
V W X Y Z
3001
Contents | Index
StringBuilder
System.Text
EnsureCapacity() Method
Example using System; using System.Text; using System.Globalization;
A B
namespace Samples { public class StringBuilderAppendFormat { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.NegativeSign = "minus"; DateTimeFormatInfo d = c.DateTimeFormat; d.DateSeparator = "-"; StringBuilder sb = new StringBuilder(); Object[] objects = {DateTime.Now, -42, "Hello world"}; string f = "Date: {0} Integer: {1,10} " + " String: {2}"; sb.AppendFormat(c, f, objects); Console.WriteLine("Length: {0}", sb.Length); Console.WriteLine(sb); } } }
C D E F G H I J K L M N O P Q
The output is
R Length: 68 Date: 23-06-2003 7:14:51 PM Integer:
S
minus42
String: Hello world
T U
StringBuilder.EnsureCapacity(System.Int32) Method
V
[ILASM]
W
.method public hidebysig instance int32 EnsureCapacity(int32 capacity) [C#]
X
public int EnsureCapacity(int capacity)
Y
Summary
Z
Ensures that the capacity of the current instance is at least a specified value.
3002
Contents | Index
System.Text
StringBuilder EnsureCapacity() Method
Parameters Parameter
Description
capacity
A System.Int32 containing the minimum capacity to ensure.
A B C
Return Value
D
A System.Int32 equal to the new System.Text.StringBuilder.Capacity of the current instance.
E
Description
G
If the specified value is less than the current System.Text.StringBuilder.Capacity, no changes are made and System.Text.StringBuilder.Capacity remains the same. [Note: For performance reasons, the new System.Text.StringBuilder.Capacity might be larger than the specified value. The amount of memory allocated by this method is implementation specific.]
H
Exceptions
L
F
I J K
M
Exception
Condition
System.ArgumentOutOfRangeException
capacity is less than zero.
N O P
Example
Q
using System; using System.Text;
R S
namespace Samples { public class StringBuilderEnsureCapacity { public static void Main() { StringBuilder sb = new StringBuilder(); Console.WriteLine("Capacity: {0}", sb.Capacity); Console.WriteLine("MaxCapacity: {0}", sb.MaxCapacity); Console.WriteLine("Length: {0}", sb.Length); sb.EnsureCapacity(256);
T U V W X Y Z
3003
Contents | Index
StringBuilder
System.Text
Equals() Method
Console.WriteLine("Capacity: {0}", sb.Capacity); Console.WriteLine("MaxCapacity: {0}", sb.MaxCapacity); Console.WriteLine("Length: {0}", sb.Length);
A B
}
C
} }
D
The output is
E F
Capacity: 16 MaxCapacity: 2147483647 Length: 0 Capacity: 257 MaxCapacity: 2147483647 Length: 0
G H I J K
StringBuilder.Equals(System.Text.StringBuilder) Method
L [ILASM]
M
.method public hidebysig instance bool Equals(class System.Text.StringBuilder sb) [C#]
N
public bool Equals(StringBuilder sb)
O P
Summary
Q
Determines whether the current instance and a specified System.Text.StringBuilder have the same value.
R S
Parameters
T U V
Parameter
Description
sb
A System.Text.StringBuilder.
W X
Return Value
Y
true if the current instance and sb have the same value; otherwise, false.
Z
3004
Contents | Index
System.Text
StringBuilder Insert() Method
Example using System; using System.Text;
A namespace Samples { public class StringBuilderEquals { public static void Main() { StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(); Console.WriteLine("sb1.Equals(sb2): {0}", sb1.Equals(sb2)); sb2.Capacity = 32; Console.WriteLine("sb1.Equals(sb2): {0}", sb1.Equals(sb2)); string s = "This is a string"; sb1.Append(s); sb2.Append(s); Console.WriteLine("sb1.Equals(sb2): {0}", sb1.Equals(sb2)); } } }
B C D E F G H I J K L M N
The output is
O P
sb1.Equals(sb2): True sb1.Equals(sb2): False sb1.Equals(sb2): True
Q R S
StringBuilder.Insert(System.Int32, System.Boolean) Method
T
[ILASM]
U
.method public hidebysig instance class System.Text.StringBuilder Insert(int32 index, bool value)
V
[C#]
W
public StringBuilder Insert(int index, bool value)
X
Summary
Y
Inserts the string representation of a System.Boolean value into the current instance at a specified index.
Z
3005
Contents | Index
StringBuilder
System.Text
Insert() Method
Parameters Parameter
Description
index
A System.Int32 containing the index at which to insert.
value
The System.Boolean value to be inserted.
A B C D E
Description
F
This method inserts value.ToString() into the current instance at the specified location. Existing characters are shifted to make room for the new text, and System.Text.StringBuilder.Capacity is adjusted as necessary.
G H
Exceptions
I J
Exception
Condition
K
index is greater than the length of the current instance.
L
System.ArgumentOutOfRangeException
M
-orindex is less than zero.
N O
Example
P
using System; using System.Text;
Q R
namespace Samples { public class StringBuilderInsert { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("true: ,"); sb.Insert(sb.Length - 1, true); sb.Append(" false: ."); sb.Insert(sb.Length - 1, false); Console.WriteLine(sb); } } }
S T U V W X Y Z
3006
Contents | Index
System.Text
StringBuilder Insert() Method
The output is true: True, false: False.
A
StringBuilder.Insert(System.Int32, System.Byte) Method
B
[ILASM]
C
.method public hidebysig instance class System.Text.StringBuilder Insert(int32 index, unsigned int8 value)
D
[C#]
E
public StringBuilder Insert(int index, byte value)
F
Summary
G
Inserts the string representation of a System.Byte into the current instance at the specified index.
H I J
Parameters
K
Parameter
Description
index
A System.Int32 containing the index at which to insert.
value
The System.Byte to be inserted.
L M N O P
Description
Q
This method inserts value.ToString() into the current instance at the specified location. Existing characters are shifted to make room for the new text, and System.Text.StringBuilder.Capacity is adjusted as necessary.
R S T
Exceptions Exception
U V
Condition
W
index is greater than the length of the current instance. System.ArgumentOutOfRangeException
X
-or-
Y
index is less than zero.
Z
3007
Contents | Index
StringBuilder
System.Text
Insert() Method
Example using System; using System.Text;
A namespace Samples { public class StringBuilderInsert { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Byte.MaxValue: ,"); sb.Insert(sb.Length - 1, Byte.MaxValue); sb.Append(" Byte.MinValue: ."); sb.Insert(sb.Length - 1, Byte.MinValue); Console.WriteLine(sb); } } }
B C D E F G H I J K
The output is
L Byte.MaxValue: 255, Byte.MinValue: 0.
M N
StringBuilder.Insert(System.Int32, System.Char) Method
O
[ILASM]
P
.method public hidebysig instance class System.Text.StringBuilder Insert(int32 index, valuetype System.Char value)
Q
[C#]
R
public StringBuilder Insert(int index, char value)
S T
Summary
U
Inserts the string representation of a Unicode character into the current instance at a specified index.
V
Parameters
W X
Parameter
Description
index
A System.Int32 containing the index at which to insert.
value
The System.Char to be inserted.
Y Z
3008
Contents | Index
System.Text
StringBuilder Insert() Method
Description This method inserts value.ToString() into the current instance at the specified location. Existing characters are shifted to make room for the new text, and System.Text.StringBuilder.Capacity is adjusted as necessary.
A B
Exceptions
C
Exception
Condition
System.ArgumentOutOfRangeException
index is greater than the length of the current instance. -orindex is less than zero.
D E F G H
Example
I
using System; using System.Text;
J K
namespace Samples { public class StringBuilderInsert { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Char: ,"); sb.Insert(sb.Length - 1, 'A'); sb.Append(" Char: ."); sb.Insert(sb.Length - 1, 'Z'); Console.WriteLine(sb); } } }
L M N O P Q R S T
The output is
U V
Char: A, Char: Z.
W X
StringBuilder.Insert(System.Int32, System.Char[]) Method
Y
[ILASM]
.method public hidebysig instance class System.Text.StringBuilder Insert(int32 index, valuetype System.Char value)
Z
[C#]
public StringBuilder Insert(int index, char[] value)
3009
Contents | Index
StringBuilder
System.Text
Insert() Method
Summary Inserts the string representation of an array of Unicode characters into the current instance at a specified index. A
Parameters
B C
Parameter
Description
E
index
A System.Int32 containing the index at which to insert.
F
value
The System.Char array to be inserted.
D
G H
Description
I
This method inserts all of the characters in the specified array into the current instance in the same order as they appear in value. Existing characters are shifted to make room for the new text, and System.Text.StringBuilder.Capacity is adjusted as necessary. If value is empty or a null reference, the System.Text.StringBuilder is not changed.
J K L M
Exceptions
N O
Exception
Condition
P
index is greater than the length of the current instance.
Q
System.ArgumentOutOfRangeException
R
-orindex is less than zero.
S T
Example
U
using System; using System.Text;
V W
namespace Samples { public class StringBuilderInsert { public static void Main() { StringBuilder sb = new StringBuilder("Hello!");
X Y Z
3010
Contents | Index
System.Text
StringBuilder Insert() Method
string s = " world"; Char[] chars = s.ToCharArray(); sb.Insert(sb.Length - 1, chars); Console.WriteLine("Length: {0}", sb.Length); Console.WriteLine(sb);
A B
}
C
} }
D
The output is
E F
Length: 12 Hello world!
G H
StringBuilder.Insert(System.Int32, System.Char[], System.Int32, System.Int32) Method
I
[ILASM]
K
.method public hidebysig instance class System.Text.StringBuilder Insert(int32 index, class System.Char[] value, int32 startIndex, int32 charCount)
L
[C#]
M
J
public StringBuilder Insert(int index, char[] value, int startIndex, int charCount)
N O
Summary
P
Inserts the string representation of a subarray of Unicode characters into the current instance at a specified index.
Q R
Parameters
S T
Parameter
Description
index
A System.Int32 containing the index at which to insert.
value
The System.Char array from which to get the characters to be inserted.
W
startIndex
A System.Int32 containing the starting index within value.
X
charCount
A System.Int32 containing the number of characters to insert from value.
U V
Y Z
3011
Contents | Index
StringBuilder
System.Text
Insert() Method
Description This method inserts the specified range of characters from value array into the current instance in the same order as they appear in value. Existing characters are shifted to make room for the new text, and System.Text.StringBuilder.Capacity is adjusted as necessary. If value is an empty array or a null reference and startIndex and charCount are both zero, the System.Text.StringBuilder is not changed.
A B C D
Exceptions
E F
Exception
Condition
System.ArgumentNullException
value is a null reference, and startIndex and charCount are not both zero.
G H I
index is greater than the length of the current instance or less than zero.
J System.ArgumentOutOfRangeException
K
-orstartIndex or charCount is less than zero or their sum is greater than the length of value.
L M N
Example
O
using System; using System.Text;
P Q
namespace Samples { public class StringBuilderInsert { public static void Main() { StringBuilder sb = new StringBuilder(" world!"); string s = "Hello Hello Hello"; Char[] chars = s.ToCharArray(); sb.Insert(0, chars, s.IndexOf('H'), s.IndexOf(' ')); Console.WriteLine("Length: {0}", sb.Length); Console.WriteLine(sb); } } }
R S T U V W X Y Z
3012
Contents | Index
System.Text
StringBuilder Insert() Method
The output is Length: 12 Hello world!
A B
StringBuilder.Insert(System.Int32, System.Decimal) Method
C
[ILASM]
D
.method public hidebysig instance class System.Text.StringBuilder Insert(int32 index, decimal value)
E
[C#]
F
public StringBuilder Insert(int index, decimal value)
G
Summary
H
Inserts the string representation of a System.Decimal into the current instance at the specified index.
I
Parameters
K
J
L
Parameter
Description
M
index
A System.Int32 containing the index at which to insert.
N
value
The System.Decimal to be inserted.
O P Q
Description
R
This method inserts value.ToString() into the current instance at the specified location. Existing characters are shifted to make room for the new text, and System.Text.StringBuilder.Capacity is adjusted as necessary. This member must be implemented if the Extended Numerics Library is present in the implementation.
S T U V
Exceptions
W
Exception
System.ArgumentOutOfRangeException
Condition
X
index is greater than the length of the current instance.
Y
-or-
Z
index is less than zero.
3013
Contents | Index
StringBuilder
System.Text
Insert() Method
Example using System; using System.Text;
A namespace Samples { public class StringBuilderInsert { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Decimal.MaxValue: ,"); sb.Insert(sb.Length - 1, Decimal.MaxValue); sb.Append(" Decimal.MinValue: ."); sb.Insert(sb.Length - 1, Decimal.MinValue); Console.WriteLine(sb); } } }
B C D E F G H I J K
The output is
L
Decimal.MaxValue: 79228162514264337593543950335, Decimal.MinValue: 79228162514264337593543950335.
M N O
StringBuilder.Insert(System.Int32, System.Double) Method
P
[ILASM]
Q
.method public hidebysig instance class System.Text.StringBuilder Insert(int32 index, float64 value)
R
[C#]
public StringBuilder Insert(int index, double value)
S T
Summary
U
Inserts the string representation of a System.Double into the current instance at the specified index.
V W
Parameters
X Y Z
Parameter
Description
index
A System.Int32 containing the index at which to insert.
value
The System.Double to be inserted.
3014
Contents | Index
System.Text
StringBuilder Insert() Method
Description This method inserts value.ToString() into the current instance at the specified location. Existing characters are shifted to make room for the new text, and System.Text.StringBuilder.Capacity is adjusted as necessary. This member must be implemented if the Extended Numerics Library is present in the implementation.
A B C
Exceptions Exception
D
Condition
E F
index is greater than the length of the current instance. System.ArgumentOutOfRangeException
-or-
G
index is less than zero.
H I
Example
J
using System; using System.Text;
K
namespace Samples { public class StringBuilderInsert { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Double.MaxValue: ,"); sb.Insert(sb.Length - 1, Double.MaxValue); sb.Append(" Double.MinValue: ."); sb.Insert(sb.Length - 1, Double.MinValue); Console.WriteLine(sb); } } }
M
L
N O P Q R S T U V
The output is
W
Double.MaxValue: 1.79769313486232E+308, Double.MinValue: -1.79769313486232E+308.
X Y Z
3015
Contents | Index
StringBuilder
System.Text
Insert() Method
StringBuilder.Insert(System.Int32, System.Single) Method [ILASM]
A
.method public hidebysig instance class System.Text.StringBuilder Insert(int32 index, float32 value)
B
[C#]
public StringBuilder Insert(int index, float value)
C D
Summary
E
Inserts the string representation of a System.Single into the current instance at the specified index.
F G
Parameters
H I J K
Parameter
Description
index
A System.Int32 containing the index at which to insert.
value
The System.Single to be inserted.
L M
Description
N
This method inserts value.ToString() into the current instance at the specified location. Existing characters are shifted to make room for the new text, and System.Text.StringBuilder.Capacity is adjusted as necessary. This member must be implemented if the Extended Numerics Library is present in the implementation.
O P Q R
Exceptions
S
Exception
T U
Condition index is greater than the length of the current instance.
System.ArgumentOutOfRangeException
V
-orindex is less than zero.
W X Y Z
3016
Contents | Index
System.Text
StringBuilder Insert() Method
Example using System; using System.Text;
A namespace Samples { public class StringBuilderInsert { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Single.MaxValue: ,"); sb.Insert(sb.Length - 1, Single.MaxValue); sb.Append(" Single.MinValue: ."); sb.Insert(sb.Length - 1, Single.MinValue); Console.WriteLine(sb); } } }
B C D E F G H I J K
The output is
L Single.MaxValue: 3.402823E+38, Single.MinValue: -3.402823E+38.
M N
StringBuilder.Insert(System.Int32, System.Int32) Method
O
[ILASM]
P
.method public hidebysig instance class System.Text.StringBuilder Insert(int32 index, int32 value)
Q
[C#]
R
public StringBuilder Insert(int index, int value)
S
Summary
T
Inserts the string representation of a System.Int32 into the current instance at the specified index.
U V
Parameters
W X
Parameter
Description
index
A System.Int32 containing the index at which to insert.
value
The System.Int32 to be inserted.
Y Z
3017
Contents | Index
StringBuilder
System.Text
Insert() Method
Description This method inserts value.ToString() into the current instance at the specified location. Existing characters are shifted to make room for the new text, and System.Text.StringBuilder.Capacity is adjusted as necessary.
A B
Exceptions
C D
Exception
Condition
E
index is greater than the length of the current instance.
F
System.ArgumentOutOfRangeException
G
-orindex is less than zero.
H I
Example
J
using System; using System.Text;
K L
namespace Samples { public class StringBuilderInsert { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Int32.MaxValue: ,"); sb.Insert(sb.Length - 1, Int32.MaxValue); sb.Append(" Int32.MinValue: ."); sb.Insert(sb.Length - 1, Int32.MinValue); Console.WriteLine(sb); } } }
M N O P Q R S T U
The output is
V W
Int32.MaxValue: 2147483647, Int32.MinValue: -2147483648.
X Y Z
3018
Contents | Index
System.Text
StringBuilder Insert() Method
StringBuilder.Insert(System.Int32, System.Int64) Method [ILASM]
.method public hidebysig instance class System.Text.StringBuilder Insert(int32 index, int64 value)
A
[C#]
B
public StringBuilder Insert(int index, long value)
C
Summary
D
Inserts the string representation of a System.Int64 into the current instance at the specified index.
E
Parameters
G
F
H
Parameter
Description
index
A System.Int32 containing the index at which to insert.
value
The System.Int64 to be inserted.
I J K L M
Description
N
This method inserts value.ToString() into the current instance at the specified location. Existing characters are shifted to make room for the new text, and System.Text.StringBuilder.Capacity is adjusted as necessary.
O P Q
Exceptions
R
Exception
Condition
S T
index is greater than the length of the current instance. System.ArgumentOutOfRangeException
-or-
U
index is less than zero.
V W X Y Z
3019
Contents | Index
StringBuilder
System.Text
Insert() Method
Example using System; using System.Text;
A namespace Samples { public class StringBuilderInsert { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Int64.MaxValue: ,"); sb.Insert(sb.Length - 1, Int64.MaxValue); sb.Append(" Int64.MinValue: ."); sb.Insert(sb.Length - 1, Int64.MinValue); Console.WriteLine(sb); } } }
B C D E F G H I J K
The output is
L Int64.MaxValue: 9223372036854775807, Int64.MinValue: -9223372036854775808.
M N O
StringBuilder.Insert(System.Int32, System.Object) Method
P
[ILASM]
Q
.method public hidebysig instance class System.Text.StringBuilder Insert(int32 index, object value) [C#]
R
public StringBuilder Insert(int index, object value)
S T
Summary
U
Inserts the string representation of an object into the current instance at a specified index.
V
Parameters
W X Y
Parameter
Description
index
A System.Int32 containing the index at which to insert.
value
The System.Object to be inserted.
Z
3020
Contents | Index
System.Text
StringBuilder Insert() Method
Description This method inserts value.ToString() into the current instance at the specified location. Existing characters are shifted to make room for the new text, and System.Text.StringBuilder.Capacity is adjusted as necessary. If value is a null reference, the System.Text.StringBuilder is not changed.
A B C
Exceptions Exception
D
Condition
E F
index is greater than the length of the current instance. System.ArgumentOutOfRangeException
-or-
G
index is less than zero.
H I
Example
J
using System; using System.Text;
K
namespace Samples { public class StringBuilderInsert { public static void Main() { StringBuilder sb = new StringBuilder(); object o = new Object(); sb.Append("Object: ,"); sb.Insert(sb.Length - 1, o); o = 42; sb.Append(" Integer: ,"); sb.Insert(sb.Length - 1, o); o = "Hello World"; sb.Append(" String: !"); sb.Insert(sb.Length - 1, o); Console.WriteLine(sb); } } }
M
L
N O P Q R S T U V W X Y
The output is
Z
Object: System.Object, Integer: 42, String: Hello World!
3021
Contents | Index
StringBuilder
System.Text
Insert() Method
StringBuilder.Insert(System.Int32, System.SByte) Method [ILASM]
A
.method public hidebysig instance class System.Text.StringBuilder Insert(int32 index, int8 value)
B
[C#]
public StringBuilder Insert(int index, sbyte value)
C D
Summary
E
Inserts the string representation of a System.SByte into the current instance at the specified index.
F G
Parameters
H I J K
Parameter
Description
index
A System.Int32 containing the index at which to insert.
value
The System.SByte to be inserted.
L M
Description
N
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Text.StringBuilder.Insert(System.Int32, System.Int16). This method inserts value.ToString() into the current instance at the specified location. Existing characters are shifted to make room for the new text, and System.Text.StringBuilder.Capacity is adjusted as necessary.
O P Q R
Exceptions
S T
Exception
Condition
U
index is greater than the length of the current instance.
V
System.ArgumentOutOfRangeException
W
-orindex is less than zero.
X Y Z
3022
Contents | Index
System.Text
StringBuilder Insert() Method
Example using System; using System.Text;
A namespace Samples { public class StringBuilderInsert { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("SByte.MaxValue: ,"); sb.Insert(sb.Length - 1, SByte.MaxValue); sb.Append(" SByte.MinValue: ."); sb.Insert(sb.Length - 1, SByte.MinValue); Console.WriteLine(sb); } } }
B C D E F G H I J K
The output is
L
SByte.MaxValue: 127, SByte.MinValue: -128.
M N
StringBuilder.Insert(System.Int32, System.Int16) Method
O [ILASM]
P
.method public hidebysig instance class System.Text.StringBuilder Insert(int32 index, int16 value)
Q
[C#]
R
public StringBuilder Insert(int index, short value)
S
Summary
T
Inserts the string representation of a System.Int16 into the current instance at a specified index.
U V
Parameters
W
Parameter
Description
index
A System.Int32 containing the index at which to insert.
value
The System.Int16 to be inserted.
X Y Z
3023
Contents | Index
StringBuilder
System.Text
Insert() Method
Description This method inserts value.ToString() into the current instance at the specified location. Existing characters are shifted to make room for the new text, and System.Text.StringBuilder.Capacity is adjusted as necessary.
A B
Exceptions
C D
Exception
E
Condition index is greater than the length of the current instance.
System.ArgumentOutOfRangeException
F
-orindex is less than zero.
G H I
Example
J
using System; using System.Text;
K namespace Samples { public class StringBuilderInsert { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Int16.MaxValue: ,"); sb.Insert(sb.Length - 1, Int16.MaxValue); sb.Append(" Int16.MinValue: ."); sb.Insert(sb.Length - 1, Int16.MinValue); Console.WriteLine(sb); } } }
L M N O P Q R S T
The output is
U
Int16.MaxValue: 32767, Int16.MinValue: -32768.
V W X
StringBuilder.Insert(System.Int32, System.String) Method
Y
[ILASM]
.method public hidebysig instance class System.Text.StringBuilder Insert(int32 index, string value)
Z
[C#]
public StringBuilder Insert(int index, string value)
3024
Contents | Index
System.Text
StringBuilder Insert() Method
Summary Inserts the string representation of a string object into the current instance at a specified index. A
Parameters
B C
Parameter
Description
index
A System.Int32 containing the index at which to insert.
E
value
The System.String to be inserted.
F
D
G H
Description
I
This method inserts value into the current instance at the specified location. Existing characters are shifted to make room for the new text, and System.Text.StringBuilder.Capacity is adjusted as necessary. If value is Empty or a null reference, the System.Text.StringBuilder is not changed.
J K L M
Exceptions Exception
N O
Condition
P
index is greater than the length of the current instance. System.ArgumentOutOfRangeException
Q
-or-
R
index is less than zero.
S T
Example
U
using System; using System.Text;
V W
namespace Samples { public class StringBuilderInsert { public static void Main() { StringBuilder sb = new StringBuilder(); Console.WriteLine("Length: {0}",
X Y Z
3025
Contents | Index
StringBuilder
System.Text
Insert() Method
sb.Length); sb.Append(" world!"); sb.Insert(0, "Hello"); Console.WriteLine("Length: {0}", sb.Length); Console.WriteLine(sb);
A B }
C
} }
D
The output is
E F
Length: 0 Length: 12 Hello world!
G H I
StringBuilder.Insert(System.Int32, System.String, System.Int32) Method
J
[ILASM]
K
.method public hidebysig instance class System.Text.StringBuilder Insert(int32 index, string value, int32 count)
L
[C#]
M
public StringBuilder Insert(int index, string value, int count)
N
Summary
O
Inserts multiple copies of a string into the current instance at a specified index.
P Q
Parameters
R S
Parameter
Description
T
index
A System.Int32 containing the index at which to insert.
value
The System.String to be inserted.
count
A System.Int32 containing the number of times the string is to be inserted.
U V W X
Description
Y
This method inserts the value string count times into the current instance at the specified location. Existing characters are shifted to make room for the new text, and System.Text.StringBuilder.Capacity is adjusted as necessary.
Z
3026
Contents | Index
System.Text
StringBuilder Insert() Method
If value is Empty or a null reference, the System.Text.StringBuilder is not changed. A
Exceptions
B
Exception
Condition
System.ArgumentOutOfRangeException
C
index is greater than the length of the current instance.
D
-or-
E
index is less than zero.
F
-or-
G
count is less than zero.
H I
Example
J
using System; using System.Text;
K L
namespace Samples { public class StringBuilderInsert { public static void Main() { StringBuilder sb = new StringBuilder(); Console.WriteLine("Length: {0}", sb.Length); sb.Append("Insert here -><-"); sb.Insert(sb.Length - 2, " Hello ", 2); Console.WriteLine("Length: {0}", sb.Length); Console.WriteLine(sb); } } }
M N O P Q R S T U V W
The output is
X Length: 0 Length: 30 Insert here -> Hello
Y Hello <-
Z
3027
Contents | Index
StringBuilder
System.Text
Insert() Method
StringBuilder.Insert(System.Int32, System.UInt32) Method [ILASM]
A
.method public hidebysig instance class System.Text.StringBuilder Insert(int32 index, unsigned int32 value)
B
[C#]
public StringBuilder Insert(int index, uint value)
C D
Summary
E
Inserts the string representation of a System.UInt32 into the current instance at the specified index.
F G
Parameters
H I J K
Parameter
Description
index
A System.Int32 containing the index at which to insert.
value
The System.UInt32 to be inserted.
L M
Description
N
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Text.StringBuilder.Insert(System.Int32, System.Int64). This method inserts value.ToString() into the current instance at the specified location. Existing characters are shifted to make room for the new text, and System.Text.StringBuilder.Capacity is adjusted as necessary.
O P Q R
Exceptions
S T
Exception
Condition
U
index is greater than the length of the current instance.
V
System.ArgumentOutOfRangeException
W
-orindex is less than zero.
X Y Z
3028
Contents | Index
System.Text
StringBuilder Insert() Method
Example using System; using System.Text;
A namespace Samples { public class StringBuilderInsert { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("UInt32.MaxValue: ,"); sb.Insert(sb.Length - 1, UInt32.MaxValue); sb.Append(" UInt32.MinValue: ."); sb.Insert(sb.Length - 1, UInt32.MinValue); Console.WriteLine(sb); } } }
B C D E F G H I J K
The output is
L M
StringBuilder.Insert(System.Int32, System.UInt64) Method
N
[ILASM]
O
.method public hidebysig instance class System.Text.StringBuilder Insert(int32 index, unsigned int64 value)
P
[C#]
Q
public StringBuilder Insert(int index, ulong value)
R
Summary
S
Inserts the string representation of a System.UInt64 into the current instance at a specified index.
T U
Parameters
V W
Parameter
Description
index
A System.Int32 containing the index at which to insert.
Y
value
The System.UInt64 to be inserted.
Z
X
3029
Contents | Index
StringBuilder
System.Text
Insert() Method
Description This member is not CLS-compliant. For a CLS-compliant alternative, use System.Text.StringBuilder.Insert(System.Int32, System.Decimal). This method inserts value.ToString() into the current instance at the specified location. Existing characters are shifted to make room for the new text, and System.Text.StringBuilder.Capacity is adjusted as necessary.
A B C D
Exceptions
E
Exception
F G
Condition index is greater than the length of the current instance.
System.ArgumentOutOfRangeException
H
-orindex is less than zero.
I J K
Example
L
using System; using System.Text;
M namespace Samples { public class StringBuilderInsert { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("UInt64.MaxValue: ,"); sb.Insert(sb.Length - 1, UInt64.MaxValue); sb.Append(" UInt64.MinValue: ."); sb.Insert(sb.Length - 1, UInt64.MinValue); Console.WriteLine(sb); } } }
N O P Q R S T U V W
The output is
X UInt64.MaxValue: 18446744073709551615, UInt64.MinValue: 0. UInt32.MaxValue: 4294967295, UInt32.MinValue: 0.
Y Z
3030
Contents | Index
System.Text
StringBuilder Insert() Method
StringBuilder.Insert(System.Int32, System.UInt16) Method [ILASM]
.method public hidebysig instance class System.Text.StringBuilder Insert(int32 index, unsigned int16 value)
A
[C#]
B
public StringBuilder Insert(int index, ushort value)
C
Summary
D
Inserts the string representation of a System.UInt16 into the current instance at the specified index.
E
Parameters
G
F
H
Parameter
Description
index
A System.Int32 containing the index at which to insert.
value
The System.UInt16 to insert.
I J K L M
Description
N
This member is not CLS-compliant. For a CLS-compliant alternative, use System.Text.StringBuilder.Insert(System.Int32, System.Int32). This method inserts value.ToString() into the current instance at the specified location. Existing characters are shifted to make room for the new text, and System.Text.StringBuilder.Capacity is adjusted as necessary.
O P Q R
Exceptions Exception
S T
Condition
U
index is greater than the length of the current instance. System.ArgumentOutOfRangeException
V
-orW
index is less than zero.
X Y Z
3031
Contents | Index
StringBuilder
System.Text
Remove() Method
Example using System; using System.Text;
A namespace Samples { public class StringBuilderInsert { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("UInt16.MaxValue: ,"); sb.Insert(sb.Length - 1, UInt16.MaxValue); sb.Append(" UInt16.MinValue: ."); sb.Insert(sb.Length - 1, UInt16.MinValue); Console.WriteLine(sb); } } }
B C D E F G H I J K
The output is
L UInt16.MaxValue: 65535, UInt16.MinValue: 0.
M N O
StringBuilder.Remove(System.Int32, System.Int32) Method
P
[ILASM]
Q
.method public hidebysig instance class System.Text.StringBuilder Remove(int32 startIndex, int32 length) [C#]
R
public StringBuilder Remove(int startIndex, int length)
S T
Summary
U
Removes a specified range of characters from the current instance.
V
Parameters
W X Y
Parameter
Description
startIndex
A System.Int32 containing the index at which to begin removal.
length
A System.Int32 containing the number of characters to be removed.
Z
3032
Contents | Index
System.Text
StringBuilder Remove() Method
Description This method removes the specified range of characters from the current instance. The characters at (startIndex + length) are moved to startIndex, and the string value of the current instance is shortened by length. [Note: The System.Text.StringBuilder.Replace method can be used to remove all instances of a string from a System.Text.StringBuilder.]
A B C D
Exceptions
E
Exception
System.ArgumentOutOfRangeException
Condition
F
startIndex or length is less than zero.
G
-or-
H
The sum of startIndex and length is greater than the length of the current instance.
I J K
Example
L
using System; using System.Text;
M N
namespace Samples { public class StringBuilderRemove { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Hello Hello world!"); sb.Remove(0, 6); Console.WriteLine(sb); } } }
O P Q R S T U V
The output is
W X
Hello world!
Y Z
3033
Contents | Index
StringBuilder
System.Text
Replace() Method
StringBuilder.Replace(System.Char, System.Char) Method [ILASM]
A
.method public hidebysig instance class System.Text.StringBuilder Replace(valuetype System.Char oldChar, valuetype System.Char newChar)
B
[C#]
public StringBuilder Replace(char oldChar, char newChar)
C D
Summary
E
Replaces all instances of a specified character in the current instance with another specified character.
F G
Parameters
H
Parameter
Description
J
oldChar
The System.Char to replace.
K
newChar
The System.Char with which to replace oldChar.
I
L M
Description
N
This method substitutes each occurrence of oldChar in the current instance with newChar. This method is case-sensitive.
O P
Example
Q
using System; using System.Text;
R S
namespace Samples { public class StringBuilderReplace { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Balance is: (42.00)"); Console.WriteLine(sb); sb.Replace('(', '-'); sb.Replace(')', ' '); Console.WriteLine(sb); } } }
T U V W X Y Z
3034
Contents | Index
System.Text
StringBuilder Replace() Method
The output is Balance is: (42.00) Balance is: -42.00
A B
StringBuilder.Replace(System.Char, System.Char, System.Int32, System.Int32) Method
C D
[ILASM]
E
.method public hidebysig instance class System.Text.StringBuilder Replace(valuetype System.Char oldChar, valuetype System.Char newChar, int32 startIndex, int32 count)
F
[C#]
G
public StringBuilder Replace(char oldChar, char newChar, int startIndex, int count)
H
Summary
I
Replaces all instances of a specified character in a specified range with another specified character.
J K
Parameters
L M
Parameter
Description
oldChar
The System.Char to replace.
newChar
The System.Char with which to replace oldChar.
startIndex
A System.Int32 containing the index from which to start replacing oldChar.
Q
count
A System.Int32 containing the length of the range in which to replace oldChar.
R
N O P
S
Description
T
This method substitutes each occurrence of oldChar in the specified range of the current instance with newChar. This method is case-sensitive.
U V W X Y Z
3035
Contents | Index
StringBuilder
System.Text
Replace() Method
Exceptions Exception
Condition
A B System.ArgumentOutOfRangeException
C
The sum of startIndex and count is larger than the length of the current instance. -orstartIndex or count is less than zero.
D E F
Example
G
using System; using System.Text;
H namespace Samples { public class StringBuilderReplace { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Balance is: (42.00)"); Console.WriteLine(sb); sb.Replace('(', '-', 0, sb.Length); sb.Replace(')', ' ', 0, sb.Length); Console.WriteLine(sb); } } }
I J K L M N O P Q R
The output is
S Balance is: (42.00) Balance is: -42.00
T U V
StringBuilder.Replace(System.String, System.String) Method
W
[ILASM]
X
.method public hidebysig instance class System.Text.StringBuilder Replace(string oldValue, string newValue)
Y
[C#]
public StringBuilder Replace(string oldValue, string newValue)
Z
3036
Contents | Index
System.Text
StringBuilder Replace() Method
Summary Replaces all instances of a specified string with another specified string. A
Parameters
B
Parameter
Description
oldValue
A System.String containing the string value to replace.
D
newValue
A System.String containing the string value with which to replace oldValue. Can be a null reference.
E
C
F G
Description
H
This method substitutes each occurrence of oldValue in the current instance with newValue. [Note: If newValue is null, instances of oldValue are removed.] This method is case-sensitive.
I J K
Exceptions
L
Exception
Condition
M
System.ArgumentNullException
oldValue is a null reference.
N
System.ArgumentException
The length of oldvalue is zero.
O P Q
Example using System; using System.Text;
R
namespace Samples { public class StringBuilderReplace { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Hi world"); Console.WriteLine(sb); sb.Replace("Hi", "Hello"); Console.WriteLine(sb); } } }
T
S
U V W X Y Z
3037
Contents | Index
StringBuilder
System.Text
Replace() Method
The output is Hi world Hello world
A B
D
StringBuilder.Replace(System.String, System.String, System.Int32, System.Int32) Method
E
[ILASM]
F
.method public hidebysig instance class System.Text.StringBuilder Replace(string oldValue, string newValue, int32 startIndex, int32 count)
C
[C#]
G
public StringBuilder Replace(string oldValue, string newValue, int startIndex, int count)
H I
Summary
J
Replaces all instances of a specified string in a specified range with another specified string.
K
Parameters
L M
Parameter
Description
oldValue
A System.String containing the string value to replace.
newValue
A System.String containing the string value with which to replace oldValue. Can be a null reference.
R
startIndex
A System.Int32 containing the location from which to start replacing oldValue.
S
count
A System.Int32 containing the length of the range in which to replace oldValue.
N O P Q
T U
Description
V
This method substitutes each occurrence of oldValue in the specified range of the current instance with newValue. [Note: If newValue is null, instances of oldValue are removed.] This method is case-sensitive.
W X Y Z
3038
Contents | Index
System.Text
StringBuilder ToString() Method
Exceptions Exception
Condition
System.ArgumentNullException
oldValue is a null reference.
A
System.ArgumentOutOfRangeException
System.ArgumentException
B
startIndex or count is less than zero.
C
-or-
D
The sum of startIndex and count is greater than the length of the current instance.
E F
The length of oldvalue is zero.
G H
Example
I
using System; using System.Text;
J K
namespace Samples { public class StringBuilderReplace { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Hi world"); Console.WriteLine(sb); sb.Replace("Hi", "Hello", 0, sb.Length); Console.WriteLine(sb); } } }
L M N O P Q R S T
The output is
U Hi world Hello world
V W X
StringBuilder.ToString() Method
Y
[ILASM]
Z
.method public hidebysig virtual string ToString() [C#]
public override string ToString()
3039
Contents | Index
StringBuilder
System.Text
ToString() Method
Summary Returns a System.String representation of the value of the current instance. A
Description
B
This method overrides System.Object.ToString.
C
Example
D
using System; using System.Text;
E F
namespace Samples { public class StringBuilderToString { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Hello "); string s = sb.ToString(); Console.WriteLine("First: {0}", s); sb.Append("world!"); s = sb.ToString(); Console.WriteLine("Second: {0}", s); } } }
G H I J K L M N O P
The output is
Q
First: Hello Second: Hello world!
R S T
StringBuilder.ToString(System.Int32, System.Int32) Method
U
[ILASM]
V
.method public hidebysig instance string ToString(int32 startIndex, int32 length)
W
public string ToString(int startIndex, int length)
[C#]
X
Summary
Y
Returns a System.String representation of a substring of the current instance.
Z
3040
Contents | Index
System.Text
StringBuilder ToString() Method
Parameters Parameter
Description
startIndex
A System.Int32 containing the index at which the substring begins.
length
A System.Int32 containing the length of the substring.
A B C D
Exceptions Exception
E F
Condition
G
startIndex or length is less than zero. System.ArgumentOutOfRangeException
H
-or-
I
The sum of startIndex and length is greater than the length of the current instance.
J K
Example
L
using System; using System.Text;
M N
namespace Samples { public class StringBuilderToString { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("0123456789"); int i = sb.Length / 2; string s = sb.ToString(0, sb.Length - i); Console.WriteLine("First: {0}", s); s = sb.ToString(sb.Length - i, i); Console.WriteLine("Second: {0}", s); } } }
O P Q R S T U V W X
The output is
Y
First: 01234 Second: 56789
Z
3041
Contents | Index
System.IO StringReader
BCL
Object
A
MarshalByRefObject
B
TextReader
IDisposable
StringReader
C D
Summary
E
Implements a System.IO.TextReader that reads from a string.
F
Type Summary
G
public class StringReader : TextReader { // Constructors public StringReader (string s);
H I J
// Methods public override void Close (); protected override void Dispose (bool disposing); public override int Peek (); public override int Read (); public override int Read (char[] buffer, int index, int count); public override string ReadLine (); public override string ReadToEnd ();
K L M N O P
}
Q R
BG StringReader and StringWriter have been some of the harder classes for people to get their heads around in the IO namespace. They are roughly similar to C++’s strstream. They allow you to read and write to a String using the same API’s you’d use to write to any Stream. Hence, the TextReader and TextWriter base classes.
S T U V W
Example
X
using System; using System.IO;
Y Z
namespace Samples { public class StringReaderSample
3042
Contents | Index
System.IO
StringReader StringReader() Constructor
{ public static void Main() { string s = "damien\nmark\nbrad\n"; using(StringReader sr = new StringReader(s)) { Console.WriteLine(sr.ReadLine()); Console.WriteLine((Char)sr.Peek()); Console.WriteLine((Char)sr.Read()); Console.WriteLine(sr.ReadToEnd()); } }
A B C D E F
} }
G
The output is
H I
damien m m ark brad
J K L M
StringReader(System.String) Constructor
N
[ILASM]
O
public rtspecialname specialname instance void .ctor(string s)
P
[C#]
public StringReader(string s)
Q R
Summary
S
Constructs and initializes a new instance of the System.IO.StringReader class that reads from the specified string.
T U
Parameters
V
Parameter
Description
s
The System.String to be initialized to.
W X Y Z
3043
Contents | Index
StringReader
System.IO
Close() Method
Exceptions Exception
Condition
System.ArgumentNullException
s is null.
A B C D
Example
E
using System; using System.IO;
F namespace Samples { public class StringReaderConstructor { public static void Main() { string s = "damien\nmark\nbrad\n"; using(StringReader sr = new StringReader(s)) { Console.WriteLine(sr.ReadLine()); Console.WriteLine((Char)sr.Peek()); Console.WriteLine((Char)sr.Read()); Console.WriteLine(sr.ReadToEnd()); } } } }
G H I J K L M N O P Q
The output is
R
damien m m ark brad
S T U V W
StringReader.Close() Method
X
[ILASM]
Y
.method public hidebysig virtual void Close() [C#]
Z
public override void Close()
3044
Contents | Index
System.IO
StringReader Close() Method
Summary Closes the System.IO.StringReader.
Description
A
Following a call to System.IO.StringReader.Close, other System.IO.StringReader methods on the current instance will throw an exception. [Note: This version of System.IO.StringReader.Close is equivalent to System.IO.StringReader.Dispose(true). This method overrides System.IO.Stream.Close.]
B C D E F
Example
G
using System; using System.IO;
H I
namespace Samples { public class StringReaderClose { public static void Main() { string s = "damien\nmark\nbrad\n"; StringReader sr = new StringReader(s); Console.WriteLine(sr.ReadLine()); Console.WriteLine((Char)sr.Peek()); Console.WriteLine((Char)sr.Read()); sr.Close(); try { Console.WriteLine(sr.ReadToEnd()); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
J K L M N O P Q R S T U V W
The output is
X Y
damien m m Exception: System.ObjectDisposedException: Cannot read from a closed TextReader. at System.IO.__Error.ReaderClosed()
Z
3045
Contents | Index
StringReader
System.IO
Dispose() Method
at System.IO.StringReader.ReadToEnd() at Samples.StringReaderClose.Main() in C:\Books\BCL\Samples\System.IO\ StringReader\Close()\StringReader.cs:line 18
A B
StringReader.Dispose(System.Boolean) Method
C
[ILASM]
D
.method family hidebysig virtual void Dispose(bool disposing) [C#]
E
protected override void Dispose(bool disposing)
F
Summary
G
Releases system resources used by the current instance.
H I
Parameters
J K L
Parameter
Description
disposing
true to release both managed and unmanaged resources; false to release only unmanaged resources.
M N
Description
O
When the disposing parameter is true, this method releases all resources held by any managed objects that this System.IO.StringReader references. This method invokes the Dispose() method of each referenced object. [Note: System.IO.StringReader.Dispose may be called multiple times by other objects. When overriding System.IO.StringReader.Dispose(System.Boolean), be careful not to reference objects that have been previously disposed in an earlier call to System.IO.StringReader.Dispose.]
P Q R S T U V
StringReader.Peek() Method
W [ILASM]
X
.method public hidebysig virtual int32 Peek() [C#]
Y
public override int Peek()
Z
3046
Contents | Index
System.IO
StringReader Peek() Method
Summary Returns the next available character but does not advance the reader’s position in the underlying string. A
Return Value
B
The next character to be read as a System.Int32, or –1 if no more characters are available.
C D
Description
E
The current position of the System.IO.StringReader is not changed by this operation. [Note: This method returns –1 when the end of the underlying string is reached because a Unicode character can contain only values between hexadecimal 0x0000 to 0xFFFF (0 to 65535). This method overrides System.IO.TextReader.Peek.]
F G H I
Exceptions
J
Exception
Condition
System.ObjectDisposedException
The current reader is closed.
K L M
Example
N
using System; using System.IO;
O P
namespace Samples { public class StringReaderPeek { public static void Main() { string s = "damien\nmark\nbrad\n"; using(StringReader sr = new StringReader(s)) { Console.WriteLine(sr.ReadLine()); for(int i = 0; i < 10; i++) Console.Write((Char)sr.Peek()); Console.WriteLine(); Console.WriteLine(sr.ReadToEnd()); } } } }
Q R S T U V W X Y Z
3047
Contents | Index
StringReader
System.IO
Read() Method
The output is damien mmmmmmmmmm mark brad
A B C D
StringReader.Read() Method
E
[ILASM]
.method public hidebysig virtual int32 Read()
F
[C#]
G
public override int Read()
H
Summary
I
Reads the next character from the input string and advances the character position by one character.
J K L
Return Value
M
The next character from the underlying string as a System.Int32, or –1 if no more characters are available.
N O
Description
P
[Note: This method returns –1 when the end of the underlying string is reached because a Unicode character can contain only values between hexadecimal 0x0000 to 0xFFFF (0 to 65535). This method overrides System.IO.TextReader.Read.]
Q R
Exceptions
S T
Exception
Condition
System.ObjectDisposedException
The current reader is closed.
U V W X
Example
Y
using System; using System.IO;
Z namespace Samples {
3048
Contents | Index
System.IO
StringReader Read() Method
public class StringReaderRead { public static void Main() { string s = "Hello world!"; using(StringReader sr = new StringReader(s)) { int i; while((i = sr.Read()) > 0) Console.Write((char) i); } } }
A B C D E F
}
G
The output is
H I
Hello world!
J K
StringReader.Read(System.Char[], System.Int32, System.Int32) Method
L
[ILASM]
M
.method public hidebysig virtual int32 Read(class System.Char[] buffer, int32 index, int32 count)
N
[C#]
O
public override int Read(char[] buffer, int index, int count)
P
Summary
Q
Reads a block of characters from the input string.
R S
Parameters
T
Parameter
Description
buffer
A System.Char array. When this method returns, contains the specified character array with the values between index and (index + count – 1) replaced by the characters read from the current source.
index
A System.Int32 that specifies the starting index in the buffer.
count
A System.Int32 that specifies the number of characters to read.
U V W X Y Z
3049
Contents | Index
StringReader
System.IO
Read() Method
Return Value A System.Int32 containing the total number of characters read into the buffer, or zero if the end of the underlying string has been reached. A B
Description
C
[Note: This method overrides System.IO.TextReader.Read.]
D
Exceptions
E F G
Exception
Condition
System.ArgumentNullException
buffer is null.
System.ArgumentException
(index + count ) > buffer.Length.
H I
index < 0.
J System.ArgumentOutOfRangeException K
-orcount < 0.
L System.ObjectDisposedException
The current reader is closed.
M N
Example
O
using System; using System.IO;
P Q
namespace Samples { public class StringReaderRead { public static void Main() { string s = "Hello world!"; using(StringReader sr = new StringReader(s)) { char[] chars = new char[5]; int count = 0; while((count = sr.Read(chars, 0, chars.Length)) != 0) for(int i = 0; i < count; i++) Console.Write(chars[i]); } } } }
R S T U V W X Y Z
3050
Contents | Index
System.IO
StringReader ReadLine() Method
The output is Hello world!
A B
StringReader.ReadLine() Method
C [ILASM]
D
.method public hidebysig virtual string ReadLine() [C#]
E
public override string ReadLine()
F
Summary
G
Reads a line from the underlying string.
H
Return Value
I
A System.String containing the next line from the underlying string, or null if the end of the underlying string is reached.
J K L
Description
M
A line is defined as a sequence of characters followed by a carriage return (0x000d), a line feed (0x000a), or a carriage return immediately followed by a line feed. The resulting string does not contain the terminating character(s). [Note: This method overrides System.IO.TextReader.ReadLine.]
N O P Q
Exceptions
R
Exception
Condition
System.ObjectDisposedException
The current reader is closed.
T
There is insufficient memory to allocate a buffer for the returned string.
U
System.OutOfMemoryException
S
V W X Y Z
3051
Contents | Index
StringReader
System.IO
ReadToEnd() Method
Example using System; using System.IO;
A namespace Samples { public class StringReaderReadLine { public static void Main() { string s = "damien\nmark\nbrad"; using(StringReader sr = new StringReader(s)) { while((s = sr.ReadLine()) != null) Console.WriteLine(s); } } } }
B C D E F G H I J K
The output is
L damien mark brad
M N O P
StringReader.ReadToEnd() Method
Q
[ILASM]
R
.method public hidebysig virtual string ReadToEnd()
S
public override string ReadToEnd()
[C#]
T
Summary
U
Returns the underlying string from the current position to the end.
V W
Description
X
[Note: This method overrides System.IO.TextReader.ReadToEnd.]
Y Z
3052
Contents | Index
System.IO
StringReader ReadToEnd() Method
Exceptions Exception
Condition
System.ObjectDisposedException
The current reader is closed.
System.OutOfMemoryException
There is insufficient memory to allocate a buffer for the returned string.
A B C D E
Example
F
using System; using System.IO;
G H
namespace Samples { public class StringReaderReadToEnd { public static void Main() { string s = "damien\nmark\nbrad"; using(StringReader sr = new StringReader(s)) { Console.WriteLine(sr.ReadToEnd()); } } } }
I J K L M N O P Q
The output is
R damien mark brad
S T U V W X Y Z
3053
Contents | Index
System.IO StringWriter
BCL
Object
A
MarshalByRefObject
B
TextWriter
IDisposable
StringWriter
C D
Summary
E
Implements a System.IO.TextWriter that writes information to a string.
F
Type Summary
G
public class StringWriter : TextWriter { // Constructors public StringWriter (); public StringWriter (IFormatProvider formatProvider); public StringWriter (StringBuilder sb); public StringWriter (StringBuilder sb, IFormatProvider formatProvider);
H I J K L
// Properties public override Encoding Encoding { get; }
M N
// Methods public override void Close (); protected override void Dispose (bool disposing); public virtual StringBuilder GetStringBuilder (); public override string ToString (); public override void Write (char value); public override void Write (char[] buffer, int index, int count); public override void Write (string value);
O P Q R S T
}
U
Example
V
using System; using System.IO;
W X
namespace Samples { public class StringWriterSample { public static void Main() {
Y Z
3054
Contents | Index
System.IO
StringWriter StringWriter() Constructor
using(StringWriter sw = new StringWriter()) { sw.Write("damien "); char[] chars = {'m', 'a', 'r', 'k', ' '}; foreach(char c in chars) sw.Write(c); sw.WriteLine("brad"); Console.WriteLine(sw); }
A B C D
} }
E
}
F
The output is
G
damien mark brad
H I J
StringWriter() Constructor
K [ILASM]
L
public rtspecialname specialname instance void .ctor() [C#]
M
public StringWriter()
N
Summary
O
Constructs and initializes a new instance of the System.IO.StringWriter class.
P
Description
Q
A new System.Text.StringBuilder is automatically created and associated with the new System.IO.StringWriter instance.
R S T
Example
U
using System; using System.IO;
V W
namespace Samples { public class StringWriterConstructor { public static void Main() { using(StringWriter sw = new StringWriter()) {
X Y Z
3055
Contents | Index
StringWriter
System.IO
StringWriter() Constructor
sw.Write("damien "); char[] chars = {'m', 'a', 'r', 'k', ' '}; foreach(char c in chars) sw.Write(c); sw.WriteLine("brad"); Console.WriteLine(sw);
A B }
C
} }
D
}
E
The output is
F
damien mark brad
G H I
StringWriter(System.IFormatProvider) Constructor
J
[ILASM]
K
public rtspecialname specialname instance void .ctor(class System.IFormatProvider formatProvider)
L
[C#]
public StringWriter(IFormatProvider formatProvider)
M N
Summary
O
Constructs and initializes a new instance of the System.IO.StringWriter class with the specified format provider.
P Q
Parameters
R S T
Parameter
Description
formatProvider
A System.IFormatProvider object that defines formatting.
U V
Example
W
using System; using System.IO; using System.Globalization;
X Y
namespace Samples { public class StringWriterConstructor {
Z
3056
Contents | Index
System.IO
StringWriter StringWriter() Constructor
public static void Main() { CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.NegativeSign = "minus"; using(StringWriter sw = new StringWriter(c)) { sw.Write("-42 is: "); sw.Write(-42); Console.WriteLine(sw); } }
A B C D E F
} }
G
The output is
H I
-42 is: minus42
J K
StringWriter(System.Text.StringBuilder) Constructor
L
[ILASM]
M
public rtspecialname specialname instance void .ctor(class System.Text.StringBuilder sb)
N
[C#]
O
public StringWriter(StringBuilder sb)
P
Summary
Q
Constructs and initializes a new instance of the System.IO.StringWriter class that writes to the specified System.Text.StringBuilder.
R S
Parameters
T
Parameter
Description
sb
The System.Text.StringBuilder to write to.
U V W X Y Z
3057
Contents | Index
StringWriter
System.IO
StringWriter() Constructor
Exceptions Exception
Condition
System.ArgumentNullException
sb is null.
A B C
Example
D
using System; using System.Text; using System.IO;
E F G
namespace Samples { public class StringWriterConstructor { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("Hello "); using(StringWriter sw = new StringWriter(sb)) { sw.Write("world!"); Console.WriteLine(sw); } } } }
H I J K L M N O P Q
The output is
R
Hello world!
S T
V
StringWriter(System.Text.StringBuilder, System.IFormatProvider) Constructor
W
[ILASM]
X
public rtspecialname specialname instance void .ctor(class System.Text.StringBuilder sb, class System.IFormatProvider formatProvider)
Y
[C#]
U
public StringWriter(StringBuilder sb, IFormatProvider formatProvider)
Z
3058
Contents | Index
System.IO
StringWriter StringWriter() Constructor
Summary Constructs and initializes a new instance of the System.IO.StringWriter class that writes to the specified System.Text.StringBuilder and has the specified format provider. A
Parameters
B C
Parameter
Description
sb
The System.Text.StringBuilder to write to.
E
formatProvider
A System.IFormatProvider object that defines formatting.
F
D
G H
Exceptions
I
Exception
Condition
J
System.ArgumentNullException
sb is null.
K L M
Example using using using using
N
System; System.IO; System.Globalization; System.Text;
O P Q
namespace Samples { public class StringWriterConstructor { public static void Main() { StringBuilder sb = new StringBuilder(); sb.Append("-42 is: "); CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.NegativeSign = "minus"; using(StringWriter sw = new StringWriter(sb, c)) { sw.Write(-42); Console.WriteLine(sw); } } } }
R S T U V W X Y Z
3059
Contents | Index
StringWriter
System.IO
Encoding Property
The output is -42 is: minus42
A B
StringWriter.Encoding Property
C
[ILASM]
D
.property class System.Text.Encoding Encoding { public hidebysig virtual specialname class System.Text.Encoding get_Encoding() }
E
[C#]
public override Encoding Encoding { get; }
F G
Summary
H
Gets the System.Text.Encoding in which the output is written.
I
Usage
J
This property is required in some XML scenarios where a header must be written containing the encoding used by the System.IO.StringWriter. This allows XML code to consume an arbitrary System.IO.StringWriter and generate a correct XML header.
K L M
Example
N
using System; using System.IO;
O namespace Samples { public class StringWriterEncoding { public static void Main() { using(StringWriter sw = new StringWriter()) { Console.WriteLine(sw.Encoding); } } } }
P Q R S T U V W X
The output is
Y System.Text.UnicodeEncoding
Z
3060
Contents | Index
System.IO
StringWriter Close() Method
StringWriter.Close() Method [ILASM]
.method public hidebysig virtual void Close() [C#]
A
public override void Close()
B C
Summary
D
Closes the current System.IO.StringWriter instance.
E
Description
F
[Note: This version of System.IO.StringWriter.Close is equivalent to System.IO.StringWriter.Dispose(true). This method overrides System.IO.Stream.Close.]
G H I
Example
J
using System; using System.IO;
K L
namespace Samples { public class StringWriterClose { public static void Main() { StringWriter sw = new StringWriter(); sw.Write("damien "); char[] chars = {'m', 'a', 'r', 'k', ' '}; foreach(char c in chars) sw.Write(c); sw.WriteLine("brad"); Console.WriteLine(sw); sw.Close(); try { sw.WriteLine(sw); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); } } } }
M N O P Q R S T U V W X Y Z
3061
Contents | Index
StringWriter
System.IO
Dispose() Method
The output is damien mark brad
A
Exception: System.ObjectDisposedException: Cannot write to a closed TextWriter. at System.IO.__Error.WriterClosed() at System.IO.StringWriter.Write(Char[] buffer, Int32 index, Int32 count) at System.IO.TextWriter.WriteLine(String value) at System.IO.TextWriter.WriteLine(Object value) at Samples.StringWriterClose.Main() in C:\Books\BCL\Samples\System.IO\ StringWriter\Close()\StringWriter.cs:line 20
B C D E F G
StringWriter.Dispose(System.Boolean) Method
H
[ILASM]
I
.method family hidebysig virtual void Dispose(bool disposing) [C#]
J
protected override void Dispose(bool disposing)
K L
Summary
M
Releases the unmanaged resources used by the System.IO.StringWriter and optionally releases the managed resources.
N
Parameters
O P
Parameter
Description
disposing
true to release both managed and unmanaged resources; false to release only unmanaged resources.
Q R S T
Description
U
When the disposing parameter is true, this method releases all resources held by any managed objects that this System.IO.StringWriter references. This method invokes the Dispose() method of each referenced object. [Note: System.IO.StringWriter.Dispose may be called multiple times by other objects. When overriding System.IO.StringWriter.Dispose(System.Boolean), be careful not to reference objects that have been previously disposed in an earlier call to System.IO.StringWriter.Dispose.]
V W X Y Z
3062
Contents | Index
System.IO
StringWriter GetStringBuilder() Method
StringWriter.GetStringBuilder() Method [ILASM]
.method public hidebysig virtual class System.Text.StringBuilder GetStringBuilder()
A
[C#]
B
public virtual StringBuilder GetStringBuilder()
C
Summary
D
Returns the underlying System.Text.StringBuilder.
E
Description
F
This method returns either the System.Text.StringBuilder that was passed to the constructor, or the System.Text.StringBuilder that was automatically created.
G H I
Example
J
using System; using System.IO; using System.Text;
K L
namespace Samples { public class StringWriterGetStringBuilder { public static void Main() { using(StringWriter sw = new StringWriter()) { sw.Write("damien mark "); sw.WriteLine("brad"); StringBuilder sb = sw.GetStringBuilder(); Console.WriteLine("Capacity: {0}", sb.Capacity); Console.WriteLine("Length: {0}", sb.Length); Console.WriteLine("MaxCapacity: {0}", sb.MaxCapacity); Console.WriteLine(sb); } } } }
M N O P Q R S T U V W X
The output is
Y
Capacity: 32 Length: 18 MaxCapacity: 2147483647 damien mark brad
Z
3063
Contents | Index
StringWriter
System.IO
ToString() Method
StringWriter.ToString() Method [ILASM]
.method public hidebysig virtual string ToString()
A
[C#]
public override string ToString()
B C
Summary
D
Returns a string containing the characters written to the current System.IO.StringWriter instance so far.
E F
Description
G
[Note: This method overrides System.Object.ToString.]
H I
Example
J
using System; using System.IO;
K namespace Samples { public class StringWriterToString { public static void Main() { using(StringWriter sw = new StringWriter()) { sw.Write("Hello "); Console.WriteLine(sw.ToString()); sw.WriteLine("world"); Console.WriteLine(sw.ToString()); sw.WriteLine('!'); Console.WriteLine(sw.ToString()); } } } }
L M N O P Q R S T U V W
The output is
X Hello Hello world
Y Z
Hello world !
3064
Contents | Index
System.IO
StringWriter Write() Method
StringWriter.Write(System.Char) Method [ILASM]
.method public hidebysig virtual void Write(valuetype System.Char value) [C#]
A
public override void Write(char value)
B C
Summary
D
Writes a character to the current instance of the System.IO.StringWriter.
E
Parameters
F
Parameter
Description
value
The System.Char to write.
G H I J
Description
K
[Note: This method overrides System.IO.TextWriter.Write.]
L M
Exceptions
N
Exception
Condition
System.ObjectDisposedException
The writer is closed.
O P Q R
Example
S
using System; using System.IO;
T U
namespace Samples { public class StringWriterWrite { public static void Main() { using(StringWriter sw = new StringWriter()) { string s = "Hello world!"; foreach(char c in s) sw.Write(c);
V W X Y Z
3065
Contents | Index
StringWriter
System.IO
Write() Method
sw.WriteLine(); Console.WriteLine(sw); } }
A
} }
B C
The output is
D
Hello world!
E F
StringWriter.Write(System.Char[], System.Int32, System.Int32) Method
G
[ILASM]
H
.method public hidebysig virtual void Write(class System.Char[] buffer, int32 index, int32 count)
I
[C#]
J
public override void Write(char[] buffer, int index, int count)
K
Summary
L
Writes the specified region of a character array to this instance of the System.IO.StringWriter.
M N
Parameters
O P
Parameter
Description
buffer
The System.Char array to read data from.
S
index
A System.Int32 that specifies the index at which to begin reading from buffer.
T
count
A System.Int32 that specifies the maximum number of characters to write.
Q R
U V
Description
W
[Note: This method overrides System.IO.TextWriter.Write.]
X Y Z
3066
Contents | Index
System.IO
StringWriter Write() Method
Exceptions Exception
Condition
System.ArgumentNullException
buffer is null.
System.ArgumentOutOfRangeException
index < 0. -orcount < 0.
A
System.ArgumentException
(index + count ) > buffer.Length.
System.ObjectDisposedException
The writer is closed.
B C D E F G H
Example
I
using System; using System.IO;
J K
namespace Samples { public class StringWriterWrite { public static void Main() { using(StringWriter sw = new StringWriter()) { sw.Write("Hello "); char[] chars = {'w', 'o', 'r', 'l', 'd'}; sw.Write(chars, 0, chars.Length); sw.WriteLine('!'); Console.WriteLine(sw); } } } }
L M N O P Q R S T U
The output is
V Hello world!
W X
StringWriter.Write(System.String) Method
Y
[ILASM]
Z
.method public hidebysig virtual void Write(string value) [C#]
public override void Write(string value)
3067
Contents | Index
StringWriter
System.IO
Write() Method
Summary Writes a string to the current instance of the System.IO.StringWriter. A
Parameters
B C
Parameter
Description
D
value
The System.String to write. If value is null, nothing is written.
E F
Description
G
[Note: This method overrides System.IO.TextWriter.Write.]
H
Exceptions
I J
Exception
Condition
System.ObjectDisposedException
The writer is closed.
K L M N
Example
O
using System; using System.IO;
P namespace Samples { public class StringWriterWrite { public static void Main() { using(StringWriter sw = new StringWriter()) { sw.Write("Hello "); sw.Write("world"); sw.Write("!"); Console.WriteLine(sw); } } } }
Q R S T U V W X Y Z
The output is Hello world!
3068
Contents | Index
System.Threading SynchronizationLockException
BCL
Object Exception
ISerializable
NotStandardized
A B
SystemException SynchronizationLockException
C D
Summary
E
Represents the error that occurs when a method requires the caller to own the lock on a given System.Threading.Monitor, and the method is invoked by a caller that does not own that lock.
F G H
Type Summary
I
CF public class SynchronizationLockException : SystemException { // Constructors CF public SynchronizationLockException (); CF public SynchronizationLockException (string message); CF public SynchronizationLockException (string message, Exception innerException); MS CF protected SynchronizationLockException (SerializationInfo info, StreamingContext context); }
J K L M N O
Description
P
System.Threading.SynchronizationLockException is thrown if the System.Threading.Monitor.Pulse, System.Threading.Monitor.PulseAll, or System.Threading.Monitor.Wait methods are invoked for a specified object, but the caller does not own the lock on that object. System.Threading.SynchronizationLockException is also thrown when the System.Threading.Monitor.Exit method is called to release the lock on an object, but the caller does not own the lock on that object. To acquire the lock on an object, use System.Threading.Monitor.Enter. To release the lock on an object, use System.Threading.Monitor.Exit.
Q R S T U V W X Y Z
3069
Contents | Index
SynchronizationLockException
System.Threading
SynchronizationLockException() Constructor
Example using System; using System.Threading; using System.Collections;
A B
namespace Samples { public class SynchronizationLockExceptionSample { private static Object o = new Object(); public static void Main() { try { Monitor.Wait(o); } catch(SynchronizationLockException e) { Console.WriteLine("Exception: {0}", e); } } } }
C D E F G H I J K L M
The output is
N Exception: System.Threading.SynchronizationLockException: Object synchronization method was called from an unsynchronized block of code. at System.Threading.Monitor.ObjWait(Boolean exitContext, Int32 millisecondsTimeout, Object obj) at System.Threading.Monitor.Wait(Object obj, Int32 millisecondsTimeout, Boolean exitContext) at System.Threading.Monitor.Wait(Object obj) at Samples.SynchronizationLockExceptionSample.Main() in C:\Books\BCL\Samples\ System.Threading\SynchronizationLockException\SynchronizationLockException.cs:line 14
O P Q R S T U
SynchronizationLockException() Constructor
V
[ILASM]
W
public rtspecialname specialname instance void .ctor() [C#]
X
public SynchronizationLockException()
Y Z
Summary Constructs and initializes a new instance of the System.Threading.SynchronizationLockException class. 3070
Contents | Index
System.Threading
SynchronizationLockException SynchronizationLockException() Constructor
Description This constructor initializes the System.Threading.SynchronizationLockException.Message property of the new instance to a system-supplied message that describes the error, such as “Synchronization method was invoked from an unsynchronized block of code.” This message takes into account the current system culture. The System.Threading.SynchronizationLockException.InnerException property is initialized to null.
A B C D E
SynchronizationLockException(System.String) Constructor
F
[ILASM]
G
public rtspecialname specialname instance void .ctor(string message)
H
[C#]
public SynchronizationLockException(string message)
I
Summary
J
Constructs and initializes a new instance of the System.Threading.SynchronizationLockException class.
K
Parameters
M
L
N
Parameter
Description
O
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
P
message
Q R S
Description
T
This constructor initializes the System.Threading.SynchronizationLockException.Message property of the new instance using message. If message is null, the System.Threading.SynchronizationLockException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.Threading.SynchronizationLockException.InnerException property is initialized to null.
U V W X Y Z
3071
Contents | Index
SynchronizationLockException
System.Threading
SynchronizationLockException() Constructor
SynchronizationLockException(System.String, System.Exception) Constructor [ILASM]
A
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
B
[C#]
C
public SynchronizationLockException(string message, Exception innerException)
D E
Summary
F
Constructs and initializes a new instance of the System.Threading.SynchronizationLockException class.
G
Parameters
H I
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
J K L M N O P
Description
Q
This constructor initializes the System.Threading.SynchronizationLockException.Message property of the new instance using message and the System.Threading.SynchronizationLockException.InnerException property using innerException. If message is null, the System.Threading.SynchronizationLockException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For more information on inner exceptions, see System.Exception.InnerException.]
R S T U V W X Y Z
3072
Contents | Index
System.Threading
SynchronizationLockException SynchronizationLockException() Constructor
SynchronizationLockException(System.Runtime.Serialization.Serialization Info, System.Runtime.Serialization.StreamingContext) Constructor [ILASM]
A
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
B C
[C#]
protected SynchronizationLockException(SerializationInfo info, StreamingContext context)
D E
Summary
F
Initializes a new instance of the System.Threading.SynchronizationLockException class with serialized data.
G H I
Parameters
J
Parameter
Description
info
The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown.
context
The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination.
K L M N O P
Description
Q
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
R S T U V W X Y Z
3073
Contents | Index
System SystemException
BCL
Object Exception
A
ISerializable
NotStandardized
SystemException
B ArgumentException
C
ArgumentNullException
D
ArgumentOutOfRangeException
E
DuplicateWaitObjectException ArithmeticException
F DivideByZeroException
G
OverflowException
H
NotFiniteNumberException
ExtendedNumerics
ArrayTypeMismatchException
I
ExecutionEngineException
J
FormatException
K
IndexOutOfRangeException
L
InvalidCastException InvalidOperationException
M
ObjectDisposedException
N
InvalidProgramException
O
IOException DirectoryNotFoundException
P
EndOfStreamException
Q
FileLoadException
R
FileNotFoundException
S
PathTooLongException NotImplementedException
T
NotSupportedException
U NullReferenceException
V
OutOfMemoryException
W
RankException
X
SecurityException VerificationException
Y StackOverflowException
Z
SynchronizationLockException ThreadAbortException ThreadStateException TypeInitializationException
3074
UnauthorizedAccessException
Contents | Index
System
SystemException SystemException Class
Summary System.SystemException is the base class for all exceptions defined by the system. A
Type Summary
B
public class SystemException : Exception { // Constructors public SystemException (); public SystemException (string message); public SystemException (string message, Exception innerException); MS CF protected SystemException (SerializationInfo info, StreamingContext context); }
C D E F G H I
JR You should not define new exception classes derived from SystemException;
J
use Exception instead. In addition, you should not write code that catches SystemException.
K L
Description
M
This class is provided as a means to differentiate between exceptions defined by the system versus exceptions defined by applications. [Note: For more information on exceptions defined by applications, see System.ApplicationException.] [Note: System.SystemException does not provide information as to the cause of the Exception. In most scenarios, instances of this class should not be thrown. In cases where this class is instantiated, a human-readable message describing the error should be passed to the constructor.]
N O P Q R S
Example
T
The following example demonstrates catching an exception type that derives from SystemException. There is, however, no valid scenario for catching a SystemException type.
U V W
using System;
X namespace Samples { public class SystemExceptionSample { public static void Main() {
Y Z
3075
Contents | Index
SystemException
System
SystemException() Constructor
try { string s = null; Console.WriteLine(s.ToString()); } catch(SystemException e) { Console.WriteLine("Exception: {0}", e); }
A B C D
} }
E }
F
The output is
G
Exception: System.NullReferenceException: Object reference not set to an instance of an object. at Samples.SystemExceptionSample.Main() in C:\Books\BCL\Samples\System\ SystemException\SystemException.cs:line 12
H I J K L
SystemException() Constructor
M
[ILASM]
public rtspecialname specialname instance void .ctor()
N
[C#]
public SystemException()
O P
Summary
Q
Constructs and initializes a new instance of the System.SystemException class.
R
Description
S
This constructor initializes the System.SystemException.Message property of the new instance to a system-supplied message that describes the error, such as “A system error has occurred.” This message takes into account the current system culture. The System.SystemException.InnerException property is initialized to null.
T U V W X
SystemException(System.String) Constructor
Y
[ILASM]
public rtspecialname specialname instance void .ctor(string message)
Z
[C#]
public SystemException(string message)
3076
Contents | Index
System
SystemException SystemException() Constructor
Summary Constructs and initializes a new instance of the System.SystemException class. A
Parameters
B
Parameter
Description
C
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
D
message
E F G
Description
H
This constructor initializes the System.SystemException.Message property of the new instance using message. If message is null, the System.SystemException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.SystemException.InnerException property is initialized to null.
I J K L M
SystemException(System.String, System.Exception) Constructor
N [ILASM]
O
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
P
[C#]
public SystemException(string message, Exception innerException)
Q R
Summary
S
Constructs and initializes a new instance of the System.SystemException class.
T
Parameters
U
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
V W
innerException
X Y Z
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
3077
Contents | Index
SystemException
System
SystemException() Constructor
Description This constructor initializes the System.SystemException.Message property of the new instance using message, and the System.SystemException.InnerException property using innerException. If message is null, the System.SystemException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For information on inner exceptions, see System.Exception.InnerException.]
A B C D E F G
SystemException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
H
[ILASM]
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
I J
[C#]
K
protected SystemException(SerializationInfo info, StreamingContext context)
L
Summary
M
Initializes a new instance of the System.SystemException class with serialized data.
N O
Parameters
P Q
Parameter
Description
R
info
The object that holds the serialized object data.
context
The contextual information about the source or destination.
S T U
Description
V
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
W X Y Z
3078
Contents | Index
System.IO TextReader
BCL
Object
A
MarshalByRefObject TextReader
B
IDisposable
StreamReader
C
StringReader
D E
Summary
F
Represents an object that can read a sequential series of characters.
G
Type Summary
H
public abstract class TextReader : MarshalByRefObject, IDisposable { // Constructors protected TextReader ();
I J K L
// Fields public static readonly TextReader Null;
M N
// Methods public virtual void Close (); protected virtual void Dispose (bool disposing); public virtual int Peek (); public virtual int Read (); public virtual int Read (char[] buffer, int index, int count); public virtual int ReadBlock (char[] buffer, int index, int count); public virtual string ReadLine (); public virtual string ReadToEnd (); public static TextReader Synchronized (TextReader reader);
O P Q R S T U V
// Explicit Interface Members void IDisposable.Dispose ();
W X
}
Y Z
3079
Contents | Index
TextReader
System.IO
TextReader() Constructor
Description System.IO.TextReader is designed for character input, whereas the System.IO.StreamReader is designed for byte input and the System.IO.StringReader class is designed for reading from a string. By default, a System.IO.TextReader is not thread safe. For information on creating a thread-safe System.IO.TextReader, see System.IO.TextReader.Synchronized.
A B C D
Example
E
using System; using System.IO; using System.Text;
F G
namespace Samples { public class TextReaderSample { public static void Main() { string s = "textreader.txt"; using(TextReader tr = new StreamReader(s)) { Console.WriteLine(tr.ReadLine()); Console.WriteLine((Char)tr.Peek()); char[] chars = new Char[4]; tr.Read(chars, 0, chars.Length); foreach(char c in chars) Console.Write(c); Console.WriteLine(tr.ReadToEnd()); } } } }
H I J K L M N O P Q R S
The output is
T U
Hello world! G Goodbye world!
V W X
TextReader() Constructor
Y
[ILASM]
Z
family rtspecialname specialname instance void .ctor() [C#]
protected TextReader()
3080
Contents | Index
System.IO
TextReader Close() Method
Summary Constructs a new instance of the System.IO.TextReader class. A
TextReader.Null Field
B
[ILASM]
C
.field public static initOnly class System.IO.TextReader Null
D
[C#]
public static readonly TextReader Null
E F
Summary
G
Provides a System.IO.TextReader with no data to read from.
H
Description
I
Reading from the System.IO.TextReader.Null text reader is similar to reading from the end of a stream:
J K
• • •
System.IO.TextReader.Read() and System.IO.TextReader.Peek methods return –1. System.IO.TextReader.Read(System.Char[], System.Int32, System.Int32) and System.IO.TextReader.ReadBlock methods return zero. System.IO.TextReader.ReadLine and System.IO.TextReader.ReadToEnd methods return null.
L M N O P Q
TextReader.Close() Method
R
[ILASM]
S
.method public hidebysig virtual void Close()
T
[C#]
public virtual void Close()
U V
Summary
W
Closes the current System.IO.TextReader instance and releases any system resources associated with it.
X Y
Description
Z
[Note: After a call to System.IO.TextReader.Close, any IO operation on the current instance might throw an exception.]
3081
Contents | Index
TextReader
System.IO
Dispose() Method
Behaviors This method is equivalent to System.IO.TextReader.Dispose(true). A
Usage
B
Use this method to close the current instance and free any resources associated with it.
C D
TextReader.Dispose(System.Boolean) Method
E
[ILASM]
F
.method family hidebysig virtual void Dispose(bool disposing) [C#]
G
protected virtual void Dispose(bool disposing)
H
Summary
I
Releases the unmanaged resources used by the System.IO.TextReader and optionally releases the managed resources.
J K
Parameters
L M
Parameter
Description
disposing
true to release both managed and unmanaged resources; false to release only unmanaged resources.
N O P Q
Description
R
When the disposing parameter is true, this method releases all resources held by any managed objects that this System.IO.TextReader references. This method invokes the Dispose() method of each referenced object. [Note: System.IO.TextReader.Dispose may be called multiple times by other objects. When overriding System.IO.TextReader.Dispose(System.Boolean), be careful not to reference objects that have been previously disposed in an earlier call to System.IO.TextReader.Dispose.]
S T U V W X Y
TextReader.Peek() Method
Z
[ILASM]
.method public hidebysig virtual int32 Peek() [C#]
public virtual int Peek()
3082
Contents | Index
System.IO
TextReader Read() Method
Summary Reads the next character without changing the state of the reader or the character source.
Return Value
A
The next character to be read, or –1 if no more characters are available.
B C
Description
D
The position of the System.IO.TextReader in the source is not changed by this operation.
E
Default
F
The default implementation returns –1.
G H
Exceptions
I
Exception
Condition
System.IO.IOException
An I/O error has occurred.
J K L M N
TextReader.Read() Method
O [ILASM]
P
.method public hidebysig virtual int32 Read() [C#]
Q
public virtual int Read()
R
Summary
S
Reads the next character from the character source and advances the character position by one character.
T U
Return Value
V
The next character from the character source represented as a System.Int32, or –1 if at the end of the stream.
W
Default
Y
The default implementation returns –1.
Z
X
3083
Contents | Index
TextReader
System.IO
Read() Method
Exceptions Exception
Condition
System.IO.IOException
An I/O error occurred.
A B C D
TextReader.Read(System.Char[], System.Int32, System.Int32) Method
E
[ILASM]
F
.method public hidebysig virtual int32 Read(class System.Char[] buffer, int32 index, int32 count)
G
[C#]
H
public virtual int Read(char[] buffer, int index, int count)
I
Summary
J
Reads at most the specified number of characters from the current character source, and writes them to the provided character array.
K L
Parameters
M N
Parameter
Description
buffer
A System.Char array. When this method returns, contains the specified character array with the values between index and (index + count – 1) replaced by the characters read from the current source.
index
A System.Int32 that specifies the place in buffer at which to begin writing.
count
A System.Int32 that specifies the maximum number of characters to read. If the end of the stream is reached before count of characters is read into buffer, this method returns.
O P Q R S T U V
Return Value
W
A System.Int32 containing the number of characters that were read, or zero if there were no more characters left to read. Can be less than count if the end of the stream has been reached.
X Y Z
Description System.IO.TextReader.ReadBlock is a blocking version of this method.
3084
Contents | Index
System.IO
TextReader ReadBlock() Method
Behaviors The provided character array can be changed only in the specified range. A
Exceptions
B
Exception
Condition
C
System.ArgumentNullException
buffer is null.
D
System.ArgumentException
(index + count) > buffer.Length.
E F
index < 0. System.ArgumentOutOfRangeException
G
- orH
count < 0.
I System.IO.IOException
An I/O error occurred.
J K L
TextReader.ReadBlock(System.Char[], System.Int32, System.Int32) Method
M [ILASM]
N
.method public hidebysig virtual int32 ReadBlock(class System.Char[] buffer, int32 index, int32 count)
O
[C#]
public virtual int ReadBlock(char[] buffer, int index, int count)
P Q
Summary
R
Reads a specified number of characters from the current stream into a provided character array.
S T
Parameters
U V
Parameter
Description
buffer
A System.Char array. When this method returns, contains the specified character array with the values between index and (index + count – 1) replaced by the characters read from the current source.
X
index
A System.Int32 that specifies the index in buffer at which to begin writing.
Z
count
A System.Int32 that specifies the maximum number of characters to read.
W
Y
3085
Contents | Index
TextReader
System.IO
ReadLine() Method
Return Value A System.Int32 containing the number of characters that were read, or zero if there were no more characters left to read. Can be less than count if the end of the stream has been reached.
A B C
Description
D
The method blocks until either the specified number of characters are read, or no more characters are available in the source.
E
Exceptions
F G
Exception
Condition
System.ArgumentNullException
buffer is null.
System.ArgumentException
(index + count – 1) > buffer.Length.
System.ArgumentOutOfRangeException
index < 0. - orcount < 0.
System.IO.IOException
An I/O error occurred.
H I J K L M N O P
TextReader.ReadLine() Method
Q
[ILASM]
R
.method public hidebysig virtual string ReadLine()
S
public virtual string ReadLine()
[C#]
T
Summary
U
Reads a line of characters from the current character source.
V W
Return Value
X
A System.String containing the next line from the input stream, or null if all lines have been read. The returned string does not contain the line terminating character.
Y Z
Description A line is defined as a sequence of characters followed by a carriage return (0x000d), a line feed (0x000a), System.Environment.NewLine, or the end of stream marker. 3086
Contents | Index
System.IO
TextReader Synchronized() Method
Exceptions Exception
Condition
System.IO.IOException
An I/O error occurred.
System.OutOfMemoryException
There is insufficient memory to allocate a buffer for the returned string.
System.ArgumentOutOfRangeException
The number of characters in the next line is larger than System.Int32.MaxValue.
A B C D E F G
TextReader.ReadToEnd() Method
H
[ILASM]
I
.method public hidebysig virtual string ReadToEnd()
J
[C#]
public virtual string ReadToEnd()
K
Summary
L
Reads all characters from the current position in the character source to the end of the source.
M N
Exceptions
O
Exception
Condition
System.IO.IOException
An I/O error occurred.
System.OutOfMemoryException
There is insufficient memory to allocate a buffer for the returned string.
System.ArgumentOutOfRangeException
The number of characters from the current position to the end of the underlying stream is larger than System.Int32.MaxValue.
P Q R S T U V W
TextReader.Synchronized(System.IO.TextReader) Method
X
[ILASM]
Y
.method public hidebysig static class System.IO.TextReader Synchronized(class System.IO.TextReader reader)
Z
[C#]
public static TextReader Synchronized(TextReader reader)
3087
Contents | Index
TextReader
System.IO
Dispose() Method
Summary Creates a thread-safe wrapper around the specified System.IO.TextReader instance. A
Parameters
B C
Parameter
Description
D
reader
The System.IO.TextReader to synchronize.
E F
Return Value
G
A thread-safe System.IO.TextReader.
H
Description
I
This method returns a System.IO.TextReader instance that wraps around the specified System.IO.TextReader instance and restricts concurrent access to it by multiple threads.
J K L
Exceptions
M N
Exception
Condition
System.ArgumentNullException
The reader parameter is null.
O P Q R
IDisposable.Dispose() Method
S [ILASM]
T
.method private final hidebysig virtual void System.IDisposable.Dispose() [C#]
U
void IDisposable.Dispose()
V W
Summary
X
Implemented to support the System.IDisposable interface. [Note: For more information, see System.IDisposable.Dispose.]
Y Z
3088
Contents | Index
System.IO TextWriter
BCL
Object
A
MarshalByRefObject TextWriter
B
IDisposable
StreamWriter
C
StringWriter
D E
Summary
F
Represents a writer that can write a sequential series of characters.
G
Type Summary
H
public abstract class TextWriter : MarshalByRefObject, IDisposable { // Constructors protected TextWriter (); protected TextWriter (IFormatProvider formatProvider);
I J K L M
// Fields MS protected char[] CoreNewLine = new char [] {'\n'}; public static readonly TextWriter Null;
N O
// Properties public abstract Encoding Encoding { get; } public virtual IFormatProvider FormatProvider { get; } public virtual string NewLine { set; get; }
P Q R
// Methods public virtual void Close (); protected virtual void Dispose (bool disposing); public virtual void Flush (); public static TextWriter Synchronized (TextWriter writer); public virtual void Write (bool value); public virtual void Write (char value); public virtual void Write (char[] buffer); public virtual void Write (char[] buffer, int index, int count); public virtual void Write (decimal value); public virtual void Write (double value); public virtual void Write (float value); public virtual void Write (int value); public virtual void Write (long value); public virtual void Write (object value);
S T U V W X Y Z
3089
Contents | Index
TextWriter
System.IO
TextWriter Class
public virtual void Write (string value); public virtual void Write (string format, object arg0); public virtual void Write (string format, object arg0, object arg1); CF public virtual void Write (string format, object arg0, object arg1, object arg2); public virtual void Write (string format, params object[] arg); public virtual void Write (uint value); public virtual void Write (ulong value); public virtual void WriteLine (); public virtual void WriteLine (bool value); public virtual void WriteLine (char value); public virtual void WriteLine (char[] buffer); public virtual void WriteLine (char[] buffer, int index, int count); public virtual void WriteLine (decimal value); public virtual void WriteLine (double value); public virtual void WriteLine (float value); public virtual void WriteLine (int value); public virtual void WriteLine (long value); public virtual void WriteLine (object value); public virtual void WriteLine (string value); public virtual void WriteLine (string format, object arg0); public virtual void WriteLine (string format, object arg0, object arg1); CF public virtual void WriteLine (string format, object arg0, object arg1, object arg2); public virtual void WriteLine (string format, params object[] arg); public virtual void WriteLine (uint value); public virtual void WriteLine (ulong value);
A B C D E F G H I J K L M N O P Q R S T U V W X
// Explicit Interface Members void IDisposable.Dispose ();
Y }
Z
3090
Contents | Index
System.IO
TextWriter TextWriter() Constructor
Description System.IO.TextWriter is designed for character output, whereas the System.IO.Stream class is designed for byte input and output. [Note: By default, a System.IO.TextWriter is not thread safe. See System.IO.TextWriter.Synchronized for a thread-safe wrapper.]
A B C
Example
D
using System; using System.IO; using System.Text;
E F
namespace Samples { public class TextWriterSample { public static void Main() { string s = "textwriter.txt"; using(TextWriter tw = new StreamWriter(s)) { DisplayInformation(tw); tw.WriteLine(DateTime.Now.ToString()); } } public static void DisplayInformation(TextWriter tw) { Console.WriteLine("Encoding: {0}", tw.Encoding); Console.WriteLine("Format provider: {0}", tw.FormatProvider); } } }
G H I J K L M N O P Q R S T
The output is
U Encoding: System.Text.UTF8Encoding Format provider: en-AU
V W X
TextWriter() Constructor
Y [ILASM]
Z
family rtspecialname specialname instance void .ctor() [C#]
protected TextWriter()
3091
Contents | Index
TextWriter
System.IO
TextWriter() Constructor
Summary Constructs and initializes a new instance of the System.IO.TextWriter class. A B
TextWriter(System.IFormatProvider) Constructor
C
[ILASM]
D
family rtspecialname specialname instance void .ctor(class System.IFormatProvider formatProvider)
E
[C#]
protected TextWriter(IFormatProvider formatProvider)
F G
Summary
H
Constructs and initializes a new instance of the System.IO.TextWriter class with the specified format provider.
I J
Parameters
K L
Parameter
Description
M
formatProvider
A System.IFormatProvider object that supplies a formatting object.
N O P
TextWriter.CoreNewLine Field
Q
[ILASM]
.field family class System.Char[] CoreNewLine
R
[C#]
protected char[] CoreNewLine = new char [] {'\n'}
S T
Summary
U
Stores the new line characters used for this TextWriter.
V W
TextWriter.Null Field
X
[ILASM]
Y
.field public static initOnly class System.IO.TextWriter Null [C#]
Z
public static readonly TextWriter Null
3092
Contents | Index
System.IO
TextWriter FormatProvider Property
Summary Provides a System.IO.TextWriter object without a backing store.
Description
A
Use System.IO.TextWriter.Null to redirect output to a stream that will not consume any operating system resources. When a System.IO.TextWriter.Write method is invoked on System.IO.TextWriter.Null, the call simply returns, and no data is actually written to any backing store.
B C D E F
TextWriter.Encoding Property
G
[ILASM]
H
.property class System.Text.Encoding Encoding { public hidebysig virtual abstract specialname class System.Text.Encoding get_Encoding() }
I
[C#]
J
public abstract Encoding Encoding { get; }
K
Summary
L
Gets the System.Text.Encoding in which the output is written.
M
Usage
N
This property is required in some XML scenarios where a header must be written containing the encoding used by the System.IO.TextWriter. This allows XML code to consume an arbitrary System.IO.TextWriter and generate a correct XML header.
O P Q R
TextWriter.FormatProvider Property
S
[ILASM]
T
.property class System.IFormatProvider FormatProvider { public hidebysig virtual specialname class System.IFormatProvider get_FormatProvider() }
U
[C#]
V
public virtual IFormatProvider FormatProvider { get; }
W
Summary
X
Gets an object that provides formatting for the current instance.
Y Z
3093
Contents | Index
TextWriter
System.IO
NewLine Property
Property Value A System.IFormatProvider object for a specific culture, or the formatting of the current culture if no other culture is specified. A B
TextWriter.NewLine Property
C
[ILASM]
D
.property string NewLine { public hidebysig virtual specialname string get_NewLine() public hidebysig virtual specialname void set_NewLine(string value) }
E
[C#]
F
public virtual string NewLine { get; set; }
G
Summary
H
Gets or sets the line terminator string used by the current System.IO.TextWriter.
I J
Property Value
K
A System.String containing the line terminator string for the current System.IO.TextWriter.
L M
Description
N
The default line terminator string is System.Environment.NewLine. The line terminator string is written to the text stream whenever one of the System.IO.TextWriter.WriteLine methods is called. In order for text written by the System.IO.TextWriter to be readable by a System.IO.TextReader, only “\n” or System.Environment.NewLine should be used as terminator strings. If System.IO.TextWriter.NewLine is set to null, the default newline character is used instead.
O P Q R S T U
TextWriter.Close() Method
V
[ILASM]
.method public hidebysig virtual void Close()
W
[C#]
public virtual void Close()
X Y
Summary
Z
Closes the current System.IO.TextWriter instance and releases any system resources associated with it.
3094
Contents | Index
System.IO
TextWriter Flush() Method
Description [Note: After a call to System.IO.TextReader.Close, any operation on the current instance might throw an exception. This version of System.IO.TextReader.Close is equivalent to System.IO.TextReader.Dispose(true).]
A B C
TextWriter.Dispose(System.Boolean) Method
D [ILASM]
.method family hidebysig virtual void Dispose(bool disposing)
E
[C#]
F
protected virtual void Dispose(bool disposing)
G
Summary
H
Releases the unmanaged resources used by the System.IO.TextWriter and optionally releases the managed resources.
I J K
Parameters
L
Parameter
Description
disposing
true to release both managed and unmanaged resources; false to release only unmanaged resources.
M N O P
Description
Q
When the disposing parameter is true, this method releases all resources held by any managed objects that this System.IO.FileStream references. This method invokes the Dispose() method of each referenced object. [Note: System.IO.FileStream.Dispose may be called multiple times by other objects. When overriding System.IO.FileStream.Dispose(System.Boolean), be careful not to reference objects that have been previously disposed in an earlier call to System.IO.FileStream.Dispose.]
R S T U V W X
TextWriter.Flush() Method
Y
[ILASM]
.method public hidebysig virtual void Flush()
Z
[C#]
public virtual void Flush()
3095
Contents | Index
TextWriter
System.IO
Synchronized() Method
Summary Writes any buffered data to the underlying device and clears all buffers for the current System.IO.TextWriter instance. A B
Default
C
This method is not implemented in this abstract class.
D E
TextWriter.Synchronized(System.IO.TextWriter) Method
F
[ILASM]
G
.method public hidebysig static class System.IO.TextWriter Synchronized(class System.IO.TextWriter writer)
H
[C#]
public static TextWriter Synchronized(TextWriter writer)
I J
Summary
K
Creates a thread-safe wrapper around the specified System.IO.TextWriter instance.
L
Parameters
M N
Parameter
Description
writer
The System.IO.TextWriter to synchronize.
O P Q
Return Value
R
A thread-safe System.IO.TextWriter.
S T
Description
U
This method returns a class that wraps around the specified System.IO.TextWriter instance and restricts concurrent access to it by multiple threads.
V W
Exceptions
X Y Z
Exception
Condition
System.ArgumentNullException
writer is null.
3096
Contents | Index
System.IO
TextWriter Write() Method
TextWriter.Write(System.Boolean) Method [ILASM]
.method public hidebysig virtual void Write(bool value) [C#]
A
public virtual void Write(bool value)
B C
Summary
D
Writes the text representation of a specified System.Boolean value to the text stream.
E
Parameters
F G
Parameter
Description
value
The System.Boolean value to write.
H I J
Description
K
This version of System.IO.TextWriter.Write is equivalent to System.IO.TextWriter.Write(value.ToString()).
L M N
Exceptions
O
Exception
Condition
System.IO.IOException
An I/O error occurred.
P Q R S
TextWriter.Write(System.Char) Method
T
[ILASM]
U
.method public hidebysig virtual void Write(valuetype System.Char value)
V
[C#]
public virtual void Write(char value)
W
Summary
X
Writes a character to the text stream.
Y Z
3097
Contents | Index
TextWriter
System.IO
Write() Method
Parameters Parameter
Description
value
The System.Char to write to the text stream.
A B C D
Default
E
This method is not implemented in this abstract class.
F
Exceptions
G H I
Exception
Condition
System.IO.IOException
An I/O error occurred.
J K L
TextWriter.Write(System.Char[]) Method
M
[ILASM]
N
.method public hidebysig virtual void Write(class System.Char[] buffer)
O
public virtual void Write(char[] buffer)
[C#]
P
Summary
Q
Writes a character array to the text stream.
R
Parameters
S T
Parameter
Description
buffer
The System.Char array to write to the text stream. If buffer is null, nothing is written.
U V W X
Description
Y
This version of System.IO.TextWriter.Write is equivalent to System.IO.TextWriter.Write(buffer, 0, buffer.Length). [Note: This method does not search the specified array for individual newline characters (hexadecimal 0x000a) and replace them with System.IO.TextWriter.NewLine.]
Z
3098
Contents | Index
System.IO
TextWriter Write() Method
Exceptions Exception
Condition
System.IO.IOException
An I/O error occurred.
A B C D
TextWriter.Write(System.Char[], System.Int32, System.Int32) Method
E
[ILASM]
F
.method public hidebysig virtual void Write(class System.Char[] buffer, int32 index, int32 count)
G
[C#]
H
public virtual void Write(char[] buffer, int index, int count)
I
Summary
J
Writes a subarray of characters to the text stream.
K
Parameters
L
Parameter
Description
buffer
The character array from which characters are read.
index
Starting index in the buffer.
count
The number of characters to write.
M N O P Q R
Description
S
[Note: This method does not search the specified array for individual newline characters (hexadecimal 0x000a) and replace them with System.IO.TextWriter.NewLine.]
T U
Default
V
The default implementation uses the System.IO.TextWriter.Write(char[]) method.
W X Y Z
3099
Contents | Index
TextWriter
System.IO
Write() Method
Exceptions Exception
Condition
System.ArgumentNullException
buffer is null.
C
System.ArgumentException
(index + count) > buffer.Length.
D
System.ArgumentOutOfRangeException
index < 0 or count < 0.
E
System.IO.IOException
An I/O error occurred.
A B
F G H
TextWriter.Write(System.Decimal) Method
I
[ILASM]
.method public hidebysig virtual void Write(decimal value)
J
[C#]
public virtual void Write(decimal value)
K L
Summary
M
Writes the text representation of a specified System.Decimal to the text stream.
N
Parameters
O P
Parameter
Description
value
The System.Decimal to write.
Q R S
Description
T
This version of System.IO.TextWriter.Write is equivalent to System.IO.TextWriter.Write(value.ToString()). This member must be implemented if the Extended Numerics Library is present in the implementation.
U V W X
Exceptions
Y Z
Exception
Condition
System.IO.IOException
An I/O error occurred.
3100
Contents | Index
System.IO
TextWriter Write() Method
TextWriter.Write(System.Double) Method [ILASM]
.method public hidebysig virtual void Write(float64 value) [C#]
A
public virtual void Write(double value)
B C
Summary
D
Writes the text representation of a specified System.Double to the text stream.
E
Parameters
F
Parameter
Description
value
The System.Double to write.
G H I J
Description
K
This version of System.IO.TextWriter.Write is equivalent to System.IO.TextWriter.Write(value.ToString()). This member must be implemented if the Extended Numerics Library is present in the implementation.
L M N O
Exceptions
P
Exception
Condition
System.IO.IOException
An I/O error occurred.
Q R S T U
TextWriter.Write(System.Single) Method
V
[ILASM]
.method public hidebysig virtual void Write(float32 value)
W
[C#]
X
public virtual void Write(float value)
Y
Summary
Z
Writes the text representation of a specified System.Single to the text stream.
3101
Contents | Index
TextWriter
System.IO
Write() Method
Parameters Parameter
Description
value
The System.Single to write.
A B C
Description
D
This version of System.IO.TextWriter.Write is equivalent to System.IO.TextWriter.Write(value.ToString()). This member must be implemented if the Extended Numerics Library is present in the implementation.
E F G H
Exceptions
I J
Exception
Condition
K
System.IO.IOException
An I/O error occurred.
L M N
TextWriter.Write(System.Int32) Method
O
[ILASM]
.method public hidebysig virtual void Write(int32 value)
P
[C#]
public virtual void Write(int value)
Q R
Summary
S
Writes the text representation of a specified System.Int32 to the text stream.
T
Parameters
U V
Parameter
Description
value
The System.Int32 to write.
W X Y
Description
Z
This version of System.IO.TextWriter.Write is equivalent to System.IO.TextWriter.Write(value.ToString()).
3102
Contents | Index
System.IO
TextWriter Write() Method
Exceptions Exception
Condition
System.IO.IOException
An I/O error occurred.
A B C D
TextWriter.Write(System.Int64) Method
E [ILASM]
F
.method public hidebysig virtual void Write(int64 value) [C#]
G
public virtual void Write(long value)
H
Summary
I
Writes the text representation of a specified System.Int64 to the text stream.
J K
Parameters
L
Parameter
Description
M
value
The System.Int64 to write.
N O
Description
P
This version of System.IO.TextWriter.Write is equivalent to System.IO.TextWriter.Write(value.ToString()).
Q R S
Exceptions
T
Exception
Condition
U
System.IO.IOException
An I/O error occurred.
V W X
TextWriter.Write(System.Object) Method
Y
[ILASM]
Z
.method public hidebysig virtual void Write(object value) [C#]
public virtual void Write(object value)
3103
Contents | Index
TextWriter
System.IO
Write() Method
Summary Writes the text representation of a specified object to the text stream. A
Parameters
B C D
Parameter
Description
value
The object to write. If value is null, nothing is written.
E F
Description
G
This version of System.IO.TextWriter.Write is equivalent to System.IO.TextWriter.Write(value.ToString()).
H I
Default
J
The default implementation uses the System.IO.TextWriter.Write(System.String) method.
K L
Exceptions
M N
Exception
Condition
O
System.IO.IOException
An I/O error occurred.
P Q R
TextWriter.Write(System.String) Method
S
[ILASM]
.method public hidebysig virtual void Write(string value)
T
[C#]
public virtual void Write(string value)
U V
Summary
W
Writes a specified System.String to the text stream.
X Y Z
3104
Contents | Index
System.IO
TextWriter Write() Method
Parameters Parameter
Description
value
The System.String to write. If value is null, nothing is written.
A B C
Description
D
This version of System.IO.TextWriter.Write is equivalent to System.IO.TextWriter.Write(value.ToByteArray()). [Note: This method does not search the specified System.String for individual newline characters (hexadecimal 0x000a) and replace them with System.IO.TextWriter.NewLine.]
E F G H I
Exceptions
J
Exception
Condition
K
System.IO.IOException
An I/O error occurred.
L M N
TextWriter.Write(System.String, System.Object) Method
O
[ILASM]
P
.method public hidebysig virtual void Write(string format, object arg0) [C#]
Q
public virtual void Write(string format, object arg0)
R S
Summary
T
Writes out the format string to the text stream.
U
Parameters
V W
Parameter
Description
format
A System.String containing the format string.
Y
arg0
An object referenced in the format string.
Z
X
3105
Contents | Index
TextWriter
System.IO
Write() Method
Description This version of System.IO.TextWriter.Write is equivalent to System.IO.TextWriter.Write(System.String.Format(format, arg0)). [Note: If the specified object is not referenced in the format string, it is ignored. This method does not search the specified System.String for individual newline characters (hexadecimal 0x000a) and replace them with System.IO.TextWriter.NewLine.]
A B C D
Exceptions
E
Exception
F G
Condition format is null.
System.ArgumentNullException
H
-orAn object referenced in the format string is null.
I J
System.IO.IOException
K
An I/O error occurred. The format specification in format is invalid.
L
-orSystem.FormatException
M N
The number indicating an argument to be formatted is less than zero, or greater than or equal to the number of provided objects to be formatted (1).
O P Q
TextWriter.Write(System.String, System.Object, System.Object) Method
R
[ILASM]
S
.method public hidebysig virtual void Write(string format, object arg0, object arg1) [C#]
T
public virtual void Write(string format, object arg0, object arg1)
U V
Summary
W
Writes out a formatted string to the text stream.
X Y Z
3106
Contents | Index
System.IO
TextWriter Write() Method
Parameters Parameter
Description
format
A System.String containing the format string.
arg0
The first object referenced in the format string.
C
arg1
The second object referenced in the format string.
D
A B
E F
Description
G
This version of System.IO.TextWriter.Write is equivalent to System.IO.TextWriter.Write(System.String.Format(format, arg0, arg1)). [Note: If a specified object is not referenced in the format string, it is ignored. This method does not search the specified System.String for individual newline characters (hexadecimal 0x000a) and replace them with System.IO.TextWriter.NewLine.]
H I J K
Exceptions Exception
L M
Condition
N
format is null. System.ArgumentNullException
O
-orP
An object referenced in the format string is null.
Q System.IO.IOException
An I/O error occurred. R
The format specification in format is invalid.
S
-orSystem.FormatException
T
The number indicating an argument to be formatted is less than zero, or greater than or equal to the number of provided objects to be formatted (2).
U V W X Y Z
3107
Contents | Index
TextWriter
System.IO
Write() Method
TextWriter.Write(System.String, System.Object, System.Object, System.Object) Method [ILASM]
A
.method public hidebysig virtual void Write(string format, object arg0, object arg1, object arg2)
B
[C#]
C
public virtual void Write(string format, object arg0, object arg1, object arg2)
D
Summary
E
Writes out a formatted string to the text stream.
F G
Parameters
H I
Parameter
Description
J
format
A System.String containing the format string.
arg0
The first object referenced in the format string.
arg1
The second object referenced in the format string.
arg2
The third object referenced in the format string.
K L M N O P
Description
Q
This version of System.IO.TextWriter.Write is equivalent to System.IO.TextWriter.Write(System.String.Format(format, arg0, arg1, arg2)). [Note: If a specified object is not referenced in the format string, it is ignored. This method does not search the specified System.String for individual newline characters (hexadecimal 0x000a) and replace them with System.IO.TextWriter.NewLine.]
R S T U V W X Y Z
3108
Contents | Index
System.IO
TextWriter Write() Method
Exceptions Exception
Condition A
format is null. System.ArgumentNullException
B
-or-
C
An object referenced in the format string is null.
D System.IO.IOException
An I/O error occurred.
E
The format specification in format is invalid.
F
-orSystem.FormatException
G
The number indicating an argument to be formatted is less than zero, or greater than or equal to the number of provided objects to be formatted (3).
H I J K
TextWriter.Write(System.String, System.Object[]) Method
L [ILASM]
.method public hidebysig virtual void Write(string format, class System.Object[] arg)
M
[C#]
N
public virtual void Write(string format, params object[] arg)
O
Summary
P
Writes a formatted string to the text stream.
Q R
Parameters
S
Parameter
Description
format
A System.String containing the format string.
arg
The array of objects referenced from the format string.
T U V W X
Description
Y
This version of System.IO.TextWriter.Write is equivalent to System.IO.TextWriter.Write(System.String.Format(format, arg)).
Z
3109
Contents | Index
TextWriter
System.IO
Write() Method
[Note: If a specified object is not referenced in the format string, it is ignored. This method does not search the specified System.String for individual newline characters (hexadecimal 0x000a) and replace them with System.IO.TextWriter.NewLine.] A
Exceptions
B C
Exception
Condition
E
System.ArgumentNullException
format is null.
F
System.IO.IOException
An I/O error occurred.
D
G
The format specification in format is invalid. -or-
H System.FormatException I J
The number indicating an argument to be formatted is less than zero, or greater than or equal to arg.Length.
K L
TextWriter.Write(System.UInt32) Method
M
[ILASM]
N
.method public hidebysig virtual void Write(unsigned int32 value)
O
[C#]
public virtual void Write(uint value)
P Q
Summary
R
Writes the text representation of a System.UInt32 to the text stream.
S
Parameters
T U V
Parameter
Description
value
The System.UInt32 to write.
W X
Description
Y
This member is not CLS-compliant. For a CLS-compliant alternative, use System.IO.TextWriter.Write(System.Int64). This version of System.IO.TextWriter.Write is equivalent to System.IO.TextWriter.Write(value.ToString()).
Z
3110
Contents | Index
System.IO
TextWriter Write() Method
Exceptions Exception
Condition
System.IO.IOException
An I/O error occurred.
A B C D
TextWriter.Write(System.UInt64) Method
E
[ILASM]
F
.method public hidebysig virtual void Write(unsigned int64 value) [C#]
G
public virtual void Write(ulong value)
H
Summary
I
Writes the text representation of a specified System.UInt64 to the text stream.
J K
Parameters
L
Parameter
Description
value
The System.UInt64 to write.
M N O P
Description
Q
This member is not CLS-compliant. For a CLS-compliant alternative, use System.IO.TextWriter.Write(System.Decimal). This version of System.IO.TextWriter.Write is equivalent to System.IO.TextWriter.Write(value.ToString()).
R S T U
Exceptions
V
Exception
Condition
System.IO.IOException
An I/O error occurred.
W X Y Z
3111
Contents | Index
TextWriter
System.IO
WriteLine() Method
TextWriter.WriteLine() Method [ILASM]
.method public hidebysig virtual void WriteLine()
A
[C#]
public virtual void WriteLine()
B C
Summary
D
Writes a line terminator to the text stream.
E F
Description
G
This version of System.IO.TextWriter.WriteLine is equivalent to System.IO.TextWriter.Write(System.IO.TextWriter.NewLine.ToCharArray()).
H
Exceptions
I J K L
Exception
Condition
System.IO.IOException
An I/O error occurred.
M N
TextWriter.WriteLine(System.Boolean) Method
O
[ILASM]
P
.method public hidebysig virtual void WriteLine(bool value)
Q
[C#]
public virtual void WriteLine(bool value)
R S
Summary
T
Writes the text representation of a System.Boolean value followed by a line terminator to the text stream.
U V
Parameters
W X
Parameter
Description
Y
value
The System.Boolean value to write.
Z
3112
Contents | Index
System.IO
TextWriter WriteLine() Method
Description This version of System.IO.TextWriter.WriteLine is equivalent to System.IO.TextWriter.WriteLine(value.ToString()). This member must be implemented if the Extended Numerics Library is present in the implementation.
A B C
Exceptions
D
Exception
Condition
System.IO.IOException
An I/O error occurred.
E F G H
TextWriter.WriteLine(System.Char) Method
I
[ILASM]
J
.method public hidebysig virtual void WriteLine(valuetype System.Char value)
K
[C#]
L
public virtual void WriteLine(char value)
M
Summary
N
Writes a specified character followed by a line terminator to the text stream.
O
Parameters
P Q
Parameter
Description
value
The System.Char to write to the text stream.
R S T
Description
U
This version of System.IO.TextWriter.WriteLine is equivalent to System.IO.TextWriter.Write(value) followed by System.IO.TextWriter.WriteLine().
V W X
Exceptions
Y
Exception
Condition
System.IO.IOException
An I/O error occurred.
Z
3113
Contents | Index
TextWriter
System.IO
WriteLine() Method
TextWriter.WriteLine(System.Char[]) Method [ILASM]
.method public hidebysig virtual void WriteLine(class System.Char[] buffer)
A
[C#]
public virtual void WriteLine(char[] buffer)
B C
Summary
D
Writes a specified character array followed by a line terminator to the text stream.
E
Parameters
F G
Parameter
Description
buffer
The System.Char array from which data is read. If buffer is null, only the line terminator is written.
H I J K
Description
L
This version of System.IO.TextWriter.WriteLine is equivalent to System.IO.TextWriter.Write(value) followed by System.IO.TextWriter.WriteLine(). [Note: This method does not search the specified array for individual newline characters (hexadecimal 0x000a) and replace them with System.IO.TextWriter.NewLine.]
M N O P
Exceptions
Q R S
Exception
Condition
System.IO.IOException
An I/O error occurred.
T U V
TextWriter.WriteLine(System.Char[], System.Int32, System.Int32) Method
W
[ILASM]
X
.method public hidebysig virtual void WriteLine(class System.Char[] buffer, int32 index, int32 count) [C#]
Y
public virtual void WriteLine(char[] buffer, int index, int count)
Z
3114
Contents | Index
System.IO
TextWriter WriteLine() Method
Summary Writes a sub-array of characters from a specified character array, followed by a line terminator to the text stream. A
Parameters
B C
Parameter
Description
buffer
The System.Char array from which characters are read.
E
index
A System.Int32 that specifies the index in buffer at which to begin reading.
F
count
A System.Int32 that specifies the maximum number of characters to write.
D
G H I
Description
J
This version of System.IO.TextWriter.WriteLine is equivalent to System.IO.TextWriter.Write(value, index, count) followed by System.IO.TextWriter.WriteLine(). [Note: This method does not search the specified array for individual newline characters (hexadecimal 0x000a) and replace them with System.IO.TextWriter.NewLine.]
K L M N
Exceptions
O
Exception
Condition
System.ArgumentNullException
buffer is null.
Q
System.ArgumentException
(index + count) > buffer.Length.
R S
System.ArgumentOutOfRangeException
index < 0. -orcount < 0.
U
An I/O error occurred.
V
System.IO.IOException
P
T
W X
TextWriter.WriteLine(System.Decimal) Method
Y
[ILASM]
Z
.method public hidebysig virtual void WriteLine(decimal value) [C#]
public virtual void WriteLine(decimal value)
3115
Contents | Index
TextWriter
System.IO
WriteLine() Method
Summary Writes the text representation of a specified System.Decimal value followed by a line terminator to the text stream. A
Parameters
B C
Parameter
Description
value
The System.Decimal value to write.
D E F G
Description
H
This version of System.IO.TextWriter.WriteLine is equivalent to System.IO.TextWriter.WriteLine(value.ToString()). This member must be implemented if the Extended Numerics Library is present in the implementation.
I J K
Exceptions
L M N
Exception
Condition
System.IO.IOException
An I/O error occurred.
O P Q
TextWriter.WriteLine(System.Double) Method
R
[ILASM]
S
.method public hidebysig virtual void WriteLine(float64 value)
T
public virtual void WriteLine(double value)
[C#]
U
Summary
V
Writes the text representation of a specified System.Double value followed by a line terminator to the text stream.
W X Y Z
3116
Contents | Index
System.IO
TextWriter WriteLine() Method
Parameters Parameter
Description
value
The System.Double value to write.
A B C
Description
D
This version of System.IO.TextWriter.WriteLine is equivalent to System.IO.TextWriter.WriteLine(value.ToString()). This member must be implemented if the Extended Numerics Library is present in the implementation.
E F G H
Exceptions
I
Exception
Condition
System.IO.IOException
An I/O error occurred.
J K L M N
TextWriter.WriteLine(System.Single) Method
O
[ILASM]
.method public hidebysig virtual void WriteLine(float32 value)
P
[C#]
Q
public virtual void WriteLine(float value)
R
Summary
S
Writes the text representation of a specified System.Single value followed by a line terminator to the text stream.
T U
Parameters
V
Parameter
Description
value
The System.Single value to write.
W X Y Z
3117
Contents | Index
TextWriter
System.IO
WriteLine() Method
Description This version of System.IO.TextWriter.WriteLine is equivalent to System.IO.TextWriter.WriteLine(value.ToString()). This member must be implemented if the Extended Numerics Library is present in the implementation.
A B C
Exceptions
D E F
Exception
Condition
System.IO.IOException
An I/O error occurred.
G H I
TextWriter.WriteLine(System.Int32) Method
J
[ILASM]
.method public hidebysig virtual void WriteLine(int32 value)
K
[C#]
L
public virtual void WriteLine(int value)
M
Summary
N
Writes the text representation of a specified System.Int32 value followed by a line terminator to the text stream.
O P
Parameters
Q R
Parameter
Description
value
The System.Int32 value to write.
S T U V
Description
W
This version of System.IO.TextWriter.WriteLine is equivalent to System.IO.TextWriter.WriteLine(value.ToString()).
X Y Z
3118
Contents | Index
System.IO
TextWriter WriteLine() Method
Exceptions Exception
Condition
System.IO.IOException
An I/O error occurred.
A B C D
TextWriter.WriteLine(System.Int64) Method
E
[ILASM]
F
.method public hidebysig virtual void WriteLine(int64 value) [C#]
G
public virtual void WriteLine(long value)
H
Summary
I
Writes the text representation of a specified System.Int64 value followed by a line terminator to the text stream.
J K L
Parameters
M
Parameter
Description
value
The System.Int64 value to write.
N O P
Description
Q
This version of System.IO.TextWriter.WriteLine is equivalent to System.IO.TextWriter.WriteLine(value.ToString()).
R S T
Exceptions
U
Exception
Condition
System.IO.IOException
An I/O error occurred.
V W X Y Z
3119
Contents | Index
TextWriter
System.IO
WriteLine() Method
TextWriter.WriteLine(System.Object) Method [ILASM]
.method public hidebysig virtual void WriteLine(object value)
A
[C#]
public virtual void WriteLine(object value)
B C
Summary
D
Writes the text representation of a specified object followed by a line terminator to the text stream.
E F
Parameters
G H
Parameter
Description
value
The object to write. If value is null, only the line terminator is written.
I J K
Description
L
This version of System.IO.TextWriter.WriteLine is equivalent to System.IO.TextWriter.WriteLine(value.ToString()).
M N
Exceptions
O P
Exception
Condition
System.IO.IOException
An I/O error occurred.
Q R S T
TextWriter.WriteLine(System.String) Method
U
[ILASM]
V
.method public hidebysig virtual void WriteLine(string value) [C#]
W
public virtual void WriteLine(string value)
X
Summary
Y
Writes a specified System.String followed by a line terminator to the text stream.
Z
3120
Contents | Index
System.IO
TextWriter WriteLine() Method
Parameters Parameter
Description
value
The System.String to write. If value is null, only the line terminator is written.
A B C
Description
D
This version of System.IO.TextWriter.Write is equivalent to System.IO.TextWriter.Write(value.ToByteArray()). The line terminator string is defined by the System.IO.TextWriter.NewLine property. [Note: This method does not search the specified System.String for individual newline characters (hexadecimal 0x000a) and replace them with System.IO.TextWriter.NewLine.]
E F G H I J
Exceptions
K
Exception
Condition
System.IO.IOException
An I/O error occurred.
L M N O
TextWriter.WriteLine(System.String, System.Object) Method
P
[ILASM]
Q
.method public hidebysig virtual void WriteLine(string format, object arg0) [C#]
R
public virtual void WriteLine(string format, object arg0)
S T
Summary
U
Writes out a formatted string followed by a line terminator to the text stream.
V
Parameters
W
Parameter
Description
format
A System.String containing the format string.
arg0
The object referenced in the format string.
X Y Z
3121
Contents | Index
TextWriter
System.IO
WriteLine() Method
Description This version of System.IO.TextWriter.WriteLine is equivalent to System.IO.TextWriter.WriteLine(System.String.Format(format, arg0)). [Note: If the specified object is not referenced in the format string, it is ignored. This method does not search the specified System.String for individual newline characters (hexadecimal 0x000a) and replace them with System.IO.TextWriter.NewLine.]
A B C D
Exceptions
E
Exception
F G
Con9dition format is null.
System.ArgumentNullException
H
-orAn object referenced in the format string is null.
I J
System.IO.IOException
K
An I/O error occurred. The format specification in format is invalid.
L
-orSystem.FormatException
M N
The number indicating an argument to be formatted is less than zero, or greater than or equal to the number of provided objects to be formatted (1).
O P Q
TextWriter.WriteLine(System.String, System.Object, System.Object) Method
R
[ILASM]
S
.method public hidebysig virtual void WriteLine(string format, object arg0, object arg1) [C#]
T
public virtual void WriteLine(string format, object arg0, object arg1)
U V
Summary
W
Writes out a formatted string followed by a line terminator to the text stream.
X Y Z
3122
Contents | Index
System.IO
TextWriter WriteLine() Method
Parameters Parameter
Description
format
A System.String containing the format string.
arg0
The first object referenced in the format string.
C
arg1
The second object referenced in the format string.
D
A B
E
Description
F
This version of System.IO.TextWriter.WriteLine is equivalent to System.IO.TextWriter.WriteLine(System.String.Format(format, arg0, arg1)). [Note: If the specified object is not referenced in the format string, it is ignored. This method does not search the specified System.String for individual newline characters (hexadecimal 0x000a) and replace them with System.IO.TextWriter.NewLine.]
G H I J K
Exceptions
L
Exception
Condition
M
format is null.
N
-or-
O
An object referenced in the format string is null.
P
System.IO.IOException
An I/O error occurred.
Q R
System.FormatException
The format specification in format is invalid. -orThe number indicating an argument to be formatted is less than zero, or greater than or equal to the number of provided objects to be formatted (2).
System.ArgumentNullException
S T U V W
TextWriter.WriteLine(System.String, System.Object, System.Object, System.Object) Method
X Y
[ILASM]
.method public hidebysig virtual void WriteLine(string format, object arg0, object arg1, object arg2)
Z
[C#]
public virtual void WriteLine(string format, object arg0, object arg1, object arg2)
3123
Contents | Index
TextWriter
System.IO
WriteLine() Method
Summary Writes out a formatted string followed by a line terminator to the text stream. A
Parameters
B C
Parameter
Description
D
format
A System.String containing the format string.
arg0
The first object referenced in the format string.
arg1
The second object referenced in the format string.
arg2
The third object referenced in the format string.
E F G H I J
Description
K
This version of System.IO.TextWriter.WriteLine is equivalent to System.IO.TextWriter.WriteLine(System.String.Format(format, arg0, arg1, arg2)). If the value of any object parameter is null, it is treated as an empty string. [Note: If the specified object is not referenced in the format string, it is ignored. This method does not search the specified System.String for individual newline characters (hexadecimal 0x000a) and replace them with System.IO.TextWriter.NewLine.]
L M N O P
Exceptions
Q R S T
Exception
Condition
System.ArgumentNullException
format is null.
System.IO.IOException
An I/O error occurred.
U
The format specification in format is invalid. V
-orSystem.FormatException
W X
The number indicating an argument to be formatted is less than zero, or greater than or equal to the number of provided objects to be formatted (3).
Y Z
3124
Contents | Index
System.IO
TextWriter WriteLine() Method
TextWriter.WriteLine(System.String, System.Object[]) Method [ILASM]
.method public hidebysig virtual void WriteLine(string format, class System.Object[] arg)
A
[C#]
B
public virtual void WriteLine(string format, params object[] arg)
C
Summary
D
Writes out a formatted string followed by a line terminator to the text stream.
E F
Parameters
G H
Parameter
Description
format
A System.String containing the format string.
arg
The array of objects referenced from the format string.
I J K L
Description
M
This version of System.IO.TextWriter.WriteLine is equivalent to System.IO.TextWriter.WriteLine(System.String.Format(format, arg)). [Note: If the specified object is not referenced in the format string, it is ignored. This method does not search the specified System.String for individual newline characters (hexadecimal 0x000a) and replace them with System.IO.TextWriter.NewLine.]
O
Exceptions
R
N
P Q
S
Exception
Condition
System.ArgumentNullException
format or arg is null.
System.IO.IOException
An I/O error occurred.
T U V W
The format specification in format is invalid. System.FormatException
X
-or-
Y
The number indicating an argument to be formatted is less than zero, or greater than or equal to arg.Length.
Z
3125
Contents | Index
TextWriter
System.IO
WriteLine() Method
TextWriter.WriteLine(System.UInt32) Method [ILASM]
.method public hidebysig virtual void WriteLine(unsigned int32 value)
A
[C#]
public virtual void WriteLine(uint value)
B C
Summary
D
Writes the text representation of a specified System.UInt32 value followed by a line terminator to the text stream.
E F
Parameters
G H I
Parameter
Description
value
The System.UInt32 value to write.
J K
Description
L
This member is not CLS-compliant. For a CLS-compliant alternative, use System.IO.TextWriter.WriteLine(System.Int64). This version of System.IO.TextWriter.WriteLine is equivalent to System.IO.TextWriter.WriteLine(value.ToString()).
M N O P
Exceptions
Q R S
Exception
Condition
System.IO.IOException
An I/O error occurred.
T U
TextWriter.WriteLine(System.UInt64) Method
V W
[ILASM]
X
[C#]
.method public hidebysig virtual void WriteLine(unsigned int64 value) public virtual void WriteLine(ulong value)
Y Z
Summary Writes the text representation of a specified System.UInt64 value followed by a line terminator to the text stream. 3126
Contents | Index
System.IO
TextWriter Dispose() Method
Parameters Parameter
Description
value
The System.UInt64 value to write.
A B C
Description
D
This member is not CLS-compliant. For a CLS-compliant alternative, use System.IO.TextWriter.WriteLine(System.Decimal). This version of System.IO.TextWriter.WriteLine is equivalent to System.IO.TextWriter.WriteLine(value.ToString()).
E F G H
Exceptions
I
Exception
Condition
System.IO.IOException
An I/O error occurred.
J K L M N
IDisposable.Dispose() Method
O
[ILASM]
.method private final hidebysig virtual void System.IDisposable.Dispose()
P
[C#]
Q
void IDisposable.Dispose()
R
Summary
S
Implemented to support the System.IDisposable interface. [Note: For more information, see System.IDisposable.Dispose.]
T U V W X Y Z
3127
Contents | Index
System.Threading Thread
BCL
Object
A
Thread
B
Summary
C
Represents a sequential thread of execution.
D E
Type Summary public sealed class Thread { // Constructors public Thread (ThreadStart start);
F G H
// Properties MS CF public ApartmentState ApartmentState { set; get; } MS CF public static Context CurrentContext { get; } MS CF public static IPrincipal CurrentPrincipal { set; get; } public static Thread CurrentThread { get; } CF public bool IsAlive { get; } CF public bool IsBackground { set; get; } MS CF public bool IsThreadPoolThread { get; } CF public string Name { set; get; } public ThreadPriority Priority { set; get; } CF public ThreadState ThreadState { get; }
I J K L M N O P
// CF CF MS MS CF MS MS CF MS CF MS MS CF CF CF CF CF 1.1 CF MS CF MS
Q R S T U V W X Y Z
Methods public void Abort (); public void Abort (object stateInfo); public static LocalDataStoreSlot AllocateDataSlot (); public static LocalDataStoreSlot AllocateNamedDataSlot (string name); ~Thread () {} public static void FreeNamedDataSlot (string name); public static object GetData (LocalDataStoreSlot slot); public static AppDomain GetDomain (); public static int GetDomainID (); public static LocalDataStoreSlot GetNamedDataSlot (string name); public void Interrupt (); public void Join (); public bool Join (int millisecondsTimeout); public bool Join (TimeSpan timeout); public static void MemoryBarrier (); public static void ResetAbort (); public void Resume (); public static void SetData (LocalDataStoreSlot slot, object data);
3128
Contents | Index
System.Threading
Thread Thread Class
public static void Sleep (int millisecondsTimeout); CF public static void Sleep (TimeSpan timeout); MS CF public static void SpinWait (int iterations); public void Start (); MS CF public void Suspend (); CF 1.1 public static byte VolatileRead (ref byte address); CF 1.1 public static double VolatileRead (ref double address); CF 1.1 public static float VolatileRead (ref float address); CF 1.1 public static int VolatileRead (ref int address); CF 1.1 public static long VolatileRead (ref long address); CF 1.1 public static object VolatileRead (ref object address); CF 1.1 public static sbyte VolatileRead (ref sbyte address); CF 1.1 public static short VolatileRead (ref short address); CF 1.1 public static IntPtr VolatileRead (ref IntPtr address); CF 1.1 public static UIntPtr VolatileRead (ref UIntPtr address); CF 1.1 public static uint VolatileRead (ref uint address); CF 1.1 public static ulong VolatileRead (ref ulong address); CF 1.1 public static ushort VolatileRead (ref ushort address); CF 1.1 public static void VolatileWrite (ref byte address, byte value); CF 1.1 public static void VolatileWrite (ref double address, double value); CF 1.1 public static void VolatileWrite (ref float address, float value); CF 1.1 public static void VolatileWrite (ref int address, int value); CF 1.1 public static void VolatileWrite (ref long address, long value); CF 1.1 public static void VolatileWrite (ref object address, object value); CF 1.1 public static void VolatileWrite (ref sbyte address, sbyte value); CF 1.1 public static void VolatileWrite (ref short address, short value); CF 1.1 public static void VolatileWrite (ref IntPtr address, IntPtr value); CF 1.1 public static void VolatileWrite (ref UIntPtr address, UIntPtr value); CF 1.1 public static void VolatileWrite (ref uint address, uint value); CF 1.1 public static void VolatileWrite (ref ulong address, ulong value); CF 1.1 public static void VolatileWrite (ref ushort address, ushort value); }
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
3129
Contents | Index
Thread
System.Threading
Thread Class
BA The VolatileRead and VolatileWrite methods are a direct result of the standardization work. Many of the committee members felt these were very critical to have for enterprise applications. The product is better for their persistence.
A B
JM Notice all of the Volatile methods in the Thread class. They were not part of the original submission. Thread volatility was discussed at GREAT length within the standardization committee. We brought in outside content experts to discuss the issue. These methods were added as a result of the agreed upon memory model.
C D E F
Description
G
A process may create and execute one or more threads to execute a portion of the program code associated with the process. A System.Threading.ThreadStart delegate is used to specify the program code executed by a thread. Some operating systems might not utilize the concepts of threads or preemptive scheduling. Also, the concept of “thread priority” might not exist at all or its meaning may vary, depending on the underlying operating system. Implementers of the System.Threading.Thread type are required to describe their threading policies, including what thread priority means, how many threading priority levels exist, and whether scheduling is preemptive. For the duration of its existence, a thread is always in one or more of the states defined by System.Threading.ThreadState. A scheduling priority level, as defined by System.Threading.ThreadPriority, can be requested for a thread, but it might not be honored by the operating system. If an unhandled exception is thrown in the code executed by a thread created by an application, a System.AppDomain.UnhandledException event is raised (System.UnhandledExceptionEventArgs.IsTerminating is set to false), and the thread is terminated; the current process is not terminated.
H I J K L M N O P Q R S
Example
T
using System; using System.Threading;
U V
namespace Samples { public class ThreadSample { public static void StartHere() { Console.WriteLine("Thread starting"); Thread.Sleep(1000); Thread t = Thread.CurrentThread; Console.WriteLine("ThreadState within StartHere: {0}",
W X Y Z
3130
Contents | Index
System.Threading
Thread Thread Class
t.ThreadState); for(int i = 0; i < 10; i++) { Console.Write("."); Thread.Sleep(1000); } Console.WriteLine("\nThread finishing");
A B C
} public static void Main() { Thread t = new Thread(new ThreadStart(StartHere)); ThreadState ts = t.ThreadState; Console.WriteLine("Thread state: {0}", t.ThreadState); bool firstTime = true; t.Start(); while(ts != ThreadState.Stopped) { ThreadState tmp = t.ThreadState; if(ts != tmp) { ts = tmp; Console.WriteLine("Thread state: {0}", ts); Thread.Sleep(100); if(firstTime) { firstTime = false; t.Suspend(); } if((ts & ThreadState.Suspended) != 0) t.Resume(); } } t.Join(); }
D E F G H I J K L M N O P Q R S
} }
T
The output is
U V
Thread state: Unstarted Thread starting Thread state: WaitSleepJoin Thread state: SuspendRequested, WaitSleepJoin Thread state: WaitSleepJoin, Suspended Thread state: WaitSleepJoin ThreadState within StartHere: Running .......... Thread finishing Thread state: Stopped
W X Y Z
3131
Contents | Index
Thread
System.Threading
Thread() Constructor
Thread(System.Threading.ThreadStart) Constructor [ILASM] public rtspecialname specialname instance void .ctor(class System.Threading.ThreadStart start) [C#] public Thread(ThreadStart start)
A B C D
Summary
E
Constructs and initializes a new instance of the System.Threading.Thread class.
F
Parameters
G H
Parameter
Description
start
A System.Threading.ThreadStart delegate that references the methods to be invoked when the new thread begins executing.
I J K L
Description
M
[Note: To schedule the thread for execution, call System.Threading.Thread.Start.] Until System.Threading.Thread.Start is called, the thread’s state includes System.Threading.ThreadState.Unstarted.
N O
Exceptions
P Q R S
Exception
Condition
System.ArgumentNullException
start is null.
T U
Example
V
using System; using System.Threading;
W namespace Samples { public class ThreadConstructor { public static void StartHere() { Console.WriteLine("Thread starting");
X Y Z
3132
Contents | Index
System.Threading
Thread ApartmentState Property
Console.WriteLine("Thread finishing"); } public static void Main() { Thread t = new Thread(new ThreadStart(StartHere)); Console.WriteLine("Main starting"); t.Start(); t.Join(); Console.WriteLine("Main finishing"); }
A B C D
}
E
}
F
The output is
G H
Main starting Thread starting Thread finishing Main finishing
I J K
Thread.ApartmentState Property
L
[ILASM]
M
.property valuetype System.Threading.ApartmentState ApartmentState { public hidebysig specialname instance valuetype System.Threading.ApartmentState get_ApartmentState() public hidebysig specialname instance void set_ApartmentState(valuetype System.Threading.ApartmentState value) }
N O P
[C#]
public ApartmentState ApartmentState { get; set; }
Q R
Summary
S
Gets or sets the apartment state of this thread.
T
Property Value
U
One of the System.Threading.ApartmentState values. The initial value is Unknown.
V W
Description
X
The ApartmentState property marks a thread to indicate that it will execute in a singlethreaded or multithreaded apartment. This property can be set when the thread is in the Unstarted or Running thread state; however, it can be set only once for a thread. If the property has not been set, it returns Unknown.
Y Z
3133
Contents | Index
Thread
System.Threading
CurrentContext Property
Exceptions Exception
Condition
System.ArgumentException
An attempt is made to set this property to a state that is not a valid apartment state [a state other than single-threaded apartment (STA) or multithreaded apartment (MTA)].
A B C D E
Thread.CurrentContext Property
F
[ILASM]
G H
.property class System.Runtime.Remoting.Contexts.Context CurrentContext { public hidebysig static specialname class System.Runtime.Remoting.Contexts.Context get_CurrentContext() }
I
[C#]
public static Context CurrentContext { get; }
J K
Summary
L
Gets the current context in which the thread is executing.
M N
Property Value
O
A System.Runtime.Remoting.Contexts.Context representing the current thread context.
P
Exceptions
Q R
Exception
Condition
System.Security.SecurityException
The caller does not have the required permission.
S T U
Permissions
V W X
Permission
Description
System.Security.Permissions.SecurityPermissionAttribute
To get the current context. Associated enumerations: System.Security.Permissions.SecurityAction.LinkDemand and System.Security.Permissions.SecurityPermissionFlag.Infrastructure.
Y Z
3134
Contents | Index
System.Threading
Thread CurrentThread Property
Thread.CurrentPrincipal Property [ILASM]
.property class System.Security.Principal.IPrincipal CurrentPrincipal { public hidebysig static specialname class System.Security.Principal.IPrincipal get_CurrentPrincipal() public hidebysig static specialname void set_CurrentPrincipal(class System.Security.Principal.IPrincipal value) }
A B C
[C#]
public static IPrincipal CurrentPrincipal { get; set; }
D
Summary
E
Gets or sets the thread’s current principal (for role-based security).
F G
Property Value
H
A System.Security.Principal.IPrincipal value representing the security context.
I J
Exceptions
K
Exception
Condition
System.Security.SecurityException
The caller does not have the required permission.
L M N O
Permissions
P
Permission
Description
Q
System.Security.Permissions.SecurityPermission
To manipulate the principal object. Associated enumeration: System.Security.Permissions.SecurityPermissionFlag.ControlPrincipal.
R S T U
Thread.CurrentThread Property
V
[ILASM]
W
.property class System.Threading.Thread CurrentThread { public hidebysig static specialname class System.Threading.Thread get_CurrentThread() }
X
[C#]
Y
public static Thread CurrentThread { get; }
Z
3135
Contents | Index
Thread
System.Threading
IsAlive Property
Summary Gets a System.Threading.Thread instance that represents the currently executing thread. A
Example
B
using System; using System.Threading;
C
namespace Samples { public class ThreadCurrentThread { public static void Main() { Thread t = Thread.CurrentThread; t.Name = "firstThread"; Console.WriteLine("Name: {0}", t.Name); Console.WriteLine("IsAlive: {0}", t.IsAlive); Console.WriteLine("Priority: {0}", t.Priority); Console.WriteLine("IsBackground: {0}", t.IsBackground); Console.WriteLine("IsThreadPoolThread: {0}", t.IsThreadPoolThread); Console.WriteLine("ThreadState: {0}", t.ThreadState); } } }
D E F G H I J K L M N O
The output is
P
Name: firstThread IsAlive: True Priority: Normal IsBackground: False IsThreadPoolThread: False ThreadState: Running
Q R S T U V
Thread.IsAlive Property
W
[ILASM]
X
.property bool IsAlive { public hidebysig specialname instance bool get_IsAlive() } [C#]
Y
public bool IsAlive { get; }
Z
Summary Gets a System.Boolean value indicating the execution status of the current thread.
3136
Contents | Index
System.Threading
Thread IsAlive Property
Property Value true if this thread has been started and has not terminated; otherwise, false.
Description
A
Typically, this property returns true unless the System.Threading.Thread.ThreadState of the thread contains System.Threading.ThreadState.Unstarted or System.Threading.ThreadState.Stopped. However, due to atomicity issues or additional implementation-defined thread states, there may be times when the thread has started but has not terminated, yet the thread state has not been updated. In these cases, System.Threading.Thread.IsAlive is permitted to be true even if the System.Threading.Thread.ThreadState contains System.Threading.ThreadState.Unstarted or System.Threading.ThreadState.Stopped.
B C D E F G H
Example
I
using System; using System.Threading;
J K
namespace Samples { public class ThreadIsAlive { public static void Main() { Thread t = Thread.CurrentThread; t.Name = "firstThread"; Console.WriteLine("Name: {0}", t.Name); Console.WriteLine("IsAlive: {0}", t.IsAlive); Console.WriteLine("Priority: {0}", t.Priority); Console.WriteLine("IsBackground: {0}", t.IsBackground); Console.WriteLine("IsThreadPoolThread: {0}", t.IsThreadPoolThread); Console.WriteLine("ThreadState: {0}", t.ThreadState); } } }
L M N O P Q R S T U
The output is
V W
Name: firstThread IsAlive: True Priority: Normal IsBackground: False IsThreadPoolThread: False ThreadState: Running
X Y Z
3137
Contents | Index
Thread
System.Threading
IsBackground Property
Thread.IsBackground Property [ILASM]
.property bool IsBackground { public hidebysig specialname instance bool get_IsBackground() public hidebysig specialname instance void set_IsBackground(bool value) }
A B
[C#]
C
public bool IsBackground { get; set; }
D
Summary
E
Gets or sets a System.Boolean value indicating whether a thread is a background thread.
F G
Property Value
H
true if the thread is or is to become a background thread; otherwise, false.
I
Description
J
The default value of this property is false. The property value can be changed before the thread is started and before it terminates. [Note: A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads except for the fact that background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated, the execution engine ends the process by invoking System.Threading.Thread.Abort on any background threads that are still alive.]
K L M N O P
Exceptions
Q R S T
Exception
Condition
System.Threading.ThreadStateException
The thread has reached the System.Threading.ThreadState.Stopped state.
U V
Example
W
using System; using System.Threading;
X namespace Samples { public class ThreadIsBackground { public static void Main() {
Y Z
3138
Contents | Index
System.Threading
Thread Name Property
Thread t = Thread.CurrentThread; t.Name = "firstThread"; Console.WriteLine("Name: {0}", t.Name); Console.WriteLine("IsAlive: {0}", t.IsAlive); Console.WriteLine("Priority: {0}", t.Priority); Console.WriteLine("IsBackground: {0}", t.IsBackground); Console.WriteLine("IsThreadPoolThread: {0}", t.IsThreadPoolThread); Console.WriteLine("ThreadState: {0}", t.ThreadState);
A B C D
} }
E
}
F
The output is
G
Name: firstThread IsAlive: True Priority: Normal IsBackground: False IsThreadPoolThread: False ThreadState: Running
H I J K L
Thread.IsThreadPoolThread Property
M
[ILASM]
N
.property bool IsThreadPoolThread { public hidebysig specialname instance bool get_IsThreadPoolThread() }
O
[C#]
P
public bool IsThreadPoolThread { get; }
Q
Summary
R
Gets a value indicating whether or not a thread belongs to the managed thread pool.
S T
Property Value
U
true if this thread belongs to the managed thread pool; otherwise, false.
V W
Thread.Name Property
X
[ILASM]
Y
.property string Name { public hidebysig specialname instance string get_Name() public hidebysig specialname instance void set_Name(string value) }
Z
[C#]
public string Name { get; set; }
3139
Contents | Index
Thread
System.Threading
Name Property
Summary Gets or sets the name of the thread. A
Property Value
B
A System.String containing the name of the thread, or null if no name was set.
C D
Description
E
This property is write-once. Once this property has been set to a non-null value, attempts to set this property to a new value cause an exception.
F
Exceptions
G H
Exception
Condition
System.InvalidOperationException
A set operation was requested, and the Name property has already been set.
I J K L
Example
M
using System; using System.Threading;
N O
namespace Samples { public class ThreadName { public static void Main() { Thread t = Thread.CurrentThread; t.Name = "firstThread"; Console.WriteLine("Name: {0}", t.Name); Console.WriteLine("IsAlive: {0}", t.IsAlive); Console.WriteLine("Priority: {0}", t.Priority); Console.WriteLine("IsBackground: {0}", t.IsBackground); Console.WriteLine("IsThreadPoolThread: {0}", t.IsThreadPoolThread); Console.WriteLine("ThreadState: {0}", t.ThreadState); } } }
P Q R S T U V W X Y Z
3140
Contents | Index
System.Threading
Thread Priority Property
The output is Name: firstThread IsAlive: True Priority: Normal IsBackground: False IsThreadPoolThread: False ThreadState: Running
A B C D E
Thread.Priority Property
F [ILASM]
G
.property valuetype System.Threading.ThreadPriority Priority { public hidebysig specialname instance valuetype System.Threading.ThreadPriority get_Priority() public hidebysig specialname instance void set_Priority(valuetype System.Threading.ThreadPriority value) }
H I
[C#]
J
public ThreadPriority Priority { get; set; }
K
Summary
L
Gets or sets a value indicating the scheduling priority of a thread.
M
Property Value
N
A System.Threading.ThreadPriority value.
O P
Description
Q
A thread can be assigned any one of the following priority values:
R System.Threading.ThreadPriority.Highest System.Threading.ThreadPriority.AboveNormal System.Threading.ThreadPriority.Normal System.Threading.ThreadPriority.BelowNormal System.Threading.ThreadPriority.Lowest
S T U V
The default value is System.Threading.ThreadPriority.Normal. Operating systems are not required to honor the priority of a thread.
W X Y Z
3141
Contents | Index
Thread
System.Threading
Priority Property
Exceptions Exception
Condition
System.Threading.ThreadStateException
The thread is in the System.Threading.ThreadState.Stopped state.
System.ArgumentException
The value specified for a set operation is not a valid System.Threading.ThreadPriority value.
A B C D E F
Example
G
using System; using System.Threading;
H
namespace Samples { public class ThreadPriority { public static void Main() { Thread t = Thread.CurrentThread; t.Name = "firstThread"; Console.WriteLine("Name: {0}", t.Name); Console.WriteLine("IsAlive: {0}", t.IsAlive); Console.WriteLine("Priority: {0}", t.Priority); Console.WriteLine("IsBackground: {0}", t.IsBackground); Console.WriteLine("IsThreadPoolThread: {0}", t.IsThreadPoolThread); Console.WriteLine("ThreadState: {0}", t.ThreadState); } } }
I J K L M N O P Q R S T U
The output is
V Name: firstThread IsAlive: True Priority: Normal IsBackground: False IsThreadPoolThread: False ThreadState: Running
W X Y Z
3142
Contents | Index
System.Threading
Thread ThreadState Property
Thread.ThreadState Property [ILASM]
.property valuetype System.Threading.ThreadState ThreadState { public hidebysig specialname instance valuetype System.Threading.ThreadState get_ThreadState() }
A
[C#]
B
public ThreadState ThreadState { get; }
C
Summary
D
Gets a value containing the states of the current thread.
E F
Property Value
G
A combination of one or more System.Threading.ThreadState values, which indicate the state of the current thread.
H I
Description
J
A thread is running if the value returned by this property does not include System.Threading.ThreadState.Unstarted and does not include System.Threading.ThreadState.Stopped.
K L M
Example
N
using System; using System.Threading;
O P
namespace Samples { public class ThreadThreadState { public static void Main() { Thread t = Thread.CurrentThread; t.Name = "firstThread"; Console.WriteLine("Name: {0}", t.Name); Console.WriteLine("IsAlive: {0}", t.IsAlive); Console.WriteLine("Priority: {0}", t.Priority); Console.WriteLine("IsBackground: {0}", t.IsBackground); Console.WriteLine("IsThreadPoolThread: {0}", t.IsThreadPoolThread); Console.WriteLine("ThreadState: {0}", t.ThreadState); } } }
Q R S T U V W X Y Z
3143
Contents | Index
Thread
System.Threading
Abort() Method
The output is Name: firstThread IsAlive: True Priority: Normal IsBackground: False IsThreadPoolThread: False ThreadState: Running
A B C D E
Thread.Abort() Method
F
[ILASM]
.method public hidebysig instance void Abort()
G
[C#]
H
public void Abort()
I
Summary
J
Raises a System.Threading.ThreadAbortException in the thread on which it is invoked to begin the process of terminating the thread. In all but the most extraordinary situations, calling this method will terminate the thread.
K L
Description
M
When this method is invoked on a thread, the system throws a System.Threading.ThreadAbortException in the thread to abort it. Invoking System.Threading.Thread.Abort on a thread is similar to arranging for the target thread to throw a System.Threading.ThreadAbortException. Because, unlike other exceptions, a System.Threading.ThreadAbortException is sent to another thread, the exception might be delayed. A System.Threading.ThreadAbortException is required to be delayed if and while the target thread is executing any of the following:
N O P Q R S
• • • • •
T U V W
unmanaged code a catch handler a finally clause a filter clause a type initializer A thread abort begins at the earliest of the following times:
X Y
• • •
Z
when the thread transitions from unmanaged to managed code execution when the thread finishes the outermost currently executing catch handler immediately if the thread is running managed code outside of any catch handler, finally clause, filter clause or type initializer
3144
Contents | Index
System.Threading
Thread Abort() Method
Whenever an outermost catch handler finishes execution, the System.Threading.ThreadAbortException is rethrown unless the thread being aborted has called System.Threading.Thread.ResetAbort since the call to System.Threading.Thread.Abort. When all finally blocks have been called and the thread is about to transition to any unmanaged code that executed before the first entry to managed code, System.Threading.Thread.ResetAbort is called so that a return to managed code will consider the abort to have been successfully processed. Unexecuted finally blocks are executed before the thread is aborted; this includes any finally block that is executing when the exception is thrown. The thread is not guaranteed to abort immediately, or at all. This situation can occur if a thread does an unbounded amount of computation in the finally blocks that are called as part of the abort procedure, thereby indefinitely delaying the abort. To ensure a thread has aborted, invoke System.Threading.Thread.Join on the thread after calling System.Threading.Thread.Abort. If System.Threading.Thread.Abort is called on a thread that has not been started, the thread aborts when System.Threading.Thread.Start is called. If the target thread is blocked or sleeping in managed code and is not inside any of the code blocks that are required to delay an abort, the thread is resumed and immediately aborted. After System.Threading.Thread.Abort is invoked on a thread, the state of the thread includes System.Threading.ThreadState.AbortRequested. After the thread has terminated as a result of a successful call to System.Threading.Thread.Abort, the state of the thread includes System.Threading.ThreadState.Stopped and System.Threading.ThreadState.Aborted. [Note: With sufficient permissions, a thread that is the target of a System.Threading.Thread.Abort can cancel the abort using the System.Threading.Thread.ResetAbort method. For an example that demonstrates calling the System.Threading.Thread.ResetAbort method, see System.Threading.ThreadAbortException.]
A B C D E F G H I J K L M N O P Q R S
Exceptions
T U
Exception
Condition V
System.Security.SecurityException
Caller does not have System.Security.Permissions.SecurityPermissionFlag.ControlThread security permission for the thread to be aborted.
W X Y Z
3145
Contents | Index
Thread
System.Threading
Abort() Method
Permissions Permission
Description
System.Security.SecurityPermission
Requires permission to control the thread to be aborted. See System.Security.Permissions.SecurityPermissionFlag.ControlThread.
A B C D E
Example
F
using System; using System.Threading;
G namespace Samples { public class ThreadAbort { public static void StartHere() { try { Console.WriteLine("Thread starting"); Thread.Sleep(1000); Console.WriteLine("Thread finishing"); } catch(ThreadAbortException e) { Console.WriteLine("Exception: {0}", e); } finally { Console.WriteLine("In finally"); } } public static void Main() { Thread t = new Thread( new ThreadStart(StartHere)); Console.WriteLine("Main starting"); t.Start(); Thread.Sleep(500); t.Abort(); t.Join(); Console.WriteLine("Main finishing"); } } }
H I J K L M N O P Q R S T U V W X Y Z
3146
Contents | Index
System.Threading
Thread Abort() Method
The output is Main starting Thread starting Exception: System.Threading.ThreadAbortException: Thread was being aborted. at System.Threading.Thread.Sleep(Int32 millisecondsTimeout) at Samples.ThreadAbort.StartHere() in C:\Books\BCL\Samples\System.Threading\ Thread\Abort()\Thread.cs:line 13 In finally Main finishing
A B C D E
Thread.Abort(System.Object) Method
F
[ILASM]
G
.method public hidebysig instance void Abort(object stateInfo)
H
[C#]
I
public void Abort(object stateInfo)
J
Summary
K
Raises a System.Threading.ThreadAbortException in the thread on which it is invoked to begin the process of terminating the thread. In all but the most extraordinary situations, calling this method will terminate the thread.
L M N
Parameters
O
Parameter
Description
stateInfo
A System.Object that contains application-specific information, such as state, which can be used by the thread being aborted.
P Q R S
Description
T
The object passed as the stateInfo parameter can be obtained by accessing the System.Threading.ThreadAbortException.Exceptionstate property. [Note: For details on aborting threads, see System.Threading.Thread.Abort().]
U V W
Exceptions
X
Exception
Condition
Y
System.Security.SecurityException
Caller does not have System.Security.Permissions.SecurityPermissionFlag.ControlThread security permission for this thread.
Z
3147
Contents | Index
Thread
System.Threading
Abort() Method
Permissions Permission
Description
System.Security.SecurityPermission
Requires permission to control the thread to be aborted. See System.Security.Permissions.SecurityPermissionFlag.ControlThread.
A B C D E
Example
F
using System; using System.Threading;
G namespace Samples { public class ThreadAbort { public static void StartHere() { try { Console.WriteLine("Thread starting"); Thread.Sleep(1000); Console.WriteLine("Thread finishing"); } catch(ThreadAbortException e) { string s = (string) e.ExceptionState; Console.WriteLine(s); } finally { Console.WriteLine("In finally"); } } public static void Main() { Thread t = new Thread( new ThreadStart(StartHere)); Console.WriteLine("Main starting"); t.Start(); Thread.Sleep(500); t.Abort("Time to go"); t.Join(); Console.WriteLine("Main finishing"); } } }
H I J K L M N O P Q R S T U V W X Y Z
3148
Contents | Index
System.Threading
Thread AllocateNamedDataSlot() Method
The output is Main starting Thread starting Time to go In finally Main finishing
A B C D
Thread.AllocateDataSlot() Method
E
[ILASM]
F
.method public hidebysig static class System.LocalDataStoreSlot AllocateDataSlot()
G
[C#]
public static LocalDataStoreSlot AllocateDataSlot()
H
Summary
I
Allocates an unnamed data slot on all the threads.
J K
Description
L
The slot is allocated on all threads. Threads use a local store memory mechanism to store thread-specific data. The common language runtime allocates a multi-slot data store array to each process when it is created. The thread can allocate a data slot in the data store, store and retrieve a data value in the slot, and free the slot for reuse after the thread expires. Data slots are unique per thread. No other thread (not even a child thread) can get that data.
M N O P Q R
Thread.AllocateNamedDataSlot(System.String) Method
S
[ILASM]
T
.method public hidebysig static class System.LocalDataStoreSlot AllocateNamedDataSlot(string name)
U
[C#]
V
public static LocalDataStoreSlot AllocateNamedDataSlot(string name)
W
Summary
X
Allocates a named data slot on all threads.
Y Z
3149
Contents | Index
Thread
System.Threading
Finalize() Method
Parameters Parameter
Description
name
The name of the data slot to be allocated.
A B C
Description
D
Threads use a local store memory mechanism to store thread-specific data. The common language runtime allocates a multi-slot data store array to each process when it is created. The thread can allocate a data slot in the data store, store and retrieve a data value in the slot, and free the slot for reuse after the thread expires. Data slots are unique per thread. No other thread (not even a child thread) can get that data. Slots allocated with this method must be freed with System.Threading.Thread.FreeNamedDataSlot.
E F G H I J K
Thread.Finalize() Method
L [ILASM]
M
.method family hidebysig virtual void Finalize()
N
[C#]
~Thread()
O P
Summary
Q
Releases the resources held by this instance.
R
Description
S
[Note: Application code does not call this method; it is automatically invoked during garbage collection.]
T U V
Thread.FreeNamedDataSlot(System.String) Method
W
[ILASM]
.method public hidebysig static void FreeNamedDataSlot(string name)
X
[C#]
Y
public static void FreeNamedDataSlot(string name)
Z
Summary Eliminates the association between a name and a slot, for all threads in the process. 3150
Contents | Index
System.Threading
Thread GetData() Method
Parameters Parameter
Description
name
The name of the data slot to be freed.
A B C
Description
D
After any thread calls FreeNamedDataSlot, any other thread that calls System.Threading.Thread.GetNamedDataSlot with the same name will allocate a new slot associated with the name. Subsequent calls to GetNamedDataSlot by any thread will return the new slot. However, any thread that still has a System.LocalDataStoreSlot returned by an earlier call to GetNamedDataSlot can continue to use the old slot. A slot that has been associated with a name is released only when every LocalDataStoreSlot that was obtained prior to the call to FreeNamedDataSlot has been released and garbage-collected. Threads use a local store memory mechanism to store thread-specific data. The common language runtime allocates a multi-slot data store array to each process when it is created. The thread can allocate a data slot in the data store, store and retrieve a data value in the slot, and free the slot for reuse after the thread expires. Data slots are unique per thread. No other thread (not even a child thread) can get that data.
E F G H I J K L M N O
Thread.GetData(System.LocalDataStoreSlot) Method
P
[ILASM]
Q
.method public hidebysig static object GetData(class System.LocalDataStoreSlot slot)
R
[C#]
public static object GetData(LocalDataStoreSlot slot)
S
Summary
T
Retrieves the value from the specified slot on the current thread, within the current thread’s current domain.
U V W
Parameters
X
Parameter
Description
slot
The System.LocalDataStoreSlot from which to get the value.
Y Z
3151
Contents | Index
Thread
System.Threading
GetDomain() Method
Description Threads use a local store memory mechanism to store thread-specific data. The common language runtime allocates a multi-slot data store array to each process when it is created. The thread can allocate a data slot in the data store, store and retrieve a data value in the slot, and free the slot for reuse after the thread expires. Data slots are unique per thread. No other thread (not even a child thread) can get that data.
A B C D
Thread.GetDomain() Method
E
[ILASM]
F
.method public hidebysig static class System.AppDomain GetDomain()
G
[C#]
public static AppDomain GetDomain()
H I
Summary
J
Returns an object representing the application domain in which the current thread is executing.
K L
Return Value
M
A System.AppDomain object that represents the current application domain. This member must be implemented if the Runtime Infrastructure Library is present in the implementation.
N O P
Example
Q
using System; using System.Threading;
R
namespace Samples { public class ThreadGetDomain { public static void Main() { AppDomain ad = Thread.GetDomain(); Console.WriteLine("FriendlyName: {0}", ad.FriendlyName); Console.WriteLine("BaseDirectory: {0}", ad.BaseDirectory); } } }
S T U V W X Y
The output is
Z
FriendlyName: Thread.exe BaseDirectory: C:\Books\BCL\Samples\System.Threading\Thread\GetDomain()\
3152
Contents | Index
System.Threading
Thread GetNamedDataSlot() Method
Thread.GetDomainID() Method [ILASM]
.method public hidebysig static int32 GetDomainID() [C#]
A
public static int GetDomainID()
B C
Summary
D
Returns a unique application domain identifier.
E
Return Value
F
A 32-bit signed integer uniquely identifying the application domain.
G H
Thread.GetNamedDataSlot(System.String) Method
I
[ILASM]
J
.method public hidebysig static class System.LocalDataStoreSlot GetNamedDataSlot(string name)
K
[C#]
L
public static LocalDataStoreSlot GetNamedDataSlot(string name)
M
Summary
N
Looks up a named data slot.
O P
Parameters
Q
Parameter
Description
R
name
The name of the local data slot.
S T U
Return Value
V
A System.LocalDataStoreSlot allocated for this thread.
W
Description
X
Threads use a local store memory mechanism to store thread-specific data. The common language runtime allocates a multi-slot data store array to each process when it is created. The thread can allocate a data slot in the data store, store and retrieve a data value in the slot, and free the slot for reuse after the thread expires. Data slots are unique per thread. No other thread (not even a child thread) can get that data.
Y Z
3153
Contents | Index
Thread
System.Threading
Interrupt() Method
If the named slot does not exist, a new slot is allocated. Named data slots are public and can be manipulated by anyone. A B
Thread.Interrupt() Method
C
[ILASM]
.method public hidebysig instance void Interrupt()
D
[C#]
public void Interrupt()
E F
Summary
G
Interrupts a thread that is in the WaitSleepJoin thread state.
H I
Description
J
If this thread is not currently blocked in a wait, sleep, or join state, it will be interrupted when it next begins to block.
K
Exceptions
L M
Exception
Condition
System.Security.SecurityException
The caller does not have the appropriate System.Security.Permissions.SecurityPermission.
N O P Q
Permissions
R S
Permission
Description
T
System.Security.Permissions.SecurityPermission Attribute
for advanced operations on threads. Associated enumeration: System.Security.Permissions.SecurityPermissionFlag.ControlThread.
U V W X
Thread.Join() Method
Y
[ILASM]
.method public hidebysig instance void Join()
Z
[C#]
public void Join()
3154
Contents | Index
System.Threading
Thread Join() Method
Summary Blocks the calling thread until the thread on which this method is invoked terminates.
Description
A
[Note: Use this method to ensure a thread has terminated. The caller will block indefinitely if the thread does not terminate.] System.Threading.Thread.Join cannot be invoked on a thread that is in the System.Threading.ThreadState.Unstarted state. This method changes the state of the calling thread to include System.Threading.ThreadState.WaitSleepJoin.
B C D E F
Exceptions
G H
Exception
Condition
System.Threading.ThreadStateException
The caller attempted to join a thread that is in the System.Threading.ThreadState.Unstarted state.
I J K L
Example
M
using System; using System.Threading;
N O
namespace Samples { public class ThreadJoin { public static void StartHere() { Console.WriteLine("Thread starting"); Thread.Sleep(1000); Console.WriteLine("Thread finishing"); } public static void Main() { Thread t = new Thread( new ThreadStart(StartHere)); Console.WriteLine("Main starting"); t.Start(); t.Join(); Console.WriteLine("Main finishing"); } } }
P Q R S T U V W X Y Z
3155
Contents | Index
Thread
System.Threading
Join() Method
The output is Main starting Thread starting Thread finishing Main finishing
A B C D
Thread.Join(System.Int32) Method
E
[ILASM]
.method public hidebysig instance bool Join(int32 millisecondsTimeout)
F
[C#]
G
public bool Join(int millisecondsTimeout)
H
Summary
I
Blocks the calling thread until the thread on which this method is invoked terminates or the specified time elapses.
J K
Parameters
L M
Parameter
Description
millisecondsTimeout
A System.Int32 containing the number of milliseconds to wait for the thread to terminate.
N O P Q
Return Value
R
true if the thread has terminated; false if the thread has not terminated after millisecondsTimeout has elapsed.
S T
Description
U
[Note: If System.Threading.Timeout.Infinite is specified for millisecondsTimeout, this method behaves identically to Join(), except for the return value.] Join cannot be invoked on a thread that is in the System.Threading.ThreadState.Unstarted state. This method changes the state of the calling thread to include System.Threading.ThreadState.WaitSleepJoin.
V W X Y Z
3156
Contents | Index
System.Threading
Thread Join() Method
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
The value of millisecondsTimeout is negative and is not equal to System.Threading.Timeout.Infinite.
System.Threading.ThreadStateException
The caller attempted to join a thread that is in the System.Threading.ThreadState.Unstarted state.
A B C D E
Example
F
using System; using System.Threading;
G H
namespace Samples { public class ThreadJoin { public static void StartHere() { Console.WriteLine("Thread starting"); Thread.Sleep(1000); Console.WriteLine("Thread finishing"); } public static void Main() { Thread t = new Thread( new ThreadStart(StartHere)); Console.WriteLine("Main starting"); t.Start(); Console.WriteLine("Joined: {0}", t.Join(500)); Console.WriteLine("Joined: {0}", t.Join(1000)); Console.WriteLine("Main finishing"); } } }
I J K L M N O P Q R S T U V
The output is
W
Main starting Thread starting Joined: False Thread finishing Joined: True Main finishing
X Y Z
3157
Contents | Index
Thread
System.Threading
Join() Method
Thread.Join(System.TimeSpan) Method [ILASM]
.method public hidebysig instance bool Join(valuetype System.TimeSpan timeout)
A
[C#]
public bool Join(TimeSpan timeout)
B C
Summary
D
Blocks the calling thread until the thread on which this method is invoked terminates or the specified time elapses.
E F
Parameters
G H
Parameter
Description
timeout
A System.TimeSpan set to the amount of time to wait for the thread to terminate. Specify System.Threading.Timeout.Infinite milliseconds to wait indefinitely.
I J K L M
Return Value
N
true if the thread has terminated; false if the thread has not terminated after the amount of time specified by timeout has elapsed.
O
Description
P
This method converts timeout to milliseconds, tests the validity of the converted value, and calls System.Threading.Thread.Join(System.Int32). [Note: If System.Threading.Timeout.Infinite milliseconds is specified for timeout, this method behaves identically to Join(), except for the return value.] Join cannot be invoked on a thread that is in the System.Threading.ThreadState.Unstarted state. This method changes the state of the current thread to include System.Threading.ThreadState.WaitSleepJoin.
Q R S T U V W X Y Z
3158
Contents | Index
System.Threading
Thread Join() Method
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
The value of timeout is negative and is not equal to System.Threading.Timeout.Infinite milliseconds, or is greater than System.Int32.MaxValue milliseconds.
System.Threading.ThreadStateException
The caller attempted to join a thread that is in the System.Threading.ThreadState.Unstarted state.
A B C D E F G
Example
H
using System; using System.Threading;
I J
namespace Samples { public class ThreadJoin { public static void StartHere() { Console.WriteLine("Thread starting"); Thread.Sleep(1000); Console.WriteLine("Thread finishing"); } public static void Main() { Thread t = new Thread(new ThreadStart(StartHere)); Console.WriteLine("Main starting"); t.Start(); TimeSpan ts = new TimeSpan(0,0,0,1); Console.WriteLine("Joined: {0}", t.Join(ts)); Console.WriteLine("Joined: {0}", t.Join(Timeout.Infinite)); Console.WriteLine("Main finishing"); } } }
K L M N O P Q R S T U V W X Y Z
3159
Contents | Index
Thread
System.Threading
MemoryBarrier() Method
The output is Main starting Thread starting Thread finishing Joined: True Joined: True Main finishing
A B C D E
Thread.MemoryBarrier() Method
F [ILASM]
G
.method public hidebysig static void MemoryBarrier ()
H
[C#]
public static void MemoryBarrier ()
I
Summary
J
Guarantees that all subsequent loads or stores from the current thread will not access memory until after all previous loads and stores from the current thread have completed, as observed from this or other threads.
K L M N
Thread.ResetAbort() Method
O
[ILASM]
P
.method public hidebysig static void ResetAbort() [C#]
Q
public static void ResetAbort()
R S
Summary
T
Cancels a System.Threading.Thread.Abort requested for the current thread.
U
Description
V
This method cannot be called by untrusted code. When a call is made to System.Threading.Thread.Abort to destroy a thread, the system throws a System.Threading.ThreadAbortException. System.Threading.ThreadAbortException is a special exception that can be caught by application code, but is rethrown at the end of the catch block unless ResetAbort is called. ResetAbort cancels the request to abort, and prevents the ThreadAbortException from terminating the thread.
W X Y Z
3160
Contents | Index
System.Threading
Thread ResetAbort() Method
Exceptions Exception
Condition
System.Threading.ThreadStateException
System.Threading.Thread.Abort was not invoked on the current thread.
System.Security.SecurityException
Caller does not have System.Security.Permissions.SecurityPermissionFlag.ControlThread security permission for the current thread.
A B C D E F
Permissions
G
Permission
Description
System.Security.SecurityPermission
Requires permission to control the current thread. See System.Security.Permissions.SecurityPermissionFlag.ControlThread.
H I J K L
Example
M
using System; using System.Threading;
N O
namespace Samples { public class ThreadResetAbort { public static void StartHere() { try { Console.WriteLine("Thread starting"); Thread.Sleep(1000); Console.WriteLine("Thread finishing normally"); } catch(ThreadAbortException e) { Console.WriteLine("Exception: {0}", e); Thread.ResetAbort(); } finally { Console.WriteLine("In finally"); } Console.WriteLine("Thread finishing after exception");
P Q R S T U V W X Y Z
3161
Contents | Index
Thread
System.Threading
Resume() Method
} public static void Main() { Thread t = new Thread(new ThreadStart(StartHere)); Console.WriteLine("Main starting"); t.Start(); Thread.Sleep(500); t.Abort(); t.Join(); Console.WriteLine("Main finishing"); }
A B C D E
} }
F
The output is
G H
Main starting Thread starting Exception: System.Threading.ThreadAbortException: Thread was being aborted. at System.Threading.Thread.Sleep(Int32 millisecondsTimeout) at Samples.ThreadResetAbort.StartHere() in C:\Books\BCL\Samples\ System.Threading\Thread\ResetAbort()\Thread.cs:line 13 In finally Thread finishing after exception Main finishing
I J K L M N O
Thread.Resume() Method
P
[ILASM]
.method public hidebysig instance void Resume()
Q
[C#]
R
public void Resume()
S
Summary
T
Resumes a thread that has been suspended.
U
Exceptions
V W
Exception
Condition
System.Threading.ThreadStateException
The thread has not been started, is dead, or is not in the suspended state.
System.Security.SecurityException
The caller does not have the appropriate System.Security.Permissions.SecurityPermission.
X Y Z
3162
Contents | Index
System.Threading
Thread SetData() Method
Permissions Permission
Description
System.Security.Permissions.SecurityPermissionAttribute
For advanced operations on threads. Associated enumeration: System.Security.Permissions.SecurityPermissionFlag.ControlThread.
A B C D E
Thread.SetData(System.LocalDataStoreSlot, System.Object) Method
F [ILASM]
G
.method public hidebysig static void SetData(class System.LocalDataStoreSlot slot, object data)
H
[C#]
I
public static void SetData(LocalDataStoreSlot slot, object data)
J
Summary
K
Sets the data in the specified slot on the currently running thread, for that thread’s current domain.
L M
Parameters
N
Parameter
Description
slot
The System.LocalDataStoreSlot in which to set the value.
data
The value to be set.
O P Q R S
Description
T
Threads use a local store memory mechanism to store thread-specific data. The common language runtime allocates a multi-slot data store array to each process when it is created. The thread can allocate a data slot in the data store, store and retrieve a data value in the slot, and free the slot for reuse after the thread expires. Data slots are unique per thread. No other thread (not even a child thread) can get that data.
U V W X Y Z
3163
Contents | Index
Thread
System.Threading
Sleep() Method
Thread.Sleep(System.Int32) Method [ILASM]
.method public hidebysig static void Sleep(int32 millisecondsTimeout)
A
[C#]
public static void Sleep(int millisecondsTimeout)
B C
Summary
D
Blocks the current thread for the specified number of milliseconds.
E
Parameters
F G
Parameter
Description
millisecondsTimeout
A System.Int32 containing the number of milliseconds for which the thread is blocked. Specify zero to indicate that this thread should be suspended temporarily to allow other waiting threads to execute. Specify System.Threading.Timeout.Infinite to block the thread indefinitely.
H I J K L M
Description
N
The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include System.Threading.ThreadState.WaitSleepJoin.
O P
Exceptions
Q R S T
Exception
Condition
System.ArgumentOutOfRangeException
The value of millisecondsTimeout is negative and is not equal to System.Threading.Timeout.Infinite.
U V W
Example
X
using System; using System.Threading;
Y
namespace Samples { public class ThreadSleep {
Z
3164
Contents | Index
System.Threading
Thread Sleep() Method
public static void StartHere() { Console.WriteLine("Thread starting"); Thread.Sleep(1000); Console.WriteLine("Thread finishing"); } public static void Main() { Thread t = new Thread( new ThreadStart(StartHere)); Console.WriteLine("Main starting"); t.Start(); t.Join(); Console.WriteLine("Main finishing"); }
A B C D E F G H
} }
I
The output is
J
Main starting Thread starting Thread finishing Main finishing
K L M N O
Thread.Sleep(System.TimeSpan) Method
P
[ILASM]
.method public hidebysig static void Sleep(valuetype System.TimeSpan timeout)
Q
[C#]
R
public static void Sleep(TimeSpan timeout)
S
Summary
T
Blocks the current thread for a specified time.
U
Parameters
V W
Parameter
Description
timeout
A System.TimeSpan set to the amount of time for which the current thread will be blocked. Specify zero to indicate that this thread should be suspended temporarily to allow other waiting threads to execute. Specify System.Threading.Timeout.Infinite milliseconds to suspend the thread indefinitely.
X Y Z
3165
Contents | Index
Thread
System.Threading
Sleep() Method
Description This method converts timeout to milliseconds, tests the validity of the converted value, and calls System.Threading.Thread.Sleep(System.Int32). The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include System.Threading.ThreadState.WaitSleepJoin.
A B C D
Exceptions
E F G H
Exception
Condition
System.ArgumentOutOfRangeException
The value of timeout is negative and is not equal to System.Threading.Timeout.Infinite milliseconds, or is greater than System.Int32.MaxValue milliseconds.
I J
Example
K
using System; using System.Threading;
L
namespace Samples { public class ThreadSleep { public static void StartHere() { Console.WriteLine("Thread starting"); TimeSpan ts = new TimeSpan(0, 0, 0, 5); Thread.Sleep(ts); Console.WriteLine("Thread finishing"); } public static void Main() { Thread t = new Thread(new ThreadStart(StartHere)); Console.WriteLine("Main starting"); t.Start(); t.Join(); Console.WriteLine("Main finishing"); } } }
M N O P Q R S T U V W X Y
The output is
Z
Main starting Thread starting
3166
Contents | Index
System.Threading
Thread Start() Method
Thread.SpinWait(System.Int32) Method [ILASM]
.method public hidebysig static void SpinWait(int32 iterations) [C#]
A
public static void SpinWait(int iterations)
B C
Summary
D
Causes a thread to wait the number of times defined by the iterations parameter.
E
Parameters
F
Parameter
Description
iterations
A 32-bit signed integer that defines how long a thread is to wait.
G H I J K
Thread.Start() Method
L
[ILASM]
M
.method public hidebysig instance void Start() [C#]
N
public void Start()
O
Summary
P
Causes the operating system to consider the thread ready to be scheduled for execution.
Q
Description
R
Calling System.Threading.Thread.Start removes the System.Threading.ThreadState.Unstarted state from the System.Threading.Thread.ThreadState of the thread. Once a thread is started, the operating system can schedule it for execution. When the thread begins executing, the System.Threading.ThreadStart delegate supplied to the constructor for the thread invokes its methods. Once the thread terminates, it cannot be restarted with another call to System.Threading.Thread.Start.
S T U V W X Y Z
3167
Contents | Index
Thread
System.Threading
Start() Method
Exceptions Exception
Condition
System.OutOfMemoryException
There is not enough memory available to start the thread.
System.NullReferenceException
This method was invoked on a null thread reference.
System.Threading.ThreadStateException
The thread has already been started.
A B C D E F G
Example
H
using System; using System.Threading;
I namespace Samples { public class ThreadStart { public static void StartHere() { Console.WriteLine("Thread starting"); Thread.Sleep(1000); Console.WriteLine("Thread finishing"); } public static void Main() { Thread t = new Thread(new ThreadStart(StartHere)); Console.WriteLine("Main starting"); t.Start(); t.Join(); Console.WriteLine("Main finishing"); } } }
J K L M N O P Q R S T U V
The output is
W
Main starting Thread starting Thread finishing Main finishing
X Y Z
3168
Contents | Index
System.Threading
Thread VolatileRead() Method
Thread.Suspend() Method [ILASM]
.method public hidebysig instance void Suspend() [C#]
A
public void Suspend()
B C
Summary
D
Either suspends the thread, or if the thread is already suspended, has no effect.
E
Exceptions Exception
F G
Condition
H System.Threading.ThreadStateException
The thread has not been started or is dead.
System.Security.SecurityException
The caller does not have the appropriate System.Security.Permissions.SecurityPermission.
I J K L M
Permissions
N
Permission
Description
O
System.Security.Permissions.SecurityPermissionAttribute
For advanced operations on threads. Associated enumeration: System.Security.Permissions.SecurityPermissionFlag.ControlThread.
P Q R S
Thread.VolatileRead(System.Byte&) Method
T
[ILASM]
U
.method public hidebysig static byte VolatileRead (class System.Byte& address)
V
[C#]
public static byte VolatileRead (ref byte address)
W X
Summary
Y
Performs a volatile read from the specified address.
Z
3169
Contents | Index
Thread
System.Threading
VolatileRead() Method
Parameters Parameter
Description
address
A System.Byte that specifies the address in memory from which to read.
A B C D
Return Value
E
A System.Byte containing the value at the specified address after any pending writes.
F
Description
G
The value at the given address is atomically loaded with acquire semantics, meaning that the read is guaranteed to occur prior to any references to memory that occur after the execution of this method in the current thread. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileWrite if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the load IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
H I J K L M N O P
Thread.VolatileRead(System.Double&) Method
Q
[ILASM]
R
.method public hidebysig static float64 VolatileRead (class System.Double& address)
S
[C#]
public static double VolatileRead (ref double address)
T U
Summary
V
Performs a volatile read from the specified address.
W
Parameters
X Y Z
Parameter
Description
address
A System.Double that specifies the address in memory from which to read.
3170
Contents | Index
System.Threading
Thread VolatileRead() Method
Return Value A System.Double containing the value at the specified address after any pending writes.
Description
A
The value at the given address is atomically loaded with acquire semantics, meaning that the read is guaranteed to occur prior to any references to memory that occur after the execution of this method in the current thread. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileWrite if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the load IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
B C D E F G H I J
Thread.VolatileRead(System.Single&) Method
K
[ILASM]
L
.method public hidebysig static float32 VolatileRead (class System.Single& address) [C#]
M
public static float VolatileRead (ref float address)
N O
Summary
P
Performs a volatile read from the specified address.
Q
Parameters
R
Parameter
Description
address
A System.Single that specifies the address in memory from which to read.
S T U V
Return Value
W
A System.Single containing the value at the specified address after any pending writes.
X Y
Description
Z
The value at the given address is atomically loaded with acquire semantics, meaning that the read is guaranteed to occur prior to any references to memory that occur after the execution of this method in the current thread. It is recommended that System.Thread3171
Contents | Index
Thread
System.Threading
VolatileRead() Method
ing.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileWrite if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the load IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
A B C D E
Thread.VolatileRead(System.Int32&) Method
F [ILASM]
G
.method public hidebysig static int32 VolatileRead (class System.Int32& address)
H
[C#]
public static int VolatileRead (ref int address)
I J
Summary
K
Performs a volatile read from the specified address.
L
Parameters
M N O
Parameter
Description
address
A System.Int32 that specifies the address in memory from which to read.
P Q
Return Value
R
A System.Int32 containing the value at the specified address after any pending writes.
S
Description
T
The value at the given address is atomically loaded with acquire semantics, meaning that the read is guaranteed to occur prior to any references to memory that occur after the execution of this method in the current thread. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileWrite if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the load IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
U V W X Y Z
3172
Contents | Index
System.Threading
Thread VolatileRead() Method
Thread.VolatileRead(System.Int64&) Method [ILASM]
.method public hidebysig static int64 VolatileRead (class System.Int64& address) [C#]
A
public static long VolatileRead (ref long address)
B C
Summary
D
Performs a volatile read from the specified address.
E
Parameters
F
Parameter
Description
address
A System.Int64 that specifies the address in memory from which to read.
G H I J
Return Value
K
A System.Int64 containing the value at the specified address after any pending writes.
L M
Description
N
The value at the given address is atomically loaded with acquire semantics, meaning that the read is guaranteed to occur prior to any references to memory that occur after the execution of this method in the current thread. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileWrite if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the load IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
O P Q R S T U V
Thread.VolatileRead(System.Object&) Method
W
[ILASM]
X
.method public hidebysig static object VolatileRead (class System.Object& address)
Y
[C#]
Z
public static object VolatileRead (ref object address)
3173
Contents | Index
Thread
System.Threading
VolatileRead() Method
Summary Performs a volatile read from the specified address. A
Parameters
B C
Parameter
Description
D
address
A System.Object that specifies the address in memory from which to read.
E F
Return Value
G
A System.Object containing the value at the specified address after any pending writes.
H
Description
I
The value at the given address is atomically loaded with acquire semantics, meaning that the read is guaranteed to occur prior to any references to memory that occur after the execution of this method in the current thread. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileWrite if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the load IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
J K L M N O P Q R
Thread.VolatileRead(System.SByte&) Method
S [ILASM]
T
.method public hidebysig static sbyte VolatileRead (class System.Sbyte& address)
U
[C#]
public static sbyte VolatileRead (ref sbyte address)
V W
Summary
X
Performs a volatile read from the specified address.
Y Z
3174
Contents | Index
System.Threading
Thread VolatileRead() Method
Parameters Parameter
Description
address
A System.SByte that specifies the address in memory from which to read.
A B C
Return Value
D
A System.SByte containing the value at the specified address after any pending writes.
E F
Description
G
The value at the given address is atomically loaded with acquire semantics, meaning that the read is guaranteed to occur prior to any references to memory that occur after the execution of this method in the current thread. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileWrite if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the load IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
H I J K L M N O
Thread.VolatileRead(System.Int16&) Method
P
[ILASM]
Q
.method public hidebysig static int16 VolatileRead (class System.Int16& address)
R
[C#]
S
public static short VolatileRead (ref short address)
T
Summary
U
Performs a volatile read from the specified address.
V
Parameters
W X
Parameter
Description
address
A System.Int16 that specifies the address in memory from which to read.
Y Z
3175
Contents | Index
Thread
System.Threading
VolatileRead() Method
Return Value A System.Int16 containing the value at the specified address after any pending writes. A
Description
B
The value at the given address is atomically loaded with acquire semantics, meaning that the read is guaranteed to occur prior to any references to memory that occur after the execution of this method in the current thread. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileWrite if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the load IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
C D E F G H I J K
Thread.VolatileRead(System.IntPtr&) Method
L
[ILASM]
.method public hidebysig static intptr VolatileRead (class System.IntPtr& address)
M
[C#]
public static IntPtr VolatileRead (ref IntPtr address)
N O
Summary
P
Performs a volatile read from the specified address.
Q
Parameters
R S
Parameter
Description
address
A System.IntPtr that specifies the address in memory from which to read.
T U V W
Return Value
X
A System.IntPtr containing the value at the specified address after any pending writes.
Y
Description
Z
The value at the given address is atomically loaded with acquire semantics, meaning that the read is guaranteed to occur prior to any references to memory that occur after the execution of this method in the current thread. It is recommended that System.Thread3176
Contents | Index
System.Threading
Thread VolatileRead() Method
ing.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileWrite if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the load IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.] This member must be implemented if the Runtime Infrastructure Library is present in the implementation.
A B C D E F
Thread.VolatileRead(System.UIntPtr&) Method
G
[ILASM]
H
.method public hidebysig static uintPtr VolatileRead (class System.UIntPtr& address) [C#]
I
public static UIntPtr VolatileRead (ref UIntPtr address)
J K
Summary
L
Performs a volatile read from the specified address.
M
Parameters
N
Parameter
Description
address
A System.UIntPtr that specifies the address in memory from which to read.
O P Q R
Return Value
S
A System.UIntPtr containing the value at the specified address after any pending writes.
T U
Description
V
The value at the given address is atomically loaded with acquire semantics, meaning that the read is guaranteed to occur prior to any references to memory that occur after the execution of this method in the current thread. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileWrite if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the load IL instruction, except
W X Y Z
3177
Contents | Index
Thread
System.Threading
VolatileRead() Method
that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.] This member must be implemented if the Runtime Infrastructure Library is present in the implementation.
A B C
Thread.VolatileRead(System.UInt32&) Method
D [ILASM]
E
.method public hidebysig static uint32 VolatileRead (class System.UInt32& address) [C#]
F
public static uint VolatileRead (ref uint address)
G
Summary
H
Performs a volatile read from the specified address.
I J
Parameters
K L
Parameter
Description
M
address
A System.UInt32 that specifies the address in memory from which to read.
N O
Return Value
P
A System.UInt32 containing the value at the specified address after any pending writes.
Q
Description
R
The value at the given address is atomically loaded with acquire semantics, meaning that the read is guaranteed to occur prior to any references to memory that occur after the execution of this method in the current thread. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileWrite if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the load IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
S T U V W X Y Z
3178
Contents | Index
System.Threading
Thread VolatileRead() Method
Thread.VolatileRead(System.UInt64&) Method [ILASM]
.method public hidebysig static uint64 VolatileRead (class System.UInt64& address) [C#]
A
public static ulong VolatileRead (ref ulong address)
B C
Summary
D
Performs a volatile read from the specified address.
E
Parameters
F
Parameter
Description
address
A System.UInt64 that specifies the address in memory from which to read.
G H I J
Return Value
K
A System.UInt64 containing the value at the specified address after any pending writes.
L M
Description
N
The value at the given address is atomically loaded with acquire semantics, meaning that the read is guaranteed to occur prior to any references to memory that occur after the execution of this method in the current thread. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileWrite if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the load IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
O P Q R S T U V
Thread.VolatileRead(System.UInt16&) Method
W
[ILASM]
X
.method public hidebysig static uint16 VolatileRead (class System.UInt16& address)
Y
[C#]
Z
public static ushort VolatileRead (ref ushort address)
3179
Contents | Index
Thread
System.Threading
VolatileWrite() Method
Summary Performs a volatile read from the specified address. A
Parameters
B C
Parameter
Description
D
address
A System.UInt16 that specifies the address in memory from which to read.
E F
Return Value
G
A System.UInt16 containing the value at the specified address after any pending writes.
H
Description
I
The value at the given address is atomically loaded with acquire semantics, meaning that the read is guaranteed to occur prior to any references to memory that occur after the execution of this method in the current thread. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileWrite if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the load IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
J K L M N O P Q R
Thread.VolatileWrite(System.Byte&, System.Byte) Method
S
[ILASM]
T
.method public hidebysig static void VolatileWrite (class System.Byte& address, byte value)
U
[C#]
V
public static void VolatileWrite (ref byte address, byte value)
W
Summary
X
Performs a volatile write to the specified address.
Y Z
3180
Contents | Index
System.Threading
Thread VolatileWrite() Method
Parameters Parameter
Description
address
A System.Byte that specifies the address in memory at which to write.
value
A System.Byte that specifies the value to write.
A B C D
Description
E
The value is written atomically to the specified address with release semantics, meaning that the write is guaranteed to happen after any references to memory that occur prior to the execution. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileRead if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the store IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
F G H I J K L M
Thread.VolatileWrite(System.Double&, System.Double) Method
N
[ILASM]
O
.method public hidebysig static void VolatileWrite (class System.Double& address, float64 value)
P
[C#]
Q
public static void VolatileWrite (ref double address, double value)
R
Summary
S
Performs a volatile write to the specified address.
T U
Parameters
V
Parameter
Description
address
A System.Double that specifies the address in memory at which to write.
value
A System.Double that specifies the value to write.
W X Y Z
3181
Contents | Index
Thread
System.Threading
VolatileWrite() Method
Description The value is written atomically to the specified address with release semantics, meaning that the write is guaranteed to happen after any references to memory that occur prior to the execution. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileRead if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the store IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
A B C D E F G H
Thread.VolatileWrite(System.Single&, System.Single) Method
I [ILASM]
J
.method public hidebysig static void VolatileWrite (class System.Single& address, float32 value)
K
[C#]
L
public static void VolatileWrite (ref float address, float value)
M
Summary
N
Performs a volatile write to the specified address.
O
Parameters
P Q
Parameter
Description
S
address
A System.Single that specifies the address in memory at which to write.
T
value
A System.Single that specifies the value to write.
R
U V
Description
W
The value is written atomically to the specified address with release semantics, meaning that the write is guaranteed to happen after any references to memory that occur prior to the execution. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileRead if the volatile semantics are to be preserved. This method has exactly the same semantics as
X Y Z
3182
Contents | Index
System.Threading
Thread VolatileWrite() Method
using the volatile prefix on the store IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.] A B
Thread.VolatileWrite(System.Int32&, System.Int32) Method
C
[ILASM]
D
.method public hidebysig static void VolatileWrite (class System.Int32& address, int32 value)
E
[C#]
F
public static void VolatileWrite (ref int address, int value)
G
Summary
H
Performs a volatile write to the specified address.
I J
Parameters
K
Parameter
Description
address
A System.Int32 that specifies the address in memory at which to write.
value
A System.Int32 that specifies the value to write.
L M N O P
Description
Q
The value is written atomically to the specified address with release semantics, meaning that the write is guaranteed to happen after any references to memory that occur prior to the execution. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileRead if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the store IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
R S T U V W X Y Z
3183
Contents | Index
Thread
System.Threading
VolatileWrite() Method
Thread.VolatileWrite(System.Int64&, System.Int64) Method [ILASM]
A
.method public hidebysig static void VolatileWrite (class System.Int64& address, int64 value)
B
[C#]
public static void VolatileWrite (ref long address, long value)
C D
Summary
E
Performs a volatile write to the specified address.
F
Parameters
G H I
Parameter
Description
address
A System.Int64 that specifies the address in memory at which to write.
value
A System.Int64 that specifies the value to write.
J K L
Description
M
The value is written atomically to the specified address with release semantics, meaning that the write is guaranteed to happen after any references to memory that occur prior to the execution. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileRead if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the store IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
N O P Q R S T U V
Thread.VolatileWrite(System.Object&, System.Object) Method
W
[ILASM]
X
.method public hidebysig static void VolatileWrite (class System.Object& address, object value)
Y
[C#]
public static void VolatileWrite (ref object address, object value)
Z
3184
Contents | Index
System.Threading
Thread VolatileWrite() Method
Summary Performs a volatile write to the specified address. A
Parameters
B
Parameter
Description
C
address
A System.Object that specifies the address in memory at which to write.
D
value
A System.Object that specifies the value to write.
E F G
Description
H
The value is written atomically to the specified address with release semantics, meaning that the write is guaranteed to happen after any references to memory that occur prior to the execution. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileRead if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the store IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
I J K L M N O P Q
Thread.VolatileWrite(System.SByte&, System.SByte) Method
R
[ILASM]
S
.method public hidebysig static void VolatileWrite (class System.SByte& address, sbyte value) [C#]
T
public static void VolatileWrite (ref sbyte address, sbyte value)
U V
Summary
W
Performs a volatile write to the specified address.
X Y Z
3185
Contents | Index
Thread
System.Threading
VolatileWrite() Method
Parameters Parameter
Description
address
A System.SByte that specifies the address in memory at which to write.
value
A System.SByte that specifies the value to write.
A B C D E
Description
F
The value is written atomically to the specified address with release semantics, meaning that the write is guaranteed to happen after any references to memory that occur prior to the execution. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileRead if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the store IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
G H I J K L M N O
Thread.VolatileWrite(System.Int16&, System.Int16) Method
P
[ILASM]
Q
.method public hidebysig static void VolatileWrite (class System.Int16& address, int16 value) [C#]
R
public static void VolatileWrite (ref short address, short value)
S T
Summary
U
Performs a volatile write to the specified address.
V
Parameters
W X
Parameter
Description
Y
address
A System.Int16 that specifies the address in memory at which to write.
value
A System.Int16 that specifies the value to write.
Z
3186
Contents | Index
System.Threading
Thread VolatileWrite() Method
Description The value is written atomically to the specified address with release semantics, meaning that the write is guaranteed to happen after any references to memory that occur prior to the execution. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileRead if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the store IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.] This member must be implemented if the Runtime Infrastructure Library is present in the implementation.
A B C D E F G H I
Thread.VolatileWrite(System.IntPtr&, System.IntPtr) Method
J
[ILASM]
.method public hidebysig static void VolatileWrite (class System.IntPtr& address, IntPtr value)
K L
[C#]
public static void VolatileWrite (ref IntPtr address, IntPtr value)
M
Summary
N
Performs a volatile write to the specified address.
O P
Parameters
Q
Parameter
Description
address
A System.IntPtr that specifies the address in memory at which to write.
value
A System.IntPtr that specifies the value to write.
R S T U V
Description
W
The value is written atomically to the specified address with release semantics, meaning that the write is guaranteed to happen after any references to memory that occur prior to the execution. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileRead if the
X Y Z
3187
Contents | Index
Thread
System.Threading
VolatileWrite() Method
volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the store IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.] This member must be implemented if the Runtime Infrastructure Library is present in the implementation.
A B C D E
Thread.VolatileWrite(System.UIntPtr&, System.UIntPtr) Method
F
[ILASM]
G
.method public hidebysig static void VolatileWrite (class System.UIntPtr& address, UIntPtr value) [C#]
H
public static void VolatileWrite (ref UIntPtr address, UIntPtr value)
I
Summary
J
Performs a volatile write to the specified address.
K L
Parameters
M
Parameter
Description
O
address
A System.UIntPtr that specifies the address in memory at which to write.
P
value
A System.UIntPtr that specifies the value to write.
N
Q R
Description
S
The value is written atomically to the specified address with release semantics, meaning that the write is guaranteed to happen after any references to memory that occur prior to the execution. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileRead if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the store IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.] This member must be implemented if the Runtime Infrastructure Library is present in the implementation.
T U V W X Y Z
3188
Contents | Index
System.Threading
Thread VolatileWrite() Method
Thread.VolatileWrite(System.UInt32&, System.UInt32) Method [ILASM]
.method public hidebysig static void VolatileWrite (class System.UInt32& address, uint32 value)
A
[C#]
B
public static void VolatileWrite (ref uint address, uint value)
C
Summary
D
Performs a volatile write to the specified address.
E
Parameters
F G
Parameter
Description
address
A System.UInt32 that specifies the address in memory at which to write.
value
A System.UInt32 that specifies the value to write.
H I J K L
Description
M
The value is written atomically to the specified address with release semantics, meaning that the write is guaranteed to happen after any references to memory that occur prior to the execution. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileRead if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the store IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
N O P Q R S T U
Thread.VolatileWrite(UInt64&, System.UInt64) Method
V
[ILASM]
W
.method public hidebysig static void VolatileWrite (class System.UInt64& address, uint64 value)
X
[C#]
Y
public static void VolatileWrite (ref ulong address, ulong value)
Z
Summary Performs a volatile write to the specified address. 3189
Contents | Index
Thread
System.Threading
VolatileWrite() Method
Parameters Parameter
Description
address
A System.UInt64 that specifies the address in memory at which to write.
value
A System.UInt64 that specifies the value to write.
A B C D E
Description
F
The value is written atomically to the specified address with release semantics, meaning that the write is guaranteed to happen after any references to memory that occur prior to the execution. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileRead if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the store IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
G H I J K L M N
Thread.VolatileWrite(System.UInt16&, System.UInt16) Method
O
[ILASM]
P
.method public hidebysig static void VolatileWrite (class System.UInt16& address, uint16 value) [C#]
Q
public static void VolatileWrite (ref ushort address, ushort value)
R
Summary
S
Performs a volatile write to the specified address.
T
Parameters
U V
Parameter
Description
address
A System.UInt16 that specifies the address in memory at which to write.
value
A System.UInt16 that specifies the value to write.
W X Y Z
3190
Contents | Index
System.Threading
Thread VolatileWrite() Method
Description The value is written atomically to the specified address with release semantics, meaning that the write is guaranteed to happen after any references to memory that occur prior to the execution. It is recommended that System.Threading.Thread.VolatileRead and System.Threading.Thread.VolatileWrite be used in conjunction. Calling this method affects only this single access; other accesses to the same location are required to also be made using this method or System.Threading.Thread.VolatileRead if the volatile semantics are to be preserved. This method has exactly the same semantics as using the volatile prefix on the store IL instruction, except that atomicity is provided for all types, not just those 32 bits or smaller in size. [Note: For additional information, see Partition I of the CLI Specification.]
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
3191
Contents | Index
System.Threading ThreadAbortException
BCL
Object
A
Exception
B
ISerializable
NotStandardized
SystemException ThreadAbortException
C D
Summary
E
Thrown by the system when a call is made to System.Threading.Thread.Abort.
F
Type Summary
G
CF public sealed class ThreadAbortException : SystemException { // Properties CF public object ExceptionState { get; } }
H I J K
Description
L
Instances of this exception type can only be created by the system. When a call is made to System.Threading.Thread.Abort to terminate a thread, the system throws a System.Threading.ThreadAbortException in the target thread. System.Threading.ThreadAbortException is a special exception that can be caught by application code, but is rethrown at the end of the catch block unless System.Threading.Thread.ResetAbort is called. When the ThreadAbortException exception is raised, the system executes any finally blocks for the target thread. The finally blocks are executed even if System.Threading.Thread.ResetAbort is called. If the abort is successful, the target thread is left in the System.Threading.ThreadState.Stopped and System.Threading.ThreadState.Aborted states.
M N O P Q R S T U
Example
V
using System; using System.Threading;
W
namespace Samples { public class ThreadAbortExceptionSample { public static void StartHere() { try {
X Y Z
3192
Contents | Index
System.Threading
ThreadAbortException ExceptionState Property
Console.WriteLine("Thread starting"); Thread.Sleep(1000); Console.WriteLine("Thread finishing"); } catch(ThreadAbortException e) { string s = (string) e.ExceptionState; Console.WriteLine(s); } finally { Console.WriteLine("In finally"); }
A B C D E F
} public static void Main() { Thread t = new Thread( new ThreadStart(StartHere)); Console.WriteLine("Main starting"); t.Start(); Thread.Sleep(500); t.Abort("Time to go"); t.Join(); Console.WriteLine("Main finishing"); }
G H I J K L M N
} }
O
The output is
P Q
Main starting Thread starting Time to go In finally Main finishing
R S T U
ThreadAbortException.ExceptionState Property
V
[ILASM]
W
.property object ExceptionState { public hidebysig specialname instance object get_ExceptionState() }
X
[C#]
Y
public object ExceptionState { get; }
Z
3193
Contents | Index
ThreadAbortException
System.Threading
ExceptionState Property
Summary Gets an object that contains application-specific information related to the thread abort. A
Description
B
The object returned by this property is specified via the stateInfo parameter of System.Threading.Thread.Abort. This property returns null if no object was specified, or the System.Threading.Thread.Abort method with no parameters was called. The exact content and usage of this object are application-defined; they are typically used to convey information that is meaningful to the thread being aborted.
C D E F G H I J K L M N O P Q R S T U V W X Y Z
3194
Contents | Index
System.Threading ThreadPriority Enum
BCL
Object
A
IComparable
ValueType Enum
B
IFormattable ThreadPriority
IConvertible
NotStandardized
C D
Summary
E
Specifies the scheduling priority of a System.Threading.Thread.
F G
Type Summary public enum ThreadPriority AboveNormal = 3, BelowNormal = 1, Highest = 4, Lowest= 0, Normal= 2, }
{
H I J K L
Description
M
System.Threading.ThreadPriority values specify the relative scheduling priority of threads. Operating systems are not guaranteed to support preemptive scheduling. Also, the concept of “thread priority” may not exist at all or its meaning may vary, depending on the underlying operating system. Implementers of this type are required to describe how the notion of thread priority maps to operating system priority. For more information about threads, see the System.Threading.Thread class. The System.Threading.Thread.Priority property sets and returns the priority value information for a thread. Applications can request a scheduling priority for a thread by setting the System.Threading.Thread.Priority property to the appropriate ThreadPriority value. The default thread priority is System.Threading.ThreadPriority.Normal. [Note: A thread cannot be scheduled if it is in the System.Threading.ThreadState.Unstarted state or the System.Threading.ThreadState.Stopped state.]
N O P Q R S T U V W X Y Z
3195
Contents | Index
ThreadPriority Enum
System.Threading
ThreadPriority Enum
Example using System; using System.Threading;
A namespace Samples { public class ThreadPrioritySample { public static void StartHere() { ThreadPriority[] tps = {ThreadPriority.AboveNormal, ThreadPriority.BelowNormal, ThreadPriority.Normal, ThreadPriority.Highest, ThreadPriority.Lowest}; Thread t = Thread.CurrentThread; foreach(ThreadPriority tp in tps) { t.Priority = tp; Console.WriteLine("ThreadPriority: {0}", t.Priority); } } public static void Main() { Thread t = new Thread( new ThreadStart(StartHere)); Console.WriteLine("Main starting"); t.Start(); t.Join(); Console.WriteLine("Main finishing"); } } }
B C D E F G H I J K L M N O P Q R S T U
The output is
V
Main starting ThreadPriority: ThreadPriority: ThreadPriority: ThreadPriority: ThreadPriority: Main finishing
W X Y Z
AboveNormal BelowNormal Normal Highest Lowest
3196
Contents | Index
System.Threading
ThreadPriority Enum Lowest Field
ThreadPriority.AboveNormal Field [ILASM]
.field public static literal valuetype System.Threading.ThreadPriority AboveNormal
A
[C#]
B
AboveNormal = 3
C
Summary
D
Threads with this priority may be scheduled after threads with System.Threading.ThreadPriority.Highest priority and before those with System.Threading.ThreadPriority.Normal priority.
E F G H
ThreadPriority.BelowNormal Field
I [ILASM]
.field public static literal valuetype System.Threading.ThreadPriority BelowNormal
J
[C#]
K
BelowNormal = 1
L
Summary
M
Threads with this priority may be scheduled after threads with System.Threading.ThreadPriority.Normal priority, and before those with System.Threading.ThreadPriority.Lowest priority.
N O P Q
ThreadPriority.Highest Field
R [ILASM]
S
.field public static literal valuetype System.Threading.ThreadPriority Highest [C#]
T
Highest = 4
U
Summary
V
Threads with this priority may be scheduled before threads with any other priority.
W X
ThreadPriority.Lowest Field
Y
[ILASM]
Z
.field public static literal valuetype System.Threading.ThreadPriority Lowest [C#]
Lowest = 0
3197
Contents | Index
ThreadPriority Enum
System.Threading
Normal Field
Summary Threads with this priority may be scheduled after threads with any other priority. A B
ThreadPriority.Normal Field
C
[ILASM]
.field public static literal valuetype System.Threading.ThreadPriority Normal
D
[C#]
Normal = 2
E F
Summary
G
Threads with this priority may be scheduled after threads with System.Threading.ThreadPriority.AboveNormal priority and before those with System.Threading.ThreadPriority.BelowNormal priority. Threads have System.Threading.ThreadPriority.Normal priority by default.
H I J K L M N O P Q R S T U V W X Y Z
3198
Contents | Index
System.Threading ThreadStart Delegate
BCL
Object ICloneable
A
Delegate ISerializable MulticastDelegate
NotStandardized
NotStandardized
B
ThreadStart
C D
Summary
E
Defines the shape of methods that are called when a System.Threading.Thread is started.
F G
Type Summary
H
public delegate void ThreadStart ();
I J
JR It is a pity that this delegate wasn’t defined with an Object parameter, allowing
K
the creator of the thread to pass some initialization data into the new thread. To get initialization data into a new thread, you need to define a class, add fields to the class, and add the thread method (whose prototype matches this delegate) to this class. Then, when you want to create a thread, you construct an instance of the object, set the fields to the desired initialization data, and new up the Thread object, passing the ThreadStart delegate wrapped around the thread method that’s defined in the class. When the thread starts running, it can access the fields.
L M N O P Q
Description
R
[Note: A new instance of the System.Threading.Thread class is created using a constructor that takes a System.Threading.ThreadStart delegate as its only parameter. When System.Threading.Thread.Start is invoked and the thread begins executing, all of the methods in the invocation list of the specified delegate are invoked in the execution context of the thread. If a method in the invocation list receives an unhandled exception, the thread is terminated, but not the process that contains the thread.] [Note: For an example that demonstrates creating a ThreadStart delegate, see System.Threading.Thread.Start.]
S T U V W X Y Z
3199
Contents | Index
ThreadStart Delegate
System.Threading
ThreadStart Delegate
Example using System; using System.Threading;
A namespace Samples { public class ThreadStartSample { public static void StartHere() { Console.WriteLine("Thread starting"); Thread.Sleep(1000); Console.WriteLine("Thread finishing"); } public static void Main() { Console.WriteLine("Main starting"); Thread t = new Thread( new ThreadStart(StartHere)); t.Start(); t.Join(); Console.WriteLine("Main finishing"); } } }
B C D E F G H I J K L M N
The output is
O P
Main starting Thread starting Thread finishing Main finishing
Q R S T U V W X Y Z
3200
Contents | Index
System.Threading ThreadState Enum
BCL
Object
A
IComparable
ValueType Enum
B
IFormattable ThreadState
IConvertible
NotStandardized
C D
Summary
E
Specifies the execution states of a System.Threading.Thread.
F G
Type Summary CF public enum ThreadState { CF Aborted = 0x100, CF AbortRequested = 0x80, CF Background = 0x4, CF Running = 0x0, CF Stopped = 0x10, CF StopRequested = 0x1, CF Suspended = 0x40, CF SuspendRequested = 0x2, CF Unstarted = 0x8, CF WaitSleepJoin= 0x20, }
H I J K L M N O
Description
P
System.Threading.ThreadState defines the set of possible execution states for threads. Once a thread is created, it is in one or more of these states until it terminates. Not all combinations of ThreadState values are valid; for example, a thread cannot be in both the System.Threading.ThreadState.Stopped and System.Threading.ThreadState.Unstarted states. The following table shows the actions that cause a thread to change state.
Q R S T U V
Action
ThreadState after Action
The thread is created.
Unstarted
System.Threading.Thread.Start is invoked on the thread.
Running
The thread calls System.Threading.Thread.Sleep.
WaitSleepJoin
W X Y Z
3201
Contents | Index
ThreadState Enum
System.Threading
ThreadState Enum
Action
ThreadState after Action
The thread calls System.Threading.Monitor.Wait to wait on an object.
WaitSleepJoin
The thread calls System.Threading.Thread.Join to wait for another thread to terminate.
WaitSleepJoin
The System.Threading.ThreadStart delegate methods finish executing.
Stopped
AbortRequested
G
Another thread requests the thread to System.Threading.Thread.Abort.
H
The thread accepts a System.Threading.Thread.Abort request.
Aborted
A B C D E F
I J
In addition to the states noted above, there is also the System.Threading.ThreadState.Background state, which indicates whether the thread is running in the background or foreground. The current state of a thread can be retrieved from the System.Threading.Thread.ThreadState property, whose value is a combination of the System.Threading.ThreadState values. Once a thread has reached the System.Threading.ThreadState.Stopped state, it cannot change to any other state.
K L M N O P Q
Example
R
using System; using System.Threading;
S
namespace Samples { public class ThreadStateSample { public static void StartHere() { Console.WriteLine("Thread: starting"); Thread.Sleep(1000); Thread t = Thread.CurrentThread; Console.WriteLine("ThreadState: {0}", t.ThreadState); for(int i = 0; i < 40; i++) Console.Write("."); Console.WriteLine(); Thread.Sleep(1000);
T U V W X Y Z
3202
Contents | Index
System.Threading
ThreadState Enum ThreadState Enum
Console.WriteLine("Thread: finishing"); } public static void Main() { Thread t = new Thread( new ThreadStart(StartHere)); Console.WriteLine("1) Thread state: {0}", t.ThreadState); t.Start(); Thread.Sleep(100); Console.WriteLine("2) Thread state: {0}", t.ThreadState); t.Suspend(); Console.WriteLine("3) Thread state: {0}", t.ThreadState); Thread.Sleep(1000); Console.WriteLine("4) Thread state: {0}", t.ThreadState); t.Resume(); Console.WriteLine("5) Thread state: {0}", t.ThreadState); Console.WriteLine("6) Thread state: {0}", t.ThreadState); t.Join(); Console.WriteLine("7) Thread state: {0}", t.ThreadState); }
A B C D E F G H I J K L M N O
} }
P Q
The output is
R 1) Thread state: Unstarted Thread: starting 2) Thread state: WaitSleepJoin 3) Thread state: SuspendRequested, WaitSleepJoin 4) Thread state: WaitSleepJoin, Suspended 5) Thread state: WaitSleepJoin 6) Thread state: WaitSleepJoin ThreadState: Running ........................................ Thread: finishing 7) Thread state: Stopped
S T U V W X Y Z
3203
Contents | Index
ThreadState Enum
System.Threading
Aborted Field
ThreadState.Aborted Field [ILASM]
.field public static literal valuetype System.Threading.ThreadState Aborted
A
[C#]
B
Aborted = 0x100
C
Summary
D
The thread represented by an instance of System.Threading.Thread has terminated as a result of a call to System.Threading.Thread.Abort. A thread in this state is also in the System.Threading.ThreadState.Stopped state.
E F G
ThreadState.AbortRequested Field
H
[ILASM]
I
.field public static literal valuetype System.Threading.ThreadState AbortRequested [C#]
J
AbortRequested = 0x80
K
Summary
L
The System.Threading.Thread.Abort method has been invoked on the thread, but the thread has not yet received the pending System.Threading.ThreadAbortException that will attempt to terminate it.
M N O P
ThreadState.Background Field
Q
[ILASM]
.field public static literal valuetype System.Threading.ThreadState Background
R
[C#]
S
Background = 0x4
T
Summary
U
The thread represented by an instance of System.Threading.Thread is being executed as a background thread, as opposed to a foreground thread. [Note: This state is controlled by setting the System.Threading.Thread.IsBackground property.]
V W X Y
ThreadState.Running Field
Z
[ILASM]
.field public static literal valuetype System.Threading.ThreadState Running [C#]
Running = 0x0
3204
Contents | Index
System.Threading
ThreadState Enum Suspended Field
Summary The thread represented by an instance of System.Threading.Thread has been started and has not terminated. To determine if a thread is running, check that its state does not include System.Threading.ThreadState.Unstarted and does not include System.Threading.ThreadState.Stopped.
A B C D
ThreadState.Stopped Field
E
[ILASM]
F
.field public static literal valuetype System.Threading.ThreadState Stopped
G
[C#]
Stopped = 0x10
H
Summary
I
The thread represented by an instance of System.Threading.Thread has terminated.
J K
ThreadState.StopRequested Field
L
[ILASM]
M
.field public static literal valuetype System.Threading.ThreadState StopRequested
N
[C#]
O
StopRequested = 0x1
P
Summary
Q
The thread is being requested to stop. This is for internal use only.
R S
ThreadState.Suspended Field
T
[ILASM]
U
.field public static literal valuetype System.Threading.ThreadState Suspended
V
[C#]
W
Suspended = 0x40
X
Summary
Y
The thread has been suspended.
Z
3205
Contents | Index
ThreadState Enum
System.Threading
SuspendRequested Field
ThreadState.SuspendRequested Field [ILASM]
.field public static literal valuetype System.Threading.ThreadState SuspendRequested
A
[C#]
B
SuspendRequested = 0x2
C D
Summary
E
The thread is being requested to suspend.
F G
ThreadState.Unstarted Field
H
[ILASM]
.field public static literal valuetype System.Threading.ThreadState Unstarted
I
[C#]
Unstarted = 0x8
J K
Summary
L
The System.Threading.Thread.Start method has not been invoked on the thread.
M N
ThreadState.WaitSleepJoin Field
O P
[ILASM]
Q
[C#]
.field public static literal valuetype System.Threading.ThreadState WaitSleepJoin WaitSleepJoin = 0x20
R S
Summary
T
The thread represented by an instance of System.Threading.Thread is blocked as a result of a call to System.Threading.Monitor.Wait, System.Threading.Thread.Sleep, or System.Threading.Thread.Join.
U V W X Y Z
3206
Contents | Index
System.Threading ThreadStateException
BCL
Object Exception
ISerializable
A
NotStandardized
B
SystemException ThreadStateException
C D
Summary
E
Represents errors that occur when a method is invoked on a System.Threading.Thread and the thread is in a System.Threading.Thread.ThreadState that is invalid for the method.
F G H
Type Summary
I
public class ThreadStateException : SystemException { // Constructors public ThreadStateException (); public ThreadStateException (string message); public ThreadStateException (string message, Exception innerException); MS CF protected ThreadStateException (SerializationInfo info, StreamingContext context); }
J K L M N O
Description
P
Once a thread is created, it is in one or more states, as defined by System.Threading.ThreadState, until it terminates. System.Threading.ThreadStateException is thrown by methods that cannot perform the requested operation due to the current state of a thread. For example, calling System.Threading.Thread.Start on a thread that has terminated results in a System.Threading.ThreadStateException exception.
Q R S T U
Example
V
using System; using System.Threading;
W X
namespace Samples { public class ThreadStateExceptionSample { public static void StartHere() {
Y Z
3207
Contents | Index
ThreadStateException
System.Threading
ThreadStateException() Constructor
Console.WriteLine("Thread: starting"); Console.WriteLine("Thread: finishing"); } public static void Main() { Thread t = new Thread( new ThreadStart(StartHere)); t.Start(); Thread.Sleep(1000); Console.WriteLine("2) Thread state: {0}", t.ThreadState); try { t.Suspend(); } catch(ThreadStateException e) { Console.WriteLine("Exception: {0}", e); } }
A B C D E F G H I J K
} }
L
The output is
M N
Thread: starting Thread: finishing 2) Thread state: Stopped Exception: System.Threading.ThreadStateException: Thread is not running; it cannot be suspended. at System.Threading.Thread.SuspendInternal() at System.Threading.Thread.Suspend() at Samples.ThreadStateExceptionSample.Main() in C:\Books\BCL\Samples\ System.Threading\ThreadStateException\ThreadStateException.cs:line 23
O P Q R S T U
ThreadStateException() Constructor
V
[ILASM]
public rtspecialname specialname instance void .ctor()
W
[C#]
public ThreadStateException()
X Y
Summary
Z
Constructs and initializes a new instance of the System.Threading.ThreadStateException class.
3208
Contents | Index
System.Threading
ThreadStateException ThreadStateException() Constructor
Description This constructor initializes the System.Threading.ThreadStateException.Message property of the new instance to a system-supplied message that describes the error, such as “The requested operation cannot be performed on the thread due to its current state.” This message takes into account the current system culture. The System.Threading.ThreadStateException.InnerException property of the new instance is initialized to null.
A B C D E
ThreadStateException(System.String) Constructor
F
[ILASM]
G
public rtspecialname specialname instance void .ctor(string message)
H
[C#]
public ThreadStateException(string message)
I
Summary
J
Constructs and initializes a new instance of the System.Threading.ThreadStateException class.
K
Parameters
M
L
N
Parameter
Description
O
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
P
message
Q R S
Description
T
This constructor initializes the System.Threading.ThreadStateException.Message property of the new instance using message. If message is null, the System.Threading.ThreadStateException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.Threading.ThreadStateException.InnerException property of the new instance is initialized to null.
U V W X Y Z
3209
Contents | Index
ThreadStateException
System.Threading
ThreadStateException() Constructor
ThreadStateException(System.String, System.Exception) Constructor [ILASM]
A
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
B
[C#]
public ThreadStateException(string message, Exception innerException)
C D
Summary
E
Constructs and initializes a new instance of the System.Threading.ThreadStateException class.
F
Parameters
G H
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current Exception was raised in a catch block handling innerException.
I J K L M N O
Description
P
This constructor initializes the System.Threading.ThreadStateException.Message property of the new instance using message and the System.Threading.ThreadStateException.InnerException property using innerException. If message is null, the System.Threading.ThreadStateException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For more information on inner exceptions, see System.Exception.InnerException.]
Q R S T U V
ThreadStateException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
W X
[ILASM]
Y
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
Z
[C#]
protected ThreadStateException(SerializationInfo info, StreamingContext context)
3210
Contents | Index
System.Threading
ThreadStateException ThreadStateException() Constructor
Summary Initializes a new instance of the System.Threading.ThreadStateException class with serialized data. A
Parameters
B C
Parameter
Description
info
The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown.
context
The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination.
D E F G H I
Description
J
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
K L M N O P Q R S T U V W X Y Z
3211
Contents | Index
System.Threading Timeout
BCL
Object
A
Timeout
B
Summary
C
Contains a constant used to specify an infinite amount of time.
D
Type Summary
E
public sealed class Timeout { // Fields public const int Infinite = -1; }
F G H I
Example
J
using System; using System.Threading;
K L
namespace Samples { public class TimeoutSample { public static void StartHere() { Console.WriteLine("Thread starting"); Thread.Sleep(1000); Console.WriteLine("Thread finishing"); } public static void Main() { Thread t = new Thread( new ThreadStart(StartHere)); Console.WriteLine("Main starting"); t.Start(); TimeSpan ts = new TimeSpan(100); Console.WriteLine("Joined: {0}", t.Join(ts)); Console.WriteLine("Joined: {0}", t.Join(Timeout.Infinite)); Console.WriteLine("Main finishing"); } } }
M N O P Q R S T U V W X Y Z
3212
Contents | Index
System.Threading
Timeout Infinite Field
The output is Main starting Thread starting Joined: False Thread finishing Joined: True Main finishing
A B C D E
Timeout.Infinite Field
F [ILASM]
.field public static literal int32 Infinite
G
[C#]
H
public const int Infinite = –1
I
Summary
J
A constant used to specify an infinite waiting period.
K L
Description
M
The value of this constant is –1. [Note: For threading methods that accept a timeout parameter, such as System.Threading.Thread.Sleep and System.Threading.Thread.Join, this value is used to suppress method behavior that would normally occur due to elapsed time.]
N O P Q R S T U V W X Y Z
3213
Contents | Index
System.Threading Timer
BCL
Object
A
MarshalByRefObject
B
Timer
IDisposable
C
Summary
D
Provides a mechanism for executing methods at specified intervals.
E F
Type Summary public sealed class Timer : MarshalByRefObject, IDisposable { // Constructors public Timer (TimerCallback callback, object state, int dueTime, int period); MS public Timer (TimerCallback callback, object state, long dueTime, long period); public Timer (TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period); MS public Timer (TimerCallback callback, object state, uint dueTime, uint period);
G H I J K L M N
// Methods public bool Change (int dueTime, int period); MS public bool Change(long dueTime, long period); public bool Change(TimeSpan dueTime, TimeSpan period); MS public bool Change(uint dueTime, uint period); public void Dispose (); CF public bool Dispose (WaitHandle notifyObject); ~Timer () {}
O P Q R S }
T U
KC We ended up shipping three timers in the .NET Framework. Luckily only this one got into the CLI Standard. We tried to unify them, but because all three have slightly different design objectives, we decided unification would not be the right thing to do. In general, it’s great to unify APIs for similar functionality. In some case, however, one needs to be careful not to take the idea of unification too far.
V W X Y Z
3214
Contents | Index
System.Threading
Timer Timer Class
Description A System.Threading.TimerCallback delegate is used to specify the methods associated with a Timer. The methods do not execute in the thread that created the timer; they execute in a separate thread that is automatically allocated by the system. The timer delegate is specified when the timer is constructed, and cannot be changed. When creating a timer, the application specifies an amount of time to wait before the first invocation of the delegate methods (due time), and an amount of time to wait between subsequent invocations (period). A timer invokes its methods once when its due time elapses, and invokes its methods once per period thereafter. These values may be changed, or the timer disabled using the System.Threading.Timer.Change method. When a timer is no longer needed, use the System.Threading.Timer.Dispose method to free the resources held by the timer.
A B C D E F G H
Example using System; using System.Threading;
I
namespace Samples { public class TimerSample { public static AutoResetEvent are = new AutoResetEvent(false); public static Timer t = null; public const int number = 9; public class StateHolder { public int counter = 0; } static void CallMe(Object s) { StateHolder sh = (StateHolder) s; Console.WriteLine("{0}: {1}", sh.counter++, DateTime.Now); if(sh.counter > number) { t.Dispose(are); } } public static void Main() { StateHolder sh = new StateHolder(); TimerCallback tcb = new TimerCallback(CallMe); t = new Timer( tcb, sh, 1000, 1000);
K
J
L M N O P Q R S T U V W X Y Z
3215
Contents | Index
Timer
System.Threading
Timer() Constructor
are.WaitOne(); } } }
A
The output is
B 0: 1: 2: 3: 4: 5: 6: 7: 8: 9:
C D E F G H
24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003
3:26:06 3:26:07 3:26:08 3:26:09 3:26:10 3:26:11 3:26:12 3:26:13 3:26:14 3:26:15
AM AM AM AM AM AM AM AM AM AM
I J K
Timer(System.Threading.TimerCallback, System.Object, System.Int32, System.Int32) Constructor
L
[ILASM]
M
public rtspecialname specialname instance void .ctor(class System.Threading. TimerCallback callback, object state, int32 dueTime, int32 period)
N
[C#]
public Timer(TimerCallback callback, object state, int dueTime, int period)
O P
Summary
Q
Constructs and initializes a new instance of the Timer class.
R
Parameters
S T U V
Parameter
Description
callback
A System.Threading.TimerCallback delegate.
state
A System.Object containing application-specific information relevant to the methods invoked by callback, or null.
dueTime
A System.Int32 containing the amount of time to delay before callback invokes its methods, in milliseconds. Specify System.Threading.Timeout.Infinite to prevent the timer from starting. Specify zero to start the timer immediately.
period
A System.Int32 containing the time interval between invocations of the methods referenced by callback, in milliseconds. Specify System.Threading.Timeout.Infinite to disable periodic signaling.
W X Y Z
3216
Contents | Index
System.Threading
Timer Timer() Constructor
Description callback invokes its methods once after dueTime elapses, and then invokes its methods each time the period time interval elapses. If dueTime is zero, callback performs its first invocation immediately. If dueTime is System.Threading.Timeout.Infinite, callback does not invoke its methods; the timer is disabled, but may be re-enabled using the System.Threading.Timer.Change method. If period is zero or System.Threading.Timeout.Infinite and dueTime is not System.Threading.Timeout.Infinite, callback invokes its methods exactly once; the periodic behavior of the timer is disabled, but may be re-enabled using the System.Threading.Timer.Change method.
A B C D E F G
Exceptions
H
Exception
Condition
System.ArgumentOutOfRangeException
dueTime or period is negative and is not equal to System.Threading.Timeout.Infinite.
System.ArgumentNullException
callback is a null reference.
I J K L M N
Example
O
using System; using System.Threading;
P Q
namespace Samples { public class TimerConstructor { public static object o = new Object(); public static Timer t = null; public const int number = 9; public class StateHolder { public int counter = 0; } static void CallMe(Object s) { StateHolder sh = (StateHolder) s; Console.WriteLine("{0}: {1}", sh.counter++, DateTime.Now); if(sh.counter > number) {
R S T U V W X Y Z
3217
Contents | Index
Timer
System.Threading
Timer() Constructor
t.Dispose(); Monitor.Enter(o); Monitor.PulseAll(o); Monitor.Exit(o);
A
} } public static void Main() { StateHolder sh = new StateHolder(); TimerCallback tcb = new TimerCallback(CallMe); t = new Timer( tcb, sh, 1000, 1000); Monitor.Enter(o); Monitor.Wait(o); Monitor.Exit(o); }
B C D E F G H I
} }
J K
The output is
L
0: 1: 2: 3: 4: 5: 6: 7: 8: 9:
M N O P Q R
24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003
3:27:53 3:27:54 3:27:55 3:27:56 3:27:57 3:27:58 3:27:59 3:28:00 3:28:01 3:28:02
AM AM AM AM AM AM AM AM AM AM
S
U
Timer(System.Threading.TimerCallback, System.Object, System.Int64, System.Int64) Constructor
V
[ILASM]
W
public rtspecialname specialname instance void .ctor(class System.Threading. TimerCallback callback, object state, int64 dueTime, int64 period)
X
[C#]
T
public Timer(TimerCallback callback, object state, long dueTime, long period)
Y
Summary
Z
Initializes a new instance of the Timer class, using 64-bit signed integers to measure time intervals. 3218
Contents | Index
System.Threading
Timer Timer() Constructor
Parameters Parameter
Description
callback
A System.Threading.TimerCallback delegate representing a method to be executed.
state
An object containing information to be used by the callback method, or null.
dueTime
The amount of time to delay before callback is invoked, in milliseconds. Specify System.Threading.Timeout.Infinite to prevent the timer from starting. Specify zero (0) to start the timer immediately.
E
The time interval between invocations of callback, in milliseconds. Specify System.Threading.Timeout.Infinite to disable periodic signaling.
G
A B C D
period
F
H I
Description
J
The delegate specified by the callback parameter is invoked once after dueTime elapses, and thereafter each time the period time interval elapses. Visual Basic users can omit the System.Threading.TimerCallback constructor, and simply use the AddressOf operator when specifying the callback method. Visual Basic automatically calls the correct delegate constructor. If dueTime is zero (0), callback is invoked immediately. If dueTime is System.Threading.Timeout.Infinite, callback is not invoked; the timer is disabled, but can be re-enabled by calling the System.Threading.Timer.Change method. If period is zero (0) or System.Threading.Timeout.Infinite and dueTime is not System.Threading.Timeout.Infinite, callback is invoked once; the periodic behavior of the timer is disabled, but can be re-enabled using the System.Threading.Timer.Change method.
K L M N O P Q R S T
Exceptions
U
Exception
Condition
V
The dueTime or period parameter is negative and is not equal to System.Threading.Timeout.Infinite.
W
System.ArgumentOutOfRangeException
System.NotSupportedException
The dueTime or period parameter is greater than 4294967294.
X Y Z
3219
Contents | Index
Timer
System.Threading
Timer() Constructor
Timer(System.Threading.TimerCallback, System.Object, System.TimeSpan, System.TimeSpan) Constructor A
[ILASM]
B
public rtspecialname specialname instance void .ctor(class System.Threading. TimerCallback callback, object state, valuetype System.TimeSpan dueTime, valuetype System.TimeSpan period)
C
[C#]
public Timer(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period)
D E F
Summary
G
Constructs and initializes a new instance of the Timer class.
H
Parameters
I J
Parameter
Description
K
callback
A System.Threading.TimerCallback delegate.
state
A System.Object containing application-specific information relevant to the methods invoked by callback, or null.
dueTime
A System.TimeSpan set to the amount of time to delay before callback invokes its methods. Set the value to System.Threading.Timeout.Infinite milliseconds to prevent the timer from starting. Specify zero to start the timer immediately.
period
A System.TimeSpan set to the time interval between invocations of the methods referenced by callback. Set the value to System.Threading.Timeout.Infinite milliseconds to disable periodic signaling.
L M N O P Q R S T
Description
U
The callback delegate invokes its methods once after dueTime elapses, and then invokes its methods each time the period time interval elapses. If dueTime, in milliseconds, is zero, callback performs its first invocation immediately. If dueTime is System.Threading.Timeout.Infinite, no method invocation occurs. The timer is disabled, but may be re-enabled using the System.Threading.Timer.Change method. If period is zero or System.Threading.Timeout.Infinite milliseconds and dueTime is not System.Threading.Timeout.Infinite, callback invokes its methods
V W X Y Z
3220
Contents | Index
System.Threading
Timer Timer() Constructor
exactly once. The periodic behavior of the timer is disabled, but may be re-enabled using the System.Threading.Timer.Change method. A
Exceptions
B
Exception
Condition
System.ArgumentOutOfRangeException
The number of milliseconds in the value of dueTime or period is negative and not equal to System.Threading.Timeout.Infinite, or is greater than System.Int32.MaxValue.
System.ArgumentNullException
callback is a null reference.
C D E F G H I
Timer(System.Threading.TimerCallback, System.Object, System.UInt32, System.UInt32) Constructor
J K
[ILASM]
public rtspecialname specialname instance void .ctor(class System.Threading.TimerCallback callback, object state, unsigned int32 dueTime, unsigned int32 period)
L M
[C#]
N
public Timer(TimerCallback callback, object state, uint dueTime, uint period)
O
Summary
P
Initializes a new instance of the Timer class, using 32-bit unsigned integers to measure time intervals.
Q R
Parameters
S
Parameter
Description
callback
A System.Threading.TimerCallback delegate representing a method to be executed.
state
An object containing information to be used by the callback method, or null.
dueTime
The amount of time to delay before callback is invoked, in milliseconds. Specify System.Threading.Timeout.Infinite to prevent the timer from starting. Specify zero (0) to start the timer immediately.
period
The time interval between invocations of callback, in milliseconds. Specify System.Threading.Timeout.Infinite to disable periodic signaling.
T U V W X Y Z
3221
Contents | Index
Timer
System.Threading
Change() Method
Description The delegate specified by the callback parameter is invoked once after dueTime elapses, and thereafter each time the period time interval elapses. Visual Basic users can omit the System.Threading.TimerCallback constructor, and simply use the AddressOf operator when specifying the callback method. Visual Basic automatically calls the correct delegate constructor. If dueTime is zero (0), callback is invoked immediately. If dueTime is System.Threading.Timeout.Infinite, callback is not invoked; the timer is disabled, but can be re-enabled by calling the System.Threading.Timer.Change method. If period is zero (0) or System.Threading.Timeout.Infinite and dueTime is not System.Threading.Timeout.Infinite, callback is invoked once; the periodic behavior of the timer is disabled, but can be re-enabled using the System.Threading.Timer.Change method. This member is not CLS-compliant.
A B C D E F G H I
Exceptions
J K
Exception
Condition
System.ArgumentOutOfRangeException
The dueTime or period parameter is negative and is not equal to System.Threading.Timeout.Infinite.
System.ArgumentNullException
The callback parameter is null.
L M N O P Q R
Timer.Change(System.Int32, System.Int32) Method
S
[ILASM]
.method public hidebysig instance bool Change(int32 dueTime, int32 period)
T
[C#]
public bool Change(int dueTime, int period)
U V
Summary
W
Changes the start time and interval between method invocations for a timer.
X Y Z
3222
Contents | Index
System.Threading
Timer Change() Method
Parameters Parameter
Description
dueTime
A System.Int32 containing the amount of time to delay before the delegate specified at System.Threading.Timer construction time invokes its methods, in milliseconds. Specify System.Threading.Timeout.Infinite to prevent the timer from restarting. Specify zero to restart the timer immediately.
period
A System.Int32 containing the time interval between invocations of the methods referenced by the delegate specified at System.Threading.Timer construction time, in milliseconds. Specify System.Threading.Timeout.Infinite to disable periodic signaling.
A B C D E F G H
Return Value
I
true if the current instance has not been disposed; otherwise, false.
J
Description
K
The delegate specified at System.Threading.Timer construction time invokes its methods once after dueTime elapses, and then invokes its methods each time the period time interval elapses. If dueTime is zero, the delegate specified at System.Threading.Timer construction time performs its next invocation immediately. If dueTime is System.Threading.Timeout.Infinite, no method invocation occurs. The timer is disabled, but may be reenabled by calling this method and specifying a non-negative value for dueTime. If period is zero or System.Threading.Timeout.Infinite and dueTime is not System.Threading.Timeout.Infinite, the delegate specified at System.Threading.Timer construction time invokes its methods exactly once. The periodic behavior of the timer is disabled, but may be re-enabled by calling this method and specifying a positive value for period.
L M N O P Q R S T U
Exceptions
V
Exception
Condition
W
System.ArgumentOutOfRangeException
dueTime or period is negative and is not equal to System.Threading.Timeout.Infinite.
X Y Z
3223
Contents | Index
Timer
System.Threading
Change() Method
Example using System; using System.Threading;
A namespace Samples { public class TimerChange { public static object o = new Object(); public static Timer t = null; public const int number = 10; public class StateHolder { public int counter = 0; } static void CallMe(Object s) { StateHolder sh = (StateHolder) s; Console.WriteLine("{0}: {1}", sh.counter++, DateTime.Now); if(sh.counter == number / 2) t.Change(2000,2000); if(sh.counter >= number) { t.Dispose(); Monitor.Enter(o); Monitor.PulseAll(o); Monitor.Exit(o); } } public static void Main() { StateHolder sh = new StateHolder(); TimerCallback tcb = new TimerCallback(CallMe); t = new Timer(tcb, sh, 1000, 1000); Monitor.Enter(o); Monitor.Wait(o); Monitor.Exit(o); } } }
B C D E F G H I J K L M N O P Q R S T U V W X Y Z
3224
Contents | Index
System.Threading
Timer Change() Method
The output is 0: 1: 2: 3: 4: 5: 6: 7: 8: 9:
24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003
3:31:10 3:31:11 3:31:12 3:31:13 3:31:14 3:31:16 3:31:18 3:31:20 3:31:22 3:31:24
AM AM AM AM AM AM AM AM AM AM
A B C D E F G
Timer.Change(System.Int64, System.Int64) Method
H
[ILASM]
I
.method public hidebysig instance bool Change(int64 dueTime, int64 period)
J
[C#]
public bool Change(long dueTime, long period)
K L
Summary
M
Changes the start time and the interval between method invocations for a timer, using 64bit signed integers to measure time intervals.
N O
Parameters
P
Parameter
Description
dueTime
The amount of time to delay before invoking the callback method specified when the System.Threading.Timer was constructed, in milliseconds. Specify System.Threading.Timeout.Infinite to prevent the timer from restarting. Specify zero (0) to restart the timer immediately.
period
Q R S T U
The time interval between invocations of the callback method specified when the System.Threading.Timer was constructed, in milliseconds. Specify System.Threading.Timeout.Infinite to disable periodic signaling.
V W X
Return Value
Y
true if the current instance has not been disposed; otherwise, false.
Z
3225
Contents | Index
Timer
System.Threading
Change() Method
Description The callback method is invoked once after dueTime elapses, and thereafter each time the time interval specified by period elapses. If dueTime is zero (0), the callback method is invoked immediately. If dueTime is System.Threading.Timeout.Infinite, the callback method is never invoked; the timer is disabled, but can be re-enabled by calling System.Threading.Timer.Change and specifying a positive value for dueTime. If period is zero (0) or System.Threading.Timeout.Infinite, and dueTime is not Infinite, the callback method is invoked once; the periodic behavior of the timer is disabled, but can be re-enabled by calling System.Threading.Timer.Change and specifying a positive value for period.
A B C D E F G
Exceptions
H I
Exception
Condition
System.ObjectDisposedException
The System.Threading.Timer has already been disposed.
System.ArgumentOutOfRangeException
The dueTime or period parameter is less than –1.
System.NotSupportedException
The dueTime or period parameter is greater than 4294967294.
J K L M N O P Q
Timer.Change(System.TimeSpan, System.TimeSpan) Method
R
[ILASM]
S
.method public hidebysig instance bool Change(valuetype System.TimeSpan dueTime, valuetype System.TimeSpan period)
T
[C#]
U
public bool Change(TimeSpan dueTime, TimeSpan period)
V
Summary
W
Changes the start time and interval between method invocations for a timer.
X Y Z
3226
Contents | Index
System.Threading
Timer Change() Method
Parameters Parameter
Description
dueTime
A System.TimeSpan set to the amount of time to delay before the delegate specified at System.Threading.Timer construction time invokes its methods. Specify System.Threading.Timeout.Infinite milliseconds to prevent the timer from restarting. Specify zero to restart the timer immediately.
period
A System.TimeSpan set to the time interval between invocations of the methods referenced by the delegate specified at System.Threading.Timer construction time. Specify System.Threading.Timeout.Infinite milliseconds to disable periodic signaling.
A B C D E F G H
Return Value
I
true if the current instance has not been disposed; otherwise, false.
J
Description
K
The delegate specified at System.Threading.Timer construction time invokes its methods once after dueTime elapses, and then invokes its methods each time the period time interval elapses. If dueTime, in milliseconds, is zero, the delegate specified at System.Threading.Timer construction time performs its next invocation immediately. If dueTime is System.Threading.Timeout.Infinite milliseconds, no method invocation occurs. The timer is disabled, but may be re-enabled by calling this method and specifying a nonnegative value for dueTime. If period is zero or System.Threading.Timeout.Infinite milliseconds and dueTime is not System.Threading.Timeout.Infinite milliseconds, the delegate specified at System.Threading.Timer construction time invokes its methods exactly once. The periodic behavior of the timer is disabled, but may be re-enabled by calling this method and specifying a positive value for period.
L M N O P Q R S T U
Example
V
using System; using System.Threading;
W X
namespace Samples { public class TimerChange { public static object o = new Object(); public static Timer t = null;
Y Z
3227
Contents | Index
Timer
System.Threading
Change() Method
public const int number = 10; public class StateHolder { public int counter = 0; } static void CallMe(Object s) { StateHolder sh = (StateHolder) s; Console.WriteLine("{0}: {1}", sh.counter++, DateTime.Now); if(sh.counter == number / 2) { TimeSpan ts = new TimeSpan(0, 0, 0, 2); t.Change(ts, ts); } if(sh.counter >= number) { t.Dispose(); Monitor.Enter(o); Monitor.PulseAll(o); Monitor.Exit(o); } } public static void Main() { StateHolder sh = new StateHolder(); TimerCallback tcb = new TimerCallback(CallMe); t = new Timer( tcb, sh, 1000, 1000); Monitor.Enter(o); Monitor.Wait(o); Monitor.Exit(o); }
A B C D E F G H I J K L M N O P Q R S
} }
T
The output is
U V
0: 1: 2: 3: 4: 5: 6: 7: 8: 9:
W X Y Z
24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003
3:32:57 3:32:58 3:32:59 3:33:00 3:33:01 3:33:03 3:33:05 3:33:07 3:33:09 3:33:11
AM AM AM AM AM AM AM AM AM AM
3228
Contents | Index
System.Threading
Timer Change() Method
Timer.Change(System.UInt32, System.UInt32) Method [ILASM]
.method public hidebysig instance bool Change(unsigned int32 dueTime, unsigned int32 period)
A
[C#]
B
public bool Change(uint dueTime, uint period)
C
Summary
D
Changes the start time and the interval between method invocations for a timer, using 32bit unsigned integers to measure time intervals.
E
Parameters
G
F
H
Parameter
Description
dueTime
The amount of time to delay before the invoking the callback method specified when the System.Threading.Timer was constructed, in milliseconds. Specify System.Threading.Timeout.Infinite to prevent the timer from restarting. Specify zero (0) to restart the timer immediately.
period
I J K L
The time interval between invocations of the callback method specified when the System.Threading.Timer was constructed, in milliseconds. Specify System.Threading.Timeout.Infinite to disable periodic signaling.
M N O
Return Value
P
true if the current instance has not been disposed; otherwise, false.
Q R
Description
S
The callback method is invoked once after dueTime elapses, and thereafter each time the time interval specified by period elapses. If dueTime is zero (0), the callback method is invoked immediately. If dueTime is System.Threading.Timeout.Infinite, the callback method is never invoked; the timer is disabled, but can be re-enabled by calling System.Threading.Timer.Change and specifying a positive value for dueTime. If period is zero (0) or System.Threading.Timeout.Infinite, and dueTime is not Infinite, the callback method is invoked once; the periodic behavior of the timer is disabled, but can be re-enabled by calling System.Threading.Timer.Change and specifying a positive value for period. This member is not CLS-compliant.
T U V W X Y Z
3229
Contents | Index
Timer
System.Threading
Dispose() Method
Exceptions Exception
Condition
System.ObjectDisposedException
The System.Threading.Timer has already been disposed.
A B C D E
Timer.Dispose() Method
F
[ILASM]
.method public final hidebysig virtual void Dispose()
G
[C#]
H
public void Dispose()
I
Summary
J
Releases the resources held by the current instance.
K L
Description
M
[Note: This method is implemented to support the System.IDisposable interface.]
N
Example
O
using System; using System.Threading;
P Q
namespace Samples { public class TimerDispose { public static object o = new Object(); public static Timer t = null; public const int number = 9; public class StateHolder { public int counter = 0; } static void CallMe(Object s) { StateHolder sh = (StateHolder) s; Console.WriteLine("{0}: {1}", sh.counter++, DateTime.Now); if(sh.counter > number) {
R S T U V W X Y Z
3230
Contents | Index
System.Threading
Timer Dispose() Method
t.Dispose(); Monitor.Enter(o); Monitor.PulseAll(o); Monitor.Exit(o);
A
} } public static void Main() { StateHolder sh = new StateHolder(); TimerCallback tcb = new TimerCallback(CallMe); t = new Timer(tcb, sh, 1000, 1000); Monitor.Enter(o); Monitor.Wait(o); Monitor.Exit(o); }
B C D E F G H
}
I
}
J
The output is
K 0: 1: 2: 3: 4: 5: 6: 7: 8: 9:
24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003
3:34:49 3:34:50 3:34:51 3:34:52 3:34:53 3:34:54 3:34:55 3:34:56 3:34:57 3:34:58
AM AM AM AM AM AM AM AM AM AM
L M N O P Q R S
Timer.Dispose(System.Threading.WaitHandle) Method
T [ILASM]
U
.method public hidebysig instance bool Dispose(class System.Threading.WaitHandle notifyObject)
V
[C#]
W
public bool Dispose(WaitHandle notifyObject)
X
Summary
Y
Releases the resources held by the current instance.
Z
3231
Contents | Index
Timer
System.Threading
Dispose() Method
Parameters Parameter
Description
notifyObject
Specifies a System.Threading.WaitHandle to be signaled when the timer has been disposed of.
A B C D
Return Value
E
true if the call succeeds; otherwise, false.
F
Description
G
When this method completes, the System.Threading.WaitHandle specified by notifyObject is signaled. This method calls System.GC.SuppressFinalize to prevent the garbage collector from finalizing the current instance.
H I J K
Exceptions
L M
Exception
Condition
N
System.ArgumentNullException
notifyObject is null.
O P
Example
Q
using System; using System.Threading;
R
namespace Samples { public class TimerDispose { public static AutoResetEvent are = new AutoResetEvent(false); public static Timer t = null; public const int number = 9; public class StateHolder { public int counter = 0; } static void CallMe(Object s) { StateHolder sh = (StateHolder) s; Console.WriteLine("{0}: {1}",
S T U V W X Y Z
3232
Contents | Index
System.Threading
Timer Finalize() Method
sh.counter++, DateTime.Now); if(sh.counter > number) { t.Dispose(are); }
A
} public static void Main() { StateHolder sh = new StateHolder(); TimerCallback tcb = new TimerCallback(CallMe); t = new Timer(tcb, sh, 1000, 1000); are.WaitOne(); }
B C D E F G
} }
H
The output is 0: 1: 2: 3: 4: 5: 6: 7: 8: 9:
24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003
3:36:30 3:36:31 3:36:32 3:36:33 3:36:34 3:36:35 3:36:36 3:36:37 3:36:38 3:36:39
I J
AM AM AM AM AM AM AM AM AM AM
K L M N O P Q
Timer.Finalize() Method
R
[ILASM]
S
.method family hidebysig virtual void Finalize()
T
[C#]
~Timer()
U
Summary
V
Releases the resources held by the current instance.
W X
Description
Y
[Note: Application code does not call this method; it is automatically invoked during garbage collection unless finalization by the garbage collector has been disabled. For more information, see System.GC.SuppressFinalize, and System.Object.Finalize. This method overrides System.Object.Finalize.]
Z
3233
Contents | Index
System.Threading TimerCallback Delegate
BCL
Object ICloneable
A
Delegate ISerializable
B
MulticastDelegate
NotStandardized
NotStandardized
TimerCallback
C D
Summary
E
Defines the shape of methods that are called by an instance of the System.Threading.Timer class.
F G
Type Summary
H
public delegate void TimerCallback (object state);
I J
Parameters
K L M
Parameter
Description
state
A System.Object containing application-specific information relevant to the methods invoked by instances of this delegate, or null.
N O
Description
P
A TimerCallback delegate invokes its methods once after the start time elapses, and continues invoking its methods once per period until the System.Threading.Timer.Dispose method is called. [Note: The start time for a System.Threading.Timer is passed in the dueTime parameter of the Timer constructors, and the period is passed via the period parameter.] [Note: For an example that demonstrates creating and using a TimerCallback delegate, see the System.Threading.Timer class.]
Q R S T U V
Example
W
using System; using System.Threading;
X Y
namespace Samples { public class TimerCallbackSample { public static AutoResetEvent are =
Z
3234
Contents | Index
System.Threading
TimerCallback Delegate TimerCallback Delegate
new AutoResetEvent(false); public static Timer t = null; public const int number = 9; public class StateHolder { public int counter = 0; } static void CallMe(Object s) { StateHolder sh = (StateHolder) s; Console.WriteLine("{0}: {1}", sh.counter++, DateTime.Now); if(sh.counter > number) { t.Dispose(are); } } public static void Main() { StateHolder sh = new StateHolder(); TimerCallback tcb = new TimerCallback(CallMe); t = new Timer(tcb, sh, 1000, 1000); are.WaitOne(); }
A B C D E F G H I J K L M N
} }
O
The output is 0: 1: 2: 3: 4: 5: 6: 7: 8: 9:
24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003 24/06/2003
3:38:29 3:38:30 3:38:31 3:38:32 3:38:33 3:38:34 3:38:35 3:38:36 3:38:37 3:38:38
P Q
AM AM AM AM AM AM AM AM AM AM
R S T U V W X Y Z
3235
Contents | Index
System TimeSpan Structure
BCL
Object
A
ValueType
B
TimeSpan
IComparable
C
Summary
D
Represents an interval of time.
E F
Type Summary public struct TimeSpan : IComparable { // Constructors public TimeSpan (int hours, int minutes, int seconds); public TimeSpan (int days, int hours, int minutes, int seconds); public TimeSpan (int days, int hours, int minutes, int seconds, int milliseconds); public TimeSpan (long ticks);
G H I J K L M
// Fields public public public public public public public public
N O P Q R S
static readonly TimeSpan MaxValue = new TimeSpan (Int64.MaxValue); static readonly TimeSpan MinValue = new TimeSpan (Int64.MinValue); const long TicksPerDay = TicksPerHour * 24; const long TicksPerHour = TicksPerMinute * 60; const long TicksPerMillisecond = 10000; const long TicksPerMinute = TicksPerSecond * 60; const long TicksPerSecond = TicksPerMillisecond * 1000; static readonly TimeSpan Zero = new TimeSpan (0);
// Properties public int Days { get; } public int Hours { get; } public int Milliseconds { get; } public int Minutes { get; } public int Seconds { get; } public long Ticks { get; } public double TotalDays { get; } public double TotalHours { get; } public double TotalMilliseconds { get; } public double TotalMinutes { get; } public double TotalSeconds { get; }
T U V W X Y Z
// Methods public TimeSpan Add (TimeSpan ts);
3236
Contents | Index
System
TimeSpan Structure TimeSpan Structure
public static int Compare (TimeSpan t1, TimeSpan t2); public int CompareTo (object value); public TimeSpan Duration (); public override bool Equals (object value); public static bool Equals (TimeSpan t1, TimeSpan t2); public static TimeSpan FromDays (double value); public static TimeSpan FromHours (double value); public static TimeSpan FromMilliseconds (double value); public static TimeSpan FromMinutes (double value); public static TimeSpan FromSeconds (double value); public static TimeSpan FromTicks (long value); public override int GetHashCode (); public TimeSpan Negate (); public static TimeSpan operator +(TimeSpan t1, TimeSpan t2); public static bool operator ==(TimeSpan t1, TimeSpan t2); public static bool operator >(TimeSpan t1, TimeSpan t2); public static bool operator >=(TimeSpan t1, TimeSpan t2); public static bool operator !=(TimeSpan t1, TimeSpan t2); public static bool operator <(TimeSpan t1, TimeSpan t2); public static bool operator <=(TimeSpan t1, TimeSpan t2); public static TimeSpan operator -(TimeSpan t1, TimeSpan t2); public static TimeSpan operator -(TimeSpan t); CF public static TimeSpan operator +(TimeSpan t); public static TimeSpan Parse (string s); public TimeSpan Subtract (TimeSpan ts); public override string ToString ();
A B C D E F G H I J K L M N O P Q R S T
}
U V
KG A number of customer requests for TimeSpan include the ability to get how many months or years the TimeSpan represents. Because TimeSpan doesn’t have a fixed starting point, it is impossible for us to accurately describe values, e.g., are there 29 days in a month? We could have, however, defined some common behavior for these operations, and included them for the general case. The problem is that every user who cares would probably define their own in order to reflect their needs accurately.
W X Y Z
3237
Contents | Index
TimeSpan Structure
System
TimeSpan Structure
Description The System.TimeSpan structure represents an interval of time with values ranging from System.Int64.MinValue to System.Int64.MaxValue 100-nanosecond ticks. [Note: The value of a System.TimeSpan is represented internally as a number of 100nanosecond ticks. Both the specification of a number of ticks and the value of a System.TimeSpan can be positive or negative. A System.TimeSpan can be represented as a string in the format “[–]d.hh:mm:ss.ff” where “–” is an optional sign for negative System.TimeSpan values, the “d” component is days, “hh” is hours, “mm” is minutes, “ss” is seconds, and “ff” is fractions of a second. For example, a System.TimeSpan initialized with 1013 ticks would be represented as “11.13:46:40”, which is 11 days, 13 hours, 46 minutes, and 40 seconds. Due to a varying number of days in months and years, the longest unit of time that is used by this structure is the day.]
A B C D E F G H
Example
I
using System;
J namespace Samples { public class TimeSpanSample { public static void Main() { DateTime start = DateTime.Now; Console.WriteLine("MaxValue: {0}", TimeSpan.MaxValue); Console.WriteLine("MinValue: {0}", TimeSpan.MinValue); Console.WriteLine("TicksPerDay: {0}", TimeSpan.TicksPerDay); Console.WriteLine("TicksPerHour: {0}", TimeSpan.TicksPerHour); Console.WriteLine("TicksPerMinute: {0}", TimeSpan.TicksPerMinute); Console.WriteLine("TicksPerSecond: {0}", TimeSpan.TicksPerSecond); Console.WriteLine("TicksPerMillisecond: {0}", TimeSpan.TicksPerMillisecond); TimeSpan ts = new DateTime(1973, 9, 25) new DateTime(1959, 9, 3); Console.WriteLine("Damien is older than Brad by: "); Console.Write("Days: {0}", ts.Days); Console.Write(" Hours: {0}", ts.Hours); Console.Write(" Minutes: {0}", ts.Minutes); Console.Write(" Seconds: {0}", ts.Seconds); Console.WriteLine(" Milliseconds: {0}", ts.Milliseconds); Console.WriteLine("TotalDays: {0}", ts.TotalDays); Console.WriteLine("TotalHours: {0}", ts.TotalHours);
K L M N O P Q R S T U V W X Y Z
3238
Contents | Index
System
TimeSpan Structure TimeSpan() Constructor
Console.WriteLine("TotalMinutes: {0}", ts.TotalMinutes); Console.WriteLine("TotalSeconds: {0}", ts.TotalSeconds); Console.WriteLine("TotalMilliseconds: {0}", ts.TotalMilliseconds); Console.WriteLine("MaxValue is: {0} ticks", ts.Ticks); TimeSpan diff = DateTime.Now - start; Console.WriteLine ("Time to run this program: {0} ",diff);
A B C
} }
D
}
E
The output is
F
MaxValue: 10675199.02:48:05.4775807 MinValue: -10675199.02:48:05.4775808 TicksPerDay: 864000000000 TicksPerHour: 36000000000 TicksPerMinute: 600000000 TicksPerSecond: 10000000 TicksPerMillisecond: 10000 Damien is older than Brad by: Days: 5136 Hours: 0 Minutes: 0 Seconds: 0 Milliseconds: 0 TotalDays: 5136 TotalHours: 123264 TotalMinutes: 7395840 TotalSeconds: 443750400 TotalMilliseconds: 443750400000 MaxValue is: 4437504000000000 ticks Time to run this program: 00:00:00.3404896
G H I J K L M N O P Q R
TimeSpan(System.Int32, System.Int32, System.Int32) Constructor
S
[ILASM]
T
public rtspecialname specialname instance void .ctor(int32 hours, int32 minutes, int32 seconds)
U
[C#]
public TimeSpan(int hours, int minutes, int seconds)
V W
Summary
X
Constructs and initializes a new System.TimeSpan with the specified numbers of hours, minutes, and seconds.
Y Z
3239
Contents | Index
TimeSpan Structure
System
TimeSpan() Constructor
Parameters Parameter
Description
hours
A System.Int32 that specifies the number of hours with which to initialize the new System.TimeSpan.
minutes
A System.Int32 that specifies the number of minutes with which to initialize the new System.TimeSpan.
seconds
A System.Int32 that specifies the number of seconds with which to initialize the new System.TimeSpan.
A B C D E F G H
Description
I
The specified hours, minutes, and seconds are converted to ticks, and that value is used to initialize the new System.TimeSpan.
J K
Exceptions
L M
Exception
Condition
System.ArgumentOutOfRangeException
The parameters specify a System.TimeSpan value less than System.TimeSpan.MinValue or greater than System.TimeSpan.MaxValue.
N O P Q
Example
R
using System;
S namespace Samples { public class TimeSpanConstructor { public static void Main() { TimeSpan ts = new TimeSpan(24, 0, 0); Console.WriteLine("TotalMinutes: {0}", ts.TotalMinutes); DateTime dt = DateTime.Now + ts; Console.WriteLine( "In one day it will be: {0}", dt); } } }
T U V W X Y Z
3240
Contents | Index
System
TimeSpan Structure TimeSpan() Constructor
The output is TotalMinutes: 1440 In one day it will be: 25/06/2003 4:47:21 AM
A B
TimeSpan(System.Int32, System.Int32, System.Int32, System.Int32) Constructor
D
[ILASM]
E
public rtspecialname specialname instance void .ctor(int32 days, int32 hours, int32 minutes, int32 seconds)
F
C
[C#]
G
public TimeSpan(int days, int hours, int minutes, int seconds)
H
Summary
I
Constructs and initializes a new System.TimeSpan with the specified numbers of days, hours, minutes, and seconds.
J K
Parameters
L M
Parameter
Description
days
A System.Int32 that specifies the number of days with which to initialize the new System.TimeSpan.
hours
A System.Int32 that specifies the number of hours with which to initialize the new System.TimeSpan.
minutes
A System.Int32 that specifies the number of minutes with which to initialize the new System.TimeSpan.
seconds
A System.Int32 that specifies the number of seconds with which to initialize the new System.TimeSpan.
N O P Q R S T U V
Description
W
The specified days, hours, minutes, and seconds are converted to ticks, and that value is used to initialize the new System.TimeSpan.
X Y Z
3241
Contents | Index
TimeSpan Structure
System
TimeSpan() Constructor
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
The parameters specify a System.TimeSpan value less than System.TimeSpan.MinValue or greater than System.TimeSpan.MaxValue.
A B C D E
Example
F
using System;
G
namespace Samples { public class TimeSpanConstructor { public static void Main() { TimeSpan ts = new TimeSpan(0, 24, 0, 0); Console.WriteLine("TotalSeconds: {0}", ts.TotalSeconds); DateTime dt = DateTime.Now + ts; Console.WriteLine( "In one day it will be: {0}", dt); } } }
H I J K L M N O P
The output is
Q R
TotalSeconds: 86400 In one day it will be: 25/06/2003 4:49:20 AM
S T
V
TimeSpan(System.Int32, System.Int32, System.Int32, System.Int32, System.Int32) Constructor
W
[ILASM]
X
public rtspecialname specialname instance void .ctor(int32 days, int32 hours, int32 minutes, int32 seconds, int32 milliseconds)
U
[C#]
Y
public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds)
Z
3242
Contents | Index
System
TimeSpan Structure TimeSpan() Constructor
Summary Constructs and initializes a new System.TimeSpan with the specified numbers of days, hours, minutes, seconds, and milliseconds. A
Parameters
B C
Parameter
Description
days
A System.Int32 that specifies the number of days with which to initialize the new System.TimeSpan.
hours
A System.Int32 that specifies the number of hours with which to initialize the new System.TimeSpan.
minutes
A System.Int32 that specifies the number of minutes with which to initialize the new System.TimeSpan.
seconds
A System.Int32 that specifies the number of seconds with which to initialize the new System.TimeSpan.
milliseconds
A System.Int32 that specifies the number of milliseconds with which to initialize the new System.TimeSpan.
D E F G H I J K L M N
Description
O
The specified days, hours, minutes, seconds, and milliseconds are converted to ticks, and that value is used to initialize the new System.TimeSpan.
P Q
Exceptions
R S
Exception
Condition T
System.ArgumentOutOfRangeException
The parameters specify a System.TimeSpan value less than System.TimeSpan.MinValue or greater than System.TimeSpan.MaxValue.
U V W X Y Z
3243
Contents | Index
TimeSpan Structure
System
TimeSpan() Constructor
Example using System; namespace Samples { public class TimeSpanConstructor { public static void Main() { TimeSpan ts = new TimeSpan(24, 0, 0, 0, 0); Console.WriteLine("TotalMilliseconds: {0}", ts.TotalMilliseconds); DateTime dt = DateTime.Now + ts; Console.WriteLine( "In one day it will be: {0}", dt); } } }
A B C D E F G H I J
The output is
K L
TotalMilliseconds: 2073600000 In one day it will be: 18/07/2003 4:48:33 AM
M N O
TimeSpan(System.Int64) Constructor
P
[ILASM]
public rtspecialname specialname instance void .ctor(int64 ticks)
Q
[C#]
public TimeSpan(long ticks)
R S
Summary
T
Constructs and initializes a new System.TimeSpan with the specified number of ticks.
U
Parameters
V W
Parameter
Description
ticks
A System.Int64 that specifies the number of ticks with which to initialize the new System.TimeSpan.
X Y Z
3244
Contents | Index
System
TimeSpan Structure MaxValue Field
Example using System; namespace Samples { public class TimeSpanConstructor { public static void Main() { long i = DateTime.Now.Ticks; TimeSpan ts = new TimeSpan(i); DateTime dt = DateTime.MinValue + ts; Console.WriteLine(dt); } } }
A B C D E F G H I
The output is
J 24/06/2003 4:46:44 AM
K L
TimeSpan.MaxValue Field
M
[ILASM]
N
.field public static initOnly valuetype System.TimeSpan MaxValue
O
[C#]
public static readonly TimeSpan MaxValue= new TimeSpan (Int64.MaxValue)
P Q
Summary
R
Returns a System.TimeSpan whose value is the maximum value for the System.TimeSpan type.
S T
Description
U
This field is a System.TimeSpan containing System.Int64.MaxValue ticks, the maximum System.TimeSpan value. The string representation of this value is positive 10675199.02:48:05.4775807.
V W X Y Z
3245
Contents | Index
TimeSpan Structure
System
MinValue Field
Example using System; namespace Samples { public class TimeSpanMaxValue { public static void Main() { Console.WriteLine("MaxValue: {0}", TimeSpan.MaxValue); Console.WriteLine("MinValue: {0}", TimeSpan.MinValue); Console.WriteLine("TicksPerDay: {0}", TimeSpan.TicksPerDay); Console.WriteLine("TicksPerHour: {0}", TimeSpan.TicksPerHour); Console.WriteLine("TicksPerMinute: {0}", TimeSpan.TicksPerMinute); Console.WriteLine("TicksPerSecond: {0}", TimeSpan.TicksPerSecond); Console.WriteLine("TicksPerMillisecond: {0}", TimeSpan.TicksPerMillisecond); } } }
A B C D E F G H I J K L M N O
The output is
P
MaxValue: 10675199.02:48:05.4775807 MinValue: -10675199.02:48:05.4775808 TicksPerDay: 864000000000 TicksPerHour: 36000000000 TicksPerMinute: 600000000 TicksPerSecond: 10000000 TicksPerMillisecond: 10000
Q R S T U V W
TimeSpan.MinValue Field
X
[ILASM]
.field public static initOnly valuetype System.TimeSpan MinValue
Y
[C#]
public static readonly TimeSpan MinValue = new TimeSpan (Int64.MinValue)
Z
3246
Contents | Index
System
TimeSpan Structure MinValue Field
Summary Returns a System.TimeSpan whose value is the minimum value for the System.TimeSpan type. A
Description
B
This field is a System.TimeSpan containing System.Int64.MinValue ticks, the minimum System.TimeSpan value. The string representation of this value is negative 10675199.02:48:05.4775808.
C D E
Example
F
using System;
G
namespace Samples { public class TimeSpanMinValue { public static void Main() { Console.WriteLine("MaxValue: {0}", TimeSpan.MaxValue); Console.WriteLine("MinValue: {0}", TimeSpan.MinValue); Console.WriteLine("TicksPerDay: {0}", TimeSpan.TicksPerDay); Console.WriteLine("TicksPerHour: {0}", TimeSpan.TicksPerHour); Console.WriteLine("TicksPerMinute: {0}", TimeSpan.TicksPerMinute); Console.WriteLine("TicksPerSecond: {0}", TimeSpan.TicksPerSecond); Console.WriteLine("TicksPerMillisecond: {0}", TimeSpan.TicksPerMillisecond); } } }
H I J K L M N O P Q R S T U V
The output is
W
MaxValue: 10675199.02:48:05.4775807 MinValue: -10675199.02:48:05.4775808 TicksPerDay: 864000000000 TicksPerHour: 36000000000 TicksPerMinute: 600000000 TicksPerSecond: 10000000 TicksPerMillisecond: 10000
X Y Z
3247
Contents | Index
TimeSpan Structure
System
TicksPerDay Field
TimeSpan.TicksPerDay Field [ILASM]
.field public static literal int64 TicksPerDay
A
[C#]
public const long TicksPerDay = TicksPerHour * 24
B C
Summary
D
Represents the number of ticks in 1 day.
E F
Description
G
The value of this constant is 864 billion (8.64 × 1011).
H
Example
I
using System;
J
namespace Samples { public class TimeSpanTicksPerDay { public static void Main() { Console.WriteLine("MaxValue: {0}", TimeSpan.MaxValue); Console.WriteLine("MinValue: {0}", TimeSpan.MinValue); Console.WriteLine("TicksPerDay: {0}", TimeSpan.TicksPerDay); Console.WriteLine("TicksPerHour: {0}", TimeSpan.TicksPerHour); Console.WriteLine("TicksPerMinute: {0}", TimeSpan.TicksPerMinute); Console.WriteLine("TicksPerSecond: {0}", TimeSpan.TicksPerSecond); Console.WriteLine("TicksPerMillisecond: {0}", TimeSpan.TicksPerMillisecond); } } }
K L M N O P Q R S T U V W X
The output is
Y Z
MaxValue: 10675199.02:48:05.4775807 MinValue: -10675199.02:48:05.4775808 TicksPerDay: 864000000000
3248
Contents | Index
System
TimeSpan Structure TicksPerHour Field
TicksPerHour: 36000000000 TicksPerMinute: 600000000 TicksPerSecond: 10000000 TicksPerMillisecond: 10000
A B
TimeSpan.TicksPerHour Field
C
[ILASM]
D
.field public static literal int64 TicksPerHour
E
[C#]
public const long TicksPerHour = TicksPerMinute * 60
F G
Summary
H
Represents the number of ticks in 1 hour.
I
Description
J
The value of this constant is 36 billion (3.6 × 1010).
K
Example
L
using System;
M N
namespace Samples { public class TimeSpanTicksPerHour { public static void Main() { Console.WriteLine("MaxValue: {0}", TimeSpan.MaxValue); Console.WriteLine("MinValue: {0}", TimeSpan.MinValue); Console.WriteLine("TicksPerDay: {0}", TimeSpan.TicksPerDay); Console.WriteLine("TicksPerHour: {0}", TimeSpan.TicksPerHour); Console.WriteLine("TicksPerMinute: {0}", TimeSpan.TicksPerMinute); Console.WriteLine("TicksPerSecond: {0}", TimeSpan.TicksPerSecond); Console.WriteLine("TicksPerMillisecond: {0}", TimeSpan.TicksPerMillisecond); } } }
O P Q R S T U V W X Y Z
3249
Contents | Index
TimeSpan Structure
System
TicksPerMillisecond Field
The output is MaxValue: 10675199.02:48:05.4775807 MinValue: -10675199.02:48:05.4775808 TicksPerDay: 864000000000 TicksPerHour: 36000000000 TicksPerMinute: 600000000 TicksPerSecond: 10000000 TicksPerMillisecond: 10000
A B C D E F
TimeSpan.TicksPerMillisecond Field
G
[ILASM]
H
.field public static literal int64 TicksPerMillisecond
I
public const long TicksPerMillisecond = 10000
[C#]
J
Summary
K
Represents the number of ticks in 1 millisecond.
L M
Description
N
The value of this constant is 10 thousand (104).
O
Example
P
using System;
Q
namespace Samples { public class TimeSpanTicksPerMillisecond { public static void Main() { Console.WriteLine("MaxValue: {0}", TimeSpan.MaxValue); Console.WriteLine("MinValue: {0}", TimeSpan.MinValue); Console.WriteLine("TicksPerDay: {0}", TimeSpan.TicksPerDay); Console.WriteLine("TicksPerHour: {0}", TimeSpan.TicksPerHour); Console.WriteLine("TicksPerMinute: {0}", TimeSpan.TicksPerMinute); Console.WriteLine("TicksPerSecond: {0}",
R S T U V W X Y Z
3250
Contents | Index
System
TimeSpan Structure TicksPerMinute Field
TimeSpan.TicksPerSecond); Console.WriteLine("TicksPerMillisecond: {0}", TimeSpan.TicksPerMillisecond); }
A
} }
B C
The output is
D MaxValue: 10675199.02:48:05.4775807 MinValue: -10675199.02:48:05.4775808 TicksPerDay: 864000000000 TicksPerHour: 36000000000 TicksPerMinute: 600000000 TicksPerSecond: 10000000 TicksPerMillisecond: 10000
E F G H I J
TimeSpan.TicksPerMinute Field
K [ILASM]
L
.field public static literal int64 TicksPerMinute [C#]
M
public const long TicksPerMinute = TicksPerSecond * 60
N
Summary
O
Represents the number of ticks in 1 minute.
P
Description
Q
The value of this constant is 600 million (6 × 108).
R S
Example
T
using System;
U namespace Samples { public class TimeSpanTicksPerMinute { public static void Main() { Console.WriteLine("MaxValue: {0}", TimeSpan.MaxValue); Console.WriteLine("MinValue: {0}", TimeSpan.MinValue);
V W X Y Z
3251
Contents | Index
TimeSpan Structure
System
TicksPerSecond Field
Console.WriteLine("TicksPerDay: {0}", TimeSpan.TicksPerDay); Console.WriteLine("TicksPerHour: {0}", TimeSpan.TicksPerHour); Console.WriteLine("TicksPerMinute: {0}", TimeSpan.TicksPerMinute); Console.WriteLine("TicksPerSecond: {0}", TimeSpan.TicksPerSecond); Console.WriteLine("TicksPerMillisecond: {0}", TimeSpan.TicksPerMillisecond);
A B C D }
E }
F
}
G
The output is
H MaxValue: 10675199.02:48:05.4775807 MinValue: -10675199.02:48:05.4775808 TicksPerDay: 864000000000 TicksPerHour: 36000000000 TicksPerMinute: 600000000 TicksPerSecond: 10000000 TicksPerMillisecond: 10000
I J K L M N
TimeSpan.TicksPerSecond Field
O [ILASM]
P
.field public static literal int64 TicksPerSecond
Q
[C#]
public const long TicksPerSecond = TicksPerMillisecond * 1000
R S
Summary
T
Represents the number of ticks in 1 second.
U
Description
V
The value of this constant is 10 million (107).
W
Example
X
using System;
Y
namespace Samples { public class TimeSpanTicksPerSecond {
Z
3252
Contents | Index
System
TimeSpan Structure Zero Field
public static void Main() { Console.WriteLine("MaxValue: {0}", TimeSpan.MaxValue); Console.WriteLine("MinValue: {0}", TimeSpan.MinValue); Console.WriteLine("TicksPerDay: {0}", TimeSpan.TicksPerDay); Console.WriteLine("TicksPerHour: {0}", TimeSpan.TicksPerHour); Console.WriteLine("TicksPerMinute: {0}", TimeSpan.TicksPerMinute); Console.WriteLine("TicksPerSecond: {0}", TimeSpan.TicksPerSecond); Console.WriteLine("TicksPerMillisecond: {0}", TimeSpan.TicksPerMillisecond); }
A B C D E F G H I
} }
J K
The output is
L
MaxValue: 10675199.02:48:05.4775807 MinValue: -10675199.02:48:05.4775808 TicksPerDay: 864000000000 TicksPerHour: 36000000000 TicksPerMinute: 600000000 TicksPerSecond: 10000000 TicksPerMillisecond: 10000
M N O P Q R
TimeSpan.Zero Field
S
[ILASM]
T
.field public static initOnly valuetype System.TimeSpan Zero [C#]
U
public static readonly TimeSpan Zero = new TimeSpan (0)
V
Summary
W
Returns a System.TimeSpan whose value is 0.
X
Description
Y
This field is a System.TimeSpan whose value is 0 ticks. [Note: This provides a convenient source for 0 in System.TimeSpan calculations.]
Z
3253
Contents | Index
TimeSpan Structure
System
Days Property
Example using System; namespace Samples { public class TimeSpanZero { public static void Main() { TimeSpan ts = TimeSpan.Zero; Console.WriteLine("TimeSpan.Zero has: "); Console.WriteLine("Days: {0}", ts.Days); Console.WriteLine("Hours: {0}", ts.Hours); Console.WriteLine("Minutes: {0}", ts.Minutes); Console.WriteLine("Seconds: {0}", ts.Seconds); Console.WriteLine("Milliseconds: {0}", ts.Milliseconds); Console.WriteLine("TotalDays: {0}", ts.TotalDays); Console.WriteLine("TotalHours: {0}", ts.TotalHours); Console.WriteLine("TotalMinutes: {0}", ts.TotalMinutes); Console.WriteLine("TotalSeconds: {0}", ts.TotalSeconds); Console.WriteLine("TotalMilliseconds: {0}", ts.TotalMilliseconds); } } }
A B C D E F G H I J K L M N O
The output is
P
TimeSpan.Zero has: Days: 0 Hours: 0 Minutes: 0 Seconds: 0 Milliseconds: 0 TotalDays: 0 TotalHours: 0 TotalMinutes: 0 TotalSeconds: 0 TotalMilliseconds: 0
Q R S T U V W X
TimeSpan.Days Property
Y
[ILASM]
Z
.property int32 Days { public hidebysig specialname instance int32 get_Days() } [C#]
public int Days { get; }
3254
Contents | Index
System
TimeSpan Structure Hours Property
Summary Gets the number of days represented by the current instance.
Property Value
A
A System.Int32 represents the days component of the current instance. [Note: See System.TimeSpan.ToString for a more detailed description of the days component.]
B C D
Example
E
using System;
F namespace Samples { public class TimeSpanDays { public static void Main() { TimeSpan ts = TimeSpan.MaxValue; Console.WriteLine("MaxValue has: "); Console.WriteLine("Days: {0}", ts.Days); Console.WriteLine("Hours: {0}", ts.Hours); Console.WriteLine("Minutes: {0}", ts.Minutes); Console.WriteLine("Seconds: {0}", ts.Seconds); Console.WriteLine("Milliseconds: {0}", ts.Milliseconds); } } }
G H I J K L M N O P Q
The output is
R
MaxValue has: Days: 10675199 Hours: 2 Minutes: 48 Seconds: 5 Milliseconds: 477
S T U V W
TimeSpan.Hours Property
X
[ILASM]
Y
.property int32 Hours { public hidebysig specialname instance int32 get_Hours() }
Z
[C#]
public int Hours { get; }
3255
Contents | Index
TimeSpan Structure
System
Milliseconds Property
Summary Gets the number of hours represented by the current instance. A
Property Value
B
A System.Int32 between 0 and 23 inclusive that represents the hours component of the current instance. [Note: See System.TimeSpan.ToString for a more detailed description of the hours component.]
C D E
Example
F
using System;
G
namespace Samples { public class TimeSpanHours { public static void Main() { TimeSpan ts = TimeSpan.MaxValue; Console.WriteLine("MaxValue has: "); Console.WriteLine("Days: {0}", ts.Days); Console.WriteLine("Hours: {0}", ts.Hours); Console.WriteLine("Minutes: {0}", ts.Minutes); Console.WriteLine("Seconds: {0}", ts.Seconds); Console.WriteLine("Milliseconds: {0}", ts.Milliseconds); } } }
H I J K L M N O P Q
The output is
R
MaxValue has: Days: 10675199 Hours: 2 Minutes: 48 Seconds: 5 Milliseconds: 477
S T U V W X
TimeSpan.Milliseconds Property
Y
[ILASM]
Z
.property int32 Milliseconds { public hidebysig specialname instance int32 get_Milliseconds() } [C#]
public int Milliseconds { get; }
3256
Contents | Index
System
TimeSpan Structure Minutes Property
Summary Gets the number of milliseconds represented by the current instance.
Property Value
A
A System.Int32 between 0 and 999 inclusive that represents the fractional seconds component of the current instance converted to milliseconds. [Note: See System.TimeSpan.ToString for a more detailed description of the fractional seconds component.]
B C D
Example
E
using System;
F
namespace Samples { public class TimeSpanMilliseconds { public static void Main() { TimeSpan ts = TimeSpan.MaxValue; Console.WriteLine("MaxValue has: "); Console.WriteLine("Days: {0}", ts.Days); Console.WriteLine("Hours: {0}", ts.Hours); Console.WriteLine("Minutes: {0}", ts.Minutes); Console.WriteLine("Seconds: {0}", ts.Seconds); Console.WriteLine("Milliseconds: {0}", ts.Milliseconds); } } }
G H I J K L M N O P Q
The output is
R
MaxValue has: Days: 10675199 Hours: 2 Minutes: 48 Seconds: 5 Milliseconds: 477
S T U V W
TimeSpan.Minutes Property
X
[ILASM]
Y
.property int32 Minutes { public hidebysig specialname instance int32 get_Minutes() }
Z
[C#]
public int Minutes { get; }
3257
Contents | Index
TimeSpan Structure
System
Seconds Property
Summary Gets the number of minutes represented by the current instance. A
Property Value
B
A System.Int32 between 0 and 59 inclusive that represents the minutes component of the current instance. [Note: See System.TimeSpan.ToString for a more detailed description of the minutes component.]
C D E
Example
F
using System;
G
namespace Samples { public class TimeSpanMinutes { public static void Main() { TimeSpan ts = TimeSpan.MaxValue; Console.WriteLine("MaxValue has: "); Console.WriteLine("Days: {0}", ts.Days); Console.WriteLine("Hours: {0}", ts.Hours); Console.WriteLine("Minutes: {0}", ts.Minutes); Console.WriteLine("Seconds: {0}", ts.Seconds); Console.WriteLine("Milliseconds: {0}", ts.Milliseconds); } } }
H I J K L M N O P Q
The output is
R
MaxValue has: Days: 10675199 Hours: 2 Minutes: 48 Seconds: 5 Milliseconds: 477
S T U V W X
TimeSpan.Seconds Property
Y
[ILASM]
Z
.property int32 Seconds { public hidebysig specialname instance int32 get_Seconds() } [C#]
public int Seconds { get; }
3258
Contents | Index
System
TimeSpan Structure Ticks Property
Summary Gets the number of seconds represented by the current instance.
Property Value
A
A System.Int32 between 0 and 59 inclusive that represents the seconds component of the current instance. [Note: See System.TimeSpan.ToString for a more detailed description of the seconds component.]
B C D
Example
E
using System;
F G
namespace Samples { public class TimeSpanSeconds { public static void Main() { TimeSpan ts = TimeSpan.MaxValue; Console.WriteLine("MaxValue has: "); Console.WriteLine("Days: {0}", ts.Days); Console.WriteLine("Hours: {0}", ts.Hours); Console.WriteLine("Minutes: {0}", ts.Minutes); Console.WriteLine("Seconds: {0}", ts.Seconds); Console.WriteLine("Milliseconds: {0}", ts.Milliseconds); } } }
H I J K L M N O P Q
The output is
R S
MaxValue has: Days: 10675199 Hours: 2 Minutes: 48 Seconds: 5 Milliseconds: 477
T U V W X
TimeSpan.Ticks Property
Y
[ILASM]
Z
.property int64 Ticks { public hidebysig specialname instance int64 get_Ticks() } [C#]
public long Ticks { get; }
3259
Contents | Index
TimeSpan Structure
System
TotalDays Property
Summary Gets the number of ticks represented by the current instance. A
Property Value
B
A System.Int64 specifying the number of ticks represented by the current instance.
C
Example
D
using System;
E namespace Samples { public class TimeSpanTicks { public static void Main() { TimeSpan ts = TimeSpan.MaxValue; Console.WriteLine("MaxValue has: "); Console.WriteLine("Days: {0}", ts.Days); Console.WriteLine("Hours: {0}", ts.Hours); Console.WriteLine("Minutes: {0}", ts.Minutes); Console.WriteLine("Seconds: {0}", ts.Seconds); Console.WriteLine("Milliseconds: {0}", ts.Milliseconds); Console.WriteLine( "MaxValue is: {0} ticks", ts.Ticks); } } }
F G H I J K L M N O P Q
The output is
R MaxValue has: Days: 10675199 Hours: 2 Minutes: 48 Seconds: 5 Milliseconds: 477 MaxValue is: 9223372036854775807 ticks
S T U V W X
TimeSpan.TotalDays Property
Y
[ILASM]
.property float64 TotalDays { public hidebysig specialname instance float64 get_TotalDays() }
Z
[C#]
public double TotalDays { get; }
3260
Contents | Index
System
TimeSpan Structure TotalDays Property
Summary Gets the value of the current instance expressed in days.
Property Value
A
A System.Double that specifies the total number of days represented by the current instance.
B C D
Description
E
[Note: This property converts the value of the current instance from ticks to days. This number may include whole and fractional days.] This member must be implemented if the Extended Numerics Library is present in the implementation.
F G H
Example
I
using System;
J
namespace Samples { public class TimeSpanTotalDays { public static void Main() { TimeSpan ts = TimeSpan.MaxValue; Console.WriteLine("MaxValue is: "); Console.WriteLine("TotalDays: {0}", ts.TotalDays); Console.WriteLine("TotalHours: {0}", ts.TotalHours); Console.WriteLine("TotalMinutes: {0}", ts.TotalMinutes); Console.WriteLine("TotalSeconds: {0}", ts.TotalSeconds); Console.WriteLine("TotalMilliseconds: {0}", ts.TotalMilliseconds); Console.WriteLine("Ticks: {0}", ts.Ticks); } } }
K L M N O P Q R S T U V W X Y Z
3261
Contents | Index
TimeSpan Structure
System
TotalHours Property
The output is MaxValue is: TotalDays: 10675199.1167301 TotalHours: 256204778.801522 TotalMinutes: 15372286728.0913 TotalSeconds: 922337203685.478 TotalMilliseconds: 922337203685477 Ticks: 9223372036854775807
A B C D E F
TimeSpan.TotalHours Property
G
[ILASM]
H
.property float64 TotalHours { public hidebysig specialname instance float64 get_TotalHours() } [C#]
I
public double TotalHours { get; }
J
Summary
K
Gets the value of the current instance expressed in hours.
L M
Property Value
N
A System.Double that specifies the total number of hours represented by the current instance.
O P
Description
Q
[Note: This property converts the value of the current instance from ticks to hours. This number may include whole and fractional hours.] This member must be implemented if the Extended Numerics Library is present in the implementation.
R S T
Example
U
using System;
V namespace Samples { public class TimeSpanTotalHours { public static void Main() { TimeSpan ts = TimeSpan.MaxValue; Console.WriteLine("MaxValue is: "); Console.WriteLine("TotalDays: {0}",
W X Y Z
3262
Contents | Index
System
TimeSpan Structure TotalMilliseconds Property
ts.TotalDays); Console.WriteLine("TotalHours: {0}", ts.TotalHours); Console.WriteLine("TotalMinutes: {0}", ts.TotalMinutes); Console.WriteLine("TotalSeconds: {0}", ts.TotalSeconds); Console.WriteLine("TotalMilliseconds: {0}", ts.TotalMilliseconds); Console.WriteLine("Ticks: {0}", ts.Ticks);
A B C D
}
E
}
F
}
G
The output is
H MaxValue is: TotalDays: 10675199.1167301 TotalHours: 256204778.801522 TotalMinutes: 15372286728.0913 TotalSeconds: 922337203685.478 TotalMilliseconds: 922337203685477 Ticks: 9223372036854775807
I J K L M N
TimeSpan.TotalMilliseconds Property
O
[ILASM]
P
.property float64 TotalMilliseconds { public hidebysig specialname instance float64 get_TotalMilliseconds() }
Q
[C#]
R
public double TotalMilliseconds { get; }
S
Summary
T
Gets the value of the current instance expressed in milliseconds.
U
Description
V
[Note: This property converts the value of the current instance from ticks to milliseconds. This number may include whole and fractional milliseconds.] This member must be implemented if the Extended Numerics Library is present in the implementation.
W X Y Z
3263
Contents | Index
TimeSpan Structure
System
TotalMinutes Property
Example using System; namespace Samples { public class TimeSpanTotalMilliseconds { public static void Main() { TimeSpan ts = TimeSpan.MaxValue; Console.WriteLine("MaxValue is: "); Console.WriteLine("TotalDays: {0}", ts.TotalDays); Console.WriteLine("TotalHours: {0}", ts.TotalHours); Console.WriteLine("TotalMinutes: {0}", ts.TotalMinutes); Console.WriteLine("TotalSeconds: {0}", ts.TotalSeconds); Console.WriteLine("TotalMilliseconds: {0}", ts.TotalMilliseconds); Console.WriteLine("Ticks: {0}", ts.Ticks); } } }
A B C D E F G H I J K L M N
The output is
O P
MaxValue is: TotalDays: 10675199.1167301 TotalHours: 256204778.801522 TotalMinutes: 15372286728.0913 TotalSeconds: 922337203685.478 TotalMilliseconds: 922337203685477 Ticks: 9223372036854775807
Q R S T U V
TimeSpan.TotalMinutes Property
W
[ILASM]
X
.property float64 TotalMinutes { public hidebysig specialname instance float64 get_TotalMinutes() }
Y
[C#]
public double TotalMinutes { get; }
Z
3264
Contents | Index
System
TimeSpan Structure TotalMinutes Property
Summary Gets the value of the current instance expressed in minutes.
Description
A
[Note: This property converts the value of the current instance from ticks to minutes. This number may include whole and fractional minutes.] This member must be implemented if the Extended Numerics Library is present in the implementation.
B C D
Example
E
using System;
F G
namespace Samples { public class TimeSpanTotalMinutes { public static void Main() { TimeSpan ts = TimeSpan.MaxValue; Console.WriteLine("MaxValue is: "); Console.WriteLine("TotalDays: {0}", ts.TotalDays); Console.WriteLine("TotalHours: {0}", ts.TotalHours); Console.WriteLine("TotalMinutes: {0}", ts.TotalMinutes); Console.WriteLine("TotalSeconds: {0}", ts.TotalSeconds); Console.WriteLine("TotalMilliseconds: {0}", ts.TotalMilliseconds); Console.WriteLine("Ticks: {0}", ts.Ticks); } } }
H I J K L M N O P Q R S T U
The output is
V MaxValue is: TotalDays: 10675199.1167301 TotalHours: 256204778.801522 TotalMinutes: 15372286728.0913 TotalSeconds: 922337203685.478 TotalMilliseconds: 922337203685477 Ticks: 9223372036854775807
W X Y Z
3265
Contents | Index
TimeSpan Structure
System
TotalSeconds Property
TimeSpan.TotalSeconds Property [ILASM]
A
.property float64 TotalSeconds { public hidebysig specialname instance float64 get_TotalSeconds() }
B
[C#]
public double TotalSeconds { get; }
C D
Summary
E
Gets the value of the current instance expressed in seconds.
F
Property Value
G
A System.Double that specifies the total number of seconds represented by the current instance.
H I
Description
J
[Note: This property converts the value of the current instance from ticks to seconds. This number may include whole and fractional seconds.] This member must be implemented if the Extended Numerics Library is present in the implementation.
K L M
Example
N
using System;
O
namespace Samples { public class TimeSpanTotalSeconds { public static void Main() { TimeSpan ts = TimeSpan.MaxValue; Console.WriteLine("MaxValue is: "); Console.WriteLine("TotalDays: {0}", ts.TotalDays); Console.WriteLine("TotalHours: {0}", ts.TotalHours); Console.WriteLine("TotalMinutes: {0}", ts.TotalMinutes); Console.WriteLine("TotalSeconds: {0}", ts.TotalSeconds); Console.WriteLine("TotalMilliseconds: {0}", ts.TotalMilliseconds); Console.WriteLine("Ticks: {0}", ts.Ticks); } } }
P Q R S T U V W X Y Z
3266
Contents | Index
System
TimeSpan Structure Add() Method
The output is MaxValue is: TotalDays: 10675199.1167301 TotalHours: 256204778.801522 TotalMinutes: 15372286728.0913 TotalSeconds: 922337203685.478 TotalMilliseconds: 922337203685477 Ticks: 9223372036854775807
A B C D E
TimeSpan.Add(System.TimeSpan) Method
F
[ILASM]
G
.method public hidebysig instance valuetype System.TimeSpan Add(valuetype System.TimeSpan ts)
H
[C#]
I
public TimeSpan Add(TimeSpan ts)
J
Summary
K
Adds the specified System.TimeSpan to the current instance.
L M
Parameters
N O
Parameter
Description
ts
A System.TimeSpan instance to add to the current instance.
P Q R
Return Value
S
A System.TimeSpan that represents the value of the current instance plus the value of ts.
T U
Exceptions
V
Exception
Condition
System.OverflowException
The sum of the value of the current instance and the value of ts is less than System.TimeSpan.MinValue or greater than System.TimeSpan.MaxValue.
W X Y Z
3267
Contents | Index
TimeSpan Structure
System
Compare() Method
Example using System; namespace Samples { public class TimeSpanAdd { public static void Main() { DateTime dt = DateTime.Now; TimeSpan ts = new TimeSpan(7, 0, 0, 0); Console.WriteLine( "In 1 week it will be {0}", dt + ts); ts = ts.Add(ts); Console.WriteLine( "In a 2 weeks it will be {0}", dt + ts); ts = ts.Add(ts); Console.WriteLine( "In a 4 weeks it will be {0}", dt + ts); } } }
A B C D E F G H I J K L M
The output is
N In 1 week it will be 1/07/2003 4:58:52 AM In a 2 weeks it will be 8/07/2003 4:58:52 AM In a 4 weeks it will be 22/07/2003 4:58:52 AM
O P Q R
TimeSpan.Compare(System.TimeSpan, System.TimeSpan) Method
S
[ILASM]
T
.method public hidebysig static int32 Compare(valuetype System.TimeSpan t1, valuetype System.TimeSpan t2)
U
[C#]
public static int Compare(TimeSpan t1, TimeSpan t2)
V W
Summary
X
Returns the sort order of two System.TimeSpan structures.
Y Z
3268
Contents | Index
System
TimeSpan Structure Compare() Method
Parameters Parameter
Description
t1
The first System.TimeSpan to compare.
t2
The second System.TimeSpan to compare.
A B C D
Return Value
E
A System.Int32 containing a value that reflects the sort order of t1 as compared to t2. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number.
F G H I
Value
Condition
J
any negative number
t1 < t2.
K
zero
t1 == t2.
any positive number
t1 > t2.
L M N O
Example
P
using System;
Q
namespace Samples { public class TimeSpanCompare { public static void Main() { TimeSpan ts1 = new TimeSpan(1, 0, 0, 0); TimeSpan ts2 = new TimeSpan(24, 0, 0); Console.WriteLine( "TimeSpan.Compare(ts1, ts2) yields: {0}", TimeSpan.Compare(ts1, ts2)); Console.WriteLine("Increasing ts2"); ts2 = ts2.Add(new TimeSpan(0,0, 1)); Console.WriteLine( "TimeSpan.Compare(ts1, ts2) yields: {0}", TimeSpan.Compare(ts1, ts2)); Console.WriteLine(
R S T U V W X Y Z
3269
Contents | Index
TimeSpan Structure
System
CompareTo() Method
"TimeSpan.Compare(ts2, ts1) yields: {0}", TimeSpan.Compare(ts2, ts1)); } }
A
}
B
The output is
C TimeSpan.Compare(ts1, ts2) yields: 0 Increasing ts2 TimeSpan.Compare(ts1, ts2) yields: -1 TimeSpan.Compare(ts2, ts1) yields: 1
D E F G
TimeSpan.CompareTo(System.Object) Method
H [ILASM]
I
.method public final hidebysig virtual int32 CompareTo(object value)
J
[C#]
public int CompareTo(object value)
K L
Summary
M
Returns the sort order of the current instance compared to the specified System.Object.
N
Parameters
O P Q
Parameter
Description
value
The System.Object to compare to the current instance.
R S
Return Value
T
A System.Int32 containing a value that reflects the sort order of the current instance as compared to value. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number.
U V W
Value
Condition
Y
any negative number
Current instance < value.
Z
zero
Current instance == value.
any positive number
Current instance > value, or value is a null reference.
X
3270
Contents | Index
System
TimeSpan Structure CompareTo() Method
Description [Note: This method is implemented to support the System.IComparable interface.] A
Exceptions
B
Exception
Condition
C
value is not a System.TimeSpan and is not a null reference.
D
System.ArgumentException
E F
Example
G
using System;
H
namespace Samples { public class TimeSpanCompareTo { private static string CompareTimeSpans(TimeSpan ts1, TimeSpan ts2) { int i = ts1.CompareTo(ts2); if(0 == i) return String.Format("{0} is equal to {1}", ts1, ts2); if(i > 0) return String.Format("{0} is greater than {1}", ts1, ts2); else return String.Format("{0} is less than {1}", ts1, ts2); } public static void Main() { TimeSpan ts1 = new TimeSpan(1, 0, 0, 0); TimeSpan ts2 = new TimeSpan(24, 0, 1); Console.WriteLine(CompareTimeSpans(ts1, ts1)); Console.WriteLine(CompareTimeSpans(ts1, ts2)); Console.WriteLine(CompareTimeSpans(ts2, ts1)); } } }
I J K L M N O P Q R S T U V W X
The output is
Y Z
1.00:00:00 is equal to 1.00:00:00 1.00:00:00 is less than 1.00:00:01 1.00:00:01 is greater than 1.00:00:00
3271
Contents | Index
TimeSpan Structure
System
Duration() Method
TimeSpan.Duration() Method [ILASM]
.method public hidebysig instance valuetype System.TimeSpan Duration()
A
[C#]
B
public TimeSpan Duration()
C
Summary
D
Returns a System.TimeSpan whose value is the absolute value of the current instance.
E
Exceptions
F G H
Exception
Condition
System.OverflowException
The value of the current instance is System.TimeSpan.MinValue.
I J
Example
K
using System;
L namespace Samples { public class TimeSpanDuration { public static void Main() { TimeSpan ts = new TimeSpan(-24, 0, 0); Console.WriteLine("ts is: {0}", ts); Console.WriteLine("ts.Duration() is: {0}", ts.Duration()); } } }
M N O P Q R S T
The output is
U V
ts is: -1.00:00:00 ts.Duration() is: 1.00:00:00
W X
TimeSpan.Equals(System.Object) Method
Y
[ILASM]
Z
.method public hidebysig virtual bool Equals(object value) [C#]
public override bool Equals(object value)
3272
Contents | Index
System
TimeSpan Structure Equals() Method
Summary Determines whether the current instance and the specified System.Object represent the same type and value. [Note: This method overrides System.Object.Equals.] A
Parameters
B
Parameter
Description
value
The System.Object to compare to the current instance.
C D E F
Return Value
G
true if value represents the same type and value as the current instance. If value is a null reference or is not a System.TimeSpan, returns false.
H I
Example
J
using System;
K namespace Samples { public class TimeSpanEquals { public static void Main() { TimeSpan ts1 = new TimeSpan(1, 0, 0, 0); TimeSpan ts2 = new TimeSpan(24, 0, 0); Console.WriteLine( "ts1.Equals(ts2) yields: {0}", ts1.Equals(ts2)); Console.WriteLine("Increasing ts2"); ts2 = ts2.Add(new TimeSpan(0,0, 1)); Console.WriteLine( "ts1.Equals(ts2) yields: {0}", ts1.Equals(ts2)); Console.WriteLine( "ts2.Equals(ts1) yields: {0}", ts2.Equals(ts1)); } } }
L M N O P Q R S T U V W X
The output is
Y
ts1.Equals(ts2) yields: True Increasing ts2 ts1.Equals(ts2) yields: False ts2.Equals(ts1) yields: False
Z
3273
Contents | Index
TimeSpan Structure
System
Equals() Method
TimeSpan.Equals(System.TimeSpan, System.TimeSpan) Method [ILASM]
.method public hidebysig static bool Equals(valuetype System.TimeSpan t1, valuetype System.TimeSpan t2)
A
[C#]
B
public static bool Equals(TimeSpan t1, TimeSpan t2)
C
Summary
D
Determines whether two System.TimeSpan structures represent the same type and value.
E
Parameters
F G
Parameter
Description
t1
The first instance of System.TimeSpan to compare for equality.
t2
The second instance of System.TimeSpan to compare for equality.
H I J K
Return Value
L
true if t1 and t2 represent the same value; otherwise, false.
M
Example
N
using System;
O
namespace Samples { public class TimeSpanEquals { public static void Main() { TimeSpan ts1 = new TimeSpan(1, 0, 0, 0); TimeSpan ts2 = new TimeSpan(24, 0, 0); Console.WriteLine( "TimeSpan.Equals(ts1, ts2) yields: {0}", TimeSpan.Equals(ts1, ts2)); Console.WriteLine("Increasing ts2"); ts2 = ts2.Add(new TimeSpan(0,0, 1)); Console.WriteLine( "TimeSpan.Equals(ts1, ts2) yields: {0}", TimeSpan.Equals(ts1, ts2)); Console.WriteLine( "TimeSpan.Equals(ts2, ts1) yields: {0}", TimeSpan.Equals(ts2, ts1)); } } }
P Q R S T U V W X Y Z
3274
Contents | Index
System
TimeSpan Structure FromDays() Method
The output is TimeSpan.Equals(ts1, ts2) yields: True Increasing ts2 TimeSpan.Equals(ts1, ts2) yields: False TimeSpan.Equals(ts2, ts1) yields: False
A B C D
TimeSpan.FromDays(System.Double) Method
E
[ILASM]
.method public hidebysig static valuetype System.TimeSpan FromDays(float64 value)
F
[C#]
G
public static TimeSpan FromDays(double value)
H
Summary
I
Returns a System.TimeSpan that represents the specified number of days where the specification is accurate to the nearest millisecond.
J K
Parameters
L
Parameter
Description
value
A System.Double that specifies the number of days with which the new System.TimeSpan is initialized.
M N O P Q
Description
R
value will only be considered accurate to the nearest millisecond. If value is System.Double.PositiveInfinity, a System.TimeSpan with the value System.TimeSpan.MaxValue is returned. If value is System.Double.NegativeInfinity, a System.TimeSpan with the value System.TimeSpan.MinValue is returned. This member must be implemented if the Extended Numerics Library is present in the implementation.
S T U V W X Y Z
3275
Contents | Index
TimeSpan Structure
System
FromDays() Method
Exceptions Exception
Condition
System.OverflowException
The System.TimeSpan represented by value is greater than System.TimeSpan.MaxValue or less than System.TimeSpan.MinValue.
System.ArgumentException
value is equal to System.Double.NaN.
A B C D E F
Example
G
using System;
H namespace Samples { public class TimeSpanFromDays { public static void Main() { TimeSpan ts = TimeSpan.FromDays(7); Console.WriteLine("TotalDays: {0}", ts.TotalDays); Console.WriteLine("TotalHours: {0}", ts.TotalHours); Console.WriteLine("TotalMinutes: {0}", ts.TotalMinutes); Console.WriteLine("TotalSeconds: {0}", ts.TotalSeconds); Console.WriteLine("TotalMilliseconds: {0}", ts.TotalMilliseconds); Console.WriteLine("Ticks: {0}", ts.Ticks); } } }
I J K L M N O P Q R S T U V
The output is
W TotalDays: 7 TotalHours: 168 TotalMinutes: 10080 TotalSeconds: 604800 TotalMilliseconds: 604800000 Ticks: 6048000000000
X Y Z
3276
Contents | Index
System
TimeSpan Structure FromHours() Method
TimeSpan.FromHours(System.Double) Method [ILASM]
.method public hidebysig static valuetype System.TimeSpan FromHours(float64 value) [C#]
A
public static TimeSpan FromHours(double value)
B C
Summary
D
Returns a System.TimeSpan that represents the specified number of hours where the specification is accurate to the nearest millisecond.
E F
Parameters
G H
Parameter
Description
value
A System.Double that specifies the number of hours with which the new System.TimeSpan is initialized.
I J K
Description
L
value will only be considered accurate to the nearest millisecond. If value is System.Double.PositiveInfinity, a System.TimeSpan with the value System.TimeSpan.MaxValue is returned. If value is System.Double.NegativeInfinity, a System.TimeSpan with the value System.TimeSpan.MinValue is returned. This member must be implemented if the Extended Numerics Library is present in the implementation.
M
Exceptions
R
N O P Q
S
Exception
Condition
T
The System.TimeSpan represented by value is greater than System.TimeSpan.MaxValue or less than System.TimeSpan.MinValue.
U
System.OverflowException
System.ArgumentException
value is equal to System.Double.NaN.
V W X Y Z
3277
Contents | Index
TimeSpan Structure
System
FromMilliseconds() Method
Example using System; namespace Samples { public class TimeSpanFromHours { public static void Main() { TimeSpan ts = TimeSpan.FromHours(12); Console.WriteLine("TotalDays: {0}", ts.TotalDays); Console.WriteLine("TotalHours: {0}", ts.TotalHours); Console.WriteLine("TotalMinutes: {0}", ts.TotalMinutes); Console.WriteLine("TotalSeconds: {0}", ts.TotalSeconds); Console.WriteLine("TotalMilliseconds: {0}", ts.TotalMilliseconds); Console.WriteLine("Ticks: {0}", ts.Ticks); } } }
A B C D E F G H I J K L M N
The output is
O TotalDays: 0.5 TotalHours: 12 TotalMinutes: 720 TotalSeconds: 43200 TotalMilliseconds: 43200000 Ticks: 432000000000
P Q R S T U
TimeSpan.FromMilliseconds(System.Double) Method
V
[ILASM]
W
.method public hidebysig static valuetype System.TimeSpan FromMilliseconds(float64 value)
X
[C#]
public static TimeSpan FromMilliseconds(double value)
Y
Summary
Z
Returns a System.TimeSpan that represents the specified number of milliseconds where the specification is accurate to the nearest millisecond. 3278
Contents | Index
System
TimeSpan Structure FromMilliseconds() Method
Parameters Parameter
Description
value
A System.Double that specifies the number of milliseconds with which the new System.TimeSpan is initialized.
A B C D
Description
E
value will only be considered accurate to the nearest millisecond. If value is System.Double.PositiveInfinity, a System.TimeSpan with the value System.TimeSpan.MaxValue is returned. If value is System.Double.NegativeInfinity, a System.TimeSpan with the value System.TimeSpan.MinValue is returned. This member must be implemented if the Extended Numerics Library is present in the implementation.
F G H I J
Exceptions
K
Exception
Condition
System.OverflowException
The System.TimeSpan represented by value is greater than System.TimeSpan.MaxValue or less than System.TimeSpan.MinValue.
L M N O
System.ArgumentException
value is equal to System.Double.NaN.
P Q R
Example
S
using System;
T
namespace Samples { public class TimeSpanFromMilliseconds { public static void Main() { TimeSpan ts = TimeSpan.FromMilliseconds( 604800000); Console.WriteLine("TotalDays: {0}", ts.TotalDays); Console.WriteLine("TotalHours: {0}", ts.TotalHours); Console.WriteLine("TotalMinutes: {0}",
U V W X Y Z
3279
Contents | Index
TimeSpan Structure
System
FromMinutes() Method
ts.TotalMinutes); Console.WriteLine("TotalSeconds: {0}", ts.TotalSeconds); Console.WriteLine("TotalMilliseconds: {0}", ts.TotalMilliseconds); Console.WriteLine("Ticks: {0}", ts.Ticks);
A B }
C
} }
D
The output is
E F
TotalDays: 7 TotalHours: 168 TotalMinutes: 10080 TotalSeconds: 604800 TotalMilliseconds: 604800000 Ticks: 6048000000000
G H I J K
TimeSpan.FromMinutes(System.Double) Method
L [ILASM]
M
.method public hidebysig static valuetype System.TimeSpan FromMinutes(float64 value) [C#]
N
public static TimeSpan FromMinutes(double value)
O P
Summary
Q
Returns a System.TimeSpan that represents the specified number of minutes where the specification is accurate to the nearest millisecond.
R
Parameters
S T
Parameter
Description
value
A System.Double that specifies the number of minutes with which the new System.TimeSpan is initialized.
U V W X
Description
Y
value will only be considered accurate to the nearest millisecond. If value is System.Double.PositiveInfinity, a System.TimeSpan with the value System.TimeSpan.MaxValue is returned. If value is System.Double.NegativeInfinity, a System.TimeSpan with the value System.TimeSpan.MinValue is
Z
3280
Contents | Index
System
TimeSpan Structure FromMinutes() Method
returned. This member must be implemented if the Extended Numerics Library is present in the implementation. A
Exceptions
B
Exception
Condition
System.OverflowException
The System.TimeSpan represented by value is greater than System.TimeSpan.MaxValue or less than System.TimeSpan.MinValue.
System.ArgumentException
value is equal to System.Double.NaN.
C D E F G H
Example
I
using System;
J namespace Samples { public class TimeSpanFromMinutes { public static void Main() { TimeSpan ts = TimeSpan.FromMinutes(30); Console.WriteLine("TotalDays: {0}", ts.TotalDays); Console.WriteLine("TotalHours: {0}", ts.TotalHours); Console.WriteLine("TotalMinutes: {0}", ts.TotalMinutes); Console.WriteLine("TotalSeconds: {0}", ts.TotalSeconds); Console.WriteLine("TotalMilliseconds: {0}", ts.TotalMilliseconds); Console.WriteLine("Ticks: {0}", ts.Ticks); } } }
K L M N O P Q R S T U V W
The output is
X
TotalDays: 0.0208333333333333 TotalHours: 0.5 TotalMinutes: 30 TotalSeconds: 1800 TotalMilliseconds: 1800000 Ticks: 18000000000
Y Z
3281
Contents | Index
TimeSpan Structure
System
FromSeconds() Method
TimeSpan.FromSeconds(System.Double) Method [ILASM]
.method public hidebysig static valuetype System.TimeSpan FromSeconds(float64 value)
A
[C#]
public static TimeSpan FromSeconds(double value)
B C
Summary
D
Returns a System.TimeSpan that represents the specified number of seconds where the specification is accurate to the nearest millisecond.
E F
Parameters
G H
Parameter
Description
value
A System.Double that specifies the number of seconds with which the new System.TimeSpan is initialized.
I J K L
Description
M
value will only be considered accurate to the nearest millisecond. If value is System.Double.PositiveInfinity, a System.TimeSpan with the value System.TimeSpan.MaxValue is returned. If value is System.Double.NegativeInfinity, a System.TimeSpan with the value System.TimeSpan.MinValue is returned. This member must be implemented if the Extended Numerics Library is present in the implementation.
N O P Q R
Exceptions
S T
Exception
Condition
System.OverflowException
The System.TimeSpan represented by value is greater than System.TimeSpan.MaxValue or less than System.TimeSpan.MinValue.
System.ArgumentException
value is equal to System.Double.NaN.
U V W X Y Z
3282
Contents | Index
System
TimeSpan Structure FromTicks() Method
Example using System; namespace Samples { public class TimeSpanFromSeconds { public static void Main() { TimeSpan ts = TimeSpan.FromSeconds(180); Console.WriteLine("TotalDays: {0}", ts.TotalDays); Console.WriteLine("TotalHours: {0}", ts.TotalHours); Console.WriteLine("TotalMinutes: {0}", ts.TotalMinutes); Console.WriteLine("TotalSeconds: {0}", ts.TotalSeconds); Console.WriteLine("TotalMilliseconds: {0}", ts.TotalMilliseconds); Console.WriteLine("Ticks: {0}", ts.Ticks); } } }
A B C D E F G H I J K L M N
The output is
O TotalDays: 0.00208333333333333 TotalHours: 0.05 TotalMinutes: 3 TotalSeconds: 180 TotalMilliseconds: 180000 Ticks: 1800000000
P Q R S T
TimeSpan.FromTicks(System.Int64) Method
U
[ILASM]
V
.method public hidebysig static valuetype System.TimeSpan FromTicks(int64 value) [C#]
W
public static TimeSpan FromTicks(long value)
X Y
Summary
Z
Returns a System.TimeSpan that represents the specified number of ticks.
3283
Contents | Index
TimeSpan Structure
System
FromTicks() Method
Parameters Parameter
Description
value
A System.Int64 that specifies the number of ticks with which the new System.TimeSpan is initialized.
A B C D
Description
E
This method is equivalent to the System.TimeSpan(System.Int64) constructor.
F
Example
G
using System;
H
namespace Samples { public class TimeSpanFromTicks { public static void Main() { TimeSpan ts = TimeSpan.FromTicks( 6048000000000); Console.WriteLine("TotalDays: {0}", ts.TotalDays); Console.WriteLine("TotalHours: {0}", ts.TotalHours); Console.WriteLine("TotalMinutes: {0}", ts.TotalMinutes); Console.WriteLine("TotalSeconds: {0}", ts.TotalSeconds); Console.WriteLine("TotalMilliseconds: {0}", ts.TotalMilliseconds); Console.WriteLine("Ticks: {0}", ts.Ticks); } } }
I J K L M N O P Q R S T U V W
The output is
X
TotalDays: 7 TotalHours: 168 TotalMinutes: 10080 TotalSeconds: 604800 TotalMilliseconds: 604800000 Ticks: 6048000000000
Y Z
3284
Contents | Index
System
TimeSpan Structure GetHashCode() Method
TimeSpan.GetHashCode() Method [ILASM]
.method public hidebysig virtual int32 GetHashCode() [C#]
A
public override int GetHashCode()
B C
Summary
D
Generates a hash code for the current instance.
E
Description
F
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
G H
Example
I
using System;
J
namespace Samples { public class TimeSpanGetHashCode { public static void Main() { TimeSpan ts = TimeSpan.MaxValue; Console.WriteLine("Value: {0} HashCode: {1}", ts, ts.GetHashCode()); ts = TimeSpan.Zero; Console.WriteLine("Value: {0} HashCode: {1}", ts, ts.GetHashCode()); ts = TimeSpan.MinValue; Console.WriteLine("Value: {0} HashCode: {1}", ts, ts.GetHashCode()); } } }
K L M N O P Q R S T U V
The output is
W X
Value: 10675199.02:48:05.4775807 HashCode: -2147483648 Value: 00:00:00 HashCode: 0 Value: -10675199.02:48:05.4775808 HashCode: -2147483648
Y Z
3285
Contents | Index
TimeSpan Structure
System
Negate() Method
TimeSpan.Negate() Method [ILASM]
.method public hidebysig instance valuetype System.TimeSpan Negate()
A
[C#]
public TimeSpan Negate()
B C
Summary
D
Returns a System.TimeSpan with the same absolute value but opposite sign as the current instance.
E F
Exceptions
G H
Exception
Condition
System.OverflowException
The value of the current instance is System.TimeSpan.MinValue.
I J K
Example
L
using System;
M namespace Samples { public class TimeSpanNegate { public static void Main() { TimeSpan ts = TimeSpan.MaxValue; Console.WriteLine("Value: {0} Negate: {1}", ts, ts.Negate()); ts = TimeSpan.Zero; Console.WriteLine("Value: {0} Negate: {1}", ts, ts.Negate()); ts = TimeSpan.MinValue; try { Console.WriteLine("Value: {0} Negate: {1}", ts, ts.Negate()); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
N O P Q R S T U V W X Y Z
3286
Contents | Index
System
TimeSpan Structure op_Addition() Method
The output is Value: 10675199.02:48:05.4775807 Negate: -10675199.02:48:05.4775807 Value: 00:00:00 Negate: 00:00:00 Exception: System.OverflowException: Negating the minimum value of a twos complement number is invalid. at System.TimeSpan.Negate() at Samples.TimeSpanNegate.Main() in C:\Books\BCL\Samples\System\TimeSpan\ Negate()\TimeSpan.cs:line 18
A B C D E
TimeSpan.op_Addition(System.TimeSpan, System.TimeSpan) Method
F
[ILASM]
G
.method public hidebysig static specialname valuetype System.TimeSpan op_Addition(valuetype System.TimeSpan t1, valuetype System.TimeSpan t2)
H
[C#]
I
public static TimeSpan operator +(TimeSpan t1, TimeSpan t2)
J
Summary
K
Adds the values of two System.TimeSpan instances.
L M
Parameters
N O
Parameter
Description
t1
The first System.TimeSpan.
t2
The second System.TimeSpan.
P Q R S
Return Value
T
A System.TimeSpan whose value is the sum of the values of t1 and t2.
U V
Exceptions
W
Exception
Condition
X
System.OverflowException
The sum of t1 and t2 is less than System.TimeSpan.MinValue or greater than System.TimeSpan.MaxValue.
Y Z
3287
Contents | Index
TimeSpan Structure
System
op_Equality() Method
Example using System; namespace Samples { public class TimeSpanOp_Addition { public static void Main() { DateTime dt = DateTime.Now; TimeSpan ts = new TimeSpan(7, 0, 0, 0); Console.WriteLine( "In 1 week it will be {0}", dt + ts); ts = ts + ts; Console.WriteLine( "In a 2 weeks it will be {0}", dt + ts); ts += ts; Console.WriteLine( "In a 4 weeks it will be {0}", dt + ts); } } }
A B C D E F G H I J K L M
The output is
N In 1 week it will be 1/07/2003 6:09:25 PM In a 2 weeks it will be 8/07/2003 6:09:25 PM In a 4 weeks it will be 22/07/2003 6:09:25 PM
O P Q R
TimeSpan.op_Equality(System.TimeSpan, System.TimeSpan) Method
S
[ILASM]
T
.method public hidebysig static specialname bool op_Equality(valuetype System.TimeSpan t1, valuetype System.TimeSpan t2)
U
[C#]
public static bool operator ==(TimeSpan t1, TimeSpan t2)
V W
Summary
X
Determines whether the value of one System.TimeSpan is equal to the value of another System.TimeSpan.
Y Z
3288
Contents | Index
System
TimeSpan Structure op_GreaterThan() Method
Parameters Parameter
Description
t1
The first System.TimeSpan.
t2
The second System.TimeSpan.
A B C D
Return Value
E
true if the values of t1 and t2 are equal; otherwise, false.
F
Example
G
using System;
H
namespace Samples { public class TimeSpanOp_Equality { public static void Main() { TimeSpan ts1 = new TimeSpan(1, 0, 0, 0); TimeSpan ts2 = new TimeSpan(24, 0, 0); Console.WriteLine("{0} == {1}: {2}", ts2, ts1, ts2 == ts1); Console.WriteLine("Increasing ts2"); ts2 = ts2.Add(new TimeSpan(0,0, 1)); Console.WriteLine("{0} == {1}: {2}", ts1, ts2, ts1 == ts2); } } }
I J K L M N O P Q R S
The output is
T
1.00:00:00 == 1.00:00:00: True Increasing ts2 1.00:00:00 == 1.00:00:01: False
U V W
TimeSpan.op_GreaterThan(System.TimeSpan, System.TimeSpan) Method
X
[ILASM]
Y
.method public hidebysig static specialname bool op_GreaterThan(valuetype System.TimeSpan t1, valuetype System.TimeSpan t2)
Z
[C#]
public static bool operator >(TimeSpan t1, TimeSpan t2)
3289
Contents | Index
TimeSpan Structure
System
op_GreaterThan() Method
Summary Determines whether the value of one System.TimeSpan is greater than the value of another System.TimeSpan. A
Parameters
B C
Parameter
Description
E
t1
The first System.TimeSpan.
F
t2
The second System.TimeSpan.
D
G H
Return Value
I
true if the value of t1 is greater than the value of t2; otherwise, false.
J
Example
K
using System;
L namespace Samples { public class TimeSpanOp_GreaterThan { public static void Main() { TimeSpan ts1 = new TimeSpan(168, 0, 0); TimeSpan ts2 = new TimeSpan(7, 0, 0, 0); Console.WriteLine("{0} > {1}: {2}", ts1, ts2, ts1 > ts2); ts2 += new TimeSpan(0, 0, 0, 1); Console.WriteLine("Increasing ts2"); Console.WriteLine("{0} > {1}: {2}", ts1, ts2, ts1 > ts2); Console.WriteLine("{0} > {1}: {2}", ts2, ts1, ts2 > ts1); } } }
M N O P Q R S T U V W X
The output is
Y
7.00:00:00 Increasing 7.00:00:00 7.00:00:01
Z
> 7.00:00:00: False ts2 > 7.00:00:01: False > 7.00:00:00: True
3290
Contents | Index
System
TimeSpan Structure op_GreaterThanOrEqual() Method
TimeSpan.op_GreaterThanOrEqual(System.TimeSpan, System.TimeSpan) Method [ILASM]
A
.method public hidebysig static specialname bool op_GreaterThanOrEqual(valuetype System.TimeSpan t1, valuetype System.TimeSpan t2)
B
[C#]
C
public static bool operator >=(TimeSpan t1, TimeSpan t2)
D
Summary
E
Determines whether the value of one System.TimeSpan is greater than or equal to the value of another System.TimeSpan.
F G
Parameters
H
Parameter
Description
I
t1
The first System.TimeSpan.
J
t2
The second System.TimeSpan.
K L M
Return Value
N
true if the value of t1 is greater than or equal to the value of t2; otherwise, false.
O
Example
P
using System;
Q namespace Samples { public class TimeSpanOp_GreaterThanOrEqual { public static void Main() { TimeSpan ts1 = new TimeSpan(168, 0, 0); TimeSpan ts2 = new TimeSpan(7, 0, 0, 0); Console.WriteLine("{0} >= {1}: {2}", ts1, ts2, ts1 >= ts2); ts2 += new TimeSpan(0, 0, 0, 1); Console.WriteLine("Increasing ts2"); Console.WriteLine("{0} >= {1}: {2}", ts1, ts2, ts1 >= ts2); Console.WriteLine("{0} >= {1}: {2}", ts2, ts1, ts2 >= ts1); } } }
R S T U V W X Y Z
3291
Contents | Index
TimeSpan Structure
System
op_Inequality() Method
The output is 7.00:00:00 Increasing 7.00:00:00 7.00:00:01
A B
>= 7.00:00:00: True ts2 >= 7.00:00:01: False >= 7.00:00:00: True
C D
TimeSpan.op_Inequality(System.TimeSpan, System.TimeSpan) Method
E
[ILASM]
.method public hidebysig static specialname bool op_Inequality(valuetype System.TimeSpan t1, valuetype System.TimeSpan t2)
F G
[C#]
H
public static bool operator !=(TimeSpan t1, TimeSpan t2)
I
Summary
J
Determines whether the value of one System.TimeSpan is unequal to the value of another System.TimeSpan.
K L
Parameters
M N
Parameter
Description
O
t1
The first System.TimeSpan.
P
t2
The second System.TimeSpan.
Q R
Return Value
S
true if the values of t1 and t2 are unequal; otherwise, false.
T
Example
U
using System;
V namespace Samples { public class TimeSpanOp_Inequality { public static void Main() { TimeSpan ts1 = new TimeSpan(1, 0, 0, 0); TimeSpan ts2 = new TimeSpan(24, 0, 0); Console.WriteLine("{0} != {1}: {2}",
W X Y Z
3292
Contents | Index
System
TimeSpan Structure op_LessThan() Method
ts2, ts1, ts2 != ts1); Console.WriteLine("Increasing ts2"); ts2 = ts2.Add(new TimeSpan(0,0, 1)); Console.WriteLine("{0} != {1}: {2}", ts1, ts2, ts1 != ts2);
A
}
B
}
C
}
D
The output is
E 1.00:00:00 != 1.00:00:00: False Increasing ts2 1.00:00:00 != 1.00:00:01: True
F G H
TimeSpan.op_LessThan(System.TimeSpan, System.TimeSpan) Method
I
[ILASM]
J
.method public hidebysig static specialname bool op_LessThan(valuetype System.TimeSpan t1, valuetype System.TimeSpan t2)
K
[C#]
L
public static bool operator <(TimeSpan t1, TimeSpan t2)
M
Summary
N
Determines whether the value of one System.TimeSpan is less than the value of another System.TimeSpan.
O P Q
Parameters
R
Parameter
Description
t1
The first System.TimeSpan.
t2
The second System.TimeSpan.
S T U V W
Return Value
X
true if the value of t1 is less than the value of t2; otherwise, false.
Y Z
3293
Contents | Index
TimeSpan Structure
System
op_LessThanOrEqual() Method
Example using System; namespace Samples { public class TimeSpanOp_LessThan { public static void Main() { TimeSpan ts1 = new TimeSpan(168, 0, 0); TimeSpan ts2 = new TimeSpan(7, 0, 0, 0); Console.WriteLine("{0} < {1}: {2}", ts1, ts2, ts1 < ts2); ts2 += new TimeSpan(0, 0, 0, 1); Console.WriteLine("Increasing ts2"); Console.WriteLine("{0} < {1}: {2}", ts1, ts2, ts1 < ts2); Console.WriteLine("{0} < {1}: {2}", ts2, ts1, ts2 < ts1); } } }
A B C D E F G H I J K L M
The output is
N 7.00:00:00 Increasing 7.00:00:00 7.00:00:01
O P
< 7.00:00:00: False ts2 < 7.00:00:01: True < 7.00:00:00: False
Q R
TimeSpan.op_LessThanOrEqual(System.TimeSpan, System.TimeSpan) Method
S T
[ILASM]
U
.method public hidebysig static specialname bool op_LessThanOrEqual(valuetype System.TimeSpan t1, valuetype System.TimeSpan t2)
V
[C#]
public static bool operator <=(TimeSpan t1, TimeSpan t2)
W X
Summary
Y
Determines whether the value of one System.TimeSpan is less than or equal to the value of another System.TimeSpan.
Z
3294
Contents | Index
System
TimeSpan Structure op_LessThanOrEqual() Method
Parameters Parameter
Description
t1
The first System.TimeSpan.
t2
The second System.TimeSpan.
A B C D
Return Value
E
true if the value of t1 is less than or equal to the value of t2; otherwise, false.
F G
Example
H
using System;
I namespace Samples { public class TimeSpanOp_LessThanOrEqual { public static void Main() { TimeSpan ts1 = new TimeSpan(168, 0, 0); TimeSpan ts2 = new TimeSpan(7, 0, 0, 0); Console.WriteLine("{0} <= {1}: {2}", ts1, ts2, ts1 <= ts2); ts2 += new TimeSpan(0, 0, 0, 1); Console.WriteLine("Increasing ts2"); Console.WriteLine("{0} <= {1}: {2}", ts1, ts2, ts1 <= ts2); Console.WriteLine("{0} <= {1}: {2}", ts2, ts1, ts2 <= ts1); } } }
J K L M N O P Q R S T U
The output is 7.00:00:00 Increasing 7.00:00:00 7.00:00:01
V W
<= 7.00:00:00: True ts2 <= 7.00:00:01: True <= 7.00:00:00: False
X Y Z
3295
Contents | Index
TimeSpan Structure
System
op_Subtraction() Method
TimeSpan.op_Subtraction(System.TimeSpan, System.TimeSpan) Method [ILASM]
A
.method public hidebysig static specialname valuetype System.TimeSpan op_Subtraction(valuetype System.TimeSpan t1, valuetype System.TimeSpan t2)
B
[C#]
public static TimeSpan operator -(TimeSpan t1, TimeSpan t2)
C D
Summary
E
Subtracts the value of one System.TimeSpan from the value of another System.TimeSpan.
F G
Parameters
H I J K
Parameter
Description
t1
The first System.TimeSpan.
t2
The second System.TimeSpan.
L M
Return Value
N
A System.TimeSpan whose value is the result of the value of t1 minus the value of t2.
O
Exceptions
P Q
Exception
Condition
System.OverflowException
The value of t2 subtracted from t1 is less than System.TimeSpan.MinValue or greater than System.TimeSpan.MaxValue.
R S T U
Example
V
using System;
W namespace Samples { public class TimeSpanOp_Subtraction { public static void Main() { DateTime dt = DateTime.Now;
X Y Z
3296
Contents | Index
System
TimeSpan Structure op_UnaryNegation() Method
TimeSpan ts = new TimeSpan(-7, 0, 0, 0); Console.WriteLine( "1 week ago it was {0}", dt + ts); ts = ts - ts.Duration(); Console.WriteLine( "2 weeks ago it was {0}", dt + ts); ts -= ts.Duration(); Console.WriteLine( "4 weeks ago it was {0}", dt + ts);
A B C D
} }
E
}
F
The output is
G H
1 week ago it was 17/06/2003 6:14:47 PM 2 weeks ago it was 10/06/2003 6:14:47 PM 4 weeks ago it was 27/05/2003 6:14:47 PM
I J K
TimeSpan.op_UnaryNegation(System.TimeSpan) Method
L
[ILASM]
M
.method public hidebysig static specialname valuetype System.TimeSpan op_UnaryNegation(valuetype System.TimeSpan t)
N
[C#]
O
public static TimeSpan operator -(TimeSpan t)
P
Summary
Q
Returns a System.TimeSpan whose value is the negated value of a specified System.TimeSpan.
R S
Parameters
T
Parameter
Description
t
A System.TimeSpan whose value will be negated.
U V W X
Return Value
Y
A System.TimeSpan with the same absolute value but the opposite sign as t.
Z
3297
Contents | Index
TimeSpan Structure
System
op_UnaryPlus() Method
Exceptions Exception
Condition
System.OverflowException
t equals System.TimeSpan.MinValue.
A B C
Example
D
using System;
E
namespace Samples { public class TimeSpanOp_UnaryNegation { public static void Main() { TimeSpan ts = new TimeSpan(-7, 0, 0, 0); Console.WriteLine( "ts is: {0}", ts); Console.WriteLine( "-ts is {0}", -ts); } } }
F G H I J K L M N O
The output is
P ts is: -7.00:00:00 -ts is 7.00:00:00
Q R S
TimeSpan.op_UnaryPlus(System.TimeSpan) Method
T [ILASM]
U
.method public hidebysig static specialname valuetype System.TimeSpan op_UnaryPlus(valuetype System.TimeSpan t)
V
[C#]
public static TimeSpan operator +(TimeSpan t)
W X
Summary
Y
Returns the specified instance of System.TimeSpan.
Z
3298
Contents | Index
System
TimeSpan Structure Parse() Method
Parameters Parameter
Description
t
A System.TimeSpan.
A B C
Example
D
using System;
E
namespace Samples { public class TimeSpanOp_UnaryPlus { public static void Main() { TimeSpan ts = new TimeSpan(-7, 0, 0, 0); Console.WriteLine( "ts is: {0}", ts); Console.WriteLine( "+ts is {0}", +ts); } } }
F G H I J K L M N O
The output is
P ts is: -7.00:00:00 +ts is -7.00:00:00
Q R S
TimeSpan.Parse(System.String) Method
T [ILASM]
U
.method public hidebysig static valuetype System.TimeSpan Parse(string s) [C#]
V
public static TimeSpan Parse(string s)
W
Summary
X
Returns the specified System.String converted to a System.TimeSpan value.
Y Z
3299
Contents | Index
TimeSpan Structure
System
Parse() Method
Parameters Parameter
Description
s
A System.String containing the value to convert. s contains a time interval in the following form: [ws][–][d.]hh:mm:ss[.ff ][ws] Items in square brackets ('[' and']') are optional. Colons and periods (':' and '.') are literal characters. For details on the remaining symbols, see the description section.
A B C D E F
Description
G
The symbols used in the parameter description for s are as follows:
H I
Item
Description
ws
White space (zero or more space and/or tab characters).
"–"
Minus sign, indicating a negative time interval.
"d"
Days.
"hh"
Hours, ranging from 0 to 23 inclusive.
O
"mm"
Minutes, ranging from 0 to 59 inclusive.
P
"ss"
Seconds, ranging from 0 to 59 inclusive.
Q
"ff"
Fractional seconds, from 1 to 7 decimal digits inclusive.
J K L M N
R
Exceptions
S T
Exception
Condition
V
System.ArgumentNullException
s is a null reference.
W
System.FormatException
s is in an invalid format.
System.OverflowException
s represents a number greater than System.TimeSpan.MaxValue or less than System.TimeSpan.MinValue. -orAt least one of the hours, minutes, or seconds components is outside its valid range.
U
X Y Z
3300
Contents | Index
System
TimeSpan Structure Subtract() Method
Example using System; namespace Samples { public class TimeSpanParse { public static void Main() { string s = TimeSpan.MaxValue.ToString(); Console.WriteLine( "Parse.(\"{0}\") yields: {1}", s, TimeSpan.Parse(s)); s = TimeSpan.Zero.ToString(); Console.WriteLine( "Parse.(\"{0}\") yields: {1}", s, TimeSpan.Parse(s)); s = TimeSpan.MinValue.ToString(); Console.WriteLine( "Parse.(\"{0}\") yields: {1}", s, TimeSpan.Parse(s)); } } }
A B C D E F G H I J K L M N
The output is
O Parse.("10675199.02:48:05.4775807") yields: 10675199.02:48:05.4775807 Parse.("00:00:00") yields: 00:00:00 Parse.("-10675199.02:48:05.4775808") yields: -10675199.02:48:05.4775808
P Q R
TimeSpan.Subtract(System.TimeSpan) Method
S
[ILASM]
T
.method public hidebysig instance valuetype System.TimeSpan Subtract(valuetype System.TimeSpan ts)
U
[C#]
V
public TimeSpan Subtract(TimeSpan ts)
W
Summary
X
Subtracts the value of the specified System.TimeSpan from the value of the current instance.
Y Z
3301
Contents | Index
TimeSpan Structure
System
Subtract() Method
Parameters Parameter
Description
ts
A System.TimeSpan whose value to subtract from the value of the current instance.
A B C D
Return Value
E
A System.TimeSpan whose value is equal to the value of the current instance minus the value of ts.
F G
Exceptions
H I
Exception
Condition
System.OverflowException
The difference between the value of the current instance and ts is less than System.TimeSpan.MinValue or greater than System.TimeSpan.MaxValue.
J K L M
Example
N
using System;
O
namespace Samples { public class TimeSpanSubtract { public static void Main() { DateTime dt = DateTime.Now; TimeSpan ts = new TimeSpan(-7, 0, 0, 0); Console.WriteLine( "1 week ago it was {0}", dt + ts); ts = ts.Subtract(ts.Duration()); Console.WriteLine( "2 weeks ago it was {0}", dt + ts); ts = ts.Subtract(ts.Duration()); Console.WriteLine( "4 weeks ago it was {0}", dt + ts); } } }
P Q R S T U V W X Y Z
3302
Contents | Index
System
TimeSpan Structure ToString() Method
The output is 1 week ago it was 17/06/2003 6:18:08 PM 2 weeks ago it was 10/06/2003 6:18:08 PM 4 weeks ago it was 27/05/2003 6:18:08 PM
A B C
TimeSpan.ToString() Method
D
[ILASM]
E
.method public hidebysig virtual string ToString()
F
[C#]
public override string ToString()
G
Summary
H
Returns a System.String representation of the value of the current instance. [Note: This method overrides System.Object.ToString.]
I
Return Value
K
A System.String representation of the current instance formatted as follows:
L
J
M
[-][d.]hh:mm:ss[.ff]
N
Items in square brackets (’[’ and ’]’) are included provisionally: ’–’ is included if and only if the current instance is negative; “d.” and “.ff” are included if and only if those components are non-zero. Colons and periods (’:’ and ’.’) are literal characters. Other components are as follows.
O P Q R S
Component
Description
"–"
Minus sign, indicating a negative time interval.
"d"
Days.
"hh"
Hours, ranging from 0 to 23 inclusive.
W
"mm"
Minutes, ranging from 0 to 59 inclusive.
X
"ss"
Seconds, ranging from 0 to 59 inclusive.
"ff"
Fractional seconds.
T U V
Y Z
3303
Contents | Index
TimeSpan Structure
System
ToString() Method
Example using System; namespace Samples { public class TimeSpanToString { public static void Main() { string s = TimeSpan.MaxValue.ToString(); Console.WriteLine( "MaxValue.ToString() yields: {0}", s); s = TimeSpan.Zero.ToString(); Console.WriteLine( "Zero.ToString() yields: {0}", s); s = TimeSpan.MinValue.ToString(); Console.WriteLine( "MinValue.ToString() yields: {0}", s); } } }
A B C D E F G H I J K L
The output is
M
MaxValue.ToString() yields: 10675199.02:48:05.4775807 Zero.ToString() yields: 00:00:00 MinValue.ToString() yields: -10675199.02:48:05.4775808
N O P Q R S T U V W X Y Z
3304
Contents | Index
System Type
BCL
Object Reflection
MemberInfo
ICustomAttributeProvider
Type
IReflect
NotStandardized
A
NotStandardized
B C
Summary
D
Provides information about a type.
E
Type Summary
F
public abstract class Type : MemberInfo, IReflect { // Constructors protected Type (); // Fields public CF public MS CF public MS CF public MS CF public public
G H I J
static static static static static static
readonly readonly readonly readonly readonly readonly
char Delimiter = '.'; Type[] EmptyTypes = new Type[0]; MemberFilter FilterAttribute; MemberFilter FilterName; MemberFilter FilterNameIgnoreCase; object Missing = Missing.Value;
K L M N
// Properties public abstract Assembly Assembly { get; } CF public abstract string AssemblyQualifiedName { get; } public TypeAttributes Attributes { get; } public abstract Type BaseType { get; } MS public override Type DeclaringType { get; } public static Binder DefaultBinder { get; } public abstract string FullName { get; } MS CF public abstract Guid GUID { get; } public bool HasElementType { get; } public bool IsAbstract { get; } MS public bool IsAnsiClass { get; } public bool IsArray { get; } MS public bool IsAutoClass { get; } public bool IsAutoLayout { get; } public bool IsByRef { get; } public bool IsClass { get; } MS public bool IsCOMObject { get; } MS CF public bool IsContextful { get; } public bool IsEnum { get; } CF public bool IsExplicitLayout { get; } public bool IsImport { get; }
O P Q R S T U V W X Y Z
3305
Contents | Index
Type
System
Type Class
public bool IsInterface { get; } CF public bool IsLayoutSequential { get; } CF public bool IsMarshalByRef { get; } public bool IsNestedAssembly { get; } public bool IsNestedFamANDAssem { get; } public bool IsNestedFamily { get; } public bool IsNestedFamORAssem { get; } public bool IsNestedPrivate { get; } public bool IsNestedPublic { get; } public bool IsNotPublic { get; } public bool IsPointer { get; } public bool IsPrimitive { get; } public bool IsPublic { get; } public bool IsSealed { get; } MS CF public bool IsSerializable { get; } public bool IsSpecialName { get; } MS public bool IsUnicodeClass { get; } public bool IsValueType { get; } MS public override MemberTypes MemberType { get; } public abstract Module Module { get; } public abstract string Namespace { get; } MS public override Type ReflectedType { get; } public abstract RuntimeTypeHandle TypeHandle { get; } CF public ConstructorInfo TypeInitializer { get; } CF public abstract Type UnderlyingSystemType { get; }
A B C D E F G H I J K L M N
// Methods MS public override bool Equals (object o); public bool Equals (Type o); MS CF public virtual Type[] FindInterfaces (TypeFilter filter, object filterCriteria); MS CF public virtual MemberInfo[] FindMembers (MemberTypes memberType, BindingFlags bindingAttr, MemberFilter filter, object filterCriteria); CF public virtual int GetArrayRank (); protected abstract TypeAttributes GetAttributeFlagsImpl (); MS CF public ConstructorInfo GetConstructor (BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers); public ConstructorInfo GetConstructor (BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers); public ConstructorInfo GetConstructor (Type[] types); MS protected abstract ConstructorInfo GetConstructorImpl (
O P Q R S T U V W X Y Z
3306
Contents | Index
System
Type Type Class
CF CF MS CF
CF MS CF
MS
BindingFlags bindingAttr, Binder binder,CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers); public ConstructorInfo[] GetConstructors (); public abstract ConstructorInfo[] GetConstructors ( BindingFlags bindingAttr); public virtual MemberInfo[] GetDefaultMembers (); public abstract Type GetElementType (); public EventInfo GetEvent (string name); public abstract EventInfo GetEvent (string name, BindingFlags bindingAttr); public virtual EventInfo[] GetEvents (); public abstract EventInfo[] GetEvents (BindingFlags bindingAttr); public FieldInfo GetField (string name); public abstract FieldInfo GetField (string name, BindingFlags bindingAttr); public FieldInfo[] GetFields (); public abstract FieldInfo[] GetFields (BindingFlags bindingAttr); public override int GetHashCode (); public Type GetInterface (string name); public abstract Type GetInterface (string name, bool ignoreCase); public virtual InterfaceMapping GetInterfaceMap (Type interfaceType); public abstract Type[] GetInterfaces (); public MemberInfo[] GetMember (string name); public virtual MemberInfo[] GetMember (string name, BindingFlags bindingAttr); public virtual MemberInfo[] GetMember (string name, MemberTypes type, BindingFlags bindingAttr); public MemberInfo[] GetMembers (); public abstract MemberInfo[] GetMembers (BindingFlags bindingAttr); public MethodInfo GetMethod (string name); public MethodInfo GetMethod (string name, BindingFlags bindingAttr); public MethodInfo GetMethod (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers); public MethodInfo GetMethod (string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers); public MethodInfo GetMethod (string name, Type[] types);
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
3307
Contents | Index
Type
System
Type Class
MS
A B C D E
CF
F G
CF
H I J K L M N O P Q R
MS
S T CF
U V W X Y Z
public MethodInfo GetMethod (string name, Type[] types, ParameterModifier[] modifiers); protected abstract MethodInfo GetMethodImpl (string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers); public MethodInfo[] GetMethods (); public abstract MethodInfo[] GetMethods (BindingFlags bindingAttr); public Type GetNestedType (string name); public abstract Type GetNestedType (string name, BindingFlags bindingAttr); public Type[] GetNestedTypes (); public abstract Type[] GetNestedTypes (BindingFlags bindingAttr); public PropertyInfo[] GetProperties (); public abstract PropertyInfo[] GetProperties (BindingFlags bindingAttr); public PropertyInfo GetProperty (string name); public PropertyInfo GetProperty (string name, BindingFlags bindingAttr); public PropertyInfo GetProperty (string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers); public PropertyInfo GetProperty (string name, Type returnType); public PropertyInfo GetProperty (string name, Type returnType, Type[] types); public PropertyInfo GetProperty (string name, Type returnType, Type[] types, ParameterModifier[] modifiers); public PropertyInfo GetProperty (string name, Type[] types); protected abstract PropertyInfo GetPropertyImpl (string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers); public static Type GetType (string typeName); public static Type GetType (string typeName, bool throwOnError);
3308
Contents | Index
System
Type Type Class
CF MS MS CF MS CF MS CF MS CF
MS CF MS CF MS CF MS CF
CF
CF
public static Type GetType (string typeName, bool throwOnError, bool ignoreCase); public static Type[] GetTypeArray (object[] args); public static TypeCode GetTypeCode (Type type); public static Type GetTypeFromCLSID (Guid clsid); public static Type GetTypeFromCLSID (Guid clsid, bool throwOnError); public static Type GetTypeFromCLSID (Guid clsid, string server); public static Type GetTypeFromCLSID (Guid clsid, string server, bool throwOnError); public static Type GetTypeFromHandle (RuntimeTypeHandle handle); public static Type GetTypeFromProgID (string progID); public static Type GetTypeFromProgID (string progID, bool throwOnError); public static Type GetTypeFromProgID (string progID, string server); public static Type GetTypeFromProgID (string progID, string server, bool throwOnError); public static RuntimeTypeHandle GetTypeHandle (object o); protected abstract bool HasElementTypeImpl (); public object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target, object[] args); public abstract object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters); public object InvokeMember (string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, CultureInfo culture); protected abstract bool IsArrayImpl (); public virtual bool IsAssignableFrom (Type c); protected abstract bool IsByRefImpl (); protected abstract bool IsCOMObjectImpl ();
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
3309
Contents | Index
Type
System
Type Class
MS CF protected virtual bool IsContextfulImpl (); public virtual bool IsInstanceOfType (object o); MS CF protected virtual bool IsMarshalByRefImpl (); protected abstract bool IsPointerImpl (); protected abstract bool IsPrimitiveImpl (); public virtual bool IsSubclassOf (Type c); MS protected virtual bool IsValueTypeImpl (); public override string ToString (); }
A B C D E
BA Notice we included only a very cut down version of System.Type in the BCL Standard. Just the core members are here to provide for implementations of the standard that could not support the entire reflection system. The rest of the members from Type are in the Reflection Library.
F G H I J
Description
K
The System.Type class is abstract, as is the System.Reflection.MemberInfo class and its subclasses System.Reflection.FieldInfo, System.Reflection.PropertyInfo, System.Reflection.MethodBase, and System.Reflection.EventInfo. System.Reflection.ConstructorInfo and System.Reflection.MethodInfo are subclasses of System.Reflection.MethodBase. The runtime provides non-public implementations of these classes. [Note: For example, System.Type.GetMethod is typed as returning a System.Reflection.MethodInfo object. The returned object is actually an instance of the non-public runtime type that implements System.Reflection.MethodInfo.] A conforming CLI program which is written to run on only the Kernel profile cannot subclass System.Type. [Note: This applies only to conforming programs, not conforming implementations.] A System.Type object that represents a type is unique; that is, two System.Type object references refer to the same object if and only if they represent the same type. This allows for comparison of System.Type objects using reference equality. [Note: An instance of System.Type can represent any one of the following types: The following table shows what members of a base class are returned by the methods that return members of types, such as System.Type.GetConstructor and System.Type.GetMethod.
L M N O P Q R S T U V W X Y Z
3310
Contents | Index
System
Type Type Class
Member Type
Static
Non-Static
constructor
No
No
A
field
No
Yes. A field is always hide-by-name-and-signature.
B
Not applicable
The common type system rule is that the inheritance of an event is the same as that of the accessors that implement the event. Reflection treats events as hide-by-name-andsignature.
event
method
No
C D E F
Yes. A method (both virtual and non-virtual) can be hideby-name or hide-by-name-and-signature.
G H
nested Type
No
No
property
Not applicable
The common type system rule is that the inheritance is the same as that of the accessors that implement the property. Reflection treats properties as hide-by-name-and-signature.
I J K L
For reflection, properties and events are hide-by-name-and-signature. If a property has both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and the setter on the base class will not be accessible.]
M N O
Example
P
using System; using System.Reflection;
Q
namespace Samples { public class TypeType { public static void Main() { Console.WriteLine("Delimiter: {0}", Type.Delimiter); Console.WriteLine( "Type: object"); Type t = typeof(object); Console.WriteLine("Assembly: {0}", t.Assembly); Console.WriteLine( "AssemblyQualifiedName: {0}",
S
R
T U V W X Y Z
3311
Contents | Index
Type
System
Type Class
t.AssemblyQualifiedName); Console.WriteLine("BaseType: {0}", t.BaseType); Console.WriteLine("DeclaringType: {0}", t.DeclaringType); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("IsAbstract: {0}", t.IsAbstract); Console.WriteLine("IsArray: {0}", t.IsArray); Console.WriteLine("IsAutoLayout: {0}", t.IsAutoLayout); Console.WriteLine("IsExplicitLayout: {0}", t.IsExplicitLayout); Console.WriteLine("IsLayoutSequential: {0}", t.IsLayoutSequential); Console.WriteLine("IsClass: {0}", t.IsClass); Console.WriteLine("IsEnum: {0}", t.IsEnum); Console.WriteLine("IsInterface: {0}", t.IsInterface); Console.WriteLine("IsMarshalByRef: {0}", t.IsMarshalByRef); Console.WriteLine("IsNestedAssembly: {0}", t.IsNestedAssembly); Console.WriteLine("IsNestedFamANDAssem: {0}", t.IsNestedFamANDAssem); Console.WriteLine("IsNestedFamily: {0}", t.IsNestedFamily); Console.WriteLine("IsNestedFamORAssem: {0}", t.IsNestedFamORAssem); Console.WriteLine("IsNestedPrivate: {0}", t.IsNestedPrivate); Console.WriteLine("IsNestedPublic: {0}", t.IsNestedPublic); Console.WriteLine("IsPublic: {0}", t.IsPublic); Console.WriteLine("IsPointer: {0}", t.IsPointer); Console.WriteLine("IsPrimitive: {0}", t.IsPrimitive); Console.WriteLine("IsSealed: {0}", t.IsSealed); Console.WriteLine("IsSpecialName: {0}", t.IsSpecialName); Console.WriteLine("IsValueType: {0}",
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
3312
Contents | Index
System
Type Type Class
t.IsValueType); Console.WriteLine("Module: {0}", t.Module); Console.WriteLine("Namespace: {0}", t.Namespace); Console.WriteLine("Members:"); MemberInfo[] members = t.GetMembers(); foreach(MemberInfo m in members) Console.WriteLine(m);
A B C D
} }
E
}
F
The output is
G H
Delimiter: . Type: object Assembly: mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 AssemblyQualifiedName: System.Object, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 BaseType: DeclaringType: FullName: System.Object IsAbstract: False IsArray: False IsAutoLayout: True IsExplicitLayout: False IsLayoutSequential: False IsClass: True IsEnum: False IsInterface: False IsMarshalByRef: False IsNestedAssembly: False IsNestedFamANDAssem: False IsNestedFamily: False IsNestedFamORAssem: False IsNestedPrivate: False IsNestedPublic: False IsPublic: True IsPointer: False IsPrimitive: False IsSealed: False IsSpecialName: False IsValueType: False Module: CommonLanguageRuntimeLibrary Namespace: System Members:
I J K L M N O P Q R S T U V W X Y Z
3313
Contents | Index
Type
System
Type() Constructor
Int32 GetHashCode() Boolean Equals(System.Object) System.String ToString() Boolean Equals(System.Object, System.Object) Boolean ReferenceEquals(System.Object, System.Object) System.Type GetType() Void .ctor()
A B C D
Type() Constructor
E
[ILASM]
F
family rtspecialname specialname instance void .ctor()
G
[C#]
protected Type()
H I
Summary
J
Constructs a new instance of the System.Type class.
K
Description
L
This member must be implemented if the Reflection Library is present in the implementation.
M N O
Type.Delimiter Field
P
[ILASM]
Q
.field public static initOnly valuetype System.Char Delimiter [C#]
R
public static readonly char Delimiter = '.'
S T
Summary
U
Specifies the character that separates elements in the fully qualified name of a System.Type.
V W
Description
X
This member must be implemented if the Reflection Library is present in the implementation.
Y Z
3314
Contents | Index
System
Type EmptyTypes Field
Example using System; using System.Reflection;
A namespace Samples { public class TypeDelimiter { public static void Main() { char c = Type.Delimiter; Console.WriteLine("Delimiter: {0}", c); string s = "System.Object"; Console.WriteLine( "In name {0} first delimiter at {1}", s, s.IndexOf(c)); } } }
B C D E F G H I J K
The output is
L M
Delimiter: . In name System.Object first delimiter at 6
N O
Type.EmptyTypes Field
P
[ILASM]
Q
.field public static initOnly class System.Type[] EmptyTypes
R
[C#]
S
public static readonly Type[] EmptyTypes = new Type[0]
T
Summary
U
Returns an empty array of type System.Type.
V
Description
W
The empty System.Type array returned by this field is used to specify that lookup methods in the System.Type class, such as System.Type.GetMethod and System.Type.GetConstructor, search for members that do not take parameters. [Note: For example, to locate the public instance constructor that takes no parameters, invoke System.Type.GetConstructor(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null,
X Y Z
3315
Contents | Index
Type
System
FilterAttribute Field
System.Type.EmptyTypes, null).] This member must be implemented if the Reflection Library is present in the implementation. A
Example
B
using System; using System.Reflection;
C namespace Samples { public class TypeEmptyTypes { public static void Main() { Type t = typeof(string); PropertyInfo pi = t.GetProperty( "Length", System.Type.EmptyTypes); Console.WriteLine(pi); } } }
D E F G H I J K L M
The output is
N
Int32 Length
O P Q
Type.FilterAttribute Field
R
[ILASM]
S
.field public static initOnly class System.Reflection.MemberFilter FilterAttribute [C#]
T
public static readonly MemberFilter FilterAttribute
U
Summary
V
Represents the member filter used on attributes.
W X
Description
Y
This field holds a reference to the delegate used by the System.Type.FindMembers method. The method encapsulated by this delegate takes two parameters: the first is a System.Reflection.MemberInfo object and the second is an Object. The method determines whether the MemberInfo object matches the criteria specified by the Object.
Z
3316
Contents | Index
System
Type FilterNameIgnoreCase Field
The Object may be assigned the value of any one of the fields on the classes System.Reflection.FieldAttributes, System.Reflection.MethodAttributes, or System.Reflection.MethodImplAttributes. For example, the Object can be assigned the value of a field from FieldAttributes such as Public. In that case, when the FilterAttribute delegate is invoked, it will return true only if the method represented by the MemberInfo object is decorated with the public field attribute in metadata. This member must be implemented if the Reflection Library is present in the implementation.
A B C D E F
Type.FilterName Field
G
[ILASM]
.field public static initOnly class System.Reflection.MemberFilter FilterName
H
[C#]
I
public static readonly MemberFilter FilterName
J
Summary
K
Represents the case-sensitive member filter used on names.
L
Description
M
This field holds a reference to the delegate used by the System.Type.FindMembers method. The method encapsulated by this delegate takes two parameters: the first is a System.Reflection.MemberInfo object and the second is an Object. The method determines whether the MemberInfo object matches the criteria specified by the Object. The Object is assigned a string value, which may include a trailing “*” wildcard character. Only wildcard end string matching is supported. For example, the Object may be assigned the value “Byte*”. In that case, when the FilterName delegate is invoked, it will return true only if the method represented by the MemberInfo object has a name that begins with “Byte”.
N O P Q R S T U
Type.FilterNameIgnoreCase Field
V
[ILASM]
W
.field public static initOnly class System.Reflection.MemberFilter FilterNameIgnoreCase
X
[C#]
Y
public static readonly MemberFilter FilterNameIgnoreCase
Z
3317
Contents | Index
Type
System
Missing Field
Summary Represents the case-insensitive member filter used on names. A
Description
B
This field holds a reference to the delegate used by the System.Type.FindMembers method. The method encapsulated by this delegate takes two parameters: the first is a System.Reflection.MemberInfo object and the second is an Object. The method determines whether the MemberInfo object matches the criteria specified by the Object. The Object is assigned a string value, which may include a trailing “*” wildcard character. Only wildcard end string matching is supported. For example, the Object may be assigned the value “ByTe*”. In that case, when the FilterName delegate is invoked, it will return true only if the method represented by the MemberInfo object has a name that begins with “byte”, ignoring case.
C D E F G H I J
Type.Missing Field
K
[ILASM]
.field public static initOnly object Missing
L
[C#]
M
public static readonly object Missing = Missing.Value
N
Summary
O
Represents a missing value in the System.Type information.
P
Description
Q
Use the Missing field for invocation through reflection to ensure that a call will be made with the default value of a parameter as specified in the metadata. [Note: If the Missing field is specified for a parameter value and there is no default value for that parameter, a System.ArgumentException is thrown.]
R S T U
Example
V
Option Strict Off Imports System Imports System.Reflection
W X
Public Class MissingSample Public Sub MyMethod(Optional ByVal i As Integer = 42) Console.WriteLine(i) End Sub End Class
Y Z
3318
Contents | Index
System
Type Assembly Property
Module MyModule Sub main() Dim ms As New MissingSample() Dim t As Type t = GetType(MissingSample) t.InvokeMember("MyMethod", _ BindingFlags.Public Or _ BindingFlags.Instance Or _ BindingFlags.InvokeMethod Or _ BindingFlags.OptionalParamBinding, _ Nothing, ms, New Object() {Type.Missing}) End Sub End Module
A B C D E F G
The output is
H 42
I J
Type.Assembly Property
K
[ILASM]
L
.property class System.Reflection.Assembly Assembly { public hidebysig virtual abstract specialname class System.Reflection.Assembly get_Assembly() }
M
[C#]
N
public abstract Assembly Assembly { get; }
O
Summary
P
Gets the System.Reflection.Assembly that the type is declared in.
Q
Property Value
R
A System.Reflection.Assembly instance that describes assembly containing the current type.
S
Description
U
This member must be implemented if the Runtime Infrastructure Library is present in the implementation.
V
T
W X
Example
Y
using System; using System.Reflection;
Z
namespace Samples {
3319
Contents | Index
Type
System
AssemblyQualifiedName Property
public class TypeAssembly { public static void Main() { Console.WriteLine( "Type: object"); Type t = typeof(object); Console.WriteLine("Assembly: {0}", t.Assembly); Console.WriteLine( "AssemblyQualifiedName: {0}", t.AssemblyQualifiedName); Console.WriteLine("FullName: {0}", t.FullName); } }
A B C D E F G H }
I
The output is
J
Type: object Assembly: mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 AssemblyQualifiedName: System.Object, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 FullName: System.Object
K L M N O P
Type.AssemblyQualifiedName Property
Q
[ILASM]
.property string AssemblyQualifiedName { public hidebysig virtual abstract specialname string get_AssemblyQualifiedName() }
R S
[C#]
public abstract string AssemblyQualifiedName { get; }
T U
Summary
V
Gets the fully qualified name of the type represented by the current instance including the name of the assembly from which the System.Type was loaded.
W X
Property Value
Y
A System.String containing the fully qualified name of the type represented by the current instance, including the name of the assembly from which the System.Type was loaded.
Z
3320
Contents | Index
System
Type AssemblyQualifiedName Property
Description This member must be implemented if the Reflection Library is present in the implementation.
Behaviors
A
Compilers emit the simple name of a nested class, and reflection constructs a mangled name when queried, in accordance with the following conventions.
B C D E
Delimiter
Meaning
backslash (\)
Escape character.
comma (,)
Precedes the Assembly name.
H
plus sign (+)
Precedes a nested class.
I
period (.)
Denotes namespace identifiers.
J
F G
K L
[Note: For example, the fully qualified name for a class might look like this:
M TopNamespace.SubNameSpace.ContainingClass+NestedClass,MyAssembly
N
If the namespace were TopNamespace.Sub+Namespace, then the string would have to precede the plus sign (+) with an escape character (\) to prevent it from being interpreted as a nesting separator. Reflection emits this string as follows: TopNamespace.Sub\+Namespace.ContainingClass+NestedClass,MyAssemblyA “++” becomes “\+\+”, and a “\” becomes “\\”.] Type names are permitted to include trailing characters that denote additional information about the type, such as whether the type is a reference type, a pointer type or an array type. To retrieve the type name without these trailing characters, use t.GetElementType().ToString(), where t is the type. Spaces are significant in all type name components except the assembly name. In the assembly name, spaces before the ’,’ separator are significant, but spaces after the ’,’ separator are ignored.
O P Q R S T U V W
Usage
X
The name returned by this method can be persisted and later used to load the System.Type. To search for and load a System.Type, use System.Type.GetType either with the type name only or with the assembly qualified type name. System.Type.GetType with the type name only will look for the System.Type in the
Y Z
3321
Contents | Index
Type
System
Attributes Property
caller’s assembly and then in the System assembly. System.Type.GetType with the assembly qualified type name will look for the System.Type in any assembly. A
Example
B
using System; using System.Reflection;
C namespace Samples { public class TypeAssemblyQualifiedName { public static void Main() { Console.WriteLine( "Type: object"); Type t = typeof(object); Console.WriteLine("Assembly: {0}", t.Assembly); Console.WriteLine( "AssemblyQualifiedName: {0}", t.AssemblyQualifiedName); Console.WriteLine("FullName: {0}", t.FullName); } } }
D E F G H I J K L M N O P
The output is
Q
Type: object Assembly: mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 AssemblyQualifiedName: System.Object, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 FullName: System.Object
R S T U V
Type.Attributes Property
W
[ILASM]
X
.property valuetype System.Reflection.TypeAttributes Attributes { public hidebysig specialname instance valuetype System.Reflection.TypeAttributes get_Attributes() }
Y
[C#]
Z
public TypeAttributes Attributes { get; }
3322
Contents | Index
System
Type Attributes Property
Summary Gets the attributes associated with the type represented by the current instance.
Property Value
A
A System.Reflection.TypeAttributes object representing the attribute set of the System.Type.
B
Description
D
This member must be implemented if the Reflection Library is present in the implementation.
E
C
F
Example
G
using System; using System.Reflection;
H I
namespace Samples { public class TypeAssembly { public static void Main() { Console.WriteLine( "Type: object"); Type t = typeof(object); Console.WriteLine("FullName: {0}", t.FullName); TypeAttributes ta = t.Attributes; Console.WriteLine("Attributes: {0}", ta); Console.WriteLine( "Type: string"); t = typeof(string); Console.WriteLine("FullName: {0}", t.FullName); ta = t.Attributes; Console.WriteLine("Attributes: {0}", ta); } } }
J K L M N O P Q R S T U V W X
The output is
Y
Type: object FullName: System.Object Attributes: AutoLayout, AnsiClass, NotPublic, Public, Serializable, BeforeFieldInit Type: string
Z
3323
Contents | Index
Type
System
BaseType Property
FullName: System.String Attributes: AutoLayout, AnsiClass, NotPublic, Public, Sealed, Serializable, BeforeFieldInit
A B
Type.BaseType Property
C
[ILASM]
D
.property class System.Type BaseType { public hidebysig virtual abstract specialname class System.Type get_BaseType() }
E
[C#]
public abstract Type BaseType { get; }
F G
Summary
H
Gets the base System.Type of the current System.Type.
I
Property Value
J
A System.Type object representing the type from which the current System.Type directly inherits, or null if the current System.Type represents the System.Object class.
K L
Example
M
using System; using System.Reflection;
N namespace Samples { public class TypeBaseType { public static void Main() { Console.WriteLine( "Type: object"); Type t = typeof(object); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("BaseType: {0}", t.BaseType); Console.WriteLine( "Type: string"); t = typeof(string); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("BaseType: {0}", t.BaseType); } } }
O P Q R S T U V W X Y Z
3324
Contents | Index
System
Type DeclaringType Property
The output is Type: object FullName: System.Object BaseType: Type: string FullName: System.String BaseType: System.Object
A B C D E
Type.DeclaringType Property
F [ILASM]
G
.property class System.Type DeclaringType { public hidebysig virtual specialname class System.Type get_DeclaringType() }
H
[C#]
I
public override Type DeclaringType { get; }
J
Summary
K
Gets the type that declares the type represented by the current instance.
L
Property Value
M
The System.Type object for the class that declares the type represented by the current instance. If the type is a nested type, this property returns the enclosing type; otherwise, returns the current instance.
N O P
Description
Q
[Note: This property overrides System.Reflection.MemberInfo.DeclaringType.] This member must be implemented if the Reflection Library is present in the implementation.
R S
Example
T
using System; using System.Reflection;
U V
namespace Samples { public class TypeDeclaringType { public class TypeInnerClass { } public static void Main() {
W X Y Z
3325
Contents | Index
Type
System
DefaultBinder Property
Console.WriteLine("Type: object"); Type t = typeof(object); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("DeclaringType: {0}", t.DeclaringType); Console.WriteLine("Type: InnerClass"); t = typeof(TypeInnerClass); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("DeclaringType: {0}", t.DeclaringType);
A B C D E F
} }
G
}
H
The output is
I
Type: object FullName: System.Object DeclaringType: Type: InnerClass FullName: Samples.TypeDeclaringType+TypeInnerClass DeclaringType: Samples.TypeDeclaringType
J K L M N O
Type.DefaultBinder Property
P
[ILASM]
.property class System.Reflection.Binder DefaultBinder { public hidebysig static specialname class System.Reflection.Binder get_DefaultBinder() }
Q R
[C#]
public static Binder DefaultBinder { get; }
S T
Summary
U
Gets the default binder used by the system.
V
Property Value
W
The default System.Reflection.Binder used by the system.
X Y
Description
Z
Reflection models the accessibility rules of the common type system. For example, if the caller is in the same assembly, the caller does not need special permissions for internal mem-
3326
Contents | Index
System
Type DefaultBinder Property
bers. Otherwise, the caller needs System.Security.Permissions.ReflectionPermission. This is consistent with lookup of members that are protected, private, and so on. [Note: The general principle is that System.Reflection.Binder.ChangeType typically performs only widening coercions, which never lose data. An example of a widening coercion is coercing a value that is a 32-bit signed integer to a value that is a 64-bit signed integer. This is distinguished from a narrowing coercion, which may lose data. An example of a narrowing coercion is coercing a 64-bit signed integer to a 32-bit signed integer.] This member must be implemented if the Reflection Library is present in the implementation. The following table lists the coercions performed by the default binder’s implementation of ChangeType.
A B C D E F G H
Source Type
Target Type
Any type
Its base type
Any type
The interface it implements
K
Char
UInt16, UInt32, Int32, UInt64, Int64, Single, Double
L
Byte
Char, UInt16, Int16, UInt32, Int32, UInt64, Int64, Single, Double
SByte
Int16, Int32, Int64, Single, Double
UInt16
UInt32, Int32, UInt64, Int64, Single, Double
P
Int16
Int32, Int64, Single, Double
Q
UInt32
UInt64, Int64, Single, Double
Int32
Int64, Single, Double
UInt64
Single, Double
U
Int64
Single, Double
V
Single
Double
Non-reference
By-reference
I J
M N O
R S T
W X Y Z
3327
Contents | Index
Type
System
FullName Property
Example using System; using System.Reflection;
A namespace Samples { public class TypeDefaultBinder { public static void Main() { string s = "IndexOf"; Type t = typeof(String); Type[][] types = new Type[][] { new Type[]{typeof(byte)}, new Type[]{typeof(string)}, new Type[]{typeof(string), typeof(Int16)} }; foreach(Type[] parameters in types) { MethodInfo mi = t.GetMethod(s, BindingFlags.Instance | BindingFlags.Public, System.Type.DefaultBinder, parameters, null); Console.WriteLine(mi); } } } }
B C D E F G H I J K L M N O P Q R S
The output is
T Int32 IndexOf(Char) Int32 IndexOf(System.String) Int32 IndexOf(System.String, Int32)
U V W X
Type.FullName Property
Y
[ILASM]
Z
.property string FullName { public hidebysig virtual abstract specialname string get_FullName() } [C#]
public abstract string FullName { get; }
3328
Contents | Index
System
Type FullName Property
Summary Gets the fully qualified name of the type represented by the current instance.
Property Value
A
A System.String containing the fully qualified name of the System.Type. [Note: For example, the fully qualified name of the C# string type is “System.String”.]
B C D
Example
E
using System; using System.Reflection;
F G
namespace Samples { public class TypeFullName { public static void Main() { Console.WriteLine( "For the \"object\" type"); Type t = typeof(object); Console.WriteLine("Assembly: {0}", t.Assembly); Console.WriteLine( "AssemblyQualifiedName: {0}", t.AssemblyQualifiedName); Console.WriteLine("FullName: {0}", t.FullName); } } }
H I J K L M N O P Q R S
The output is
T For the "object" type Assembly: mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 AssemblyQualifiedName: System.Object, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 FullName: System.Object
U V W X Y Z
3329
Contents | Index
Type
System
GUID Property
Type.GUID Property [ILASM]
A
.property valuetype System.Guid GUID { public hidebysig virtual abstract specialname valuetype System.Guid get_GUID() }
B
[C#]
public abstract Guid GUID { get; }
C D
Summary
E
Gets the GUID associated with the System.Type.
F G
Type.HasElementType Property
H
[ILASM]
I
.property bool HasElementType { public hidebysig specialname instance bool get_HasElementType() }
J
[C#]
public bool HasElementType { get; }
K L
Summary
M
Gets a System.Boolean value indicating whether the type represented by the current instance encompasses or refers to another type; that is, whether the current System.Type is an array, a pointer, or is passed by reference.
N O P
Property Value
Q
true if the System.Type is an array, a pointer, or is passed by reference; otherwise, false.
R
Description
S
[Note: For example, System.Type.GetType("System.Int32 []").HasElementType returns true, but System.Type.GetType("System.Int32").HasElementType returns false. System.Type.HasElementType also returns true for “Int32*” and “Int32&”.] This member must be implemented if the Reflection Library is present in the implementation.
T U V W X Y Z
3330
Contents | Index
System
Type IsAbstract Property
Example using System; using System.Reflection;
A namespace Samples { public class TypeHasElementType { public unsafe static void Main() { Console.WriteLine( "For the \"string[]\" type"); Type t = typeof(string[]); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("HasElementType: {0}", t.HasElementType); Console.WriteLine( "For the \"int*\" type"); t = typeof(int*); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("HasElementType: {0}", t.HasElementType); } } }
B C D E F G H I J K L M N O P
The output is
Q For the "string[]" type FullName: System.String[] HasElementType: True For the "int*" type FullName: System.Int32* HasElementType: True
R S T U V
Type.IsAbstract Property
W
[ILASM]
X
.property bool IsAbstract { public hidebysig specialname instance bool get_IsAbstract() }
Y
[C#]
Z
public bool IsAbstract { get; }
3331
Contents | Index
Type
System
IsAbstract Property
Summary Gets a System.Boolean value indicating whether the type represented by the current instance is abstract and is required to be overridden. A
Property Value
B
true if the System.Type is abstract; otherwise, false.
C D
Description
E
This member must be implemented if the Reflection Library is present in the implementation.
F
Example
G
using System; using System.Reflection;
H
namespace Samples { public class TypeIsAbstract { public static void Main() { Console.WriteLine( "For the \"System.Object\" type"); Type t = typeof(Object); Console.WriteLine("IsAbstract: {0}", t.IsAbstract); Console.WriteLine("IsClass: {0}", t.IsClass); Console.WriteLine("IsEnum: {0}", t.IsEnum); Console.WriteLine("IsInterface: {0}", t.IsInterface); Console.WriteLine("IsMarshalByRef: {0}", t.IsMarshalByRef); Console.WriteLine("IsValueType: {0}", t.IsValueType); } } }
I J K L M N O P Q R S T U V W
The output is
X
For the "System.Object" type IsAbstract: False IsClass: True IsEnum: False IsInterface: False IsMarshalByRef: False IsValueType: False
Y Z
3332
Contents | Index
System
Type IsArray Property
Type.IsAnsiClass Property [ILASM]
.property bool IsAnsiClass { public hidebysig specialname instance bool get_IsAnsiClass() }
A
[C#]
B
public bool IsAnsiClass { get; }
C
Summary
D
Gets a value indicating whether the string format attribute AnsiClass is selected for the System.Type.
E
Property Value
G
true if the string format attribute AnsiClass is selected for the System.Type; otherwise, false.
H
F
I J
Description
K
The System.Reflection.TypeAttributes.StringFormatMask selects the string format attributes. The string format attributes enhance interoperability by defining how strings should be interpreted.
L M N
Type.IsArray Property
O
[ILASM]
P
.property bool IsArray { public hidebysig specialname instance bool get_IsArray() }
Q
[C#]
R
public bool IsArray { get; }
S
Summary
T
Gets a System.Boolean value that indicates whether the current System.Type represents an array.
U
Property Value
W
true if the current System.Type represents an array; otherwise false.
X
V
Y
Description
Z
This property returns true for an array of objects, but not for the System.Array type itself, which is a class.
3333
Contents | Index
Type
System
IsAutoClass Property
Example using System; using System.Reflection;
A namespace Samples { public class TypeIsArray { public static void Main() { Console.WriteLine( "For the \"object\" type"); Type t = typeof(object); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("IsArray: {0}", t.IsArray); Console.WriteLine( "For the \"int[]\" type"); t = typeof(int[]); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("IsArray: {0}", t.IsArray); } } }
B C D E F G H I J K L M N O P
The output is
Q For the "object" type FullName: System.Object IsArray: False For the "int[]" type FullName: System.Int32[] IsArray: True
R S T U V W
Type.IsAutoClass Property
X
[ILASM]
Y
.property bool IsAutoClass { public hidebysig specialname instance bool get_IsAutoClass() } [C#]
Z
public bool IsAutoClass { get; }
3334
Contents | Index
System
Type IsAutoLayout Property
Summary Gets a value indicating whether the string format attribute AutoClass is selected for the System.Type. A
Property Value
B
true if the string format attribute AutoClass is selected for the System.Type; otherwise, false.
C D
Description
E
The System.Reflection.TypeAttributes.StringFormatMask selects the string format attributes. The string format attributes enhance interoperability by defining how strings should be interpreted.
F G H I
Type.IsAutoLayout Property
J
[ILASM]
K
.property bool IsAutoLayout { public hidebysig specialname instance bool get_IsAutoLayout() }
L
[C#]
M
public bool IsAutoLayout { get; }
N
Summary
O
Gets a System.Boolean value indicating whether the type layout attribute System.Reflection.TypeAttributes.AutoLayout is specified for the System.Type.
P Q
Property Value
R
true if the type layout attribute System.Reflection.TypeAttributes.AutoLayout is specified for the current System.Type; otherwise, false.
S
Description
U
[Note: The System.Reflection.TypeAttributes.AutoLayout attribute specifies that the system selects the layout of the objects of the type. Types marked with this attribute indicate that the system will choose the appropriate way to lay out the type; any layout information that may have been specified is ignored.] This member must be implemented if the Reflection Library is present in the implementation.
V
T
W X Y Z
3335
Contents | Index
Type
System
IsByRef Property
Example using System; using System.Reflection;
A namespace Samples { public class TypeIsAutoLayout { public static void Main() { Console.WriteLine( "For the \"object\" type"); Type t = typeof(object); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("IsAutoLayout: {0}", t.IsAutoLayout); Console.WriteLine("IsExplicitLayout: {0}", t.IsExplicitLayout); Console.WriteLine("IsLayoutSequential: {0}", t.IsLayoutSequential); } } }
B C D E F G H I J K L M N
The output is
O For the "object" type FullName: System.Object IsAutoLayout: True IsExplicitLayout: False IsLayoutSequential: False
P Q R S T
Type.IsByRef Property
U
[ILASM]
.property bool IsByRef { public hidebysig specialname instance bool get_IsByRef() }
V
[C#]
W
public bool IsByRef { get; }
X
Summary
Y
Gets a System.Boolean value indicating whether the System.Type is passed by reference.
Z
Property Value true if the System.Type is passed by reference; otherwise, false. 3336
Contents | Index
System
Type IsClass Property
Description This member must be implemented if the Reflection Library is present in the implementation.
Example
A
using System; using System.Reflection;
B C
namespace Samples { public class TypeIsByRef { public unsafe static void Main() { Console.WriteLine( "For the \"object\" type"); Type t = typeof(Object); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("IsByRef: {0}", t.IsByRef); Console.WriteLine( "For the \"int*\" type"); t = typeof(int*); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("IsByRef: {0}", t.IsByRef); } } }
D E F G H I J K L M N O P Q R
The output is
S For the "object" type FullName: System.Object IsByRef: False For the "int*" type FullName: System.Int32* IsByRef: False
T U V W X
Type.IsClass Property
Y
[ILASM]
Z
.property bool IsClass { public hidebysig specialname instance bool get_IsClass() } [C#]
public bool IsClass { get; }
3337
Contents | Index
Type
System
IsClass Property
Summary Gets a System.Boolean value that indicates whether the current System.Type represents a class. A
Property Value
B
true if the current System.Type represents a class; otherwise, false.
C D
Description
E
Note that this property returns true for System.Type instances representing System.Enum and System.ValueType.
F G
Example
H
using System; using System.Reflection;
I namespace Samples { public class TypeIsClass { public static void Main() { Console.WriteLine( "For the \"object\" type"); Type t = typeof(object); Console.WriteLine("IsAbstract: {0}", t.IsAbstract); Console.WriteLine("IsClass: {0}", t.IsClass); Console.WriteLine("IsEnum: {0}", t.IsEnum); Console.WriteLine("IsInterface: {0}", t.IsInterface); Console.WriteLine("IsMarshalByRef: {0}", t.IsMarshalByRef); Console.WriteLine("IsValueType: {0}", t.IsValueType); } } }
J K L M N O P Q R S T U V W
The output is
X
For the "object" type IsAbstract: False IsClass: True IsEnum: False IsInterface: FalseIsMarshalByRef: False IsValueType: False
Y Z
3338
Contents | Index
System
Type IsContextful Property
Type.IsCOMObject Property [ILASM]
.property bool IsCOMObject { public hidebysig specialname instance bool get_IsCOMObject() }
A
[C#]
B
public bool IsCOMObject { get; }
C
Summary
D
Gets a value indicating whether the System.Type is a COM object.
E F
Property Value
G
true if the System.Type is a COM object; otherwise, false.
H
Description
I
This method returns false for COM interfaces because they are not objects. COM interfaces can be implemented by Microsoft .NET Framework objects. You can also load a COM class and get a Type object for that COM class by using the tool.
J K L M
Type.IsContextful Property
N
[ILASM]
O
.property bool IsContextful { public hidebysig specialname instance bool get_IsContextful() }
P
[C#]
Q
public bool IsContextful { get; }
R
Summary
S
Gets a value indicating whether the System.Type can be hosted in a context.
T
Property Value
U
true if the System.Type can be hosted in a context; otherwise, false.
V W
Description
X
A context intercepts calls to the class members and enforces policies that are applied to the class, such as synchronization. For more detailed information on remoting contexts, see System.Runtime.Remoting.Contexts.Context.
Y Z
3339
Contents | Index
Type
System
IsEnum Property
Type.IsEnum Property [ILASM]
.property bool IsEnum { public hidebysig specialname instance bool get_IsEnum() }
A
[C#]
B
public bool IsEnum { get; }
C
Summary
D
Gets a System.Boolean value that indicates whether the current System.Type represents an enumeration.
E F
Property Value
G
true if the current System.Type represents an enumeration; otherwise false.
H
Description
I
This property returns true for an enumeration, but not for the System.Enum type itself, which is a class.
J K
Example
L
using System; using System.Reflection;
M N
namespace Samples { public class TypeIsEnum { public static void Main() { Console.WriteLine( "For the \"BindingFlags\" type"); Type t = typeof(BindingFlags); Console.WriteLine("IsAbstract: {0}", t.IsAbstract); Console.WriteLine("IsClass: {0}", t.IsClass); Console.WriteLine("IsEnum: {0}", t.IsEnum); Console.WriteLine("IsInterface: {0}", t.IsInterface); Console.WriteLine("IsMarshalByRef: {0}", t.IsMarshalByRef); Console.WriteLine("IsValueType: {0}", t.IsValueType); } } }
O P Q R S T U V W X Y Z
3340
Contents | Index
System
Type IsExplicitLayout Property
The output is For the "BindingFlags" type IsAbstract: False IsClass: False IsEnum: True IsInterface: False IsMarshalByRef: False IsValueType: True
A B C D E
Type.IsExplicitLayout Property
F
[ILASM]
G
.property bool IsExplicitLayout { public hidebysig specialname instance bool get_IsExplicitLayout() }
H
[C#]
I
public bool IsExplicitLayout { get; }
J
Summary
K
Gets a System.Boolean value indicating whether the type layout attribute System.Reflection.TypeAttributes.ExplicitLayout is specified for the System.Type.
L M N
Property Value
O
true if the type layout attribute System.Reflection.TypeAttributes.ExplicitLayout is specified for the current System.Type; otherwise, false.
P Q
Description
R
[Note: Types marked with the System.Reflection.TypeAttributes.ExplicitLayout attribute cause the system to ignore field sequence and to use the explicit layout rules provided, in the form of field offsets, overall class size and alignment.] This member must be implemented if the Reflection Library is present in the implementation.
S T U V W
Example
X
using System; using System.Reflection;
Y Z
namespace Samples { public class TypeIsExplicitLayout
3341
Contents | Index
Type
System
IsImport Property
{ public static void Main() { Console.WriteLine( "For the \"object\" type"); Type t = typeof(object); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("IsAutoLayout: {0}", t.IsAutoLayout); Console.WriteLine("IsExplicitLayout: {0}", t.IsExplicitLayout); Console.WriteLine("IsLayoutSequential: {0}", t.IsLayoutSequential); }
A B C D E F G H
} }
I
The output is
J K
For the "object" type FullName: System.Object IsAutoLayout: True IsExplicitLayout: False IsLayoutSequential: False
L M N O P
Type.IsImport Property
Q
[ILASM]
R
.property bool IsImport { public hidebysig specialname instance bool get_IsImport() } [C#]
S
public bool IsImport { get; }
T U
Summary
V
Gets a System.Boolean value indicating whether the System.Type was imported from another class.
W X
Property Value
Y
true if the System.Type was imported from another class; otherwise, false.
Z
Description This member must be implemented if the Reflection Library is present in the implementation.
3342
Contents | Index
System
Type IsInterface Property
Example using System; using System.Reflection;
A namespace Samples { public class TypeIsImport { public static void Main() { Console.WriteLine( "For the \"object\" type"); Type t = typeof(object); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("IsImport: {0}", t.IsImport); } } }
B C D E F G H I J K
The output is
L For the "object" type FullName: System.Object IsImport: False
M N O
Type.IsInterface Property
P
[ILASM]
Q
.property bool IsInterface { public hidebysig specialname instance bool get_IsInterface() }
R
[C#]
S
public bool IsInterface { get; }
T
Summary
U
Gets a System.Boolean value that indicates whether the current System.Type represents an interface.
V W X
Property Value
Y
true if the current System.Type represents an interface; otherwise, false.
Z
3343
Contents | Index
Type
System
IsLayoutSequential Property
Example using System; using System.Reflection;
A namespace Samples { public class TypeIsInterface { public static void Main() { Console.WriteLine( "For the \"ICloneable\" type"); Type t = typeof(ICloneable); Console.WriteLine("IsAbstract: {0}", t.IsAbstract); Console.WriteLine("IsClass: {0}", t.IsClass); Console.WriteLine("IsEnum: {0}", t.IsEnum); Console.WriteLine("IsInterface: {0}", t.IsInterface); Console.WriteLine("IsMarshalByRef: {0}", t.IsMarshalByRef); Console.WriteLine("IsValueType: {0}", t.IsValueType); } } }
B C D E F G H I J K L M N O P
The output is
Q R
For the "ICloneable" type IsAbstract: True IsClass: False IsEnum: False IsInterface: True IsMarshalByRef: False IsValueType: False
S T U V W X
Type.IsLayoutSequential Property
Y
[ILASM]
Z
.property bool IsLayoutSequential { public hidebysig specialname instance bool get_IsLayoutSequential() } [C#]
public bool IsLayoutSequential { get; }
3344
Contents | Index
System
Type IsLayoutSequential Property
Summary Gets a System.Boolean value indicating whether the type layout attribute System.Reflection.TypeAttributes.SequentialLayout is specified for the System.Type. A
Property Value
B
true if the type layout attribute System.Reflection.TypeAttributes.SequentialLayout is specified for the current System.Type; otherwise, false.
C D
Description
E
[Note: The System.Reflection.TypeAttributes.SequentialLayout attribute is used to indicate that the system is to preserve field order as emitted, but otherwise the specific offsets are calculated based on the type of the field; these may be shifted by explicit offset, padding, or alignment information.] This member must be implemented if the Reflection Library is present in the implementation.
F G H I J
Example
K
using System; using System.Reflection;
L M
namespace Samples { public class TypeIsLayoutSequential { public static void Main() { Console.WriteLine( "For the \"object\" type"); Type t = typeof(object); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("IsAutoLayout: {0}", t.IsAutoLayout); Console.WriteLine("IsExplicitLayout: {0}", t.IsExplicitLayout); Console.WriteLine("IsLayoutSequential: {0}", t.IsLayoutSequential); } } }
N O P Q R S T U V W X Y Z
3345
Contents | Index
Type
System
IsMarshalByRef Property
The output is For the "object" type FullName: System.Object IsAutoLayout: True IsExplicitLayout: False IsLayoutSequential: False
A B C D E
Type.IsMarshalByRef Property
F
[ILASM]
G
.property bool IsMarshalByRef { public hidebysig specialname instance bool get_IsMarshalByRef() } [C#]
H
public bool IsMarshalByRef { get; }
I J
Summary
K
Gets a System.Boolean value indicating whether the current type is marshaled by reference.
L M
Property Value
N
true if the System.Type is marshaled by reference; otherwise, false.
O
Description
P
This member must be implemented if the Reflection Library is present in the implementation.
Q R
Example
S
using System; using System.Reflection;
T namespace Samples { public class TypeIsMarshalByRef { public static void Main() { Console.WriteLine( "For the \"object\" type"); Type t = typeof(object); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("IsMarshalByRef: {0}",
U V W X Y Z
3346
Contents | Index
System
Type IsNestedAssembly Property
t.IsMarshalByRef); Console.WriteLine( "For the \"Assembly\" type"); t = typeof(Assembly); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("IsMarshalByRef: {0}", t.IsMarshalByRef);
A B C
}
D
} }
E F
The output is
G For the "object" type FullName: System.Object IsMarshalByRef: False For the "Assembly" type FullName: System.Reflection.Assembly IsMarshalByRef: False
H I J K L
Type.IsNestedAssembly Property
M
[ILASM]
N
.property bool IsNestedAssembly { public hidebysig specialname instance bool get_IsNestedAssembly() }
O
[C#]
P
public bool IsNestedAssembly { get; }
Q
Summary
R
Gets a System.Boolean value indicating whether the current System.Type is nested and visible only within its own assembly.
S T
Property Value
U
true if the System.Type is nested and visible only within its own assembly; otherwise, false.
V W
Description
X
This member must be implemented if the Reflection Library is present in the implementation.
Y Z
3347
Contents | Index
Type
System
IsNestedAssembly Property
Example using System; using System.Reflection;
A namespace Samples { public class TypeIsNestedAssembly { internal class NestedClass { } public static void Main() { Console.WriteLine( "For the \"NestedClass\" type"); Type t = typeof(NestedClass); Console.WriteLine("IsNestedAssembly: {0}", t.IsNestedAssembly); Console.WriteLine("IsNestedFamANDAssem: {0}", t.IsNestedFamANDAssem); Console.WriteLine("IsNestedFamily: {0}", t.IsNestedFamily); Console.WriteLine("IsNestedFamORAssem: {0}", t.IsNestedFamORAssem); Console.WriteLine("IsNestedPrivate: {0}", t.IsNestedPrivate); Console.WriteLine("IsNestedPublic: {0}", t.IsNestedPublic); Console.WriteLine("IsPublic: {0}", t.IsPublic); } } }
B C D E F G H I J K L M N O P Q R S
The output is
T U
For the "NestedClass" type IsNestedAssembly: True IsNestedFamANDAssem: False IsNestedFamily: False IsNestedFamORAssem: False IsNestedPrivate: False IsNestedPublic: False IsPublic: False
V W X Y Z
3348
Contents | Index
System
Type IsNestedFamANDAssem Property
Type.IsNestedFamANDAssem Property [ILASM]
.property bool IsNestedFamANDAssem { public hidebysig specialname instance bool get_IsNestedFamANDAssem() }
A
[C#]
B
public bool IsNestedFamANDAssem { get; }
C
Summary
D
Gets a System.Boolean value indicating whether the current System.Type is nested and visible only to classes that belong to both its own family and its own assembly.
E
Property Value
G
true if the System.Type is nested and visible only to classes that belong to both its own family and its own assembly; otherwise, false.
H
F
I J
Description
K
A System.Type object’s family is defined as all objects of the exact same System.Type and of its subclasses. This member must be implemented if the Reflection Library is present in the implementation.
L M
Example
N
using System; using System.Reflection;
O
namespace Samples { public class TypeIsNestedFamANDAssem { internal protected class NestedClass { } public static void Main() { Console.WriteLine( "For the \"NestedClass\" type"); Type t = typeof(NestedClass); Console.WriteLine("IsNestedAssembly: {0}", t.IsNestedAssembly); Console.WriteLine("IsNestedFamANDAssem: {0}", t.IsNestedFamANDAssem); Console.WriteLine("IsNestedFamily: {0}", t.IsNestedFamily);
Q
P
R S T U V W X Y Z
3349
Contents | Index
Type
System
IsNestedFamily Property
Console.WriteLine("IsNestedFamORAssem: {0}", t.IsNestedFamORAssem); Console.WriteLine("IsNestedPrivate: {0}", t.IsNestedPrivate); Console.WriteLine("IsNestedPublic: {0}", t.IsNestedPublic); Console.WriteLine("IsPublic: {0}", t.IsPublic);
A B C }
D
} }
E F
The output is
G For the "NestedClass" type IsNestedAssembly: False IsNestedFamANDAssem: False IsNestedFamily: False IsNestedFamORAssem: True IsNestedPrivate: False IsNestedPublic: False IsPublic: False
H I J K L M N
Type.IsNestedFamily Property
O
[ILASM]
P
.property bool IsNestedFamily { public hidebysig specialname instance bool get_IsNestedFamily() }
Q
[C#]
public bool IsNestedFamily { get; }
R S
Summary
T
Gets a System.Boolean value indicating whether the current System.Type is nested and visible only within its own family.
U V
Property Value
W
true if the System.Type is nested and visible only within its own family; otherwise, false.
X
Description
Y
A System.Type object’s family is defined as all objects of the exact same System.Type and of its subclasses. This member must be implemented if the Reflection Library is present in the implementation.
Z
3350
Contents | Index
System
Type IsNestedFamily Property
Example using System; using System.Reflection;
A namespace Samples { public class TypeIsNestedFamily { protected class NestedClass { } public static void Main() { Console.WriteLine( "For the \"NestedClass\" type"); Type t = typeof(NestedClass); Console.WriteLine("IsNestedAssembly: {0}", t.IsNestedAssembly); Console.WriteLine("IsNestedFamANDAssem: {0}", t.IsNestedFamANDAssem); Console.WriteLine("IsNestedFamily: {0}", t.IsNestedFamily); Console.WriteLine("IsNestedFamORAssem: {0}", t.IsNestedFamORAssem); Console.WriteLine("IsNestedPrivate: {0}", t.IsNestedPrivate); Console.WriteLine("IsNestedPublic: {0}", t.IsNestedPublic); Console.WriteLine("IsPublic: {0}", t.IsPublic); } } }
B C D E F G H I J K L M N O P Q R S
The output is
T U
For the "NestedClass" type IsNestedAssembly: False IsNestedFamANDAssem: False IsNestedFamily: True IsNestedFamORAssem: False IsNestedPrivate: False IsNestedPublic: False IsPublic: False
V W X Y Z
3351
Contents | Index
Type
System
IsNestedFamOrAssem Property
Type.IsNestedFamOrAssem Property [ILASM]
A
.property bool IsNestedFamORAssem { public hidebysig specialname instance bool get_IsNestedFamORAssem() }
B
[C#]
public bool IsNestedFamORAssem { get; }
C D
Summary
E
Gets a System.Boolean value indicating whether the current System.Type is nested and visible only to classes that belong to either its own family or to its own assembly.
F G
Property Value
H
true if the System.Type is nested and visible only to classes that belong to its own family or to its own assembly; otherwise, false.
I J
Description
K
A System.Type object’s family is defined as all objects of the exact same System.Type and of its subclasses. This member must be implemented if the Reflection Library is present in the implementation.
L M N
Example
O
using System; using System.Reflection;
P
namespace Samples { public class TypeIsNestedFamORAssem { internal protected class NestedClass { } public static void Main() { Console.WriteLine( "For the \"NestedClass\" type"); Type t = typeof(NestedClass); Console.WriteLine("IsNestedAssembly: {0}", t.IsNestedAssembly); Console.WriteLine("IsNestedFamANDAssem: {0}", t.IsNestedFamANDAssem); Console.WriteLine("IsNestedFamily: {0}", t.IsNestedFamily);
Q R S T U V W X Y Z
3352
Contents | Index
System
Type IsNestedPrivate Property
Console.WriteLine("IsNestedFamORAssem: {0}", t.IsNestedFamORAssem); Console.WriteLine("IsNestedPrivate: {0}", t.IsNestedPrivate); Console.WriteLine("IsNestedPublic: {0}", t.IsNestedPublic); Console.WriteLine("IsPublic: {0}", t.IsPublic);
A B C
}
D
} }
E F
The output is
G
For the "NestedClass" type IsNestedAssembly: False IsNestedFamANDAssem: False IsNestedFamily: False IsNestedFamORAssem: True IsNestedPrivate: False IsNestedPublic: False IsPublic: False
H I J K L M
Type.IsNestedPrivate Property
N
[ILASM]
O
.property bool IsNestedPrivate { public hidebysig specialname instance bool get_IsNestedPrivate() }
P
[C#]
Q
public bool IsNestedPrivate { get; }
R
Summary
S
Gets a System.Boolean value indicating whether the current System.Type is nested and declared private.
T U
Property Value
V
true if the System.Type is nested and declared private; otherwise, false.
W
Description
X
This member must be implemented if the Reflection Library is present in the implementation.
Y Z
3353
Contents | Index
Type
System
IsNestedPrivate Property
Example using System; using System.Reflection;
A namespace Samples { public class TypeIsNestedPrivate { private class NestedClass { } public static void Main() { Console.WriteLine( "For the \"NestedClass\" type"); Type t = typeof(NestedClass); Console.WriteLine("IsNestedAssembly: {0}", t.IsNestedAssembly); Console.WriteLine("IsNestedFamANDAssem: {0}", t.IsNestedFamANDAssem); Console.WriteLine("IsNestedFamily: {0}", t.IsNestedFamily); Console.WriteLine("IsNestedFamORAssem: {0}", t.IsNestedFamORAssem); Console.WriteLine("IsNestedPrivate: {0}", t.IsNestedPrivate); Console.WriteLine("IsNestedPublic: {0}", t.IsNestedPublic); Console.WriteLine("IsPublic: {0}", t.IsPublic); } } }
B C D E F G H I J K L M N O P Q R S
The output is
T U
For the "NestedClass" type IsNestedAssembly: False IsNestedFamANDAssem: False IsNestedFamily: False IsNestedFamORAssem: False IsNestedPrivate: True IsNestedPublic: False IsPublic: False
V W X Y Z
3354
Contents | Index
System
Type IsNestedPublic Property
Type.IsNestedPublic Property [ILASM]
.property bool IsNestedPublic { public hidebysig specialname instance bool get_IsNestedPublic() }
A
[C#]
B
public bool IsNestedPublic { get; }
C
Summary
D
Gets a System.Boolean value indicating whether the current System.Type is a public nested class.
E
Property Value
G
true if the class is nested and declared public; otherwise, false.
H
F
I
Description
J
This member must be implemented if the Reflection Library is present in the implementation.
K
Example
L
using System; using System.Reflection;
M N
namespace Samples { public class TypeIsNestedPrivate { public class TypeNestedClass { } public static void Main() { Console.WriteLine( "For the \"NestedClass\" type"); Type t = typeof(TypeNestedClass); Console.WriteLine("IsNestedAssembly: {0}", t.IsNestedAssembly); Console.WriteLine("IsNestedFamANDAssem: {0}", t.IsNestedFamANDAssem); Console.WriteLine("IsNestedFamily: {0}", t.IsNestedFamily); Console.WriteLine("IsNestedFamORAssem: {0}", t.IsNestedFamORAssem); Console.WriteLine("IsNestedPrivate: {0}", t.IsNestedPrivate);
O P Q R S T U V W X Y Z
3355
Contents | Index
Type
System
IsNotPublic Property
Console.WriteLine("IsNestedPublic: {0}", t.IsNestedPublic); Console.WriteLine("IsPublic: {0}", t.IsPublic);
A
} }
B }
C
The output is
D E
For the "NestedClass" type IsNestedAssembly: False IsNestedFamANDAssem: False IsNestedFamily: False IsNestedFamORAssem: False IsNestedPrivate: False IsNestedPublic: True IsPublic: False
F G H I J K
Type.IsNotPublic Property
L
[ILASM]
M
.property bool IsNotPublic { public hidebysig specialname instance bool get_IsNotPublic() }
N
[C#]
O
public bool IsNotPublic { get; }
P
Summary
Q
Gets a System.Boolean value indicating whether the top-level System.Type is not declared public.
R S
Property Value
T
true if the top-level System.Type is not declared public; otherwise, false.
U V
Description
W
This member must be implemented if the Reflection Library is present in the implementation.
X Y Z
3356
Contents | Index
System
Type IsNotPublic Property
Example using System; using System.Reflection;
A namespace Samples { internal class IsNotPublic { public static void Main() { Console.WriteLine( "Type: IsNotPublic"); Type t = typeof(IsNotPublic); Console.WriteLine("IsNestedAssembly: {0}", t.IsNestedAssembly); Console.WriteLine("IsNestedFamANDAssem: {0}", t.IsNestedFamANDAssem); Console.WriteLine("IsNestedFamily: {0}", t.IsNestedFamily); Console.WriteLine("IsNestedFamORAssem: {0}", t.IsNestedFamORAssem); Console.WriteLine("IsNestedPrivate: {0}", t.IsNestedPrivate); Console.WriteLine("IsNestedPublic: {0}", t.IsNestedPublic); Console.WriteLine("IsPublic: {0}", t.IsPublic); Console.WriteLine("IsNotPublic: {0}", t.IsNotPublic); } } }
B C D E F G H I J K L M N O P Q R S
The output is
T Type: IsNotPublic IsNestedAssembly: False IsNestedFamANDAssem: False IsNestedFamily: False IsNestedFamORAssem: False IsNestedPrivate: False IsNestedPublic: False IsPublic: False IsNotPublic: True
U V W X Y Z
3357
Contents | Index
Type
System
IsPointer Property
Type.IsPointer Property [ILASM]
A
.property bool IsPointer { public hidebysig specialname instance bool get_IsPointer() }
B
[C#]
public bool IsPointer { get; }
C D
Summary
E
Gets a System.Boolean value that indicates whether the current System.Type represents a pointer.
F G
Property Value
H
true if the current System.Type represents a pointer; otherwise, false.
I
Example
J
using System; using System.Reflection;
K L
namespace Samples { public class TypeIsPointer { public unsafe static void Main() { Console.WriteLine( "Type: int"); Type t = typeof(int); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("IsPointer: {0}", t.IsPointer); Console.WriteLine( "Type: int*"); t = typeof(int*); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("IsPointer: {0}", t.IsPointer); } } }
M N O P Q R S T U V W X Y Z
3358
Contents | Index
System
Type IsPrimitive Property
The output is Type: int FullName: System.Int32 IsPointer: False Type: int* FullName: System.Int32* IsPointer: True
A B C D E
Type.IsPrimitive Property
F [ILASM]
G
.property bool IsPrimitive { public hidebysig specialname instance bool get_IsPrimitive() }
H
[C#]
I
public bool IsPrimitive { get; }
J
Summary
K
Gets a System.Boolean value indicating whether the current System.Type is one of the primitive types.
L M
Property Value
N
true if the System.Type is one of the primitive types; otherwise, false.
O
Description
P
The primitive types are System.Boolean, System.Byte, System.SByte, System.Int16, System.UInt16, System.Int32, System.UInt32, System.Int64, System.UInt64, System.Char, System.Double, and System.Single. This member must be implemented if the Reflection Library is present in the implementation.
Q R S T
Example
U
using System; using System.Reflection;
V W
namespace Samples { public class TypeIsPrimitive { public unsafe static void Main() { Console.WriteLine( "Type: int");
X Y Z
3359
Contents | Index
Type
System
IsPublic Property
Type t = typeof(int); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("IsPrimitive: {0}", t.IsPrimitive); Console.WriteLine( "Type: int*"); t = typeof(int*); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("IsPrimitive: {0}", t.IsPrimitive);
A B C D E F
} }
G
}
H
The output is
I
Type: int FullName: System.Int32 IsPrimitive: True Type: int* FullName: System.Int32* IsPrimitive: False
J K L M N O
Type.IsPublic Property
P
[ILASM]
.property bool IsPublic { public hidebysig specialname instance bool get_IsPublic() }
Q R
[C#]
public bool IsPublic { get; }
S T
Summary
U
Gets a System.Boolean value indicating whether the top-level System.Type is declared public.
V W
Property Value
X
true if the top-level System.Type is declared public; otherwise, false.
Y
Description
Z
This member must be implemented if the Reflection Library is present in the implementation.
3360
Contents | Index
System
Type IsSealed Property
Example using System; using System.Reflection;
A namespace Samples { internal class TypeIsPublic { public static void Main() { Console.WriteLine( "Type: object"); Type t = typeof(object); Console.WriteLine("IsPublic: {0}", t.IsPublic); Console.WriteLine("IsNotPublic: {0}", t.IsNotPublic); Console.WriteLine( "Type: TypeIsPublic"); t = typeof(TypeIsPublic); Console.WriteLine("IsPublic: {0}", t.IsPublic); Console.WriteLine("IsNotPublic: {0}", t.IsNotPublic); } } }
B C D E F G H I J K L M N O P
The output is
Q Type: object IsPublic: True IsNotPublic: False Type: TypeIsPublic IsPublic: False IsNotPublic: True
R S T U V
Type.IsSealed Property
W
[ILASM]
X
.property bool IsSealed { public hidebysig specialname instance bool get_IsSealed() }
Y
[C#]
Z
public bool IsSealed { get; }
3361
Contents | Index
Type
System
IsSealed Property
Summary Gets a System.Boolean value indicating whether the current System.Type is declared sealed. A B
Property Value
C
true if the System.Type is declared sealed; otherwise, false.
D
Description
E
This member must be implemented if the Reflection Library is present in the implementation.
F
Example
G
using System; using System.Reflection;
H I
namespace Samples { internal class TypeIsSealed { public static void Main() { Console.WriteLine( "Type: object"); Type t = typeof(object); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("IsSealed: {0}", t.IsSealed); Console.WriteLine( "Type: string"); t = typeof(string); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("IsSealed: {0}", t.IsSealed); } } }
J K L M N O P Q R S T U V W
The output is
X
Type: object FullName: System.Object IsSealed: False Type: string FullName: System.String IsSealed: True
Y Z
3362
Contents | Index
System
Type IsSpecialName Property
Type.IsSerializable Property [ILASM]
.property bool IsSerializable { public hidebysig specialname instance bool get_IsSerializable() }
A
[C#]
B
public bool IsSerializable { get; }
C
Summary
D
Gets a value indicating whether the System.Type is serializable.
E F
Property Value
G
true if the System.Type is serializable; otherwise, false.
H I
Type.IsSpecialName Property
J
[ILASM]
K
.property bool IsSpecialName { public hidebysig specialname instance bool get_IsSpecialName() }
L
[C#]
M
public bool IsSpecialName { get; }
N
Summary
O
Gets a System.Boolean value indicating whether the current System.Type has a name that requires special handling.
P Q
Property Value
R
true if the System.Type has a name that requires special handling; otherwise, false.
S
Description
T
[Note: Names that begin with or contain an underscore character (_) are examples of type names that might require special treatment by some tools.] This member must be implemented if the Reflection Library is present in the implementation.
U V W
Example
X
using System; using System.Reflection;
Y Z
namespace Samples { public class TypeIsSpecialName
3363
Contents | Index
Type
System
IsUnicodeClass Property
{ public static void Main() { Console.WriteLine( "Type: string"); Type t = typeof(string); Console.WriteLine("FullName: {0}", t.FullName); MethodInfo[] methods = t.GetMethods(); foreach(MethodInfo m in methods) if(m.IsSpecialName) Console.WriteLine(m); }
A B C D E F }
G
}
H
The output is
I
Type: string FullName: System.String Boolean op_Equality(System.String, System.String) Boolean op_Inequality(System.String, System.String) Char get_Chars(Int32) Int32 get_Length()
J K L M N O
Type.IsUnicodeClass Property
P
[ILASM]
.property bool IsUnicodeClass { public hidebysig specialname instance bool get_IsUnicodeClass() }
Q R
[C#]
public bool IsUnicodeClass { get; }
S T
Summary
U
Gets a value indicating whether the string format attribute UnicodeClass is selected for the System.Type.
V W
Property Value
X
true if the string format attribute UnicodeClass is selected for the System.Type; otherwise, false.
Y Z
3364
Contents | Index
System
Type IsValueType Property
Description The System.Reflection.TypeAttributes.StringFormatMask is used to select the string format attributes. The string format attributes enhance interoperability by defining how strings should be interpreted.
A B C
Type.IsValueType Property
D [ILASM]
E
.property bool IsValueType { public hidebysig specialname instance bool get_IsValueType() }
F
[C#]
G
public bool IsValueType { get; }
H
Summary
I
Gets a System.Boolean value that indicates whether the current System.Type represents a value type.
J K
Property Value
L
true if the current System.Type represents a value type (structure); otherwise false.
M
Description
N
This property returns true for enumerations, but not for the System.Enum type itself, which is a class.
O
Example
Q
P
using System; using System.Reflection;
R
namespace Samples { public class TypeIsValueType { public static void Main() { Console.WriteLine( "Type: int"); Type t = typeof(int); Console.WriteLine("FullName: {0}", t.FullName); Console.WriteLine("IsClass: {0}", t.IsClass);
T
S
U V W X Y Z
3365
Contents | Index
Type
System
MemberType Property
Console.WriteLine("IsEnum: {0}", t.IsEnum); Console.WriteLine("IsInterface: {0}", t.IsInterface); Console.WriteLine("IsValueType: {0}", t.IsValueType);
A B }
C
} }
D
The output is
E F
Type: int FullName: System.Int32 IsClass: False IsEnum: False IsInterface: False IsValueType: True
G H I J K
Type.MemberType Property
L
[ILASM]
M
.property valuetype System.Reflection.MemberTypes MemberType { public hidebysig virtual specialname valuetype System.Reflection.MemberTypes get_MemberType() }
N
[C#]
O
public override MemberTypes MemberType { get; }
P
Summary
Q
Gets a bitmask indicating the member type.
R S
Property Value
T
A bitmask indicating the member type, which can be one of the following: Constructor, Event, Field, Method, Property, TypeInfo, Custom, NestedType, or All.
U V W
Type.Module Property
X
[ILASM]
Y
.property class System.Reflection.Module Module { public hidebysig virtual abstract specialname class System.Reflection.Module get_Module() }
Z
[C#]
public abstract Module Module { get; }
3366
Contents | Index
System
Type Module Property
Summary Gets the module in which the current System.Type is defined.
Property Value
A
A System.Reflection.Module that reflects the module in which the current System.Type is defined.
B C D
Description
E
This member must be implemented if the Reflection Library is present in the implementation.
F
Example
G
using System; using System.Reflection;
H I
namespace Samples { public class TypeModule { public static void Main() { Console.WriteLine( "Type: object"); Type t = typeof(object); Console.WriteLine("Assembly: {0}", t.Assembly); Console.WriteLine( "AssemblyQualifiedName: {0}", t.AssemblyQualifiedName); Console.WriteLine("Module: {0}", t.Module); Console.WriteLine("Namespace: {0}", t.Namespace); } } }
J K L M N O P Q R S T U V
The output is
W X
Type: object Assembly: mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 AssemblyQualifiedName: System.Object, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Module: CommonLanguageRuntimeLibrary Namespace: System
Y Z
3367
Contents | Index
Type
System
Namespace Property
Type.Namespace Property [ILASM]
A
.property string Namespace { public hidebysig virtual abstract specialname string get_Namespace() }
B
[C#]
public abstract string Namespace { get; }
C D
Summary
E
Gets the namespace of the System.Type.
F
Property Value
G
A System.String containing the namespace of the current System.Type.
H
Description
I
[Note: A namespace is a logical design-time naming convenience, used mainly to define scope in an application and organize classes and other types in a hierarchical structure. From the viewpoint of the system, there are no namespaces.] This member must be implemented if the Reflection Library is present in the implementation.
J K L M
Example
N
using System; using System.Reflection;
O P
namespace Samples { public class TypeNamespace { public static void Main() { Console.WriteLine( "Type: object"); Type t = typeof(object); Console.WriteLine("Assembly: {0}", t.Assembly); Console.WriteLine( "AssemblyQualifiedName: {0}", t.AssemblyQualifiedName); Console.WriteLine("Module: {0}", t.Module); Console.WriteLine("Namespace: {0}", t.Namespace); } } }
Q R S T U V W X Y Z
3368
Contents | Index
System
Type ReflectedType Property
The output is Type: object Assembly: mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 AssemblyQualifiedName: System.Object, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Module: CommonLanguageRuntimeLibrary Namespace: System
A B C D E
Type.ReflectedType Property
F
[ILASM]
G
.property class System.Type ReflectedType { public hidebysig virtual specialname class System.Type get_ReflectedType() }
H
[C#]
I
public override Type ReflectedType { get; }
J
Summary
K
Gets the type that was used to obtain the current instance.
L M
Property Value
N
The Type object through which the current instance was obtained.
O
Description
P
[Note: This property overrides System.Reflection.MemberInfo.ReflectedType.] This member must be implemented if the Reflection Library is present in the implementation.
Q
Example
S
using System; using System.Reflection;
T
R
U
namespace Samples { public abstract class ReflectedType { public abstract class BaseNestedClass { public abstract int Foo(); } public abstract class NestedClass: BaseNestedClass
V W X Y Z
3369
Contents | Index
Type
System
TypeHandle Property
{ } public static void Main(string[] args) { Type t = typeof(NestedClass); MethodInfo mi = t.GetMethod("Foo"); Console.WriteLine("ReflectedType: {0}", mi.ReflectedType); }
A B C D
} }
E F
The output is
G ReflectedType: Samples.ReflectedType+NestedClass
H I
Type.TypeHandle Property
J
[ILASM]
K
.property valuetype System.RuntimeTypeHandle TypeHandle { public hidebysig virtual abstract specialname valuetype System.RuntimeTypeHandle get_TypeHandle() }
L
[C#]
M
public abstract RuntimeTypeHandle TypeHandle { get; }
N
Summary
O
Gets the System.RuntimeTypeHandle for the current System.Type.
P Q
Description
R
The System.RuntimeTypeHandle encapsulates a pointer to an internal data structure that represents the type. This handle is unique during the process lifetime. The handle is valid only in the application domain in which it was obtained. This member must be implemented if the Runtime Infrastructure Library is present in the implementation.
S T U V
Example
W
using System; using System.Reflection;
X namespace Samples { public class TypeTypeHandle { public unsafe static void Main() {
Y Z
3370
Contents | Index
System
Type TypeInitializer Property
Type[] types = new Type[]{ typeof(object), typeof(int), typeof(string), typeof(int*), typeof(int[][])}; foreach(Type t in types) { RuntimeTypeHandle rth = t.TypeHandle; Console.WriteLine( "Type: {0} Handle Value: {1}", t, rth.Value); }
A B C D E F G
}
H
} }
I
The output is Type: Type: Type: Type: Type:
J K
System.Object Handle Value: 2041896352 System.Int32 Handle Value: 2041972160 System.String Handle Value: 2041902104 System.Int32* Handle Value: 48130594 System.Int32[][] Handle Value: 48130666
L M N O
Type.TypeInitializer Property
P
[ILASM]
Q
.property class System.Reflection.ConstructorInfo TypeInitializer { public hidebysig specialname instance class System.Reflection.ConstructorInfo get_TypeInitializer() }
R S
[C#]
T
public ConstructorInfo TypeInitializer { get; }
U
Summary
V
Gets the initializer for the type represented by the current instance.
W
Property Value
X
A System.Reflection.ConstructorInfo containing the name of the static constructor for the type represented by the current instance.
Y Z
3371
Contents | Index
Type
System
TypeInitializer Property
Description [Note: Type initializers are available through System.Type.GetMember, System.Type.GetMembers, and System.Type.GetConstructors.] This member must be implemented if the Reflection Library is present in the implementation.
A B C
Example
D
using System; using System.Reflection;
E
namespace Samples { public class TypeTypeInitializer { public unsafe static void Main() { Type[] types = new Type[]{ typeof(object), typeof(int*), typeof(string), typeof(Type), typeof(Assembly)}; foreach(Type t in types) { ConstructorInfo ci = t.TypeInitializer; Console.WriteLine( "Type: {0}, TypeInitializer: {1}", t, ci); } } } }
F G H I J K L M N O P Q R S T
The output is
U
Type: System.Object, TypeInitializer: Type: System.Int32*, TypeInitializer: Type: System.String, TypeInitializer: Void .cctor() Type: System.Type, TypeInitializer: Void .cctor() Typ: System.Reflection.Assembly, TypeInitializer:
V W X Y Z
3372
Contents | Index
System
Type UnderlyingSystemType Property
Type.UnderlyingSystemType Property [ILASM]
.property class System.Type UnderlyingSystemType { public hidebysig virtual abstract specialname class System.Type get_UnderlyingSystemType() }
A
[C#]
B
public abstract Type UnderlyingSystemType { get; }
C
Summary
D
Returns the system-supplied type that represents the current type.
E
Property Value
F
The underlying system type for the System.Type.
G H
Description
I
This member must be implemented if the Reflection Library is present in the implementation.
J
Example
K
using System; using System.Reflection;
L M
namespace Samples { public class TypeUnderlyingSystemType { enum Month {January = 1, February, March, April, May, June, July, August, September, October, November, December} public static void Main() { Type[] types = new Type[]{ typeof(object), typeof(int), typeof(string), typeof(Month)}; foreach(Type t in types) { Console.WriteLine( "Type: {0}, UnderlyingSystemType: {1}", t, t.UnderlyingSystemType); } } } }
N O P Q R S T U V W X Y Z
3373
Contents | Index
Type
System
Equals() Method
The output is Type: System.Object, UnderlyingSystemType: System.Object Type: System.Int32, UnderlyingSystemType: System.Int32 Type: System.String, UnderlyingSystemType: System.String Type: Samples.TypeUnderlyingSystemType+Month, UnderlyingSystemType: Samples.TypeUnderlyingSystemType+Month
A B C D E
Type.Equals(System.Object) Method
F
[ILASM]
.method public hidebysig virtual bool Equals(object o)
G
[C#]
public override bool Equals(object o)
H I
Summary
J
Determines if the underlying system type of the current System.Type is the same as the underlying system type of the specified System.Object.
K L
Parameters
M N
Parameter
Description
o
The System.Object whose underlying system type is to be compared with the underlying system type of the current System.Type.
O P Q R
Return Value
S
true if the underlying system type of o is the same as the underlying system type of the current System.Type; otherwise, false. This method also returns false if the object specified by the o parameter is not a Type.
T U
Permissions
V W X Y Z
Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
3374
Contents | Index
System
Type Equals() Method
Type.Equals(System.Type) Method [ILASM]
.method public hidebysig instance bool Equals(class System.Type o) [C#]
A
public bool Equals(Type o)
B C
Summary
D
Determines if the underlying system type of the current System.Type is the same as the underlying system type of the specified System.Type.
E F
Parameters
G
Parameter
Description
o
The System.Type whose underlying system type is to be compared with the underlying system type of the current System.Type.
H I J K
Return Value
L
true if the underlying system type of o is the same as the underlying system type of the current System.Type; otherwise, false.
M N O
Description
P
This member must be implemented if the Reflection Library is present in the implementation.
Q
Example
R
using System; using System.Reflection;
S T
namespace Samples { public class TypeEquals { public static void Main() { Type to = typeof(object), ts = typeof(string), ti = typeof(int); Console.WriteLine(to.Equals(to)); Console.WriteLine(to.Equals(ts)); Console.WriteLine(to.Equals(ti));
U V W X Y Z
3375
Contents | Index
Type
System
FindInterfaces() Method
Console.WriteLine(ts.Equals( typeof(string))); Console.WriteLine(ti.Equals( typeof(System.Int32)));
A
} }
B }
C
The output is
D E
True False False True True
F G H I
Type.FindInterfaces(System.Reflection.TypeFilter, System.Object) Method
J
[ILASM]
K
.method public hidebysig virtual class System.Type[] FindInterfaces(class System.Reflection.TypeFilter filter, object filterCriteria)
L
[C#]
M
public virtual Type[] FindInterfaces(TypeFilter filter, object filterCriteria)
N O
Summary
P
Returns an array of System.Type objects representing a filtered list of interfaces implemented or inherited by the current System.Type.
Q
Parameters
R S
Parameter
Description
filter
The System.Reflection.TypeFilter delegate that compares the interfaces against filterCriteria.
filterCriteria
The search criteria that determine whether an interface should be included in the returned array.
T U V W X Y Z
3376
Contents | Index
System
Type FindInterfaces() Method
Return Value An array of System.Type objects representing a filtered list of the interfaces implemented or inherited by the current System.Type, or an empty array of type System.Type, if no interfaces matching the filter are implemented or inherited by the current System.Type.
A B
Description
C
The System.Reflection.Module.FilterTypeName and System.Reflection.Module.FilterTypeNameIgnoreCase delegates supplied by the System.Reflection.Module class may also be used, in lieu of the System.Reflection.TypeFilter delegate. All of the interfaces implemented by this class are considered during the search, whether declared by a base class or this class itself. This method searches the base class hierarchy, returning each of the matching interfaces each class implements as well as all the matching interfaces each of those interfaces implements (that is, the transitive closure of the matching interfaces is returned). No duplicate interfaces are returned.
D E F G H I J K
Exceptions
L
Exception
Condition
System.ArgumentNullException
filter is null.
System.Reflection.TargetInvocationException
A static initializer is invoked and throws an exception.
M N O P Q R
Permissions
S
Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
T U V W X Y Z
3377
Contents | Index
Type
System
FindMembers() Method
Type.FindMembers(System.Reflection.MemberTypes, System.Reflection.BindingFlags, System.Reflection.MemberFilter, System.Object) Method A [ILASM]
B
.method public hidebysig virtual class System.Reflection.MemberInfo[] FindMembers(valuetype System.Reflection.MemberTypes memberType, valuetype System.Reflection.BindingFlags bindingAttr, class System.Reflection.MemberFilter filter, object filterCriteria)
C D
[C#]
E
public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bindingAttr, MemberFilter filter, object filterCriteria)
F G
Summary
H
Returns a filtered array of System.Reflection.MemberInfo objects of the specified member type.
I J
Parameters
K L
Parameter
Description
memberType
A MemberTypes object indicating the type of member to search for.
M N
A bitmask comprised of one or more System.Reflection.BindingFlags that specify how the search is conducted.
O
bindingAttr
P
-or-
Q
Zero, to return null.
R
The delegate that does the comparisons, returning true if the member currently being inspected matches the filterCriteria and false otherwise. You can use the FilterAttribute, FilterName, and FilterNameIgnoreCase delegates supplied by this class. The first uses the fields of FieldAttributes, MethodAttributes, and MethodImplAttributes as search criteria, and the other two delegates use String objects as the search criteria.
S
filter
T U V
The search criteria that determine whether a member is returned in the array of MemberInfo objects.
W
filterCriteria
X Y
The fields of FieldAttributes, MethodAttributes, and MethodImplAttributes can be used in conjunction with the FilterAttribute delegate supplied by this class.
Z
3378
Contents | Index
System
Type FindMembers() Method
Return Value A filtered array of System.Reflection.MemberInfo objects of the specified member type, or an empty array of type System.Reflection.MemberInfo, if the current System.Type does not have members of type memberType that match the filter criteria.
A B
Description
C
Members include properties, methods, fields, events, and so on. If the requested type is non-public and the caller does not have System.Security.Permissions.ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null. The following System.Reflection.BindingFlags filter flags can be used to define which members to include in the search:
D E F G H
• • • • • •
Instance to include instance members in the search. Static to include static members in the search. Public to include public members in the search. NonPublic to include non-public members (that is, private and protected members) in the search. The following System.Reflection.BindingFlags modifier flags can be used to change how the search works: DeclaredOnly to search only the members declared on the System.Type, not members that were simply inherited.
I J K L M N O P
See System.Reflection.BindingFlags for more information. Valid values for System.Type.MemberType are defined in System.Reflection.MemberInfo. If no such members are found, an empty array is returned. Class initializers are available through System.Type.GetMember, System.Type.GetMembers, System.Type.FindMembers, and System.Type.GetConstructors.
Q R S T U
Exceptions
V
Exception
Condition
System.ArgumentNullException
filter is null.
W X Y Z
3379
Contents | Index
Type
System
GetArrayRank() Method
Permissions Permission
Description
System.Security.Permissions.ReflectionPermission
For reflecting non-public objects. Associated enumeration: System.Security.Permissions. ReflectionPermissionFlag.TypeInformation.
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
A B C D E F G H
Type.GetArrayRank() Method
I
[ILASM]
J
.method public hidebysig virtual int32 GetArrayRank() [C#]
K
public virtual int GetArrayRank()
L M
Summary
N
Returns the number of dimensions in the current System.Type.
O
Exceptions
P Q R
Exception
Condition
System.ArgumentException
The current System.Type is not an array.
S T
Example
U
using System; using System.Reflection;
V W
namespace Samples { public class TypeGetArrayRank { public static void Main() { int[] indexArray = {4, 2, 3}; int[] lowboundArray = {3, 2, 1};
X Y Z
3380
Contents | Index
System
Type GetAttributeFlagsImpl() Method
Array a = Array.CreateInstance( typeof(int), indexArray, lowboundArray); Type t = a.GetType(); Console.WriteLine("GetArrayRank: {0}", t.GetArrayRank()); int[,] integers = new int[3,5]; t = integers.GetType(); Console.WriteLine("GetArrayRank: {0}", t.GetArrayRank()); try { int i = 42; t = i.GetType(); Console.WriteLine("GetArrayRank: {0}", t.GetArrayRank()); } catch(Exception e) { Console.WriteLine("Exception: {0}", e); }
A B C D E F G H I J K L
}
M
}
N
}
O
The output is
P GetArrayRank: 3 GetArrayRank: 2 Exception: System.ArgumentException: Must be an array type. at System.RuntimeType.GetArrayRank() at Samples.TypeGetArrayRank.Main() in C:\Books\BCL\Samples\System\Type\ GetArrayRank()\Type.cs:line 27
Q R S T U
Type.GetAttributeFlagsImpl() Method
V
[ILASM]
W
.method family hidebysig virtual abstract valuetype System.Reflection.TypeAttributes GetAttributeFlagsImpl()
X
[C#]
Y
protected abstract TypeAttributes GetAttributeFlagsImpl()
Z
3381
Contents | Index
Type
System
GetConstructor() Method
Summary When overridden in a derived type implements the System.Type.Attributes property and returns the attributes specified for the type represented by the current instance. A B
Return Value
C
A System.Reflection.TypeAttributes value that signifies the attributes of the type represented by the current instance.
D E
Description
F
This member must be implemented if the Reflection Library is present in the implementation.
G
Usage
H
Use this property to determine the visibility, semantics, and layout format of the type represented by the current instance. Also use this property to determine if the type represented by the current instance has a special name.
I J K L
N
Type.GetConstructor(System.Reflection.BindingFlags, System.Reflection.Binder, System.Reflection.CallingConventions, System.Type[], System.Reflection.ParameterModifier[]) Method
O
[ILASM]
M
.method public hidebysig instance class System.Reflection.ConstructorInfo GetConstructor(valuetype System.Reflection.BindingFlags bindingAttr, class System.Reflection.Binder binder, valuetype System.Reflection.CallingConventions on, class System.Type[] types, class System.Reflection.ParameterModifier[] modifiers)
P Q R
[C#]
S
public ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
T
Summary
U
Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.
V W X Y Z
3382
Contents | Index
System
Type GetConstructor() Method
Parameters Parameter
Description A
bindingAttr
binder
callConvention
A bitmask comprised of one or more System.Reflection.BindingFlags that specify how the search is conducted.
B
-or-
C
Zero, to return null.
D
A System.Reflection.Binder object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.
E
-or-
G
null, to use the System.Type.DefaultBinder.
H
The System.Reflection.CallingConventions object that specifies the set of rules to use regarding the order and layout of arguments, how the return value is passed, what registers are used for arguments, and the stack is cleaned up.
I
F
J K L
An array of System.Type objects representing the number, order, and type of the parameters for the constructor to get. types
M
-orN
An empty array of the type System.Type (that is, Type[] types = new Type[0]) to get a constructor that takes no parameters.
modifiers
O P
An array of System.Reflection.ParameterModifier objects representing the attributes associated with the corresponding element in the types array. The default binder does not process this parameter.
Q R S
Return Value
T
A System.Reflection.ConstructorInfo object representing the constructor that matches the specified requirements, if found; otherwise, null.
U V
Description
W
Although the default binder does not process System.Reflection.ParameterModifier (the modifiers parameter), you can use the abstract System.Reflection.Binder class to write a custom binder that does process modifiers. ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled.
X Y Z
3383
Contents | Index
Type
System
GetConstructor() Method
The types array and the modifiers array have the same length. A parameter specified in the types array can have the following attributes, which are specified in the modifiers array: pdIn, pdOut, pdLcid, pdRetval, pdOptional, and pdHasDefault, which represent [In], [Out], [lcid], [retval], [optional], and a value specifying whether the parameter has a default value. A parameter’s associated attributes are stored in the metadata and enhance interoperability. If an exact match does not exist, the binder will attempt to coerce the parameter types specified in the types array in order to select a match. If the binder is unable to select a match, then null is returned. The following System.Reflection.BindingFlags filter flags can be used to define which constructors to include in the search:
A B C D E F G
•
H
• •
I J K
You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return. Specify BindingFlags.Public to include public constructors in the search. Specify BindingFlags.NonPublic to include non-public constructors (that is, private and protected constructors) in the search.
See System.Reflection.BindingFlags for more information. System.Type.GetConstructor cannot be used to obtain a class initializer. Class initializers are available through System.Type.GetMember, System.Type.GetMembers, System.Type.FindMembers, System.Type.GetConstructors, and System.Type.TypeInitializer. If the requested constructor is non-public and the caller does not have System.Security.Permissions.ReflectionPermission to reflect non-public methods outside the current assembly, this method returns null. The table at the top of the following page shows what members of a base class are returned by the Get methods when reflecting on a type.
L M N O P Q R S T U V W X Y Z
3384
Contents | Index
System
Type GetConstructor() Method
Member Type
Static
Non-Static
constructor
No
No
field
No
Yes. A field is always hide-by-name-and-signature.
event
Not applicable
The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below.
method
No
Yes. A method (both virtual and non-virtual) can be hideby-name or hide-by-name-and-signature.
F
nested Type
No
No
G
Not applicable
The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below.
A B C D E
property
H I J K
1.
2.
3.
Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class. Custom attributes are not part of the common type system.
L M N O P Q R
Exceptions
S
Exception
Condition
System.ArgumentNullException
types is null. -orOne of the elements in types is null.
System.ArgumentException
T U V W X
types is multidimensional. -ormodifiers is multidimensional. -ortypes and modifiers do not have the same length.
Y Z
3385
Contents | Index
Type
System
GetConstructor() Method
Permissions Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
System.Security.Permissions.ReflectionPermission
For reflecting non-public methods. Associated enumeration: System.Security.Permissions. ReflectionPermissionFlag.TypeInformation.
A B C D E F G H
J
Type.GetConstructor(System.Reflection.BindingFlags, System.Reflection.Binder, System.Type[], System.Reflection.ParameterModifier[]) Method
K
[ILASM]
I
.method public hidebysig instance class System.Reflection.ConstructorInfo GetConstructor(valuetype System.Reflection.BindingFlags bindingAttr, class System.Reflection.Binder binder, class System.Type[] types, class System.Reflection.ParameterModifier[] modifiers)
L M N
[C#]
public ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
O P Q
Summary
R
Returns a constructor defined in the type represented by the current instance. The parameters of the constructor match the specified argument types and modifiers, under the specified binding constraints.
S T U V W X Y Z
3386
Contents | Index
System
Type GetConstructor() Method
Parameters Parameter
Description
bindingAttr
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, this method returns null.
binder
A System.Reflection.Binder object that defines a set of properties and enables the binding, coercion of argument types, and invocation of members using reflection. Specify null to use the System.Type.DefaultBinder.
types
An array of System.Type objects. The elements in the array are of the same number, in the same order, and represent the same types as the parameters for the constructor to be returned.
G
The only defined value for this parameter is null.
H
A B C
modifiers
D E F
I J
Return Value
K
A System.Reflection.ConstructorInfo object that reflects the constructor that matches the specified criteria. If an exact match does not exist, binder will attempt to coerce the parameter types specified in types to select a match. If binder is unable to select a match, returns null. If the type represented by the current instance is contained in a loaded assembly, the constructor that matches the specified criteria is not public, and the caller does not have sufficient permissions, returns null.
L M N O P
Description
Q
The following System.Reflection.BindingFlags are used to define which constructors to include in the search: • • •
R S
Specify either System.Reflection.BindingFlags.Instance or System.Reflection.BindingFlags.Static to get a return value other than null. Specify System.Reflection.BindingFlags.Public to include public constructors in the search. Specify System.Reflection.BindingFlags.NonPublic to include non-public constructors (that is, private and protected constructors) in the search.
T U V W X
[Note: For more information, see System.Reflection.BindingFlags.] This member must be implemented if the Reflection Library is present in the implementation.
Y Z
3387
Contents | Index
Type
System
GetConstructor() Method
Exceptions Exception
Condition
System.ArgumentNullException
types is null, or at least one of the elements in types is null.
System.ArgumentException
types has more than one dimension.
A B C D E
Permissions
F G
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
H I J K L
Example
M
using System; using System.Reflection;
N O
namespace Samples { public class TypeGetConstructor { public static void Main() { Type t = typeof(String); ConstructorInfo ci = t.GetConstructor( BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, System.Type.DefaultBinder, new Type[] {typeof(Char[])}, null); Console.WriteLine(ci); } } }
P Q R S T U V W X Y Z
3388
Contents | Index
System
Type GetConstructor() Method
The output is Void .ctor(Char[])
A B
Type.GetConstructor(System.Type[]) Method
C [ILASM]
D
.method public hidebysig instance class System.Reflection.ConstructorInfo GetConstructor(class System.Type[] types)
E
[C#]
public ConstructorInfo GetConstructor(Type[] types)
F G
Summary
H
Returns a public instance constructor defined in the type represented by the current instance. The parameters of the constructor match the specified argument types.
I J
Parameters
K
Parameter
Description
types
An array of System.Type objects. The elements in the array are of the same number, in the same order, and represent the same types as the parameters for the constructor to be returned. Specify System.Type.EmptyTypes to obtain a constructor that takes no parameters.
L M N O P Q
Return Value
R
A System.Reflection.ConstructorInfo object representing the public instance constructor whose parameters match exactly the types in types, if found; otherwise, null. If the type represented by the current instance is contained in a loaded assembly, the constructor that matches the specified criteria is not public, and the caller does not have sufficient permissions, returns null.
S T U V
Description
W
This version of System.Type.GetConstructor is equivalent to System.Type.GetConstructor(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, types, null). This member must be implemented if the Reflection Library is present in the implementation.
X Y Z
3389
Contents | Index
Type
System
GetConstructor() Method
Exceptions Exception
Condition
System.ArgumentNullException
types is null, or at least one of the elements in types is null.
System.ArgumentException
types has more than one dimension.
A B C D E F
Permissions
G H I J
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
K L M
Example
N
using System; using System.Reflection;
O namespace Samples { public class TypeGetConstructor { public static void Main() { Type t = typeof(String); ConstructorInfo ci = t.GetConstructor( new Type[] {typeof(Char[])}); Console.WriteLine(ci); } } }
P Q R S T U V W X
The output is
Y
Void .ctor(Char[])
Z
3390
Contents | Index
System
Type GetConstructorImpl() Method
Type.GetConstructorImpl(System.Reflection.BindingFlags, System.Reflection.Binder, System.Reflection.CallingConventions, System.Type[], System.Reflection.ParameterModifier[]) Method A [ILASM]
B
.method family hidebysig virtual abstract class System.Reflection.ConstructorInfo GetConstructorImpl(valuetype System.Reflection.BindingFlags bindingAttr, class System.Reflection.Binder binder, valuetype System.Reflection.CallingConventions callConvention, class System.Type[] types, class System.Reflection.ParameterModifier[] modifiers)
C D E
[C#]
protected abstract ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
F G H
Summary
I
When overridden in a derived class, searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.
J K L
Parameters Parameter
M N
Description
O
A bitmask comprised of one or more System.Reflection.BindingFlags that specify how the search is conducted. bindingAttr
P
-or-
Q
Zero, to return null.
binder
R
A System.Reflection.Binder object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection.
S
-or-
U
T
null, to use the System.Type.DefaultBinder.
callConvention
V
The System.Reflection.CallingConventions object that specifies the set of rules to use regarding the order and layout of arguments, how the return value is passed, what registers are used for arguments, and the stack is cleaned up.
W X Y Z
3391
Contents | Index
Type
System
GetConstructorImpl() Method
Parameter
Description An array of System.Type objects representing the number, order, and type of the parameters for the constructor to get.
A B
types
C
-orAn empty array of the type System.Type (that is, Type[] types = new Type[0]) to get a constructor that takes no parameters.
D E
modifiers
F
An array of System.Reflection.ParameterModifier objects representing the attributes associated with the corresponding element in the types array. The default binder does not process this parameter.
G H
Return Value
I
A System.Reflection.ConstructorInfo object representing the constructor that matches the specified requirements, if found; otherwise, null.
J K
Description
L
Although the default binder does not process System.Reflection.ParameterModifier (the modifiers parameter), you can use the abstract System.Reflection.Binder class to write a custom binder that does process modifiers. ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled. The types array and the modifiers array have the same length. A parameter specified in the types array can have the following attributes, which are specified in the modifiers array: pdIn, pdOut, pdLcid, pdRetval, pdOptional, and pdHasDefault, which represent [In], [Out], [lcid], [retval], [optional], and a value specifying whether the parameter has a default value. A parameter’s associated attributes are stored in the metadata and are used for interoperability. If an exact match does not exist, the binder will attempt to coerce the parameter types specified in the types array in order to select a match. If the binder is unable to select a match, then null is returned. The following System.Reflection.BindingFlags filter flags can be used to define which constructors to include in the search:
M N O P Q R S T U V W X
•
Y
• •
Z
You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return. Specify BindingFlags.Public to include public constructors in the search. Specify BindingFlags.NonPublic to include non-public constructors (that is, private and protected constructors) in the search.
3392
Contents | Index
System
Type GetConstructorImpl() Method
See System.Reflection.BindingFlags for more information. This method implements System.Type.GetConstructor. If the requested type is non-public and the caller does not have System.Security.Permissions.ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null. System.Type.GetConstructor and System.Type.GetConstructorImpl cannot be used to obtain a class initializer. Class initializers are available only through System.Type.GetMember, System.Type.GetMembers, System.Type.FindMembers, and System.Type.GetConstructors.
A B C D E F
Exceptions
G
Exception
System.ArgumentNullException
System.ArgumentException
Condition
H
types is null.
I
-or-
J
One of the elements in types is null.
K
types is multidimensional.
L
-or-
M
modifiers is multidimensional.
N
-orO
types and modifiers do not have the same length.
P Q
Permissions
R
Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
System.Security.Permissions.ReflectionPermission
For reflecting non-public objects. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
S T U V W X Y Z
3393
Contents | Index
Type
System
GetConstructors() Method
Type.GetConstructors() Method [ILASM]
A
.method public hidebysig instance class System.Reflection.ConstructorInfo[] GetConstructors()
B
[C#]
public ConstructorInfo[] GetConstructors()
C D
Summary
E
Returns an array of the public constructors defined in the type represented by the current instance.
F G
Return Value
H
An array of System.Reflection.ConstructorInfo objects that reflect the public constructors defined in the type represented by the current instance. If no public constructors are defined in the type represented by the current instance, returns an empty array.
I J K
Description
L
This version of System.Type.GetConstructors is equivalent to System.Type.GetConstructors(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance). This member must be implemented if the Reflection Library is present in the implementation.
M N O P
Example
Q
using System; using System.Reflection;
R
namespace Samples { public class TypeGetConstructors { public static void Main() { Type t = typeof(String); ConstructorInfo[] constructorInfos = t.GetConstructors(); foreach(ConstructorInfo ci in constructorInfos) Console.WriteLine(ci); } } }
S T U V W X Y Z
3394
Contents | Index
System
Type GetConstructors() Method
The output is Void Void Void Void Void Void Void Void
.ctor(Char*) .ctor(Char*, Int32, Int32) .ctor(SByte*) .ctor(SByte*, Int32, Int32) .ctor(SByte*, Int32, Int32, System.Text.Encoding) .ctor(Char[], Int32, Int32) .ctor(Char[]) .ctor(Char, Int32)
A B C D E F
Type.GetConstructors(System.Reflection.BindingFlags) Method
G
[ILASM]
H
.method public hidebysig virtual abstract class System.Reflection.ConstructorInfo[] GetConstructors(valuetype System.Reflection.BindingFlags bindingAttr)
I J
[C#]
public abstract ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
K L
Summary
M
Returns an array of constructors defined in the type represented by the current instance, under the specified binding constraints.
N O
Parameters
P
Parameter
Description
bindingAttr
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, this method returns null.
Q R S T
Return Value
U
An array of System.Reflection.ConstructorInfo objects that reflect the constructors that are defined in the type represented by the current instance and match the constraints of bindingAttr. If System.Reflection.BindingFlags.NonPublic and System.Reflection.BindingFlags.Static are specified, this array includes the type initializer if it is defined. If no constructors meeting the constraints of bindingAttr are defined in the type represented by the current instance, returns an empty array. If the type represented by the current instance is contained in a loaded assembly, the constructors that match the specified criteria are not public, and the caller does not have sufficient permission, returns null.
V W X Y Z
3395
Contents | Index
Type
System
GetConstructors() Method
Description The following System.Reflection.BindingFlags are used to define which constructors to include in the search: A
•
B C
•
D
•
E F
Specify either System.Reflection.BindingFlags.Instance or System.Reflection.BindingFlags.Static to get a return value other than null. Specify System.Reflection.BindingFlags.Public to include public constructors in the search. Specify System.Reflection.BindingFlags.NonPublic to include non-public constructors (that is, private and protected constructors) in the search.
[Note: For more information, see System.Reflection.BindingFlags.] This member must be implemented if the Reflection Library is present in the implementation.
G H I
Permissions
J K
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
L M N O P
Example
Q
using System; using System.Reflection;
R S
namespace Samples { public class TypeGetConstructors { public static void Main() { Type t = typeof(String); ConstructorInfo[] constructorInfos = t.GetConstructors( BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach(ConstructorInfo c in constructorInfos)
T U V W X Y Z
3396
Contents | Index
System
Type GetDefaultMembers() Method
Console.WriteLine(c); } } }
A
The output is Void Void Void Void Void Void Void Void Void
B C
.ctor(Char*) .ctor(Char*, Int32, Int32) .ctor(SByte*) .ctor(SByte*, Int32, Int32) .ctor(SByte*, Int32, Int32, System.Text.Encoding) .ctor(Char[], Int32, Int32) .ctor(Char[]) .ctor(Char, Int32) .cctor()
D E F G H I
Type.GetDefaultMembers() Method
J
[ILASM]
K
.method public hidebysig virtual class System.Reflection.MemberInfo[] GetDefaultMembers()
L
[C#]
M
public virtual MemberInfo[] GetDefaultMembers()
N
Summary
O
Returns an array of System.Reflection.MemberInfo objects that reflect the default members defined in the type represented by the current instance.
P Q
Return Value
R
An array of System.Reflection.MemberInfo objects reflecting the default members of the type represented by the current instance. The members returned by this method have the System.Reflection.DefaultMemberAttribute attribute. This member must be implemented if the Reflection Library is present in the implementation.
S T U V
Example
W
using System; using System.Reflection;
X Y
namespace Samples { public class TypeGetDefaultMembers { public static void Main()
Z
3397
Contents | Index
Type
System
GetElementType() Method
{ Type t = typeof(String); MemberInfo[] memberInfos = t.GetDefaultMembers(); foreach(MemberInfo mi in memberInfos) Console.WriteLine(mi);
A B C
} }
D
}
E
The output is
F
Char Chars [Int32]
G H I
Type.GetElementType() Method
J
[ILASM]
.method public hidebysig virtual abstract class System.Type GetElementType()
K
[C#]
L
public abstract Type GetElementType()
M
Summary
N
Returns the element type of the current System.Type.
O P
Return Value
Q
A System.Type that represents the type used to create the current instance if the current instance represents an array, pointer, or an argument passed by reference. Otherwise, returns null.
R S T
Example
U
using System; using System.Reflection;
V namespace Samples { public class TypeGetElementType { public static void Main() { int[] indexArray = {4, 2, 3}; int[] lowboundArray = {3, 2, 1}; Array a = Array.CreateInstance(
W X Y Z
3398
Contents | Index
System
Type GetEvent() Method
typeof(string), indexArray, lowboundArray); Type t = a.GetType(); Type e = t.GetElementType(); Console.WriteLine("GetElementType: {0}", e); int[,] integers = new int[3,5]; t = integers.GetType(); e = t.GetElementType(); Console.WriteLine("GetElementType: {0}", e);
A B C D E F
} }
G
}
H
The output is
I
GetElementType: System.String GetElementType: System.Int32
J K L
Type.GetEvent(System.String) Method
M
[ILASM]
N
.method public hidebysig instance class System.Reflection.EventInfo GetEvent(string name)
O
[C#]
P
public EventInfo GetEvent(string name)
Q
Summary
R
Returns a System.Reflection.EventInfo object reflecting the public event that has the specified name and is defined in the type represented by the current instance.
S T
Parameters
U V
Parameter
Description
name
A System.String containing the name of the public event to be returned.
W X Y Z
Return Value A System.Reflection.EventInfo object reflecting the public event that is named name and is defined in the type represented by the current instance, if found; otherwise, null. 3399
Contents | Index
Type
System
GetEvent() Method
Description This version of System.Type.GetEvent is equivalent to System.Type.GetEvent(name, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public). The search for name is case-sensitive. This member must be implemented if the Reflection Library is present in the implementation.
A B C D
Exceptions
E F G
Exception
Condition
System.ArgumentNullException
name is null.
H I
Example
J
using System; using System.Reflection;
K
namespace Samples { public class TypeGetEvent { public delegate int D(string s); public event D MyEvent; private void InvokeEvent() { if(MyEvent !=null) MyEvent("Hello world!"); } public static void Main() { Type t = typeof(TypeGetEvent); string s = "MyEvent"; EventInfo ei = t.GetEvent(s); Console.WriteLine(ei); } } }
L M N O P Q R S T U V W X
The output is
Y Z
D MyEvent
3400
Contents | Index
System
Type GetEvent() Method
Type.GetEvent(System.String, System.Reflection.BindingFlags) Method [ILASM]
.method public hidebysig virtual abstract class System.Reflection.EventInfo GetEvent(string name, valuetype System.Reflection.BindingFlags bindingAttr)
A
[C#]
B
public abstract EventInfo GetEvent(string name, BindingFlags bindingAttr)
C
Summary
D
Returns a System.Reflection.EventInfo object reflecting the event that has the specified name, is defined in the type represented by the current instance, and matches the specified binding constraints.
E F G
Parameters Parameter
H I
Description
J
name
A System.String containing the name of the event to be returned.
K
bindingAttr
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, this method returns null.
L M N
Return Value
O
A System.Reflection.EventInfo object reflecting the event that is named name, is defined in the type represented by the current instance, and matches the constraints of bindingAttr. If an event matching these criteria is not found, returns null. If the event is not public, the current instance represents a type from a loaded assembly, and the caller does not have sufficient permission, returns null.
Q
Description
T
The following System.Reflection.BindingFlags are used to define which events to include in the search:
U
•
W
• •
P
R S
V
Specify either System.Reflection.BindingFlags.Instance or System.Reflection.BindingFlags.Static to get a return value other than null. Specify System.Reflection.BindingFlags.Public to include public events in the search. Specify System.Reflection.BindingFlags.NonPublic to include non-public events (that is, private and protected events) in the search.
X Y Z
3401
Contents | Index
Type
System
GetEvent() Method
The following System.Reflection.BindingFlags value can be used to change how the search works: •
A B
System.Reflection.BindingFlags.DeclaredOnly to search only the events declared on the type, not events that were simply inherited.
[Note: For more information, see System.Reflection.BindingFlags.] This member must be implemented if the Reflection Library is present in the implementation.
C D E
Exceptions
F G H I
Exception
Condition
System.ArgumentNullException
name is null.
J K
Permissions
L M N O
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
P Q R
Example
S
using System; using System.Reflection;
T namespace Samples { public class TypeGetEvent { public delegate int D(string s); public event D MyEvent; private void InvokeEvent() { if(MyEvent !=null) MyEvent("Hello world!"); } public static void Main()
U V W X Y Z
3402
Contents | Index
System
Type GetEvents() Method
{ Type t = typeof(TypeGetEvent); string s ="MyEvent"; EventInfo ei = t.GetEvent(s, BindingFlags.Instance | BindingFlags.Public); Console.WriteLine(ei);
A B C
} }
D
}
E
The output is
F
D MyEvent
G H
Type.GetEvents() Method
I
[ILASM]
J
.method public hidebysig virtual class System.Reflection.EventInfo[] GetEvents()
K
[C#]
L
public virtual EventInfo[] GetEvents()
M
Summary
N
Returns an array of System.Reflection.EventInfo objects that reflect the public events defined in the type represented by the current instance.
O P
Return Value
Q
An array of System.Reflection.EventInfo objects that reflect the public events defined in the type represented by the current instance. If no public events are defined in the type represented by the current instance, returns an empty array.
R S T
Description
U
This member must be implemented if the Reflection Library is present in the implementation.
V
Default
W
This version of System.Type.GetEvents is equivalent to System.Type.GetEvents(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance).
X Y Z
3403
Contents | Index
Type
System
GetEvents() Method
Example using System; using System.Reflection;
A namespace Samples { public class TypeGetEvents { public delegate int D(string s); public event D MyEvent; public event D AnotherEvent; private void InvokeEvents() { if(MyEvent !=null) MyEvent("Hello world!"); if(AnotherEvent !=null) AnotherEvent("Hello world too!"); } public static void Main() { Type t = typeof(TypeGetEvents); EventInfo[] eventInfos = t.GetEvents(); foreach(EventInfo ei in eventInfos) Console.WriteLine(ei); } } }
B C D E F G H I J K L M N O P
The output is
Q D MyEvent D AnotherEvent
R S T
Type.GetEvents(System.Reflection.BindingFlags) Method
U
[ILASM]
V
.method public hidebysig virtual abstract class System.Reflection.EventInfo[] GetEvents(valuetype System.Reflection.BindingFlags bindingAttr)
W
[C#]
X
public abstract EventInfo[] GetEvents(BindingFlags bindingAttr)
Y
Summary
Z
Returns an array of System.Reflection.EventInfo objects that reflect the events that are defined in the type represented by the current instance and match the specified binding constraints. 3404
Contents | Index
System
Type GetEvents() Method
Parameters Parameter
Description
bindingAttr
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, this method returns null.
A B C D
Return Value
E
An array of System.Reflection.EventInfo objects that reflect the events that are defined in the type represented by the current instance and match the constraints of bindingAttr. If no events match these constraints, returns an empty array. If the type reflected by the current instance is from a loaded assembly and the caller does not have permission to reflect on non-public objects in loaded assemblies, returns only public events.
F G H I
Description
J
The following System.Reflection.BindingFlags are used to define which events to include in the search:
K L
• • •
Specify either System.Reflection.BindingFlags.Instance or System.Reflection.BindingFlags.Static to get a return value other than null. Specify System.Reflection.BindingFlags.Public to include public events in the search. Specify System.Reflection.BindingFlags.NonPublic to include non-public events (that is, private and protected events) in the search.
M N O P Q
[Note: For more information, see System.Reflection.BindingFlags.] This member must be implemented if the Reflection Library is present in the implementation.
R S T
Permissions
U V
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
W X Y Z
3405
Contents | Index
Type
System
GetField() Method
Example using System; using System.Reflection;
A namespace Samples { public class TypeGetEvents { public delegate int D(string s); public event D MyEvent; protected event D AnotherEvent; private void InvokeEvents() { if(MyEvent !=null) MyEvent("Hello world!"); if(AnotherEvent !=null) AnotherEvent("Hello world too!"); } public static void Main() { Type t = typeof(TypeGetEvents); EventInfo[] eventInfos = t.GetEvents( BindingFlags.Instance | BindingFlags.Public); foreach(EventInfo ei in eventInfos) Console.WriteLine(ei); } } }
B C D E F G H I J K L M N O P Q
The output is
R S
D MyEvent
T U
Type.GetField(System.String) Method
V
[ILASM]
W
.method public hidebysig instance class System.Reflection.FieldInfo GetField(string name)
X
[C#]
Y
public FieldInfo GetField(string name)
Z
3406
Contents | Index
System
Type GetField() Method
Summary Returns a System.Reflection.FieldInfo object reflecting the field that has the specified name and is defined in the type represented by the current instance. A
Parameters
B C
Parameter
Description
name
A System.String containing the name of the field to be returned.
D E F
Return Value
G
A System.Reflection.FieldInfo object reflecting the field that is named name and is defined in the type represented by the current instance, if found; otherwise, null. If the selected field is non-public, the type represented by the current instance is from a loaded assembly and the caller does not have sufficient permission to reflect on non-public objects in loaded assemblies, returns null.
H I J K
Description
L
The search for name is case-sensitive. This version of System.Type.GetField is equivalent to System.Type.GetField(name, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance). This member must be implemented if the Reflection Library is present in the implementation.
M N O P Q
Exceptions
R
Exception
Condition
System.ArgumentNullException
name is null.
S T U V
Permissions
W
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
X Y Z
3407
Contents | Index
Type
System
GetField() Method
Example using System; using System.Reflection;
A namespace Samples { public class TypeGetField { public string name; public static void Main() { Type t = typeof(TypeGetField); string s = "name"; FieldInfo fi = t.GetField(s); Console.WriteLine(fi); } } }
B C D E F G H I J
The output is
K System.String name
L M
Type.GetField(System.String, System.Reflection.BindingFlags) Method
N
[ILASM]
O
.method public hidebysig virtual abstract class System.Reflection.FieldInfo GetField(string name, valuetype System.Reflection.BindingFlags bindingAttr)
P
[C#]
Q
public abstract FieldInfo GetField(string name, BindingFlags bindingAttr)
R
Summary
S
Returns a System.Reflection.FieldInfo object reflecting the field that has the specified name, is defined in the type represented by the current instance, and matches the specified binding constraints.
T U V
Parameters
W X Y
Parameter
Description
name
A System.String containing the name of the field to be returned.
bindingAttr
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, this method returns null.
Z
3408
Contents | Index
System
Type GetField() Method
Return Value A System.Reflection.FieldInfo object reflecting the field that is named name, is defined in the type represented by the current instance, and matches the constraints of bindingAttr. If a field matching these criteria cannot be found, returns null. If the field is not public, the current type is from a loaded assembly, and the caller does not have sufficient permission, returns null.
A B C
Description
D
The following System.Reflection.BindingFlags are used to define which fields to include in the search:
E
•
G
• •
F
Specify either System.Reflection.BindingFlags.Instance or System.Reflection.BindingFlags.Static to get a return value other than null. Specify System.Reflection.BindingFlags.Public to include public fields in the search. Specify System.Reflection.BindingFlags.NonPublic to include nonpublic fields (that is, private and protected fields) in the search.
H I J K L
The following System.Reflection.BindingFlags values can be used to change how the search works:
M
•
N
•
System.Reflection.BindingFlags.DeclaredOnly to search only the fields declared in the type, not fields that were simply inherited. System.Reflection.BindingFlags.IgnoreCase to ignore the case of name.
O P
[Note: For more information, see System.Reflection.BindingFlags.] This member must be implemented if the Reflection Library is present in the implementation.
Q
Exceptions
T
R S
U
Exception
Condition
System.ArgumentNullException
name is null.
V W X Y Z
3409
Contents | Index
Type
System
GetFields() Method
Permissions Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
A B C D E
Example
F
using System; using System.Reflection;
G
namespace Samples { public class TypeGetField { public string name; public static void Main() { Type t = typeof(TypeGetField); string s = "name"; FieldInfo fi = t.GetField(s, BindingFlags.Instance | BindingFlags.Public); Console.WriteLine(fi); } } }
H I J K L M N O P Q R
The output is
S
System.String name
T U
Type.GetFields() Method
V [ILASM]
W
.method public hidebysig instance class System.Reflection.FieldInfo[] GetFields()
X
[C#]
public FieldInfo[] GetFields()
Y
Summary
Z
Returns an array of System.Reflection.FieldInfo objects that reflect the public fields defined in the type represented by the current instance. 3410
Contents | Index
System
Type GetFields() Method
Return Value An array of System.Reflection.FieldInfo objects that reflect the public fields defined in the type represented by the current instance. If no public fields are defined in the type represented by the current instance, returns an empty array.
A B
Description
C
This version of System.Type.GetFields is equivalent to System.Type.GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public). This member must be implemented if the Reflection Library is present in the implementation.
D E F G
Example
H
using System; using System.Reflection;
I J
namespace Samples { public class TypeGetFields { public string name; protected int age; public static void Main() { Type t = typeof(TypeGetFields); FieldInfo[] fieldInfos = t.GetFields(); foreach(FieldInfo fi in fieldInfos) Console.WriteLine(fi); } } }
K L M N O P Q R S T
The output is
U
System.String name
V W
Type.GetFields(System.Reflection.BindingFlags) Method
X
[ILASM]
Y
.method public hidebysig virtual abstract class System.Reflection.FieldInfo[] GetFields(valuetype System.Reflection.BindingFlags bindingAttr)
Z
[C#]
public abstract FieldInfo[] GetFields(BindingFlags bindingAttr)
3411
Contents | Index
Type
System
GetFields() Method
Summary Returns an array of System.Reflection.FieldInfo objects that reflect the fields that are defined in the type represented by the current instance and match the specified binding constraints.
A B
Parameters
C D
Parameter
Description
bindingAttr
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, this method returns null.
E F G H
Return Value
I
An array of System.Reflection.FieldInfo objects that reflect the fields that are defined in the type represented by the current instance and match the constraints of bindingAttr. If no fields match these constraints, returns an empty array. If the type represented by the current instance is from a loaded assembly and the caller does not have sufficient permission to reflect on non-public objects in loaded assemblies, returns only public fields.
J K L M
Description
N
The following System.Reflection.BindingFlags are used to define which fields to include in the search:
O P
•
Q
•
R S
•
T U
Specify either System.Reflection.BindingFlags.Instance or System.Reflection.BindingFlags.Static in order to get a return value other than null. Specify System.Reflection.BindingFlags.Public to include public fields in the search. Specify System.Reflection.BindingFlags.NonPublic to include non-public fields (that is, private and protected fields) in the search.
The following System.Reflection.BindingFlags values can be used to change how the search works:
V W
•
X Y
System.Reflection.BindingFlags.DeclaredOnly to search only the fields declared in the type, not fields that were simply inherited.
[Note: For more information, see System.Reflection.BindingFlags.] This member must be implemented if the Reflection Library is present in the implementation.
Z
3412
Contents | Index
System
Type GetHashCode() Method
Permissions Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of a type in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
A B C D E
Example
F
using System; using System.Reflection;
G H
namespace Samples { public class TypeGetFields { public string name; protected int age; public static void Main() { Type t = typeof(TypeGetFields); FieldInfo[] fieldInfos = t.GetFields( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach(FieldInfo fi in fieldInfos) Console.WriteLine(fi); } } }
I J K L M N O P Q R S
The output is
T U
System.String name Int32 age
V W
Type.GetHashCode() Method
X
[ILASM]
Y
.method public hidebysig virtual int32 GetHashCode()
Z
[C#]
public override int GetHashCode()
3413
Contents | Index
Type
System
GetInterface() Method
Summary Generates a hash code for the current instance. A
Description
B
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
C D
Example
E
using System; using System.Reflection;
F
namespace Samples { public class TypeGetHashCode { public static void Main() { Type[] types = new Type[]{typeof(object), typeof(string), typeof(int), typeof(TypeGetHashCode)}; foreach(Type t in types) Console.WriteLine("{0}.GetHashCode(): {1}", t, t.GetHashCode()); } } }
G H I J K L M N O P Q
The output is
R
System.Object.GetHashCode(): 48130732 System.String.GetHashCode(): 48130784 System.Int32.GetHashCode(): 48130836 Samples.TypeGetHashCode.GetHashCode(): 48174488
S T U V
Type.GetInterface(System.String) Method
W [ILASM]
X
.method public hidebysig instance class System.Type GetInterface(string name)
Y
[C#]
public Type GetInterface(string name)
Z
3414
Contents | Index
System
Type GetInterface() Method
Summary Searches for the interface with the specified name. A
Parameters
B
Parameter
Description
C
name
A System.String containing the name of the interface to get.
D E F
Return Value
G
A System.Type object representing the interface with the specified name, implemented or inherited by the current System.Type, if found; otherwise, null.
H I
Description
J
The search for name is case-sensitive. This member must be implemented if the Reflection Library is present in the implementation.
K L
Exceptions
M
Exception
Condition
System.ArgumentNullException
name is null.
N O P Q
Example
R
using System; using System.Reflection;
S T
namespace Samples { public class TypeGetInterface { public static void Main() { Type t = typeof(string); string[] strings = {"IComparable", "ICloneable", "IConvertible", "IEnumerable", "INoInterface"}; foreach(string s in strings) {
U V W X Y Z
3415
Contents | Index
Type
System
GetInterface() Method
Type ti = t.GetInterface(s); Console.WriteLine(ti== null? "null": ti.ToString()); }
A
} }
B
}
C
The output is
D System.IComparable System.ICloneable System.IConvertible System.Collections.IEnumerable null
E F G H I
Type.GetInterface(System.String, System.Boolean) Method
J
[ILASM]
K
.method public hidebysig virtual abstract class System.Type GetInterface(string name, bool ignoreCase)
L
[C#]
public abstract Type GetInterface(string name, bool ignoreCase)
M N
Summary
O
Returns the specified interface, specifying whether to do a case-sensitive search.
P
Parameters
Q R
Parameter
Description
name
A System.String containing the name of the interface to return.
ignoreCase
A System.Boolean where true indicates that the name search is to be done case-insensitively, and false performs a case-sensitive search.
S T U V W
Return Value
X
A System.Type object representing the interface with the specified name, implemented or inherited by the type represented by the instance, if found; otherwise, null.
Y Z
Description This member must be implemented if the Reflection Library is present in the implementation. 3416
Contents | Index
System
Type GetInterfaceMap() Method
Exceptions Exception
Condition
System.ArgumentNullException
name is null.
A B C
Example
D
using System; using System.Reflection;
E F
namespace Samples { public class TypeGetInterface { public string name; public static void Main() { Type t = typeof(string); string s = "ICloneable"; Type ti = t.GetInterface( s.ToLower(), false); Console.WriteLine(ti==null? "null": ti.ToString()); ti = t.GetInterface(s, false); Console.WriteLine(ti==null? "null": ti.ToString()); } } }
G H I J K L M N O P Q R S
The output is
T null System.ICloneable
U V W
Type.GetInterfaceMap(System.Type) Method
X
[ILASM]
Y
.method public hidebysig virtual valuetype System.Reflection.InterfaceMapping GetInterfaceMap(class System.Type interfaceType)
Z
[C#]
public virtual InterfaceMapping GetInterfaceMap(Type interfaceType)
3417
Contents | Index
Type
System
GetInterfaceMap() Method
Summary Returns an interface mapping for the specified interface type. A
Parameters
B C
Parameter
Description
D
interfaceType
The System.Type of the interface of which to retrieve a mapping.
E F
Return Value
G
A System.Reflection.InterfaceMapping object representing the interface mapping for interfaceType.
H I
Description
J
The interface map denotes how an interface is mapped into the actual methods on a class that implements that interface.
K L
Exceptions
M N
Exception
Condition
System.ArgumentException
The interfaceType parameter does not refer to an interface.
System.ArgumentNullException
interfaceType is null.
O P Q R S
Permissions
T U
Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
V W X Y Z
3418
Contents | Index
System
Type GetInterfaces() Method
Type.GetInterfaces() Method [ILASM]
.method public hidebysig virtual abstract class System.Type[] GetInterfaces() [C#]
A
public abstract Type[] GetInterfaces()
B
Summary
C
Returns all interfaces implemented or inherited by the type represented by the current instance.
D E F
Return Value
G
An array of System.Type objects representing the interfaces implemented or inherited by the type represented by the current instance. If no interfaces are found, returns an empty System.Type array.
H I
Description
J
This member must be implemented if the Reflection Library is present in the implementation.
K L
Example
M
using System; using System.Reflection;
N O
namespace Samples { public class TypeGetInterfaces { public static void Main() { Type t = typeof(string); Type[] types = t.GetInterfaces(); foreach(Type ti in types) Console.WriteLine(ti); } } }
P Q R S T U V W
The output is
X System.IComparable System.ICloneable System.IConvertible System.Collections.IEnumerable
Y Z
3419
Contents | Index
Type
System
GetMember() Method
Type.GetMember(System.String) Method [ILASM]
A
.method public hidebysig instance class System.Reflection.MemberInfo[] GetMember(string name)
B
[C#]
public MemberInfo[] GetMember(string name)
C D
Summary
E
Returns an array of System.Reflection.MemberInfo objects that reflect the public members that have the specified name and are defined in the type represented by the current instance.
F G
Parameters
H I
Parameter
Description
name
A System.String containing the name of the members to be returned.
J K L M
Return Value
N
An array of System.Reflection.MemberInfo objects that reflect the public members that are named name and are defined in the type represented by the current instance. If no public members with the specified name are defined in the type represented by the current instance, returns an empty array.
O P Q
Description
R
This version of System.Type.GetMember is equivalent to System.Type.GetMember(name, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public). The search for name is case-sensitive. This member must be implemented if the Reflection Library is present in the implementation.
S T U V
Exceptions
W X
Exception
Condition
System.ArgumentNullException
name is null.
Y Z
3420
Contents | Index
System
Type GetMember() Method
Example using System; using System.Reflection;
A namespace Samples { public abstract class TypeGetMember { public string name; public abstract int Foo(); public abstract int Foo(int i); public abstract int Foo(float f); public static void Main() { Type t = typeof(TypeGetMember); string[] strings = {"Name", "Foo"}; foreach(string s in strings) { MemberInfo[] memberInfos = t.GetMember(s); foreach(MemberInfo m in memberInfos) { Console.WriteLine(m); } } } } }
B C D E F G H I J K L M N O P Q
The output is
R Int32 Foo(Single) Int32 Foo(Int32) Int32 Foo()
S T U
Type.GetMember(System.String, System.Reflection.BindingFlags) Method
V
[ILASM]
W
.method public hidebysig virtual class System.Reflection.MemberInfo[] GetMember(string name, valuetype System.Reflection.BindingFlags bindingAttr)
X
[C#]
Y
public virtual MemberInfo[] GetMember(string name, BindingFlags bindingAttr)
Z
3421
Contents | Index
Type
System
GetMember() Method
Summary Returns an array of System.Reflection.MemberInfo objects that reflect the members defined in the type represented by the current instance that have the specified name and match the specified binding constraints.
A B
Parameters
C D
Parameter
Description
name
A System.String containing the name of the member to be returned.
bindingAttr
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, this method returns null.
E F G H I
Return Value
J
An array of System.Reflection.MemberInfo objects that reflect the members named name, are defined in the type represented by the current instance, and match the constraints of bindingAttr. If no members match these constraints, returns an empty array. If the selected member is non-public, the type reflected by the current instance is from a loaded assembly, and the caller does not have sufficient permission to reflect on non-public objects in loaded assemblies, returns null.
K L M N O
Description
P
The following System.Reflection.BindingFlags are used to define which members to include in the search:
Q R
•
S T
•
U
•
V
Specify either System.Reflection.BindingFlags.Instance or System.Reflection.BindingFlags.Static to get a return value other than null. Specify System.Reflection.BindingFlags.Public to include public members in the search. Specify System.Reflection.BindingFlags.NonPublic to include non-public members (that is, private and protected members) in the search.
W
The following System.Reflection.BindingFlags values can be used to change how the search works:
X Y
•
Z
•
System.Reflection.BindingFlags.DeclaredOnly to search only the members declared in the type, not members that were simply inherited. System.Reflection.BindingFlags.IgnoreCase to ignore the case of name.
3422
Contents | Index
System
Type GetMember() Method
[Note: For more information, see System.Reflection.BindingFlags.] This member must be implemented if the Reflection Library is present in the implementation. A
Exceptions
B
Exception
C
Condition
D System.ArgumentNullException
name is null.
E F
Permissions
G H
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
I J K L M
Example
N
using System; using System.Reflection;
O P
namespace Samples { public abstract class GetMember { public string name; public abstract int Foo(); public abstract int Foo(int i); public abstract int Foo(float f); public static void Main() { Type t = typeof(GetMember); string[] strings = {"Name", "foo"}; foreach(string s in strings) { MemberInfo[] memberInfos = t.GetMember(s, BindingFlags.Instance | BindingFlags.Public |
Q R S T U V W X Y Z
3423
Contents | Index
Type
System
GetMember() Method
BindingFlags.IgnoreCase); foreach(MemberInfo m in memberInfos) { Console.WriteLine(m); }
A }
B }
C
} }
D
The output is
E F
System.String name Int32 Foo(Single) Int32 Foo(Int32) Int32 Foo()
G H I
Type.GetMember(System.String, System.Reflection.MemberTypes, System.Reflection.BindingFlags) Method
J K L
[ILASM]
M
.method public hidebysig virtual class System.Reflection.MemberInfo[] GetMember(string name, valuetype System.Reflection.MemberTypes type, valuetype System.Reflection.BindingFlags bindingAttr)
N
[C#]
public virtual MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr)
O P Q
Summary
R
Searches for the specified members of the specified member type, using the specified binding constraints.
S
Parameters
T U
Parameter
Description
name
The System.String containing the name of the members to get.
type
The System.Type.MemberType to search for.
bindingAttr
A bitmask comprised of one or more System.Reflection.BindingFlags that specify how the search is conducted. -orZero, to return null.
V W X Y Z
3424
Contents | Index
System
Type GetMember() Method
Return Value An array of System.Reflection.MemberInfo objects representing the public members with the specified name, if found; otherwise, null. A
Description
B
Members include properties, methods, fields, events, and so on. This method searches the current classes and its base classes. If the requested type is non-public and the caller does not have System.Security.Permissions.ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null. The following System.Reflection.BindingFlags filter flags can be used to define which members to include in the search:
C D E F G H
• • • •
You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return. Specify BindingFlags.Public to include public members in the search. Specify BindingFlags.NonPublic to include non-public members (that is, private and protected members) in the search. Specify BindingFlags.FlattenHierarchy to include static members up the hierarchy.
I J K L M N
The following System.Reflection.BindingFlags modifier flags can be used to change how the search works:
O P
•
BindingFlags.IgnoreCase to ignore the case of name.
•
BindingFlags.DeclaredOnly to search only the members declared on the System.Type, not members that were simply inherited.
Q R S
See System.Reflection.BindingFlags for more information. Class initializers are available through System.Type.GetMember, System.Type.GetMembers, System.Type.FindMembers, and System.Type.GetConstructors.
T U V
Exceptions
W
Exception
Condition
System.ArgumentNullException
name is null.
System.NotSupportedException
A derived class must provide an implementation.
X Y Z
3425
Contents | Index
Type
System
GetMembers() Method
Permissions Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions. ReflectionPermissionFlag.MemberAccess.
System.Security.Permissions.ReflectionPermission
For reflecting non-public objects. Associated enumeration: System.Security.Permissions. ReflectionPermissionFlag.TypeInformation.
A B C D E F G H
Type.GetMembers() Method
I
[ILASM]
J
.method public hidebysig instance class System.Reflection.MemberInfo[] GetMembers()
K
[C#]
L
public MemberInfo[] GetMembers()
M
Summary
N
Returns an array of System.Reflection.MemberInfo objects that reflect the public members defined in the type represented by the current instance.
O P
Return Value
Q
An array of System.Reflection.MemberInfo objects that reflect the public members defined in the type represented by the current instance. If no public members are defined in the type represented by the current instance, returns an empty array.
R S T
Description
U
This version of System.Type.GetMembers is equivalent to System.Type.GetMembers(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance). This member must be implemented if the Reflection Library is present in the implementation.
V W X Y Z
3426
Contents | Index
System
Type GetMembers() Method
Example using System; using System.Reflection;
A namespace Samples { public class TypeGetMembers { public static void Main() { Type t = typeof(object); MemberInfo[] memberInfos = t.GetMembers(); foreach(MemberInfo m in memberInfos) Console.WriteLine(m); } } }
B C D E F G H I J
The output is
K L
Int32 GetHashCode() Boolean Equals(System.Object) System.String ToString() Boolean Equals(System.Object, System.Object) Boolean ReferenceEquals(System.Object, System.Object) System.Type GetType() Void .ctor()
M N O P Q
Type.GetMembers(System.Reflection.BindingFlags) Method
R
[ILASM]
S
.method public hidebysig virtual abstract class System.Reflection.MemberInfo[] GetMembers(valuetype System.Reflection.BindingFlags bindingAttr)
T
[C#]
U
public abstract MemberInfo[] GetMembers(BindingFlags bindingAttr)
V
Summary
W
Returns an array of System.Reflection.MemberInfo objects that reflect the members that are defined in the type represented by the current instance and match the specified binding constraints.
X Y Z
3427
Contents | Index
Type
System
GetMembers() Method
Parameters Parameter
Description
bindingAttr
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, this method returns null.
A B C D
Return Value
E
An array of System.Reflection.MemberInfo objects that reflect the members defined in the type represented by the current instance that match the constraints of bindingAttr. If no members match these constraints, returns an empty array. If the type represented by the current instance is from a loaded assembly and the caller does not have sufficient permission to reflect on non-public objects in loaded assemblies, returns only public members.
F G H I J
Description
K
The following System.Reflection.BindingFlags are used to define which members to include in the search:
L
•
M N
•
O
•
P Q
Specify either System.Reflection.BindingFlags.Instance or System.Reflection.BindingFlags.Static to get a return value other than null. Specify System.Reflection.BindingFlags.Public to include public members in the search. Specify System.Reflection.BindingFlags.NonPublic to include non-public members (that is, private and protected members) in the search.
The following System.Reflection.BindingFlags values can be used to change how the search works:
R S
•
T U
System.Reflection.BindingFlags.DeclaredOnly to search only the members declared in the type, not members that were simply inherited.
[Note: For more information, see System.Reflection.BindingFlags.] This member must be implemented if the Reflection Library is present in the implementation.
V W X Y Z
3428
Contents | Index
System
Type GetMethod() Method
Permissions Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
A B C D E
Example
F
using System; using System.Reflection;
G H
namespace Samples { public class TypeGetMembers { public static void Main() { Type t = typeof(object); MemberInfo[] memberInfos = t.GetMembers( BindingFlags.Instance | BindingFlags.Public); foreach(MemberInfo m in memberInfos) Console.WriteLine(m); } } }
I J K L M N O P Q R
The output is
S Int32 GetHashCode() Boolean Equals(System.Object) System.String ToString() System.Type GetType() Void .ctor()
T U V W X
Type.GetMethod(System.String) Method
Y
[ILASM]
.method public hidebysig instance class System.Reflection.MethodInfo GetMethod(string name)
Z
[C#]
public MethodInfo GetMethod(string name)
3429
Contents | Index
Type
System
GetMethod() Method
Summary Returns a System.Reflection.MethodInfo object that reflects the public method that has the specified name and is defined in the type represented by the current instance. A
Parameters
B C D E
Parameter
Description
name
A System.String containing the name of the public method to be returned.
F G
Return Value
H
A System.Reflection.MethodInfo object reflecting the public method that is defined in the type represented by the current instance and has the specified name, if found; otherwise, null.
I J
Description
K
The search for name is case-sensitive. This version of System.Type.GetMethod is equivalent to System.Type.GetMethod(name, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance, null, null, null). This member must be implemented if the Reflection Library is present in the implementation.
L M N O P
Exceptions
Q R
Exception
Condition
System.Reflection.AmbiguousMatchException
More than one method matching the specified criteria was found.
System.ArgumentNullException
name is null.
S T U V W X
Example
Y
using System; using System.Reflection;
Z namespace Samples { public class TypeGetMethod
3430
Contents | Index
System
Type GetMethod() Method
{ public static void Main() { string[] strings = {"Clone", "EndsWith", "Insert", "IndexOf"}; Type t = typeof(String); foreach(string s in strings) { try { MethodInfo mi = t.GetMethod(s); Console.WriteLine(mi); } catch(AmbiguousMatchException e) { Console.WriteLine("Exception: {0}", e); } } }
A B C D E F G H I J K
}
L
}
M
The output is
N
System.Object Clone() Boolean EndsWith(System.String) System.String Insert(Int32, System.String) Exception: System.Reflection.AmbiguousMatchException: Ambiguous match found. at System.RuntimeType.GetMethodImplInternal(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers, Boolean verifyAccess) at System.RuntimeType.GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) at System.Type.GetMethod(String name) at Samples.TypeGetMethod.Main() in C:\Books\BCL\Samples\System\Type\ GetMethod(System.String)\Type.cs:line 19
O P Q R S T U V W
Type.GetMethod(System.String, System.Reflection.BindingFlags) Method
X
[ILASM]
Y
.method public final hidebysig virtual class System.Reflection.MethodInfo GetMethod(string name, valuetype System.Reflection.BindingFlags bindingAttr)
Z
[C#]
public MethodInfo GetMethod(string name, BindingFlags bindingAttr)
3431
Contents | Index
Type
System
GetMethod() Method
Summary Returns a System.Reflection.MethodInfo object that reflects the method that has the specified name and is defined in the type represented by the current instance. A
Parameters
B C D E F
Parameter
Description
name
A System.String containing the name of the method to be returned.
bindingAttr
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, this method returns null.
G H
Return Value
I
A System.Reflection.MethodInfo object that reflects the method that is defined in the type represented by the current instance and matches the specified criteria, if found; otherwise, null.
J K L M
Description
N
The following System.Reflection.BindingFlags are used to define which members to include in the search:
O
•
P Q
•
R
•
S T
Specify either System.Reflection.BindingFlags.Instance or System.Reflection.BindingFlags.Static to get a return value other than null. Specify System.Reflection.BindingFlags.Public to include public members in the search. Specify System.Reflection.BindingFlags.NonPublic to include non-public members (that is, private and protected members) in the search.
The following System.Reflection.BindingFlags values can be used to change how the search works:
U V
•
W X
•
System.Reflection.BindingFlags.DeclaredOnly to search only the members declared in the type, not members that were simply inherited. System.Reflection.BindingFlags.IgnoreCase to ignore the case of name.
Y
[Note: For more information, see System.Reflection.BindingFlags.] This version of System.Type.GetMethod is equivalent to System.Type.GetMethod(name, bindingAttr, null, null, null).
Z
3432
Contents | Index
System
Type GetMethod() Method
This member must be implemented if the Reflection Library is present in the implementation. A
Exceptions
B
Exception
Condition
System.Reflection.AmbiguousMatchException
More than one method matching the specified criteria was found.
D
System.ArgumentNullException
name is null.
F
C
E
G
Permissions
H I
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
J K L M
Example
N
using System; using System.Reflection;
O
namespace Samples { public class TypeGetMethod { public static void Main() { string[] strings = {"Clone", "EndsWith", "Insert", "IndexOf"}; Type t = typeof(String); foreach(string s in strings) { try { MethodInfo mi = t.GetMethod(s, BindingFlags.Instance | BindingFlags.Public); Console.WriteLine(mi);
Q
P
R S T U V W X Y Z
3433
Contents | Index
Type
System
GetMethod() Method
} catch(AmbiguousMatchException e) { Console.WriteLine("Exception: {0}", e); }
A }
B
} }
C }
D
The output is
E F
System.Object Clone() Boolean EndsWith(System.String) System.String Insert(Int32, System.String) Exception: System.Reflection.AmbiguousMatchException: Ambiguous match found. at System.RuntimeType.GetMethodImplInternal(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers, Boolean verifyAccess) at System.RuntimeType.GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) at System.Type.GetMethod(String name, BindingFlags bindingAttr) at Samples.TypeGetMethod.Main() in C:\Books\BCL\Samples\System\Type\ GetMethod(System.String,System.Reflection.BindingFlags)\Type.cs:line 19
G H I J K L M N O
Q
Type.GetMethod(System.String, System.Reflection.BindingFlags, System.Reflection.Binder, System.Reflection.CallingConventions, System.Type[], System.Reflection.ParameterModifier[]) Method
R
[ILASM]
P
.method public hidebysig instance class System.Reflection.MethodInfo GetMethod(string name, valuetype System.Reflection.BindingFlags bindingAttr, class System.Reflection.Binder binder, valuetype System.Reflection.CallingConventions callConvention, class System.Type[] types, class System.Reflection.ParameterModifier[] modifiers)
S T U
[C#]
V
public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
W X
Summary
Y
Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.
Z
3434
Contents | Index
System
Type GetMethod() Method
Parameters Parameter
Description
name
The System.String containing the name of the method to get.
bindingAttr
A bitmask comprised of one or more System.Reflection.BindingFlags that specify how the search is conducted. -orZero, to return null.
A
binder
callConvention
types
modifiers
B C D E F
A System.Reflection.Binder object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection. -ornull, to use the System.Type.DefaultBinder.
G H I J
The System.Reflection.CallingConventions object that specifies the set of rules to use regarding the order and layout of arguments, how the return value is passed, what registers are used for arguments, and how the stack is cleaned up.
K L
An array of System.Type objects representing the number, order, and type of the parameters for the method to get. -orAn empty array of the type System.Type (that is, Type[] types = new Type[0]) to get a method that takes no parameters.
M
An array of System.Reflection.ParameterModifier objects representing the attributes associated with the corresponding element in the types array. The default binder does not process this parameter.
Q
N O P
R S
Return Value
T
A System.Reflection.MethodInfo object representing the method that matches the specified requirements, if found; otherwise, null.
U
Description
W
Although the default binder does not process System.Reflection.ParameterModifier (the modifiers parameter), you can use the abstract System.Reflection.Binder class to write a custom binder that does process modifiers. ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled.
X
V
Y Z
3435
Contents | Index
Type
System
GetMethod() Method
The following table shows what members of a base class are returned by the GetXXX methods when reflecting on a type. A B
Member Type
Static
Non-Static
C
Constructor
No
No
Field
No
Yes. A field is always hide-by-name-and-signature.
Event
Not applicable
The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below.
Method
No
Yes. A method (both virtual and non-virtual) can be hideby-name or hide-by-name-and-signature.
Nested Type
No
No
Property
Not applicable
The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below.
D E F G H I J K L M N
1.
O P Q
2.
R S T
3.
Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class. Custom attributes are not part of the common type system.
U
The types array and the modifiers array have the same length. A parameter specified in the types array can have the following attributes, which are specified in the modifiers array: pdIn, pdOut, pdLcid, pdRetval, pdOptional, and pdHasDefault, which represent [In], [Out], [lcid], [retval], [optional], and a value specifying whether the parameter has a default value. A parameter’s associated attributes are stored in the metadata and enhance interoperability. The following System.Reflection.BindingFlags filter flags can be used to define which methods to include in the search:
V W X Y Z
3436
Contents | Index
System
Type GetMethod() Method
• • • •
You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return. Specify BindingFlags.Public to include public methods in the search. Specify BindingFlags.NonPublic to include non-public methods (that is, private and protected members) in the search. Specify BindingFlags.FlattenHierarchy to include static methods up the hierarchy.
A B C D
The following System.Reflection.BindingFlags modifier flags can be used to change how the search works:
E
• •
G
F
BindingFlags.IgnoreCase to ignore the case of name. BindingFlags.DeclaredOnly to search only the methods declared on the System.Type, not methods that were simply inherited.
H I
See System.Reflection.BindingFlags for more information. If the requested type is non-public and the caller does not have System.Security.Permissions.ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null. You cannot omit parameters when looking up constructors and methods. You can only omit parameters when invoking.
J K L M N
Exceptions
O P
Exception
Condition
System.Reflection.AmbiguousMatchException
More than one method is found with the specified name and matching the specified binding constraints.
System.ArgumentNullException
name is null. -ortypes is null. -orOne of the elements in types is null.
Q R S T U V W
System.ArgumentException
types is multidimensional. -ormodifiers is multidimensional. -ortypes and modifiers do not have the same length.
X Y Z
3437
Contents | Index
Type
System
GetMethod() Method
Permissions Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
System.Security.Permissions.ReflectionPermission
For reflecting non-public objects. Associated enumeration: System.Security.Permissions. ReflectionPermissionFlag.TypeInformation.
A B C D E F G
Type.GetMethod(System.String, System.Reflection.BindingFlags, System.Reflection.Binder, System.Type[], System.Reflection.ParameterModifier[]) Method
H I J
[ILASM]
K
.method public final hidebysig virtual class System.Reflection.MethodInfo GetMethod(string name, valuetype System.Reflection.BindingFlags bindingAttr, class System.Reflection.Binder binder, class System.Type[] types, class System.Reflection.ParameterModifier[] modifiers)
L M
[C#]
public MethodInfo GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
N O P
Summary
Q
Returns a System.Reflection.MethodInfo object that reflects the method that matches the specified criteria and is defined in the type represented by the current instance.
R S
Parameters
T U V
Parameter
Description
name
A System.String containing the name of the method to be returned.
bindingAttr
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, this method returns null.
binder
A System.Reflection.Binder object that defines a set of properties and enables the binding, coercion of argument types, and invocation of members using reflection. Specify null to use the System.Type.DefaultBinder.
W X Y Z
3438
Contents | Index
System
Type GetMethod() Method
Parameter
Description
types
An array of System.Type objects. The elements in the array are of the same number, in the same order, and represent the same types as the parameters for the method to be returned.
B
The only defined value for this parameter is null.
C
modifiers
A
D
Return Value
E
A System.Reflection.MethodInfo object that reflects the method defined in the type represented by the current instance that matches the specified criteria. If no method matching the specified criteria is found, returns null. If the selected method is non-public, the type reflected by the current instance is from a loaded assembly, and the caller does not have permission to reflect on non-public objects in loaded assemblies, returns null.
F G H I J
Description
K
The following System.Reflection.BindingFlags are used to define which members to include in the search: • • • • • •
L M
Specify either System.Reflection.BindingFlags.Instance or System.Reflection.BindingFlags.Static to get a return value other than null. Specify System.Reflection.BindingFlags.Public to include public members in the search. Specify System.Reflection.BindingFlags.NonPublic to include non-public members (that is, private and protected members) in the search. The following System.Reflection.BindingFlags values can be used to change how the search works: System.Reflection.BindingFlags.DeclaredOnly to search only the members declared in the type, not members that were simply inherited. System.Reflection.BindingFlags.IgnoreCase to ignore the case of name.
N O P Q R S T U V
[Note: For more information, see System.Reflection.BindingFlags.] This member must be implemented if the Reflection Library is present in the implementation.
W X Y Z
3439
Contents | Index
Type
System
GetMethod() Method
Exceptions Exception
Condition
System.Reflection.AmbiguousMatchException
More than one method matching the specified criteria was found.
A B C
name or types is null.
D
System.ArgumentNullException
E
-orAt least one of the elements in types is null.
F
System.ArgumentException
types has more than one dimension.
G H
Permissions
I J
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
K L M N O
Example
P
using System; using System.Reflection;
Q namespace Samples { public class TypeGetMethod { public static void Main() { string s = "IndexOf"; Type t = typeof(String); Type[][] types = new Type[][] { new Type[]{typeof(char)}, new Type[]{typeof(string)}, new Type[]{typeof(string), typeof(int)} }; foreach(Type[] parameters in types) { MethodInfo mi = t.GetMethod(s,
R S T U V W X Y Z
3440
Contents | Index
System
Type GetMethod() Method
BindingFlags.Instance | BindingFlags.Public, System.Type.DefaultBinder, parameters, null); Console.WriteLine(mi);
A B
}
C
} }
D
}
E
The output is
F Int32 IndexOf(Char) Int32 IndexOf(System.String) Int32 IndexOf(System.String, Int32)
G H I
Type.GetMethod(System.String, System.Type[]) Method
J
[ILASM]
K
.method public hidebysig instance class System.Reflection.MethodInfo GetMethod(string name, class System.Type[] types)
L
[C#]
M
public MethodInfo GetMethod(string name, Type[] types)
N
Summary
O
Returns a System.Reflection.MethodInfo object that reflects the public method defined in the type represented by the current instance that has the specified name and parameter information.
P Q R
Parameters
S
Parameter
Description
name
A System.String containing the name of the public method to be returned.
types
An array of System.Type objects. The elements in the array are of the same number, in the same order, and represent the same types as the parameters for the method to be returned.
T U V W X Y Z
3441
Contents | Index
Type
System
GetMethod() Method
Return Value A System.Reflection.MethodInfo object reflecting the public method defined in the type represented by the current instance that matches the specified criteria. If no public method matching the specified criteria is found, returns null.
A B
Description
C
The search for name is case-sensitive. This version of System.Type.GetMethod is equivalent to System.Type.GetMethod(name, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance, null, types, null). This member must be implemented if the Reflection Library is present in the implementation.
D E F G H
Exceptions
I J K L
Exception
Condition
System.Reflection.AmbiguousMatchException
More than one method matching the specified criteria was found.
System.ArgumentNullException
name or types is null. -orAt least one of the elements in types is null.
System.ArgumentException
types has more than one dimension.
M N O P Q
Example
R
using System; using System.Reflection;
S T
namespace Samples { public class TypeGetMethod { public static void Main() { string s = "IndexOf"; Type t = typeof(String); Type[][] types = new Type[][] { new Type[]{typeof(char)}, new Type[]{typeof(string)}, new Type[]{typeof(string), typeof(int)}
U V W X Y Z
3442
Contents | Index
System
Type GetMethod() Method
}; foreach(Type[] parameters in types) { MethodInfo mi = t.GetMethod(s, parameters); Console.WriteLine(mi); }
A B
}
C
}
D
}
E
The output is
F Int32 IndexOf(Char) Int32 IndexOf(System.String) Int32 IndexOf(System.String, Int32)
G H I
Type.GetMethod(System.String, System.Type[], System.Reflection.ParameterModifier[]) Method
K
[ILASM]
L
.method public hidebysig instance class System.Reflection.MethodInfo GetMethod(string name, class System.Type[] types, class System.Reflection.ParameterModifier[] modifiers)
M
J
N
[C#]
public MethodInfo GetMethod(string name, Type[] types, ParameterModifier[] modifiers)
O
Summary
Q
Returns a System.Reflection.MethodInfo object that reflects the public method that has the specified name and is defined in the type represented by the current instance.
R
Parameters
T
P
S
U
Parameter
Description
V
name
A System.String containing the name of the public method to be returned.
W
types
An array of System.Type objects. The elements in the array are of the same number, in the same order, and represent the same types as the parameters for the method to be returned.
modifiers
X Y Z
The only defined value for this parameter is null.
3443
Contents | Index
Type
System
GetMethod() Method
Return Value A System.Reflection.MethodInfo object reflecting the public method that is defined in the type represented by the current instance and matches the specified criteria, if found; otherwise, null.
A B
Description
C
The default binder does not process modifier. The search for name is case-sensitive. This version of System.Type.GetMethod is equivalent to System.Type.GetMethod(name, System.Reflection.BindingFlags.Public |System.Reflection.BindingFlags.Static |System.Reflection.BindingFlags.Instance, null, types, modifiers). This member must be implemented if the Reflection Library is present in the implementation.
D E F G H I
Exceptions
J K
Exception
Condition
System.Reflection.AmbiguousMatchException
More than one method matching the specified criteria was found.
L M N
name or types is null.
O
System.ArgumentNullException
-orAt least one of the elements in types is null.
P Q
System.ArgumentException
types has more than one dimension.
R S
Example
T
using System; using System.Reflection;
U
namespace Samples { public class TypeGetMethod { public static void Main() { string s = "IndexOf"; Type t = typeof(String); Type[][] types = new Type[][] {
V W X Y Z
3444
Contents | Index
System
Type GetMethodImpl() Method
new Type[]{typeof(char)}, new Type[]{typeof(string)}, new Type[]{typeof(string), typeof(int)}
A
}; foreach(Type[] parameters in types) { MethodInfo mi = t.GetMethod(s, parameters, null); Console.WriteLine(mi); }
B C D E F
} }
G
}
H
The output is
I
Int32 IndexOf(Char) Int32 IndexOf(System.String) Int32 IndexOf(System.String, Int32)
J K L M
Type.GetMethodImpl(System.String, System.Reflection.BindingFlags, System.Reflection.Binder, System.Reflection.CallingConventions, System.Type[], System.Reflection.ParameterModifier[]) Method
N O P
[ILASM]
.method family hidebysig virtual abstract class System.Reflection.MethodInfo GetMethodImpl(string name, valuetype System.Reflection.BindingFlags bindingAttr, class System.Reflection.Binder binder, valuetype System.Reflection.CallingConventions callConvention, class System.Type[] types, class System.Reflection.ParameterModifier[] modifiers)
Q R S
[C#]
T
protected abstract MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
U V
Summary
W
When overridden in a derived class, searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.
X Y Z
3445
Contents | Index
Type
System
GetMethodImpl() Method
Parameters Parameter
Description
name
The System.String containing the name of the method to get.
bindingAttr
A bitmask comprised of one or more System.Reflection.BindingFlags that specify how the search is conducted. -orZero, to return null.
binder
A System.Reflection.Binder object that defines a set of properties and enables binding, which can involve selection of an overloaded method, coercion of argument types, and invocation of a member through reflection. -ornull, to use the System.Type.DefaultBinder.
callConvention
The System.Reflection.CallingConventions object that specifies the set of rules to use regarding the order and layout of arguments, how the return value is passed, what registers are used for arguments, and what process cleans up the stack.
types
An array of System.Type objects representing the number, order, and type of the parameters for the method to get. -orAn empty array of the type System.Type (that is, Type[] types = new Type[0] ) to get a method that takes no parameters. -ornull. If types is null, arguments are not matched.
modifiers
An array of System.Reflection.ParameterModifier objects representing the attributes associated with the corresponding element in the types array. The default binder does not process this parameter.
A B C D E F G H I J K L M N O P Q R S T U
Return Value
V
A System.Reflection.MethodInfo object representing the method that matches the specified requirements, if found; otherwise, null.
W X Y Z
3446
Contents | Index
System
Type GetMethodImpl() Method
Description Although the default binder does not process System.Reflection.ParameterModifier (the modifiers parameter), you can use the abstract System.Reflection.Binder class to write a custom binder that does process modifiers. ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled. If types is null, arguments are not matched. The types array and the modifiers array have the same length. A parameter specified in the types array can have the following attributes, which are specified in the modifiers array: pdIn, pdOut, pdLcid, pdRetval, pdOptional, and pdHasDefault, which represent [In], [Out], [lcid], [retval], [optional], and a value specifying whether the parameter has a default value. A parameter’s associated attributes are stored in the metadata and enhance interoperability. The following System.Reflection.BindingFlags filter flags can be used to define which methods to include in the search: • • • •
A B C D E F G H I J
You must specify either BindingFlags.Instance or BindingFlags.Static in order to get a return. Specify BindingFlags.Public to include public methods in the search. Specify BindingFlags.NonPublic to include non-public methods (that is, private and protected members) in the search. Specify BindingFlags.FlattenHierarchy to include static methods up the hierarchy.
K L M N O P
The following System.Reflection.BindingFlags modifier flags can be used to change how the search works: • •
Q R
BindingFlags.IgnoreCase to ignore the case of name. BindingFlags.DeclaredOnly to search only the methods declared on the System.Type, not methods that were simply inherited.
S T U
See System.Reflection.BindingFlags for more information. If the requested type is non-public and the caller does not have System.Security.Permissions.ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
V W X Y Z
3447
Contents | Index
Type
System
GetMethods() Method
Exceptions Exception
Condition
System.Reflection.AmbiguousMatchException
More than one method is found with the specified name and matching the specified binding constraints.
System.ArgumentNullException
name is null.
A B C D E
types is multidimensional.
F
-orSystem.ArgumentException
G
modifiers is multidimensional. -or-
H
types and modifiers do not have the same length.
I J
Permissions
K L
Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
System.Security.Permissions.ReflectionPermission
For reflecting non-public objects. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
M N O P Q R S T
Type.GetMethods() Method
U [ILASM]
V
.method public hidebysig instance class System.Reflection.MethodInfo[] GetMethods()
W
[C#]
X
public MethodInfo[] GetMethods()
Y
Summary
Z
Returns the public methods defined in the type represented by the current instance.
3448
Contents | Index
System
Type GetMethods() Method
Return Value An array of System.Reflection.MethodInfo objects reflecting the public methods defined in the type represented by the current instance under the constraints of bindingAttr. If no methods matching the constraints are found, returns an empty array.
A B
Description
C
This version of System.Type.GetMethods is equivalent to System.Type.GetMethods(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public). This member must be implemented if the Reflection Library is present in the implementation.
D E F G
Example using System; using System.Reflection;
H
namespace Samples { public class TypeGetMethods { public static void Main() { Type t = typeof(object); MethodInfo[] methodInfos = t.GetMethods(); foreach(MethodInfo mi in methodInfos) Console.WriteLine(mi); } } }
J
I
K L M N O P Q R S
The output is
T Int32 GetHashCode() Boolean Equals(System.Object) System.String ToString() Boolean Equals(System.Object, System.Object) Boolean ReferenceEquals(System.Object, System.Object) System.Type GetType()
U V W X Y Z
3449
Contents | Index
Type
System
GetMethods() Method
Type.GetMethods(System.Reflection.BindingFlags) Method [ILASM]
A
.method public hidebysig virtual abstract class System.Reflection.MethodInfo[] GetMethods(valuetype System.Reflection.BindingFlags bindingAttr)
B
[C#]
public abstract MethodInfo[] GetMethods(BindingFlags bindingAttr)
C D
Summary
E
Returns an array of System.Reflection.MethodInfo objects that reflect the methods defined in the type represented by the current instance that match the specified binding constraints.
F G
Parameters
H I
Parameter
Description
bindingAttr
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, this method returns null.
J K L M
Return Value
N
An array of System.Reflection.MethodInfo objects reflecting the methods defined in the type represented by the current instance that match the constraints of bindingAttr. If no such methods are found, returns an empty array. If the type represented by the current instance is from a loaded assembly and the caller does not have permission to reflect on non-public objects in loaded assemblies, returns only public methods.
O P Q R S
Description
T
The following System.Reflection.BindingFlags are used to define which members to include in the search:
U
•
V W
•
X
•
Y Z
Specify either System.Reflection.BindingFlags.Instance or System.Reflection.BindingFlags.Static to get a return value other than null. Specify System.Reflection.BindingFlags.Public to include public members in the search. Specify System.Reflection.BindingFlags.NonPublic to include non-public members (that is, private and protected members) in the search.
The following System.Reflection.BindingFlags values can be used to change how the search works: 3450
Contents | Index
System
Type GetMethods() Method
•
System.Reflection.BindingFlags.DeclaredOnly to search only the members declared in the type, not members that were simply inherited.
[Note: For more information, see System.Reflection.BindingFlags.] This member must be implemented if the Reflection Library is present in the implementation.
A B C
Permissions
D E
Permission
Description F
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
G H I J
Example
K
using System; using System.Reflection;
L M
namespace Samples { public class TypeGetMethods { public static void Main() { Type t = typeof(object); MethodInfo[] methodInfos = t.GetMethods( BindingFlags.Instance | BindingFlags.Public); foreach(MethodInfo mi in methodInfos) Console.WriteLine(mi); } } }
N O P Q R S T U V
The output is
W X
Int32 GetHashCode() Boolean Equals(System.Object) System.String ToString() System.Type GetType()
Y Z
3451
Contents | Index
Type
System
GetNestedType() Method
Type.GetNestedType(System.String) Method [ILASM]
.method public hidebysig instance class System.Type GetNestedType(string name)
A
[C#]
public Type GetNestedType(string name)
B C
Summary
D
Returns the public nested type defined in the type represented by the current instance
E
Parameters
F G
Parameter
Description
name
A System.String containing the name of the public nested type to return. Specify the unqualified name of the nested type. [Note: For example, for a type B nested within A, if typeA represents the type object for A, the correct invocation is typeA.GetNestedType("B").]
H I J K L
Return Value
M
A System.Type object representing the public nested type with the specified name, if found; otherwise, null.
N O
Description
P
The search for name is case-sensitive. This version of System.Type.GetNestedTypes is equivalent to System.Type.GetNestedTypes(name, System.Reflection.BindingFlags.Public). This member must be implemented if the Reflection Library is present in the implementation.
Q R S T
Exceptions
U V W
Exception
Condition
System.ArgumentNullException
name is null.
X Y Z
3452
Contents | Index
System
Type GetNestedType() Method
Example using System; using System.Reflection;
A namespace Samples { public class TypeGetNestedType { public class TypeNestedClass { } public static void Main() { Type t = typeof(TypeGetNestedType); t = t.GetNestedType("TypeNestedClass"); Console.WriteLine(t); } } }
B C D E F G H I J K
The output is
L Samples.TypeGetNestedType+TypeNestedClass
M N
Type.GetNestedType(System.String, System.Reflection.BindingFlags) Method
O P
[ILASM]
Q
.method public hidebysig virtual abstract class System.Type GetNestedType(string name, valuetype System.Reflection.BindingFlags bindingAttr)
R
[C#]
S
public abstract Type GetNestedType(string name, BindingFlags bindingAttr)
T
Summary
U
Returns a nested types defined in the type represented by the current instance that match the specified binding constraints.
V W X Y Z
3453
Contents | Index
Type
System
GetNestedType() Method
Parameters Parameter
Description
name
A System.String containing the name of the nested type to return. Specify the unqualified name of the nested type. [Note: For example, for a type B nested within A, if typeA represents the type object for A, the correct invocation is typeA.GetNestedType("B").]
bindingAttr
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, this method returns null.
A B C D E F G
Return Value
H
A System.Type object representing the nested type that matches the specified criteria, if found; otherwise, null. If the selected nested type is non-public, the current instance represents a type contained in a loaded assembly and the caller does not have sufficient permissions, returns null.
I J K L
Description
M
The following System.Reflection.BindingFlags are used to define which members to include in the search:
N
•
O P
•
Q
•
R S T
Specify either System.Reflection.BindingFlags.Instance or System.Reflection.BindingFlags.Static to get a return value other than null. Specify System.Reflection.BindingFlags.Public to include public members in the search. Specify System.Reflection.BindingFlags.NonPublic to include non-public members (that is, private and protected members) in the search.
U
The following System.Reflection.BindingFlags values can be used to change how the search works:
V
•
W
•
X
System.Reflection.BindingFlags.DeclaredOnly to search only the members declared in the type, not members that were simply inherited. System.Reflection.BindingFlags.IgnoreCase to ignore the case of name.
[Note: For more information, see System.Reflection.BindingFlags.] This member must be implemented if the Reflection Library is present in the implementation.
Y Z
3454
Contents | Index
System
Type GetNestedType() Method
Exceptions Exception
Condition
System.ArgumentNullException
name is null.
A B C
Permissions
D E
Permission
Description F
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
G H I J
Example
K
using System; using System.Reflection;
L M
namespace Samples { public class TypeGetNestedType { private class NestedPrivateClass { } public static void Main() { Type t = typeof(TypeGetNestedType); t = t.GetNestedType("NestedPrivateClass", BindingFlags.NonPublic); Console.WriteLine(t); } } }
N O P Q R S T U V W
The output is
X Y
Samples.TypeGetNestedType+TypeNestedClass
Z
3455
Contents | Index
Type
System
GetNestedTypes() Method
Type.GetNestedTypes() Method [ILASM]
.method public hidebysig instance class System.Type[] GetNestedTypes()
A
[C#]
public Type[] GetNestedTypes()
B C
Summary
D
Returns all the public types nested within the current System.Type.
E F
Return Value
G
An array of System.Type objects representing all public types nested within the type represented by the current instance, if any. Otherwise, returns an empty System.Type array.
H I
Description
J
This version of System.Type.GetNestedTypes is equivalent to System.Type.GetNestedTypes(System.Reflection.BindingFlags.Public). This member must be implemented if the Reflection Library is present in the implementation.
K L M
Example
N
using System; using System.Reflection;
O namespace Samples { public class TypeGetNestedType { public class TypeNestedPublicClass { } private class NestedPrivateClass { } public static void Main() { Type t = typeof(TypeGetNestedType); Type[] types = t.GetNestedTypes(); foreach(Type t1 in types) Console.WriteLine(t1); } } }
P Q R S T U V W X Y Z
3456
Contents | Index
System
Type GetNestedTypes() Method
The output is Samples.TypeGetNestedType+TypeNestedPublicClass
A B
Type.GetNestedTypes(System.Reflection.BindingFlags) Method
C [ILASM]
D
.method public hidebysig virtual abstract class System.Type[] GetNestedTypes(valuetype System.Reflection.BindingFlags bindingAttr)
E
[C#]
public abstract Type[] GetNestedTypes(BindingFlags bindingAttr)
F G
Summary
H
Returns an array containing the nested types defined in the type represented by the current instance that match the specified binding constraints.
I J
Parameters
K
Parameter
Description
bindingAttr
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, this method returns null.
L M N O
Return Value
P
An array of System.Type objects representing all types nested within the type represented by the current instance that match the specified binding constraints, if any. Otherwise, returns an empty System.Type array. If the type reflected by the current instance is contained in a loaded assembly, the type that matches the specified criteria is not public, and the caller does not have sufficient permission, returns only public types.
Q R S T U
Description
V
The following System.Reflection.BindingFlags are used to define which members to include in the search: • •
W X
Specify System.Reflection.BindingFlags.Public to include public members in the search. Specify System.Reflection.BindingFlags.NonPublic to include non-public members (that is, private and protected members) in the search.
Y Z
3457
Contents | Index
Type
System
GetNestedTypes() Method
The following System.Reflection.BindingFlags values can be used to change how the search works: •
A B
System.Reflection.BindingFlags.DeclaredOnly to search only the members declared in the type, not members that were simply inherited.
[Note: For more information, see System.Reflection.BindingFlags.] This member must be implemented if the Reflection Library is present in the implementation.
C D E
Permissions
F G H I J
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
K L M
Example
N
using System; using System.Reflection;
O
namespace Samples { public class TypeGetNestedType { public class NestedPublicClass { } private class NestedPrivateClass { } public static void Main() { Type t = typeof(TypeGetNestedType); Type[] types = t.GetNestedTypes( BindingFlags.Public | BindingFlags.NonPublic); foreach(Type t1 in types) Console.WriteLine(t1); } } }
P Q R S T U V W X Y Z
3458
Contents | Index
System
Type GetProperties() Method
The output is Samples.TypeGetNestedType+NestedPublicClass Samples.TypeGetNestedType+NestedPrivateClass
A B
Type.GetProperties() Method
C
[ILASM]
D
.method public hidebysig instance class System.Reflection.PropertyInfo[] GetProperties()
E
[C#]
F
public PropertyInfo[] GetProperties()
G
Summary
H
Returns an array of System.Reflection.PropertyInfo objects that reflect the public properties defined in the type represented by the current instance.
I
Return Value
K
An array of System.Reflection.PropertyInfo objects that reflect the public properties defined in the type represented by the current instance. If no public properties are found, returns an empty array.
L M
Description
O
This version of System.Type.GetProperties is equivalent to System.Type.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public). A property is considered by reflection to be public if it has at least one accessor that is public. Otherwise, the property is considered to be not public. This member must be implemented if the Reflection Library is present in the implementation.
P
J
N
Q R S T
Example
U
using System; using System.Reflection;
V W
namespace Samples { public class TypeGetProperties { public static void Main() { Type t = typeof(string);
X Y Z
3459
Contents | Index
Type
System
GetProperties() Method
PropertyInfo[] propertyInfos = t.GetProperties(); foreach(PropertyInfo pi in propertyInfos) Console.WriteLine(pi);
A }
B }
C
}
D
The output is
E Char Chars [Int32] Int32 Length
F G H
Type.GetProperties(System.Reflection.BindingFlags) Method
I [ILASM]
J
.method public hidebysig virtual abstract class System.Reflection.PropertyInfo[] GetProperties(valuetype System.Reflection.BindingFlags bindingAttr)
K
[C#]
L
public abstract PropertyInfo[] GetProperties(BindingFlags bindingAttr)
M
Summary
N
Returns an array of System.Reflection.PropertyInfo objects that reflect the properties defined for the type represented by the current instance that match the specified binding constraints.
O P Q
Parameters
R S
Parameter
Description
bindingAttr
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, this method returns null.
T U V W
Return Value
X
An array of System.Reflection.PropertyInfo objects that reflect the properties defined in the type represented by the current instance and match the constraints of bindingAttr. If no matching properties are found, returns an empty array. If the type represented by the current instance is from a loaded assembly and the caller does not have permission to reflect on non-public objects in loaded assemblies, returns only public properties.
Y Z
3460
Contents | Index
System
Type GetProperties() Method
Description The following System.Reflection.BindingFlags are used to define which members to include in the search: A
• • •
Specify either System.Reflection.BindingFlags.Instance or System.Reflection.BindingFlags.Static to get a return value other than null. Specify System.Reflection.BindingFlags.Public to include public members in the search. Specify System.Reflection.BindingFlags.NonPublic to include non-public members (that is, private and protected members) in the search.
B C D E F
The following System.Reflection.BindingFlags values can be used to change how the search works: •
G H
System.Reflection.BindingFlags.DeclaredOnly to search only the members declared in the type, not members that were simply inherited.
I J
[Note: For more information, see System.Reflection.BindingFlags.] This member must be implemented if the Reflection Library is present in the implementation. A property is considered by reflection to be public if it has at least one accessor that is public. Otherwise, the property is not public.
K L M N O
Permissions
P
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
Q R S T U
Example
V
using System; using System.Reflection;
W
namespace Samples { public class TypeGetProperties { public static void Main()
Y
X
Z
3461
Contents | Index
Type
System
GetProperty() Method
{ Type t = typeof(string); PropertyInfo[] propertyInfos = t.GetProperties( BindingFlags.Instance | BindingFlags.Public); foreach(PropertyInfo pi in propertyInfos) Console.WriteLine(pi);
A B C D
} }
E }
F
The output is
G H
Char Chars [Int32] Int32 Length
I J K
Type.GetProperty(System.String) Method
L
[ILASM]
M
.method public hidebysig instance class System.Reflection.PropertyInfo GetProperty(string name)
N
[C#]
public PropertyInfo GetProperty(string name)
O P
Summary
Q
Returns a System.Reflection.PropertyInfo object that reflects the public property defined in the type represented by the current instance that has the specified name.
R S
Parameters
T U V
Parameter
Description
name
A System.String containing the name of the property to be returned.
W X
Return Value
Y
A System.Reflection.PropertyInfo object reflecting the public property defined on the type represented by the current instance that has the specified name. If no matching property is found, returns null.
Z
3462
Contents | Index
System
Type GetProperty() Method
Description This version of System.Type.GetProperty is equivalent to System.Type.GetPropertyImpl(name, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public, null, null, null, null). The search for name is case-sensitive. This member must be implemented if the Reflection Library is present in the implementation.
A B C D
Exceptions
E
Exception
Condition
System.Reflection.AmbiguousMatchException
More than one property matching the specified criteria was found.
System.ArgumentNullException
name is null.
F G H I J K
Example
L
using System; using System.Reflection;
M N
namespace Samples { public class TypeGetProperty { public static void Main() { Type t = typeof(string); string[] strings = {"Chars", "Length"}; foreach(string s in strings) { PropertyInfo pi = t.GetProperty(s); Console.WriteLine(pi); } } } }
O P Q R S T U V W X Y
The output is
Z Char Chars [Int32] Int32 Length
3463
Contents | Index
Type
System
GetProperty() Method
Type.GetProperty(System.String, System.Reflection.BindingFlags) Method [ILASM]
A
.method public final hidebysig virtual class System.Reflection.PropertyInfo GetProperty(string name, valuetype System.Reflection.BindingFlags bindingAttr)
B
[C#]
public PropertyInfo GetProperty(string name, BindingFlags bindingAttr)
C D
Summary
E
Returns a System.Reflection.PropertyInfo object that reflects the property defined in the type represented by the current instance that matches the specified search criteria.
F G
Parameters
H I J
Parameter
Description
name
A System.String containing the name of the property to be returned.
bindingAttr
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, this method returns null.
K L M N
Return Value
O
A System.Reflection.PropertyInfo object reflecting the property defined in the type represented by the current instance that matches the specified criteria. If no matching property is found, returns null. If the type reflected by the current instance is contained in a loaded assembly, the property that matches the specified criteria is not public, and the caller does not have sufficient permission, returns null.
P Q R S
Description
T
The following System.Reflection.BindingFlags are used to define which members to include in the search:
U V
•
W
•
X Y
•
Z
Specify either System.Reflection.BindingFlags.Instance or System.Reflection.BindingFlags.Static to get a return value other than null. Specify System.Reflection.BindingFlags.Public to include public members in the search. Specify System.Reflection.BindingFlags.NonPublic to include non-public members (that is, private and protected members) in the search.
3464
Contents | Index
System
Type GetProperty() Method
The following System.Reflection.BindingFlags values can be used to change how the search works: • •
System.Reflection.BindingFlags.DeclaredOnly to search only the members declared in the type, not members that were simply inherited. System.Reflection.BindingFlags.IgnoreCase to ignore the case of name.
A B C
[Note: For more information, see System.Reflection.BindingFlags.] This version of System.Type.GetProperty is equivalent to System.Type.GetPropertyImpl(name, bindingAttr, null, null, null, null). The search for name is case-sensitive. This member must be implemented if the Reflection Library is present in the implementation.
D E F G H
Exceptions
I
Exception
Condition
J
System.Reflection.AmbiguousMatchException
More than one property matching the specified criteria was found.
K
System.ArgumentNullException
name is null.
M
L
N O
Permissions
P
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
Q R S T U
Example
V
using System; using System.Reflection;
W X
namespace Samples { public class TypeGetProperty { public static void Main() {
Y Z
3465
Contents | Index
Type
System
GetProperty() Method
Type t = typeof(string); string[] strings = {"chars", "length"}; foreach(string s in strings) { PropertyInfo pi = t.GetProperty(s, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); Console.WriteLine(pi); }
A B C D E }
F
} }
G
The output is
H I
Char Chars [Int32] Int32 Length
J K L
Type.GetProperty(System.String, System.Reflection.BindingFlags, System.Reflection.Binder, System.Type, System.Type[], System.Reflection.ParameterModifier[]) Method
M N
[ILASM]
O
Q
.method public final hidebysig virtual class System.Reflection.PropertyInfo GetProperty(string name, valuetype System.Reflection.BindingFlags bindingAttr, class System.Reflection.Binder binder, class System.Type returnType, class System.Type[] types, class System.Reflection.ParameterModifier[] modifiers)
R
[C#]
S
public PropertyInfo GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
P
T
Summary
U
Returns a System.Reflection.PropertyInfo object that reflects the property defined in the type represented by the current instance that matches the specified search criteria.
V W X Y Z
3466
Contents | Index
System
Type GetProperty() Method
Parameters Parameter
Description
name
A System.String containing the name of the property to be returned.
bindingAttr
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, this method returns null.
binder
A System.Reflection.Binder object that defines a set of properties and enables the binding, coercion of argument types, and invocation of members using reflection. Specify null to use the System.Type.DefaultBinder.
E
returnType
A System.Type object that represents the type of the property to be returned.
G
types
An array of System.Type objects. The elements in the array are of the same number, in the same order, and represent the same types as the parameters for the indexer to be returned. Specify System.Type.EmptyTypes to obtain a property that is not indexed.
A B C D
modifiers
F
H I J K
The only defined value for this parameter is null.
L M
Return Value
N
A System.Reflection.PropertyInfo object reflecting the property that is defined in the type represented by the current instance and matches the specified criteria. If no matching property is found, returns null. If the type reflected by the current instance is contained in a loaded assembly, the property that matches the specified criteria is not public, and the caller does not have sufficient permission, returns null.
O P Q R
Description
S
The following System.Reflection.BindingFlags are used to define which members to include in the search:
T U
• • •
Specify either System.Reflection.BindingFlags.Instance or System.Reflection.BindingFlags.Static to get a return value other than null. Specify System.Reflection.BindingFlags.Public to include public members in the search. Specify System.Reflection.BindingFlags.NonPublic to include non-public members (that is, private and protected members) in the search.
V W X Y Z
3467
Contents | Index
Type
System
GetProperty() Method
The following System.Reflection.BindingFlags values can be used to change how the search works: •
A B
•
System.Reflection.BindingFlags.DeclaredOnly to search only the members declared in the type, not members that were simply inherited. System.Reflection.BindingFlags.IgnoreCase to ignore the case of name.
C
[Note: For more information, see System.Reflection.BindingFlags.] This version of System.Type.GetProperty is equivalent to System.Type.GetPropertyImpl(name, bindingAttr, binder, returnType, types, modifiers). The search for name is case-sensitive. Different programming languages use different syntax to specify indexed properties. Internally, this property is referred to by the name “Item” in the metadata. Therefore, any attempt to retrieve an indexed property using reflection is required to specify this internal name in order for the PropertyInfo to be returned correctly. This member must be implemented if the Reflection Library is present in the implementation.
D E F G H I J K
Exceptions
L M
Exception
Condition
System.Reflection.AmbiguousMatchException
More than one property matching the specified criteria was found.
System.ArgumentNullException
name or types is null, or at least one of the elements in types is null.
System.ArgumentException
types has more than one dimension.
N O P Q R S
Permissions
T U
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
V W X Y Z
3468
Contents | Index
System
Type GetProperty() Method
Example using System; using System.Reflection;
A namespace Samples { public class TypeGetProperty { public static void Main() { Type t = typeof(string); PropertyInfo pi = t.GetProperty("Chars", BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase, System.Type.DefaultBinder, typeof(char), new Type[]{typeof(int)}, null); Console.WriteLine(pi); } } }
B C D E F G H I J K L M N
The output is
O Char Chars [Int32]
P Q
Type.GetProperty(System.String, System.Type) Method
R
[ILASM]
S
.method public hidebysig instance class System.Reflection.PropertyInfo GetProperty(string name, class System.Type returnType)
T
[C#]
U
public PropertyInfo GetProperty(string name, Type returnType)
V
Summary
W
Returns a System.Reflection.PropertyInfo object that reflects the public property defined in the type represented by the current instance that matches the specified search criteria.
X Y Z
3469
Contents | Index
Type
System
GetProperty() Method
Parameters Parameter
Description
name
A System.String containing the name of the property to be returned.
returnType
A System.Type object that represents the type of the property to be returned.
A B C D E
Return Value
F
A System.Reflection.PropertyInfo object reflecting the public property defined on the type represented by the current instance that matches the specified criteria. If no matching property is found, returns null.
G H
Description
I
This version of System.Type.GetProperty is equivalent to System.Type.GetPropertyImpl(name, System.Reflection.BindingFlags.Static|System.Reflection.BindingFlags.Instance|System.Reflection.BindingFlags.Public, null, returnType, null, null). The search for name is case-sensitive. This member must be implemented if the Reflection Library is present in the implementation.
J K L M N
Exceptions
O P
Exception
Condition
System.Reflection.AmbiguousMatchException
More than one property matching the specified criteria was found.
System.ArgumentNullException
name is null.
Q R S T U
Example
V
using System; using System.Reflection;
W X
namespace Samples { public class TypeGetProperty { public static void Main() { Type t = typeof(string);
Y Z
3470
Contents | Index
System
Type GetProperty() Method
PropertyInfo pi = t.GetProperty( "Chars", typeof(char)); Console.WriteLine(pi); pi = t.GetProperty( "Length", typeof(int)); Console.WriteLine(pi);
A B C D
} }
E
}
F
The output is
G
Char Chars [Int32] Int32 Length
H I J
Type.GetProperty(System.String, System.Type, System.Type[]) Method
K
[ILASM]
L
.method public hidebysig instance class System.Reflection.PropertyInfo GetProperty(string name, class System.Type returnType, class System.Type[] types)
M
[C#]
N
public PropertyInfo GetProperty(string name, Type returnType, Type[] types)
O
Summary
P
Returns a System.Reflection.PropertyInfo object that reflects the public property defined in the type represented by the current instance that matches the specified search criteria.
Q R S
Parameters
T
Parameter
Description
name
A System.String containing the name of the public property to be returned.
returnType
A System.Type object that represents the type of the public property to be returned.
types
An array of System.Type objects. The elements in the array are of the same number, in the same order, and represent the same types as the parameters for the indexer to be returned. Specify System.Type.EmptyTypes for a property that is not indexed.
U V W X Y Z
3471
Contents | Index
Type
System
GetProperty() Method
Return Value A System.Reflection.PropertyInfo object reflecting the public property defined in the type represented by the current instance that matches the specified criteria. If no matching property is found, returns null.
A B
Description
C
This version of System.Type.GetProperty is equivalent to System.Type.GetPropertyImpl(name, System.Reflection.BindingFlags.Static|System.Reflection.BindingFlags.Instance|System.Reflection.BindingFlags.Public, null, returnTypes, types, null). The search for name is case-sensitive. Different programming languages use different syntax to specify indexed properties. Internally, this property is referred to by the name “Item” in the metadata. Therefore, any attempt to retrieve an indexed property using reflection is required to specify this internal name in order for the PropertyInfo to be returned correctly. This member must be implemented if the Reflection Library is present in the implementation.
D E F G H I J K L
Exceptions
M N
Exception
Condition
O
System.Reflection.AmbiguousMatchException
More than one property matching the specified criteria was found.
System.ArgumentNullException
name or types is null, or at least one of the elements in types is null.
System.ArgumentException
types has more than one dimension.
P Q R S T
Example
U
using System; using System.Reflection;
V W
namespace Samples { public class TypeGetProperty { public static void Main() { Type t = typeof(string); PropertyInfo pi = t.GetProperty(
X Y Z
3472
Contents | Index
System
Type GetProperty() Method
"Chars", typeof(char), new Type[]{typeof(int)}); Console.WriteLine(pi);
A
} }
B
}
C
The output is
D Char Chars [Int32]
E F
Type.GetProperty(System.String, System.Type, System.Type[], System.Reflection.ParameterModifier[]) Method
G H
[ILASM]
I
.method public hidebysig instance class System.Reflection.PropertyInfo GetProperty(string name, class System.Type returnType, class System.Type[] types, class System.Reflection.ParameterModifier[] modifiers)
J
[C#]
K
public PropertyInfo GetProperty(string name, Type returnType, Type[] types, ParameterModifier[] modifiers)
L M
Summary
N
Searches for the specified public property whose parameters match the specified argument types and modifiers.
O P
Parameters
Q R
Parameter
Description
name
The System.String containing the name of the public property to get.
returnType
The return type of the property.
U
An array of System.Type objects representing the number, order, and type of the parameters for the indexed property to get.
V
S
types
modifiers
T
W
-orAn empty array of the type System.Type (that is, Type[] types = new Type[0]) to get a property that is not indexed.
X
An array of System.Reflection.ParameterModifier objects representing the attributes associated with the corresponding element in the types array. The default binder does not process this parameter.
Z
Y
3473
Contents | Index
Type
System
GetProperty() Method
Return Value A System.Reflection.PropertyInfo object representing the public property that matches the specified requirements, if found; otherwise, null. A B
Description
C
Although the default binder does not process System.Reflection.ParameterModifier (the modifiers parameter), you can use the abstract System.Reflection.Binder class to write a custom binder that does process modifiers. ParameterModifier is only used when calling through COM interop, and only parameters that are passed by reference are handled. The types array and the modifiers array have the same length. A parameter specified in the types array can have the following attributes, which are specified in the modifiers array: pdIn, pdOut, pdLcid, pdRetval, pdOptional, and pdHasDefault, which represent [In], [Out], [lcid], [retval], [optional], and a value specifying whether the parameter has a default value. A parameter’s associated attributes are stored in the metadata and enhance interoperability. The search for name is case-sensitive. If the requested type is non-public and the caller does not have System.Security.Permissions.ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.
D E F G H I J K L M N
Exceptions
O P
Exception
Condition
System.Reflection.AmbiguousMatchException
More than one property is found with the specified name and matching the specified argument types and modifiers.
System.ArgumentNullException
name is null. -ortypes is null. -orOne of the elements in types is null.
System.ArgumentException
types is multidimensional. -ormodifiers is multidimensional. -ortypes and modifiers do not have the same length.
Q R S T U V W X Y Z
3474
Contents | Index
System
Type GetProperty() Method
Permissions Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
A B C D E F
Type.GetProperty(System.String, System.Type[]) Method
G
[ILASM]
.method public hidebysig instance class System.Reflection.PropertyInfo GetProperty(string name, class System.Type[] types)
H
[C#]
I
public PropertyInfo GetProperty(string name, Type[] types)
J
Summary
K
Returns a System.Reflection.PropertyInfo object that reflects the public property defined in the type represented by the current instance that matches the specified search criteria.
L M N
Parameters
O
Parameter
Description
P
name
A System.String containing the name of the public property to be returned.
Q
types
An array of System.Type objects. The elements in the array are of the same number, in the same order, and represent the same types as the parameters for the indexer to be returned. Specify System.Type.EmptyTypes to obtain a property that is not indexed.
R S T U
Return Value
V
A System.Reflection.PropertyInfo object reflecting the public property defined on the type represented by the current instance that matches the specified criteria. If no matching property is found, returns null.
W X Y
Description
Z
This version of System.Type.GetProperty is equivalent to System.Type.GetPropertyImpl(name, System.Reflection.BindingFlags.Static|System.Reflec3475
Contents | Index
Type
System
GetProperty() Method
tion.BindingFlags.Instance|System.Reflection.BindingFlags.Public, null, null, types, null). The search for name is case-sensitive. Different programming languages use different syntax to specify indexed properties. Internally, this property is referred to by the name “Item” in the metadata. Therefore, any attempt to retrieve an indexed property using reflection is required to specify this internal name in order for the PropertyInfo to be returned correctly. This member must be implemented if the Reflection Library is present in the implementation.
A B C D E F
Exceptions
G H I J K
Exception
Condition
System.Reflection.AmbiguousMatchException
More than one property matching the specified criteria was found.
System.ArgumentNullException
name or types is null, or at least one of the elements in types is null.
System.ArgumentException
types has more than one dimension.
L M N
Example
O
using System; using System.Reflection;
P Q
namespace Samples { public class TypeGetProperty { public static void Main() { Type t = typeof(string); PropertyInfo pi = t.GetProperty( "Chars", new Type[]{typeof(int)}); Console.WriteLine(pi); pi = t.GetProperty( "Length", System.Type.EmptyTypes); Console.WriteLine(pi); } } }
R S T U V W X Y Z
3476
Contents | Index
System
Type GetPropertyImpl() Method
The output is Char Chars [Int32] Int32 Length
A B
Type.GetPropertyImpl(System.String, System.Reflection.BindingFlags, System.Reflection.Binder, System.Type, System.Type[], System.Reflection.ParameterModifier[]) Method
C D E
[ILASM]
F
.method family hidebysig virtual abstract class System.Reflection.PropertyInfo GetPropertyImpl(string name, valuetype System.Reflection.BindingFlags bindingAttr, class System.Reflection.Binder binder, class System.Type returnType, class System.Type[] types, class System.Reflection.ParameterModifier[] modifiers)
G H
[C#]
I
protected abstract PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
J K
Summary
L
When overridden in a derived class implements the System.Type.GetProperty method and returns a System.Reflection.PropertyInfo object that reflects the property defined in the type represented by the current instance that matches the specified search criteria.
M N O
Parameters
P
Parameter
Description
Q
name
A System.String containing the name of the property to be returned.
R
bindingAttr
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, this method returns null. A System.Reflection.Binder object that defines a set of properties and enables the binding, coercion of argument types, and invocation of members using reflection. Specify null to use the System.Type.DefaultBinder.
U
binder returnType
A System.Type object that represents the type of the property to be returned.
W
types
An array of System.Type objects. The elements in the array are of the same number, in the same order, and represent the same types as the parameters for the indexer to be returned. Specify System.Type.EmptyTypes to obtain a property that is not indexed.
modifiers
S T
V
X Y Z
The only defined value for this parameter is null.
3477
Contents | Index
Type
System
GetPropertyImpl() Method
Return Value A System.Reflection.PropertyInfo object representing the property that matches the specified search criteria, if found; otherwise, null. If the type reflected by the current instance is from a loaded assembly, the matching property is not public, and the caller does not have permission to reflect on non-public objects in loaded assemblies, returns null.
A B C
Description
D
The following System.Reflection.BindingFlags are used to define which members to include in the search:
E F
•
G
•
H I
•
J
Specify either System.Reflection.BindingFlags.Instance or System.Reflection.BindingFlags.Static to get a return value other than null. Specify System.Reflection.BindingFlags.Public to include public members in the search. Specify System.Reflection.BindingFlags.NonPublic to include non-public members (that is, private and protected members) in the search.
K
The following System.Reflection.BindingFlags values can be used to change how the search works:
L M
•
N O
•
P
System.Reflection.BindingFlags.DeclaredOnly to search only the members declared in the type, not members that were simply inherited. System.Reflection.BindingFlags.IgnoreCase to ignore the case of name.
[Note: For more information, see System.Reflection.BindingFlags.] This member must be implemented if the Reflection Library is present in the implementation.
Q R S
Behaviors
T
Different programming languages use different syntax to specify indexed properties. Internally, this property is referred to by the name “Item” in the metadata. Therefore, any attempt to retrieve an indexed property using reflection is required to specify this internal name in order for the PropertyInfo to be returned correctly.
U V W X Y Z
3478
Contents | Index
System
Type GetType() Method
Exceptions Exception
Condition
System.Reflection.AmbiguousMatchException
More than one property matching the specified criteria was found.
System.ArgumentNullException
name or types is null, or at least one of the elements in types is null.
System.ArgumentException
types has more than one dimension.
A B C D E F G
Permissions
H
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
I J K L M N
Type.GetType(System.String) Method
O
[ILASM]
P
.method public hidebysig static class System.Type GetType(string typeName)
Q
[C#]
public static Type GetType(string typeName)
R S
Summary
T
Returns the System.Type with the specified name.
U
Parameters
V
Parameter
Description
typeName
A System.String containing the case-sensitive name of the System.Type to return.
W X Y Z
3479
Contents | Index
Type
System
GetType() Method
Return Value The System.Type with the specified name, if found; otherwise, null. If the requested type is non-public and the caller does not have permission to reflect non-public objects outside the current assembly, this method returns null.
A B
Description
C
This method is equivalent to System.Type.GetType(name, false, false). typeName can be a simple type name, a type name that includes a namespace, or a complex name that includes an assembly name specification. If typeName includes only the name of the System.Type, this method searches in the calling object’s assembly, then in the mscorlib.dll assembly. If typeName is fully qualified with the partial or complete assembly name, this method searches in the specified assembly. [Note: System.Type.AssemblyQualifiedName can return a fully qualified type name including nested types and the assembly name. For complete details, see System.Type.GetType(System.String, System.Boolean, System.Boolean).] This member must be implemented if the Reflection Library is present in the implementation.
D E F G H I J K L
Exceptions
M N O
Exception
Condition
System.ArgumentNullException
typeName is null.
System.Reflection.TargetInvocationException
A type initializer was invoked and threw an exception.
P Q R S
Permissions
T U
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
V W X Y Z
3480
Contents | Index
System
Type GetType() Method
Example using System; using System.Reflection;
A namespace Samples { public class TypeGetType { public string name; public static void Main() { string[] strings = {"System.Object", "System.String", "NotExists"}; foreach(string s in strings) { try { Type t = Type.GetType(s); Console.WriteLine(t); } catch(TypeLoadException e) { Console.WriteLine("Exception: {0}", e); } } } } }
B C D E F G H I J K L M N O P
The output is
Q R
System.Object System.String
S T
Type.GetType(System.String, System.Boolean) Method
U
[ILASM]
V
.method public hidebysig static class System.Type GetType(string typeName, bool throwOnError)
W
[C#]
X
public static Type GetType(string typeName, bool throwOnError)
Y
Summary
Z
Returns the System.Type with the specified name, optionally throwing an exception if an error occurs while loading the System.Type. 3481
Contents | Index
Type
System
GetType() Method
Parameters Parameter
Description
typeName
A System.String containing the case-sensitive name of the System.Type to return.
throwOnError
A System.Boolean. Specify true to throw a System.TypeLoadException if an error occurs while loading the System.Type. Specify false to ignore errors while loading the System.Type.
A B C D E F
Return Value
G
The System.Type with the specified name, if found; otherwise, null. If the requested type is non-public and the caller does not have permission to reflect non-public objects outside the current assembly, this method returns null.
H I J
Description
K
This method is equivalent to System.Type.GetType(name, throwOnError, false). typeName can be a simple type name, a fully qualified name, or a complex name that includes an assembly name specification. If typeName includes only the name of the System.Type, this method searches in the calling object’s assembly, then in the mscorlib.dll assembly. If typeName is fully qualified with the partial or complete assembly name, this method searches in the specified assembly. [Note: System.Type.AssemblyQualifiedName can return a fully qualified type name including nested types and the assembly name. For complete details, see System.Type.GetType(System.String, System.Boolean, System.Boolean).] This member must be implemented if the Reflection Library is present in the implementation.
L M N O P Q R S T
Exceptions
U V
Exception
Condition
W
System.ArgumentNullException
typeName is null.
System.Reflection.TargetInvocationException
A type initializer was invoked and threw an exception.
System.TypeLoadException
throwOnError is true and an error was encountered while loading the System.Type.
X Y Z
3482
Contents | Index
System
Type GetType() Method
Permissions Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public objects. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
A B C D
Example
E
using System; using System.Reflection;
F G
namespace Samples { public class TypeGetType { public string name; public static void Main() { string[] strings = {"System.Object", "system.string"}; foreach(string s in strings) { try { Type t = Type.GetType(s, true); Console.WriteLine(t); } catch(TypeLoadException e) { Console.WriteLine("Exception: {0}", e); } } } } }
H I J K L M N O P Q R S T U V
The output is
W X
System.Object Exception: System.TypeLoadException: Could not load type system.string from assembly Type, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null. at System.Type.GetType(String typeName, Boolean throwOnError) at Samples.TypeGetType.Main() in C:\Books\BCL\Samples\System\Type\ GetType(System.String,System.Boolean)\Type.cs:line 17
Y Z
3483
Contents | Index
Type
System
GetType() Method
Type.GetType(System.String, System.Boolean, System.Boolean) Method [ILASM]
A
.method public hidebysig static class System.Type GetType(string typeName, bool throwOnError, bool ignoreCase)
B
[C#]
public static Type GetType(string typeName, bool throwOnError, bool ignoreCase)
C D
Summary
E
Returns the System.Type with the specified name, optionally performing a case-sensitive search and throwing an exception if an error occurs while loading the System.Type.
F G
Parameters
H I J
Parameter
Description
typeName
A System.String containing the name of the System.Type to return.
throwOnError
A System.Boolean. Specify true to throw a System.TypeLoadException if an error occurs while loading the System.Type. Specify false to ignore errors while loading the System.Type.
ignoreCase
A System.Boolean. Specify true to perform a case-insensitive search for typeName. Specify false to perform a case-sensitive search for typeName.
K L M N O P
Return Value
Q
The System.Type with the specified name, if found; otherwise, null. If the requested type is non-public and the caller does not have permission to reflect non-public objects outside the current assembly, this method returns null.
R S T
Description
U
typeName can be a simple type name, a fully qualified name, or a complex name that includes an assembly name. [Note: System.Type.AssemblyQualifiedName returns a fully qualified type name including nested types and the assembly name.] If typeName includes only the name of the System.Type, this method searches in the calling object’s assembly, then in the mscorlib.dll assembly. If typeName is fully qualified with the partial or complete assembly name, this method searches in the specified assembly. This member must be implemented if the Reflection Library is present in the implementation.
V W X Y Z
3484
Contents | Index
System
Type GetType() Method
Exceptions Exception
Condition
System.ArgumentNullException
typeName is null.
System.Reflection.TargetInvocationException
A type initializer was invoked and threw an exception.
System.TypeLoadException
throwOnError is true and an error was encountered while loading the selected System.Type.
A B C D E F G
Permissions
H
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
I J K L M
Example
N
using System; using System.Reflection;
O P
namespace Samples { public class TypeGetType { public string name; public static void Main() { string[] strings = {"system.object", "system.string", "notexist"}; foreach(string s in strings) { try { Type t = Type.GetType(s, true, true); Console.WriteLine(t); }
Q R S T U V W X Y Z
3485
Contents | Index
Type
System
GetTypeArray() Method
catch(TypeLoadException e) { Console.WriteLine("Exception: {0}", e); }
A
} }
B
} }
C D
The output is
E
System.Object System.String Exception: System.TypeLoadException: Could not load type notexist from assembly Type, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null. at System.Type.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase) at Samples.TypeGetType.Main() in C:\Books\BCL\Samples\System\Type\ GetType(System.String,System.Boolean,System.Boolea)\Type.cs:line 18
F G H I J K
Type.GetTypeArray(System.Object[]) Method
L
[ILASM]
M
.method public hidebysig static class System.Type[] GetTypeArray(class System.Object[] args)
N
[C#]
public static Type[] GetTypeArray(object[] args)
O P
Summary
Q
Returns the types of the objects in the specified array.
R
Parameters
S T
Parameter
Description
args
An array of objects whose types are to be returned.
U V W
Return Value
X
An array of System.Type objects representing the types of the corresponding elements in args. If a requested type is not public and the caller does not have permission to reflect nonpublic objects outside the current assembly, the corresponding element in the array returned by this method will be null.
Y Z
3486
Contents | Index
System
Type GetTypeArray() Method
Description This member must be implemented if the Reflection Library is present in the implementation. A
Exceptions
B
Exception
Condition
C
System.ArgumentNullException
args is null.
D
System.Reflection.TargetInvocationException
The type initializers were invoked and at least one threw an exception.
E F G H
Permissions
I
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
J K L M N
Example
O
using System; using System.Reflection;
P Q
namespace Samples { public class TypeGetTypeArray { public string name; public static void Main() { Object[] objects = new Object[]{ new Object(), typeof(Object), 42, 42f, "Hello world!"}; Type[] types = Type.GetTypeArray(objects); foreach(Type t in types) Console.WriteLine(t); } } }
R S T U V W X Y Z
3487
Contents | Index
Type
System
GetTypeCode() Method
The output is System.Object System.RuntimeType System.Int32 System.Single System.String
A B C D
Type.GetTypeCode(System.Type) Method
E [ILASM]
F
.method public hidebysig static valuetype System.TypeCode GetTypeCode(class System.Type type)
G
[C#]
H
public static TypeCode GetTypeCode(Type type)
I
Summary
J
Gets the underlying type code of the specified System.Type.
K
Parameters
L M
Parameter
Description
type
The System.Type whose underlying type code to get.
N O P Q
Permissions
R S T U
Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
V W X
Type.GetTypeFromCLSID(System.Guid) Method
Y
[ILASM]
.method public hidebysig static class System.Type GetTypeFromCLSID(valuetype System.Guid clsid)
Z
[C#]
public static Type GetTypeFromCLSID(Guid clsid)
3488
Contents | Index
System
Type GetTypeFromCLSID() Method
Summary Gets the type associated with the specified class identifier (CLSID). A
Parameters
B
Parameter
Description
C
clsid
The CLSID of the type to get.
D E F
Return Value
G
System.ComObject regardless of whether the CLSID is valid.
H
Permissions
I
Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
J K L M N O
Type.GetTypeFromCLSID(System.Guid, System.Boolean) Method
P
[ILASM]
Q
.method public hidebysig static class System.Type GetTypeFromCLSID(valuetype System.Guid clsid, bool throwOnError)
R
[C#]
S
public static Type GetTypeFromCLSID(Guid clsid, bool throwOnError)
T
Summary
U
Gets the type associated with the specified class identifier (CLSID), specifying whether to throw an exception if an error occurs while loading the type.
V W X Y Z
3489
Contents | Index
Type
System
GetTypeFromCLSID() Method
Parameters Parameter
Description
clsid
The CLSID of the type to get.
A B
true to throw any exception that occurs.
C
throwOnError
D
-orfalse to ignore any exception that occurs.
E F
Return Value
G
System.ComObject regardless of whether the CLSID is valid.
H I
Description
J
Exceptions such as System.OutOfMemoryException will be thrown when specifying true for throwOnError, but it will not fail for unregistered CLSIDs.
K L
Permissions
M N
Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
O P Q R S
Type.GetTypeFromCLSID(System.Guid, System.String) Method
T
[ILASM]
U
.method public hidebysig static class System.Type GetTypeFromCLSID(valuetype System.Guid clsid, string server)
V
[C#]
W
public static Type GetTypeFromCLSID(Guid clsid, string server)
X
Summary
Y
Gets the type associated with the specified class identifier (CLSID) from the specified server.
Z
3490
Contents | Index
System
Type GetTypeFromCLSID() Method
Parameters Parameter
Description
clsid
The CLSID of the type to get.
server
The server from which to load the type. If the server name is null, this method automatically reverts to the local machine.
A B C D E
Return Value
F
System.ComObject regardless of whether the CLSID is valid.
G
Permissions
H I
Permission
Description J
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
K L M N
Type.GetTypeFromCLSID(System.Guid, System.String, System.Boolean) Method
O
[ILASM]
Q
.method public hidebysig static class System.Type GetTypeFromCLSID(valuetype System.Guid clsid, string server, bool throwOnError)
R
[C#]
S
P
public static Type GetTypeFromCLSID(Guid clsid, string server, bool throwOnError)
T
Summary
U
Gets the type associated with the specified class identifier (CLSID) from the specified server, specifying whether to throw an exception if an error occurs while loading the type.
V W X Y Z
3491
Contents | Index
Type
System
GetTypeFromHandle() Method
Parameters Parameter
Description
clsid
The CLSID of the type to get.
server
The server from which to load the type. If the server name is null, this method automatically reverts to the local machine.
A B C D true to throw any exception that occurs. E
throwOnError
F
-orfalse to ignore any exception that occurs.
G H
Return Value
I
System.ComObject regardless of whether the CLSID is valid.
J
Description
K
Exceptions such as System.OutOfMemoryException will be thrown when specifying true for throwOnError, but it will not fail for unregistered CLSIDs.
L M
Permissions
N O
Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions. ReflectionPermissionFlag.MemberAccess.
P Q R S T U
Type.GetTypeFromHandle(System.RuntimeTypeHandle) Method
V
[ILASM]
W
.method public hidebysig static class System.Type GetTypeFromHandle(valuetype System.RuntimeTypeHandle handle)
X
[C#]
public static Type GetTypeFromHandle(RuntimeTypeHandle handle)
Y
Summary
Z
Gets the System.Type referenced by the specified type handle.
3492
Contents | Index
System
Type GetTypeFromHandle() Method
Parameters Parameter
Description
handle
The System.RuntimeTypeHandle object that refers to the desired System.Type.
A B C D
Return Value
E
The System.Type referenced by the specified System.RuntimeTypeHandle.
F
Description
G
The handles are valid only in the application domain in which they were obtained. This member must be implemented if the Runtime Infrastructure Library is present in the implementation.
H I J
Exceptions
K
Exception
Condition
System.ArgumentNullException
handle is null.
System.Security.SecurityException
The requested type is non-public and outside the current assembly, and the caller does not have the required permission.
L M
System.Reflection.TargetInvocationException
N O P Q
A type initializer was invoked and threw an exception.
R S
Permissions
T U
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on non-public objects. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
V W X Y Z
3493
Contents | Index
Type
System
GetTypeFromProgID() Method
Example using System; using System.Reflection;
A namespace Samples { public class TypeGetTypeFromHandle { public static void Main() { Object[] objects = new Object[]{ new Object(), new Object(), typeof(Object), 42, 42f, "Hello world!", "Goodbye world!"}; foreach(object o in objects) { RuntimeTypeHandle rth = Type.GetTypeHandle(o); Console.Write("Handle value {0} ", rth.Value); Console.WriteLine("Type {0}", Type.GetTypeFromHandle(rth)); } } } }
B C D E F G H I J K L M N O P
The output is
Q R
Handle Handle Handle Handle Handle Handle Handle
S T U
value value value value value value value
2041896352 2041896352 2041991276 2041972160 2042057868 2041902104 2041902104
Type Type Type Type Type Type Type
System.Object System.Object System.RuntimeType System.Int32 System.Single System.String System.String
V W X
Type.GetTypeFromProgID(System.String) Method
Y
[ILASM]
.method public hidebysig static class System.Type GetTypeFromProgID(string progID)
Z
[C#]
public static Type GetTypeFromProgID(string progID)
3494
Contents | Index
System
Type GetTypeFromProgID() Method
Summary Gets the type associated with the specified program identifier (ProgID), returning null if an error is encountered while loading the System.Type. A
Parameters
B C
Parameter
Description
progID
The ProgID of the type to get.
D E F
Return Value
G
The type associated with the specified ProgID, if progID is a valid entry in the registry and a type is associated with it; otherwise, null.
H
Description
J
This method is provided for COM support. ProgIDs are not used in the Microsoft .NET Framework because they have been superseded by the concept of namespace.
K
I
L M
Exceptions
N
Exception
Condition
System.ArgumentException
progID is null.
O P Q R
Permissions
S
Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
System.Security.Permissions.ReflectionPermission
For reflecting members that are not public. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
T U V W X Y Z
3495
Contents | Index
Type
System
GetTypeFromProgID() Method
Type.GetTypeFromProgID(System.String, System.Boolean) Method [ILASM]
A
.method public hidebysig static class System.Type GetTypeFromProgID(string progID, bool throwOnError)
B
[C#]
public static Type GetTypeFromProgID(string progID, bool throwOnError)
C D
Summary
E
Gets the type associated with the specified program identifier (ProgID), specifying whether to throw an exception if an error occurs while loading the type.
F G
Parameters
H I J
Parameter
Description
progID
The progID of the type to get.
K
true to throw any exception that occurs.
L
throwOnError
-orfalse to ignore any exception that occurs.
M N O
Return Value
P
The type associated with the specified program identifier (ProgID), if progID is a valid entry in the registry and a type is associated with it; otherwise, null.
Q R
Description
S
This method is provided for COM support. Program IDs are not used in Microsoft .NET Framework because they have been superseded by the concept of namespace.
T U
Exceptions
V W
Exception
Condition
System.ArgumentException
progID is null.
System.Runtime.InteropServices.COMException
The specified ProgID is not registered.
X Y Z
3496
Contents | Index
System
Type GetTypeFromProgID() Method
Permissions Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
System.Security.Permissions.ReflectionPermission
For reflecting members that are not public. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
A B C D E F G H
Type.GetTypeFromProgID(System.String, System.String) Method
I
[ILASM]
J
.method public hidebysig static class System.Type GetTypeFromProgID(string progID, string server)
K
[C#]
L
public static Type GetTypeFromProgID(string progID, string server)
M
Summary
N
Gets the type associated with the specified program identifier (progID) from the specified server, returning null if an error is encountered while loading the type.
O P
Parameters
Q
Parameter
Description
progID
The progID of the type to get.
server
The server from which to load the type. If the server name is null, this method automatically reverts to the local machine.
R S T U V W
Return Value
X
The type associated with the specified program identifier (ProgID), if progID is a valid entry in the registry and a type is associated with it; otherwise, null.
Y Z
3497
Contents | Index
Type
System
GetTypeFromProgID() Method
Description This method is provided for COM support. Program IDs are not used in Microsoft .NET Framework because they have been superseded by the concept of namespace. A
Exceptions
B C
Exception
Condition
System.ArgumentException
progID is null.
D E F
Example
G
The following example retrieves a type by passing a ProgID and server name. The example then displays the ClassID related to the ProgID, or throws an exception if the ProgID or the server name is invalid.
H I J
Permissions
K L
Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
System.Security.Permissions.ReflectionPermission
For reflecting members that are not public. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
M N O P Q R S
U
Type.GetTypeFromProgID(System.String, System.String, System.Boolean) Method
V
[ILASM]
W
.method public hidebysig static class System.Type GetTypeFromProgID(string progID, string server, bool throwOnError)
T
[C#]
X
public static Type GetTypeFromProgID(string progID, string server, bool throwOnError)
Y Z
3498
Contents | Index
System
Type GetTypeFromProgID() Method
Summary Gets the type associated with the specified program identifier (progID) from the specified server, specifying whether to throw an exception if an error occurs while loading the type. A
Parameters
B C
Parameter
Description
progID
The progID of the System.Type to get.
E
server
The server from which to load the type. If the server name is null, this method automatically reverts to the local machine.
F
throwOnError
D
G
true to throw any exception that occurs.
H
-or-
I
false to ignore any exception that occurs.
J K
Return Value
L
The System.Type associated with the specified program identifier (progID), if progID is a valid entry in the registry and a type is associated with it; otherwise, null.
M N
Description
O
This method is provided for COM support. Program IDs are not used in Microsoft .NET Framework because they have been superseded by the concept of namespace.
P Q R
Exceptions
S
Exception
Condition
System.ArgumentException
progID is null.
System.Runtime.InteropServices.COMException
The specified progID is not registered.
T U V W X Y Z
3499
Contents | Index
Type
System
GetTypeHandle() Method
Permissions Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
System.Security.Permissions.ReflectionPermission
For reflecting members that are not public. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
A B C D E F G H
Type.GetTypeHandle(System.Object) Method
I
[ILASM]
J
.method public hidebysig static valuetype System.RuntimeTypeHandle GetTypeHandle(object o)
K
[C#]
L
public static RuntimeTypeHandle GetTypeHandle(object o)
M
Summary
N
Returns the handle for the System.Type of the specified object.
O P
Parameters
Q R S
Parameter
Description
o
The object for which to get the type handle.
T U
Return Value
V
The System.RuntimeTypeHandle for the System.Type of the specified System.Object.
W X
Description
Y
The handle is valid only in the application domain in which it was obtained. This member must be implemented if the Runtime Infrastructure Library is present in the implementation.
Z
3500
Contents | Index
System
Type HasElementTypeImpl() Method
Example using System; using System.Reflection;
A namespace Samples { public class TypeGetTypeHandle { public static void Main() { Object[] objects = new Object[]{ new Object(), new Object(), typeof(Object), 42, 42f, "Hello world!", "Goodbye world!"}; foreach(object o in objects) { RuntimeTypeHandle rth = Type.GetTypeHandle(o); Console.Write("Handle value {0} ", rth.Value); Console.WriteLine("Type {0}", Type.GetTypeFromHandle(rth)); } } } }
B C D E F G H I J K L M N O P
The output is Handle Handle Handle Handle Handle Handle Handle
value value value value value value value
2041896352 2041896352 2041991276 2041972160 2042057868 2041902104 2041902104
Q Type Type Type Type Type Type Type
R
System.Object System.Object System.RuntimeType System.Int32 System.Single System.String System.String
S T U V W
Type.HasElementTypeImpl() Method
X
[ILASM]
Y
.method family hidebysig virtual abstract bool HasElementTypeImpl()
Z
[C#]
protected abstract bool HasElementTypeImpl()
3501
Contents | Index
Type
System
InvokeMember() Method
Summary When overridden in a derived class, implements the System.Type.HasElementType property and determines whether the current System.Type encompasses or refers to another type; that is, whether the current System.Type is an array, a pointer, or is passed by reference.
A B C
Return Value
D
true if the System.Type is an array, a pointer, or is passed by reference; otherwise, false.
E
Description
F
[Note: For example, System.Type.GetType("System.Int32[]").HasElementTypeImpl returns true, but System.Type.GetType("System.Int32").HasElementTypeImpl returns false. System.Type.HasElementTypeImpl also returns true for “System.Int32*” and “System.Int32&”.] This member must be implemented if the Reflection Library is present in the implementation.
G H I J K
Type.InvokeMember(System.String, System.Reflection.BindingFlags, System.Reflection.Binder, System.Object, System.Object[]) Method
L M N
[ILASM]
O
.method public hidebysig instance object InvokeMember(string name, valuetype System.Reflection.BindingFlags invokeAttr, class System.Reflection.Binder binder, object target, class System.Object[] args)
P
[C#]
public object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args)
Q R S
Summary
T
Invokes the specified member, using the specified binding constraints and matching the specified argument list.
U V W X Y Z
3502
Contents | Index
System
Type InvokeMember() Method
Parameters Parameter
Description
name
A System.String containing the name of the constructor or method to invoke, or property or field to access. If the type represented by the current instance has a default member, specify System.String.Empty to invoke that member. [Note: For more information on default members, see System.Reflection.DefaultMemberAttribute.]
A
invokeAttr
B C D E
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance is used by default.
binder
A System.Reflection.Binder object that defines a set of properties and enables the binding, coercion of argument types, and invocation of members using reflection. Specify null to use the System.Type.DefaultBinder.
target
A System.Object on which to invoke the member that matches the other specified criteria. If the matching member is static, this parameter is ignored.
args
An array of objects containing the arguments to pass to the member to be invoked. The elements of this array are of the same number and in the same order by assignment-compatible type as specified by the contract of the member to be bound. Specify an empty array or null for a member that has no parameters.
F G H I J K L M N O
Return Value
P
A System.Object containing the return value of the invoked member. If the invoked member does not have a return value, returns a System.Object containing System.Void.
Q
Description
S
This version of System.Type.InvokeMember is equivalent to System.Type.InvokeMember(name, invokeAttr, binder, target, args, null, null, null). [Note: For a demonstration of the use of System.Type.InvokeMember, see the example for System.Type.InvokeMember(System.String, System.Reflection.BindingFlags, System.Reflection.Binder, System.Object, System.Object[], System.Reflection.ParameterModifier[], System.Globalization.CultureInfo, System.String[]).] This member must be implemented if the Reflection Library is present in the implementation.
T
R
U V W X Y Z
3503
Contents | Index
Type
System
InvokeMember() Method
Exceptions Exception
Condition
System.ArgumentNullException
name is null.
System.ArgumentException
args has more than one dimension. -orinvokeAttr is not a valid System.Reflection.BindingFlags value. -orThe member to be invoked is a constructor and System.Reflection.BindingFlags.CreateInstance is not specified in invokeAttr. -orThe member to be invoked is a method that is not a type initializer or instance constructor, and System.Reflection.BindingFlags.InvokeMethod is not specified in invokeAttr. -orThe member to be accessed is a field, and neither System.Reflection.BindingFlags.GetField nor System.Reflection.BindingFlags.SetField is specified in invokeAttr. -orThe member to be accessed is a property, and neither System.Reflection.BindingFlags.GetProperty nor System.Reflection.BindingFlags.SetProperty is specified in invokeAttr. -orinvokeAttr contains System.Reflection.BindingFlags.CreateInstance and at least one of System.Reflection.BindingFlags.InvokeMethod, System.Reflection.BindingFlags.GetField, System.Reflection.BindingFlags.SetField, System.Reflection.BindingFlags.GetProperty, or System.Reflection.BindingFlags.SetProperty. -orinvokeAttr contains both System.Reflection.BindingFlags.GetField and System.Reflection.BindingFlags.SetField. -orinvokeAttr contains both System.Reflection.BindingFlags.GetProperty and System.Reflection.BindingFlags.SetProperty. -orinvokeAttr contains System.Reflection.BindingFlags.InvokeMethod and at least one of System.Reflection.BindingFlags.SetField or System.Reflection.BindingFlags.SetProperty. -orinvokeAttr contains System.Reflection.BindingFlags.SetField and args has more than one element.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
3504
Contents | Index
System
Type InvokeMember() Method
Exception
Condition
System.MissingFieldException
A field or property matching the specified criteria was not found.
System.MissingMethodException
A method matching the specified criteria cannot be found.
System.MethodAccessException
The requested member is non-public and the caller does not have the required permission.
System.Reflection.TargetException
The member matching the specified criteria cannot be invoked on target.
System.Reflection.TargetInvocationException
The member matching the specified criteria threw an exception.
System.Reflection.AmbiguousMatchException
More than one member matches the specified criteria.
A B C D E F G H I J K L
Permissions
M
Permission
Description
N
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
O
System.Security.Permissions.ReflectionPermission
P Q R
Example
S
using System; using System.IO; using System.Reflection;
T U V
namespace Samples { public class TypeInvokeMember { public static void Main() { Type t = typeof (string); string s = "Hello world!"; Console.WriteLine("InvokeMember yields: {0}", t.InvokeMember("ToString",
W X Y Z
3505
Contents | Index
Type
System
InvokeMember() Method
BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance, System.Type.DefaultBinder, s, new object [] {})); Console.WriteLine("InvokeMember yields: {0}", t.InvokeMember("Length", BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty, System.Type.DefaultBinder, s, new object [] {}));
A B C D E F G
}
H
} }
I
The output is
J K
InvokeMember yields: Hello world! InvokeMember yields: 12
L M
Type.InvokeMember(System.String, System.Reflection.BindingFlags, System.Reflection.Binder, System.Object, System.Object[], System.Reflection.ParameterModifier[], System.Globalization.CultureInfo, System.String[]) Method
N O P Q
[ILASM]
R
.method public hidebysig virtual abstract object InvokeMember(string name, valuetype System.Reflection.BindingFlags invokeAttr, class System.Reflection.Binder binder, object target, class System.Object[] args, class System.Reflection.ParameterModifier[] modifiers, class System.Globalization.CultureInfo culture, class System.String[] namedParameters)
S T U
[C#]
public abstract object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
V W X
Summary
Y
Invokes or accesses a member defined on the type represented by the current instance that matches the specified binding criteria.
Z
3506
Contents | Index
System
Type InvokeMember() Method
Parameters Parameter
Description
name
A System.String containing the name of the constructor or method to invoke, or property or field to access. If the type represented by the current instance has a default member, specify System.String.Empty to invoke that member. [Note: For more information on default members, see System.Reflection.DefaultMemberAttribute.]
A
invokeAttr
B C D E
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance is used by default.
F G
A System.Reflection.Binder that defines a set of properties, and enables the binding, coercion of argument types, and invocation of members using reflection. Specify null to use System.Type.DefaultBinder.
H
A System.Object on which to invoke the member that matches the other specified criteria. If the matching member is static, this parameter is ignored.
K
target
args
An array of objects containing the arguments to pass to the member to be invoked. The elements of this array are of the same number and in the same order by assignment-compatible type as specified by the contract of the member to be bound if and only if namedParameters is null. If namedParameters is not null, the order of the elements in args corresponds to the order of the parameters specified in namedParameters. Specify an empty array or null for a member that takes no parameters.
binder
I J
L M N O P Q
modifiers
The only defined value for this parameter is null.
R
culture
The only defined value for this parameter is null.
S
namedParameters
An array of System.String objects containing the names of the parameters to which the values in args are passed. These names are processed in a case-sensitive manner and have a one-to-one correspondence with the elements of args. Specify an empty array or null for a member that takes no parameters. Specify null to have this parameter ignored.
T U V W X
Return Value
Y
A System.Object containing the return value of the invoked or accessed member. If the member does not have a return value, returns a System.Object containing System.Void.
Z
3507
Contents | Index
Type
System
InvokeMember() Method
Description System.Type.InvokeMember calls a constructor or a method, gets or sets a property, gets or sets a field, or gets or sets an element of an array. The binder finds all of the matching members. These members are found based upon the type of binding specified by invokeAttr. The System.Reflection.Binder.BindToMethod is responsible for selecting the method to be invoked. The default binder selects the most specific match. The set of members is then filtered by name, number of arguments, and a set of search modifiers defined in the binder. After the member is selected, it is invoked or accessed. Accessibility is checked at that point. Access restrictions are ignored for fully trusted code; that is, private constructors, methods, fields, and properties can be accessed and invoked via reflection whenever the code is fully trusted. The following System.Reflection.BindingFlags are used to define which members to include in the search:
A B C D E F G H
•
I J
•
K L
•
M N
Specify either System.Reflection.BindingFlags.Instance or System.Reflection.BindingFlags.Static to get a return value other than null. Specify System.Reflection.BindingFlags.Public to include public members in the search. Specify System.Reflection.BindingFlags.NonPublic to include non-public members (that is, private and protected members) in the search.
O
The following System.Reflection.BindingFlags values can be used to change how the search works:
P
•
Q
•
R S
System.Reflection.BindingFlags.DeclaredOnly to search only the members declared in the type, not members that were simply inherited. System.Reflection.BindingFlags.IgnoreCase to ignore the case of name.
[Note: For more information, see System.Reflection.BindingFlags.] This member must be implemented if the Reflection Library is present in the implementation.
T U V
Behaviors
W
Each parameter in the namedParameters array is assigned the value in the corresponding element in the args array. If the length of args is greater than the length of namedParameters, the remaining argument values are passed in order. A member will be found only if the number of parameters in the member declaration equals the number of arguments in the args array (unless default arguments are defined on the member). Also, the type of each argument is required to be convertible by the binder to the type of the parameter.
X Y Z
3508
Contents | Index
System
Type InvokeMember() Method
It is required that the caller specify values for invokeAttr as follows:
Action
BindingFlags
Invoke a constructor.
System.Reflection.BindingFlags.CreateInstance. This flag is not valid with the other flags in this table. If this flag is specified, name is ignored.
Invoke a method.
System.Reflection.BindingFlags.InvokeMethod. This flag is not valid with System.Reflection.BindingFlags.CreateInstance, System.Reflection.BindingFlags.SetField, or System.Reflection.BindingFlags.SetProperty.
A B
Define a field value.
Return a field value.
Set a property.
Get a property.
C D E F G
System.Reflection.BindingFlags.SetField. This flag is not valid with System.Reflection.BindingFlags.CreateInstance, System.Reflection.BindingFlags.InvokeMethod, or System.Reflection.BindingFlags.GetField.
H I J
System.Reflection.BindingFlags.GetField. This flag is not valid with System.Reflection.BindingFlags.CreateInstance, System.Reflection.BindingFlags.InvokeMethod, or System.Reflection.BindingFlags.SetField.
K L
System.Reflection.BindingFlags.SetProperty. This flag is not valid with System.Reflection.BindingFlags.CreateInstance, System.Reflection.BindingFlags.InvokeMethod, or System.Reflection.BindingFlags.GetProperty.
M
System.Reflection.BindingFlags.GetProperty. This flag is not valid with System.Reflection.BindingFlags.CreateInstance, System.Reflection.BindingFlags.InvokeMethod, or System.Reflection.BindingFlags.SetProperty.
P
N O
Q R S
[Note: For more information, see System.Reflection.BindingFlags.]
T U
Usage
V
System.Type.InvokeMember can be used to invoke methods with parameters that have default values. To bind to these methods, System.Reflection.BindingFlags.OptionalParamBinding must be specified. For a parameter that has a default value, the caller can supply a value or supply System.Type.Missing to use the default value. System.Type.InvokeMember can be used to set a field to a particular value by specifying System.Reflection.BindingFlags.SetField. For example, to set a public instance field named F on class C, where F is a string, the value is set using the following statement:
W X Y Z
3509
Contents | Index
Type
System
InvokeMember() Method
typeof(C).InvokeMember("F", BindingFlags.SetField, null, C, new Object{ "strings new value"}, null, null, null);
A string array F can be initialized as follows:
A B
typeof(C).InvokeMember("F", BindingFlags.SetField, null, C, new Object{new String[]{"a","z","c","d"}, null, null, null);
C
Use System.Type.InvokeMember to set the value of an element in an array by specifying the index of the value and the new value for the element as follows:
D E
typeof(C).InvokeMember("F", BindingFlags.SetField, null, C, new Object{1, "b"}, null, null, null);
F G
The preceding statement changes “z” in array F to “b”.
H I
Exceptions
J K
Exception
Condition
L
System.ArgumentNullException
name is null.
M
args has more than one dimension.
N
-or-
O
invokeAttr is not a valid System.Reflection.BindingFlags value.
P
-or-
Q R
The member to be invoked is a constructor and System.Reflection.BindingFlags.CreateInstance is not specified in invokeAttr.
S
-or-
T
System.ArgumentException
U
The member to be invoked is a method that is not a type initializer or instance constructor, and System.Reflection.BindingFlags.InvokeMethod is not specified in invokeAttr. -or-
V
The member to be accessed is a field, and neither System.Reflection.BindingFlags.GetField nor System.Reflection.BindingFlags.SetField is specified in invokeAttr.
W X
-or-
Y
The member to be accessed is a property, and neither System.Reflection.BindingFlags.GetProperty nor System.Reflection.BindingFlags.SetProperty is specified in invokeAttr.
Z
-or-
3510
Contents | Index
System
Type InvokeMember() Method
Exception
System.ArgumentException
Condition invokeAttr contains System.Reflection.BindingFlags.CreateInstance and at least one of System.Reflection.BindingFlags.InvokeMethod, System.Reflection.BindingFlags.GetField, System.Reflection.BindingFlags.SetField, System.Reflection.BindingFlags.GetProperty, or System.Reflection.BindingFlags.SetProperty.
B
-or-
D
invokeAttr contains both System.Reflection.BindingFlags.GetField and System.Reflection.BindingFlags.SetField.
E
-or-
G
invokeAttr contains both System.Reflection.BindingFlags.GetProperty and System.Reflection.BindingFlags.SetProperty.
H
-or-
J
A
C
F
I
invokeAttr contains System.Reflection.BindingFlags.InvokeMethod and at least one of System.Reflection.BindingFlags.SetField or System.Reflection.BindingFlags.SetProperty.
K L
-or-
M
invokeAttr contains System.Reflection.BindingFlags.SetField and args has more than one element.
N O
-ornamedParameters.Length > args.Length.
P
-or-
Q
At least one element in namedParameters is null.
R
-or-
S
At least one element in args is not assignment-compatible with the corresponding parameter in namedParameters. System.MissingFieldException
A field or property matching the specified criteria was not found.
System.MissingMethodException
A method matching the specified criteria cannot be found.
System.MethodAccessException
The requested member is non-public and the caller does not have the required permission.
System.Reflection.TargetException
The member matching the specified criteria cannot be invoked on target.
T U V W X Y Z
3511
Contents | Index
Type
System
InvokeMember() Method
A B C D
Exception
Condition
System.Reflection.TargetInvocationException
The member matching the specified criteria threw an exception.
System.Reflection.AmbiguousMatchException
More than one member matches the specified criteria.
E
Permissions
F G
Permission
Description
System.Security.Permissions.ReflectionPermisson
Requires permission to retrieve information on non-public members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
H I J K L
Example
M
using System; using System.IO; using System.Reflection;
N O
namespace Samples { public class TypeInvokeMember { public static void Main() { Type t = typeof (string); string s = "Hello "; Console.WriteLine("Insert: {0}", t.InvokeMember("Insert", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance, System.Type.DefaultBinder, s, new object [] {"world!", 6}, null, null, new string[]{"value", "startIndex"}));
P Q R S T U V W X Y Z
3512
Contents | Index
System
Type InvokeMember() Method
Console.WriteLine("InvokeMember yields: {0}", t.InvokeMember("Insert", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance, System.Type.DefaultBinder, s, new object [] {6, "world!"}, null));
A B C D
} }
E
}
F
The output is
G H
Insert: Hello world! InvokeMember yields: Hello world!
I J
Type.InvokeMember(System.String, System.Reflection.BindingFlags, System.Reflection.Binder, System.Object, System.Object[], System.Globalization.CultureInfo) Method
K L M
[ILASM]
N
.method public hidebysig instance object InvokeMember(string name, valuetype System.Reflection.BindingFlags invokeAttr, class System.Reflection.Binder binder, object target, class System.Object[] args, class System.Globalization.CultureInfo culture)
O P
[C#]
Q
public object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, CultureInfo culture)
R S
Summary
T
Invokes the specified member, using the specified binding constraints and matching the specified argument list and culture.
U V W X Y Z
3513
Contents | Index
Type
System
InvokeMember() Method
Parameters Parameter
Description
name
A System.String containing the name of the constructor or method to invoke, or property or field to access. If the type represented by the current instance has a default member, specify System.String.Empty to invoke that member. [Note: For more information on default members, see System.Reflection.DefaultMemberAttribute.]
invokeAttr
A bitwise combination of System.Reflection.BindingFlags values that control the binding process. If zero is specified, System.Reflection.BindingFlags.Public|System.Reflection.BindingFlags.Instance is used by default.
binder
A System.Reflection.Binder object that defines a set of properties and enables the binding, coercion of argument types, and invocation of members using reflection. Specify null to use the System.Type.DefaultBinder.
target
A System.Object on which to invoke the member that matches the other specified criteria. If the matching member is static, this parameter is ignored.
args
An array of objects containing the arguments to pass to the member to be invoked. The elements of this array are of the same number and in the same order by assignment-compatible type as specified by the contract of the member to be bound. Specify an empty array or null for a member that has no parameters.
culture
The only defined value for this parameter is null.
A B C D E F G H I J K L M N O P Q
Return Value
R
A System.Object containing the return value of the invoked member. If the invoked member does not have a return value, returns a System.Object containing System.Void.
S T U
Description
V
This version of System.Type.InvokeMember is equivalent to System.Type.InvokeMember(name, invokeAttr, binder, target, args, null, culture, null). This member must be implemented if the Reflection Library is present in the implementation.
W X Y Z
3514
Contents | Index
System
Type InvokeMember() Method
Exceptions Exception
Condition
System.ArgumentNullException
name is null.
System.ArgumentException
args has more than one dimension. -orinvokeAttr is not a valid System.Reflection.BindingFlags value. -orThe member to be invoked is a constructor and System.Reflection.BindingFlags.CreateInstance is not specified in invokeAttr. -orThe member to be invoked is a method that is not a type initializer or instance constructor, and System.Reflection.BindingFlags.InvokeMethod is not specified in invokeAttr. -orThe member to be accessed is a field, and neither System.Reflection.BindingFlags.GetField nor System.Reflection.BindingFlags.SetField is specified in invokeAttr. -orThe member to be accessed is a property, and neither System.Reflection.BindingFlags.GetProperty nor System.Reflection.BindingFlags.SetProperty is specified in invokeAttr. -orinvokeAttr contains System.Reflection.BindingFlags.CreateInstance and at least one of System.Reflection.BindingFlags.InvokeMethod, System.Reflection.BindingFlags.GetField, System.Reflection.BindingFlags.SetField, System.Reflection.BindingFlags.GetProperty, or System.Reflection.BindingFlags.SetProperty. -orinvokeAttr contains both System.Reflection.BindingFlags.GetField and System.Reflection.BindingFlags.SetField. -orinvokeAttr contains both System.Reflection.BindingFlags.GetProperty and System.Reflection.BindingFlags.SetProperty. -orinvokeAttr contains System.Reflection.BindingFlags. InvokeMethod and at least one of System.Reflection.BindingFlags.SetField or System.Reflection.BindingFlags.SetProperty. -orinvokeAttr contains System.Reflection.BindingFlags.SetField and args has more than one element.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
3515
Contents | Index
Type
System
InvokeMember() Method
A B C D
Exception
Condition
System.MissingFieldException
A field or property matching the specified criteria was not found.
System.MissingMethodException
A method matching the specified criteria was not found.
System.MethodAccessException
The requested member is non-public and the caller does not have the required permission.
System.Reflection.TargetException
The member matching the specified criteria cannot be invoked on target.
System.Reflection.TargetInvocationException
The member matching the specified criteria threw an exception.
System.Reflection.AmbiguousMatchException
More than one member matches the specified criteria.
E F G H I J K L
Permissions
M N
Permission
Description
System.Security.Permissions.ReflectionPermission
Requires permission to retrieve information on nonpublic members of types in loaded assemblies. See System.Security.Permissions.ReflectionPermissionFlag.TypeInformation.
O P Q R S
Example
T
using System; using System.IO; using System.Reflection;
U V
namespace Samples { public class TypeInvokeMember { public static void Main() { Type t = typeof (string); string s = "Hello world!"; Console.WriteLine("ToString: {0}",
W X Y Z
3516
Contents | Index
System
Type IsArrayImpl() Method
t.InvokeMember("ToString", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance, System.Type.DefaultBinder, s, new object [] {}, null)); Console.WriteLine("InvokeMember yields: {0}", t.InvokeMember("Length", BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty, System.Type.DefaultBinder, s, new object [] {}, null));
A B C D E F G H I
} }
J
}
K
The output is
L M
ToString: Hello world! InvokeMember yields: 12
N O
Type.IsArrayImpl() Method
P
[ILASM]
Q
.method family hidebysig virtual abstract bool IsArrayImpl()
R
[C#]
protected abstract bool IsArrayImpl()
S
Summary
T
When overridden in a derived class implements the System.Type.IsArray property returning a System.Boolean value that indicates whether the type represented by the current instance is an array.
U V W
Return Value
X
true if the System.Type is an array; otherwise, false.
Y Z
3517
Contents | Index
Type
System
IsAssignableFrom() Method
Description An instance of the System.Array class is required to return false because it is an object, not an array. This member must be implemented if the Reflection Library is present in the implementation.
A B C
Type.IsAssignableFrom(System.Type) Method
D [ILASM]
E
.method public hidebysig virtual bool IsAssignableFrom(class System.Type c)
F
[C#]
public virtual bool IsAssignableFrom(Type c)
G H
Summary
I
Determines whether an instance of the current System.Type can be assigned from an instance of the specified System.Type.
J K
Parameters
L M N
Parameter
Description
c
The System.Type to compare with the current System.Type.
O P
Return Value
Q
false if c is a null reference. true if one or more of the following statements are true; otherwise, false.
R S
• • •
T U V
If c and the current System.Type represent the same type. If the current System.Type is in the inheritance hierarchy of c. If the current System.Type is an interface and c supports that interface.
Example
W
using System; using System.Reflection;
X Y
namespace Samples { public class TypeIsAssignableFrom { public static void Main()
Z
3518
Contents | Index
System
Type IsByRefImpl() Method
{ Type to = typeof(object), ts = typeof(string), ti = typeof(int); Console.WriteLine( "to.IsAssignableFrom(to): to.IsAssignableFrom(to)); Console.WriteLine( "to.IsAssignableFrom(ts): to.IsAssignableFrom(ts)); Console.WriteLine( "ts.IsAssignableFrom(to): ts.IsAssignableFrom(to)); Console.WriteLine( "ts.IsAssignableFrom(ti): ts.IsAssignableFrom(ti)); Console.WriteLine( "ti.IsAssignableFrom(ts): ti.IsAssignableFrom(ts));
A {0}",
B C
{0}",
D E
{0}",
F G
{0}",
H I
{0}",
J
}
K
} }
L
The output is to.IsAssignableFrom(to): to.IsAssignableFrom(ts): ts.IsAssignableFrom(to): ts.IsAssignableFrom(ti): ti.IsAssignableFrom(ts):
M N
True True False False False
O P Q R
Type.IsByRefImpl() Method
S
[ILASM]
T
.method family hidebysig virtual abstract bool IsByRefImpl()
U
[C#]
protected abstract bool IsByRefImpl()
V W
Summary
X
When overridden in a derived class, implements the System.Type.IsByRef property and determines whether the System.Type is passed by reference.
Y Z
Return Value true if the System.Type is passed by reference; otherwise, false.
3519
Contents | Index
Type
System
IsCOMObjectImpl() Method
Description This member must be implemented if the Reflection Library is present in the implementation. A B
Type.IsCOMObjectImpl() Method
C
[ILASM]
.method family hidebysig virtual abstract bool IsCOMObjectImpl()
D
[C#]
protected abstract bool IsCOMObjectImpl()
E F
Summary
G
Reserved.
H
Return Value
I
false J K
Description
L
This abstract method is required to be present for legacy implementations. Conforming implementations are permitted to throw the System.NotSupportedException as their implementation. This member must be implemented if the Reflection Library is present in the implementation.
M N O P
Type.IsContextfulImpl() Method
Q [ILASM]
R
.method family hidebysig virtual bool IsContextfulImpl() [C#]
S
protected virtual bool IsContextfulImpl()
T
Summary
U
Implements the System.Type.IsContextful property and determines whether the System.Type can be hosted in a context.
V W
Return Value
X
true if the System.Type can be hosted in a context; otherwise, false.
Y Z
Description A context intercepts calls to the class members and enforce policies that are applied to the class, such as synchronization. 3520
Contents | Index
System
Type IsInstanceOfType() Method
Permissions Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
A B C D E F
Type.IsInstanceOfType(System.Object) Method
G
[ILASM]
.method public hidebysig virtual bool IsInstanceOfType(object o)
H
[C#]
I
public virtual bool IsInstanceOfType(object o)
J
Summary
K
Determines whether the specified object is an instance of the current System.Type.
L M
Parameters
N
Parameter
Description
o
The object to compare with the current System.Type.
O P Q
Return Value
R
true if either of the following statements is true; otherwise, false.
S
• •
T
If the current System.Type is in the inheritance hierarchy of o. If the current System.Type is an interface and o supports that interface.
U V
If o is a null reference, returns false.
W
Example
X
using System; using System.Reflection;
Y Z
namespace Samples {
3521
Contents | Index
Type
System
IsInstanceOfType() Method
public class TypeIsInstanceOfType { public static void Main() { Type to = typeof(object), ts = typeof(string), ti = typeof(int); object o = new object(); int i = 42; string s = "Hello world!"; Console.WriteLine( "to.IsInstanceOfType(o): to.IsInstanceOfType(o)); Console.WriteLine( "to.IsInstanceOfType(i): to.IsInstanceOfType(i)); Console.WriteLine( "to.IsInstanceOfType(s): to.IsInstanceOfType(s)); Console.WriteLine( "ts.IsInstanceOfType(s): ts.IsInstanceOfType(s)); Console.WriteLine( "ti.IsInstanceOfType(i): ti.IsInstanceOfType(i)); Console.WriteLine( "ti.IsInstanceOfType(o): ti.IsInstanceOfType(o)); Console.WriteLine( "ti.IsInstanceOfType(s): ti.IsInstanceOfType(s)); } }
A B C D E F G H I J K L M N O P Q R S
{0}",
{0}",
{0}",
{0}",
{0}",
{0}",
{0}",
}
T
The output is
U to.IsInstanceOfType(o): to.IsInstanceOfType(i): to.IsInstanceOfType(s): ts.IsInstanceOfType(s): ti.IsInstanceOfType(i): ti.IsInstanceOfType(o): ti.IsInstanceOfType(s):
V W X Y
True True True True True False False
Z
3522
Contents | Index
System
Type IsPointerImpl() Method
Type.IsMarshalByRefImpl() Method [ILASM]
.method family hidebysig virtual bool IsMarshalByRefImpl() [C#]
A
protected virtual bool IsMarshalByRefImpl()
B C
Summary
D
Implements the System.Type.IsMarshalByRef property and determines whether the System.Type is marshalled by reference.
E F
Return Value
G
true if the System.Type is marshalled by reference; otherwise, false.
H
Permissions
I J
Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
K L M N O P
Type.IsPointerImpl() Method
Q [ILASM]
R
.method family hidebysig virtual abstract bool IsPointerImpl() [C#]
S
protected abstract bool IsPointerImpl()
T
Summary
U
When overridden in a derived class, implements the System.Type.IsPointer property and determines whether the System.Type is a pointer.
V W
Return Value
X
true if the System.Type is a pointer; otherwise, false.
Y Z
Description This member must be implemented if the Reflection Library is present in the implementation.
3523
Contents | Index
Type
System
IsPrimitiveImpl() Method
Type.IsPrimitiveImpl() Method [ILASM]
.method family hidebysig virtual abstract bool IsPrimitiveImpl()
A
[C#]
protected abstract bool IsPrimitiveImpl()
B C
Summary
D
When overridden in a derived class, implements the System.Type.IsPrimitive property and determines whether the System.Type is one of the primitive types.
E F
Return Value
G
true if the System.Type is one of the primitive types; otherwise, false.
H I
Description
J
This member must be implemented if the Reflection Library is present in the implementation.
K
Behaviors
L
This method returns true if the underlying type of the current instance is one of the following: System.Boolean, System.Byte, System.SByte, System.Int16, System.UInt16, System.Int32, System.UInt32, System.Int64, System.UInt64, System.Char, System.Double, and System.Single.
M N O P Q
Type.IsSubclassOf(System.Type) Method
R
[ILASM]
.method public hidebysig virtual bool IsSubclassOf(class System.Type c)
S
[C#]
public virtual bool IsSubclassOf(Type c)
T U
Summary
V
Determines whether the current System.Type derives from the specified System.Type.
W
Parameters
X Y
Parameter
Description
c
The System.Type to compare with the current System.Type.
Z
3524
Contents | Index
System
Type IsSubclassOf() Method
Return Value true if c and the current System.Type represent classes, and the class represented by the current System.Type derives from the class represented by c; otherwise, false. Returns false if c and the current System.Type represent the same class.
A B
Example
C
using System; using System.Reflection; namespace Samples { public class TypeIsSubclassOf { public static void Main() { Type to = typeof(object), ts = typeof(string), ti = typeof(int); Console.WriteLine( "to.IsSubclassOf(to): to.IsSubclassOf(to)); Console.WriteLine( "to.IsSubclassOf(ts): to.IsSubclassOf(ts)); Console.WriteLine( "to.IsSubclassOf(ti): to.IsSubclassOf(ti)); Console.WriteLine( "ts.IsSubclassOf(to): ts.IsSubclassOf(to)); Console.WriteLine( "ts.IsSubclassOf(ts): ts.IsSubclassOf(ts)); Console.WriteLine( "ts.IsSubclassOf(ti): ts.IsSubclassOf(ti)); Console.WriteLine( "ti.IsSubclassOf(to): ti.IsSubclassOf(to)); Console.WriteLine( "ti.IsSubclassOf(ts): ti.IsSubclassOf(ts)); Console.WriteLine( "ti.IsSubclassOf(ti): ti.IsSubclassOf(ti)); } } }
D E F G H I J K
{0}",
L {0}",
M N
{0}",
O P
{0}",
Q R
{0}",
S {0}",
T U
{0}",
V W
{0}",
X Y
{0}",
Z
3525
Contents | Index
Type
System
IsValueTypeImpl() Method
The output is to.IsSubclassOf(to): to.IsSubclassOf(ts): to.IsSubclassOf(ti): ts.IsSubclassOf(to): ts.IsSubclassOf(ts): ts.IsSubclassOf(ti): ti.IsSubclassOf(to): ti.IsSubclassOf(ts): ti.IsSubclassOf(ti):
A B C D E
False False False True False False True False False
F G
Type.IsValueTypeImpl() Method
H
[ILASM]
I
.method family hidebysig virtual bool IsValueTypeImpl() [C#]
J
protected virtual bool IsValueTypeImpl()
K L
Summary
M
Implements the System.Type.IsValueType property and determines whether the System.Type is a value type; that is, not a class or an interface.
N O
Return Value
P
true if the System.Type is a value type; otherwise, false
Q
Description
R
Value types describe values that are represented as sequences of bits; value types are not classes or interfaces. These are referred to as “structs” in some programming languages. Enums are value types.
S T U
Permissions
V W
Permission
Description
System.Security.Permissions.ReflectionPermission
To enhance security and performance when invoked late-bound through mechanisms such as System.Type.InvokeMember. Associated enumeration: System.Security.Permissions.ReflectionPermissionFlag.MemberAccess.
X Y Z
3526
Contents | Index
System
Type ToString() Method
Type.ToString() Method [ILASM]
.method public hidebysig virtual string ToString() [C#]
A
public override string ToString()
B
Summary
C
Returns a System.String representation of the current System.Type.
D E
Return Value
F
Returns System.Type.FullName.
G
Description
H
[Note: This method overrides System.Object.ToString.]
I
Example
J
using System; using System.Reflection;
K L
namespace Samples { public class TypeToString { public static void Main() { Type to = typeof(object), ts = typeof(string), ti = typeof(int); Console.WriteLine( "to.ToString(): {0}", to.ToString()); Console.WriteLine( "ts.ToString(): {0}", ts.ToString()); Console.WriteLine( "ti.ToString(): {0}", ti.ToString()); } } }
M N O P Q R S T U V W X Y
The output is
Z to.ToString(): System.Object ts.ToString(): System.String ti.ToString(): System.Int32
3527
Contents | Index
System TypeInitializationException
BCL
Object
A
Exception
B
ISerializable
NotStandardized
SystemException TypeInitializationException
C D
Summary
E
Represents the error that occurs when an exception is thrown inside the static constructor of a type.
F G
Type Summary
H
CF public sealed class TypeInitializationException : SystemException { // Properties CF public string TypeName { get; }
I J K
// Methods MS CF public override void GetObjectData (SerializationInfo info, StreamingContext context); }
L M N
Description
O
When a static constructor fails to initialize a type, a System.TypeInitializationException instance is created and passed a reference to the exception thrown by the static constructor. The System.TypeInitializationException.InnerException property stores the exception that was thrown by the static constructor.
P Q R S
Example
T
using System;
U namespace Samples { public class TypeInitializationExceptionSample { static TypeInitializationExceptionSample() { Console.WriteLine("Type Initializer"); throw new ApplicationException( "TypeInitializationException"); } public TypeInitializationExceptionSample()
V W X Y Z
3528
Contents | Index
System
TypeInitializationException TypeName Property
{ Console.WriteLine("Instance Initializer"); } static public void Main() { TypeInitializationExceptionSample t = new TypeInitializationExceptionSample(); }
A B C
}
D
}
E
The output is
F
Type Initializer
G
Unhandled Exception: System.TypeInitializationException: The type initializer for "Samples.TypeInitializationExceptionSample" threw an exception. ---> System.ApplicationException: TypeInitializationException at Samples.TypeInitializationExceptionSample..cctor() in C:\Books\BCL\Samples\ System\TypeInitializationException\TypeInitializationException.cs:line 10 --- End of inner exception stack trace --at Samples.TypeInitializationExceptionSample.Main()
H I J K L M
TypeInitializationException.TypeName Property
N
[ILASM]
O
.property string TypeName { public hidebysig specialname instance string get_TypeName() }
P
[C#]
Q
public string TypeName { get; }
R
Summary
S
Gets the fully qualified name of the type that causes the exception.
T U
Description
V
The System.TypeInitializationException.TypeName property returns the same value as was passed into the constructor.
W X Y Z
3529
Contents | Index
TypeInitializationException
System
GetObjectData() Method
TypeInitializationException.GetObjectData(System.Runtime.Serialization. SerializationInfo, System.Runtime.Serialization.StreamingContext) Method A
[ILASM]
B
.method public hidebysig virtual void GetObjectData(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
C
[C#]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
D E F
Summary
G
Sets the System.Runtime.Serialization.SerializationInfo object with the type name and additional exception information.
H I
Parameters
J K L
Parameter
Description
info
The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown.
context
The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination.
M N O P Q R S T U V W X Y Z
3530
Contents | Index
System UInt16 Structure
BCL
Object ValueType UInt16
A
IComparable
B
IFormattable IConvertible
NotStandardized
C D
Summary
E
Represents a 16-bit unsigned integer. This type is not CLS-compliant.
F
Type Summary
G
public struct UInt16 : IComparable, IFormattable, IConvertible { // Fields public const ushort MaxValue = 65535; public const ushort MinValue = 0;
H I J K L
// Methods public int CompareTo (object value); public override bool Equals (object obj); public override int GetHashCode (); MS public TypeCode GetTypeCode (); public static ushort Parse (string s); public static ushort Parse (string s, NumberStyles style); public static ushort Parse (string s, NumberStyles style, IFormatProvider provider); CF public static ushort Parse (string s, IFormatProvider provider); public override string ToString (); public string ToString (string format); public string ToString (string format, IFormatProvider provider); public string ToString (IFormatProvider provider); // MS MS MS MS MS MS MS MS MS MS
M N O P Q R S T U
Explicit Interface Members bool IConvertible.ToBoolean(IFormatProvider provider); byte IConvertible.ToByte(IFormatProvider provider); char IConvertible.ToChar(IFormatProvider provider); DateTime IConvertible.ToDateTime(IFormatProvider provider); decimal IConvertible.ToDecimal(IFormatProvider provider); double IConvertible.ToDouble(IFormatProvider provider); short IConvertible.ToInt16(IFormatProvider provider); int IConvertible.ToInt32(IFormatProvider provider); long IConvertible.ToInt64(IFormatProvider provider); sbyte IConvertible.ToSByte(IFormatProvider provider);
V W X Y Z
3531
Contents | Index
UInt16 Structure
System
UInt16 Structure
MS MS MS MS MS
A
float IConvertible.ToSingle(IFormatProvider provider); object IConvertible.ToType(Type type,IFormatProvider provider); ushort IConvertible.ToUInt16(IFormatProvider provider); uint IConvertible.ToUInt32(IFormatProvider provider); ulong IConvertible.ToUInt64(IFormatProvider provider);
}
B C
Description
D
The System.UInt16 data type represents integer values ranging from 0 to positive 65,535 (hexadecimal 0xFFFF).
E F
Example
G
using System;
H namespace Samples { public class UInt16Sample { public static void Main() { ushort max = ushort.MaxValue, min = ushort.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); Console.WriteLine("Is {0} equal to {1}: {2}", max, max, max.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", max, min, max.Equals(min)); Console.WriteLine("{0} has hashcode of: {1}", max, max.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", min, min.GetHashCode()); string s = max.ToString(); Console.WriteLine("\"{0}\" parsed from string yields: {1}", s, UInt16.Parse(s)); s = min.ToString(); Console.WriteLine("\"{0}\" parsed from string yields: {1}", s, UInt16.Parse(s)); string[] formats = {"c", "d", "e", "f", "g", "n", "p", "x" }; foreach(string f in formats) Console.WriteLine("{0}: {1}", max, max.ToString(f)); } } }
I J K L M N O P Q R S T U V W X Y Z
3532
Contents | Index
System
UInt16 Structure MaxValue Field
The output is MaxValue: 65535 MinValue: 0 Is 65535 equal to 65535: True Is 65535 equal to 0: False 65535 has hashcode of: 65535 0 has hashcode of: 0 "65535" parsed from string yields: 65535 "0" parsed from string yields: 0 65535: $65,535.00 65535: 65535 65535: 6.553500e+004 65535: 65535.00 65535: 65535 65535: 65,535.00 65535: 6,553,500.00 % 65535: ffff
A B C D E F G H I J K
UInt16.MaxValue Field
L
[ILASM]
.field public static literal unsigned int16 MaxValue
M
[C#]
N
public const ushort MaxValue = 65535
O
Summary
P
Contains the maximum value for the System.UInt16 type.
Q R
Description
S
The value of this constant is 65,535 (hexadecimal 0xFFFF).
T
Example
U
using System;
V
namespace Samples { public class UInt16MaxValue { public static void Main() { ushort max = ushort.MaxValue, min = ushort.MinValue;
W X Y Z
3533
Contents | Index
UInt16 Structure
System
MinValue Field
Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); } }
A
}
B
The output is
C
MaxValue: 65535 MinValue: 0
D E F
UInt16.MinValue Field
G H
[ILASM]
I
[C#]
.field public static literal unsigned int16 MinValue public const ushort MinValue = 0
J K
Summary
L
Contains the minimum value for the System.UInt16 type.
M
Description
N
The value of this constant is 0.
O P
Example
Q
using System;
R
namespace Samples { public class UInt16MinValue { public static void Main() { ushort max = ushort.MaxValue, min = ushort.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); } } }
S T U V W X Y Z
3534
Contents | Index
System
UInt16 Structure CompareTo() Method
The output is MaxValue: 65535 MinValue: 0
A B
UInt16.CompareTo(System.Object) Method
C
[ILASM]
D
.method public final hidebysig virtual int32 CompareTo(object value)
E
[C#]
public int CompareTo(object value)
F G
Summary
H
Returns the sort order of the current instance compared to the specified System.Object.
I
Parameters Parameter
J K
Description
L
value
The System.Object to compare to the current instance.
M N
Return Value
O
A System.Int32 containing a value that reflects the sort order of the current instance as compared to value. The following table defines the conditions under which the return value is a negative number, zero, or a positive number.
P Q R S
Return Value
Description
any negative number
Current instance < value.
U
zero
Current instance == value.
V
any positive number
Current instance > value, or value is a null reference.
T
W X Y
Description
Z
[Note: This method is implemented to support the System.IComparable interface.]
3535
Contents | Index
UInt16 Structure
System
Equals() Method
Exceptions Exception
Condition
System.ArgumentException
value is not a System.UInt16 and is not a null reference.
A B C
Example
D
using System;
E
namespace Samples { public class UInt16CompareTo { private static string CompareUInt16s(ushort u1, ushort u2) { int i = u1.CompareTo(u2); if(0 == i) return String.Format("{0} is equal to {1}", u1, u2); if(i > 0) return String.Format("{0} is greater than {1}", u1, u2); else return String.Format("{0} is less than {1}", u1, u2); } public static void Main() { ushort max = ushort.MaxValue, min = ushort.MinValue; Console.WriteLine(CompareUInt16s(min, min)); Console.WriteLine(CompareUInt16s(min, max)); Console.WriteLine(CompareUInt16s(max, min)); } } }
F G H I J K L M N O P Q R S T
The output is
U 0 is equal to 0 0 is less than 65535 65535 is greater than 0
V W X Y
UInt16.Equals(System.Object) Method
Z
[ILASM]
.method public hidebysig virtual bool Equals(object obj) [C#]
public override bool Equals(object obj)
3536
Contents | Index
System
UInt16 Structure Equals() Method
Summary Determines whether the current instance and the specified System.Object represent the same value and type. A
Parameters
B C
Parameter
Description
obj
The System.Object to compare to the current instance.
D E F
Return Value
G
true if obj represents the same value and type as the current instance. If obj is a null reference or is not an instance of System.UInt16, returns false.
H
Description
J
[Note: This method overrides System.Object.Equals.]
K
I
L
Example
M
using System;
N namespace Samples { public class UInt16Equals { public static void Main() { ushort max = ushort.MaxValue, min = ushort.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); Console.WriteLine("Is {0} equal to {1}: {2}", max, max, max.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", max, min, max.Equals(min)); Console.WriteLine("Is {0} equal to {1}: {2}", min, max, min.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", min, min, min.Equals(min)); } } }
O P Q R S T U V W X Y Z
3537
Contents | Index
UInt16 Structure
System
GetHashCode() Method
The output is MaxValue: 65535 MinValue: 0 Is 65535 equal to 65535: True Is 65535 equal to 0: False Is 0 equal to 65535: False Is 0 equal to 0: True
A B C D E
UInt16.GetHashCode() Method
F
[ILASM]
G
.method public hidebysig virtual int32 GetHashCode() [C#]
H
public override int GetHashCode()
I
Summary
J
Generates a hash code for the current instance.
K L
Return Value
M
A System.Int32 containing the hash code for the current instance.
N
Description
O
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
P Q
Example
R
using System;
S
namespace Samples { public class UInt16GetHashCode { public static void Main() { ushort max = ushort.MaxValue, min = ushort.MinValue; Console.WriteLine("{0} has hashcode of: {1}", max, max.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", min, min.GetHashCode()); } } }
T U V W X Y Z
3538
Contents | Index
System
UInt16 Structure Parse() Method
The output is 65535 has hashcode of: 65535 0 has hashcode of: 0
A B
UInt16.GetTypeCode() Method
C
[ILASM]
D
.method public final hidebysig virtual valuetype System.TypeCode GetTypeCode()
E
[C#]
public TypeCode GetTypeCode()
F G
Summary
H
Returns the System.TypeCode for value type System.UInt16.
I J
UInt16.Parse(System.String) Method
K
[ILASM]
L
.method public hidebysig static unsigned int16 Parse(string s)
M
[C#]
public static ushort Parse(string s)
N
Summary
O
Returns the specified System.String converted to a System.UInt16 value.
P Q
Parameters
R
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Integer style.
S T U V
Return Value
W
The System.UInt16 value obtained from s.
X Y
Description
Z
This version of System.UInt16.Parse is equivalent to System.UInt16.Parse(s, NumberStyles.Integer, null).
3539
Contents | Index
UInt16 Structure
System
Parse() Method
The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.] This method is not CLS-compliant. For a CLS-compliant alternative use System.Int32.Parse(System.String).
A B C
Exceptions
D E F G H
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.UInt16.MaxValue or less than System.UInt16.MinValue.
I J K L
Example
M
using System;
N namespace Samples { public class UInt16Parse { public static void Main() { string s; try { s = (UInt16.MaxValue).ToString(); Console.WriteLine("String {0} yields {1}", s, UInt16.Parse(s)); s = (UInt16.MinValue).ToString(); Console.WriteLine("String {0} yields {1}", s, UInt16.Parse(s)); s = String.Empty; Console.WriteLine("String {0} yields {1}", s, UInt16.Parse(s)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e);
O P Q R S T U V W X Y Z
3540
Contents | Index
System
UInt16 Structure Parse() Method
} try { s = (UInt16.MaxValue + 1).ToString(); Console.WriteLine("String {0} yields {1}", s, Int16.Parse(s)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E
}
F
} }
G
The output is
H I
String 65535 yields 65535 String 0 yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseUInt32(String s, NumberStyles style, NumberFormatInfo info) at System.UInt16.Parse(String s, NumberStyles style, IFormatProvider provider) at System.UInt16.Parse(String s) at Samples.UInt16Parse.Main() in C:\Books\BCL\Samples\System\UInt16\ Parse(System.String)\UInt16.cs:line 19 Exception: System.OverflowException: Value was either too large or too small for an Int16. at System.Int16.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Int16.Parse(String s) at Samples.UInt16Parse.Main() in C:\Books\BCL\Samples\System\UInt16\ Parse(System.String)\UInt16.cs:line 29
J K L M N O P Q R S
UInt16.Parse(System.String, System.Globalization.NumberStyles) Method
T [ILASM]
U
.method public hidebysig static unsigned int16 Parse(string s, valuetype System.Globalization.NumberStyles style)
V
[C#]
W
public static ushort Parse(string s, NumberStyles style)
X
Summary
Y
Returns the specified System.String converted to a System.UInt16 value.
Z
3541
Contents | Index
UInt16 Structure
System
Parse() Method
Parameters Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Integer style.
A B C D E F G
Return Value
H
The System.UInt16 value obtained from s.
I
Description
J
This version of System.UInt16.Parse is equivalent to System.UInt16.Parse (s, style, null). The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.] This method is not CLS-compliant. For a CLS-compliant alternative use System.Int32.Parse(System.String, NumberStyles).
K L M N O P
Exceptions
Q R
Exception
Condition
T
System.ArgumentNullException
s is a null reference.
U
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.UInt16.MaxValue or less than System.UInt16.MinValue.
S
V W X Y Z
3542
Contents | Index
System
UInt16 Structure Parse() Method
Example using System; using System.Globalization;
A namespace Samples { public class UInt16Parse { public static void Main() { string s; try { s = "$0"; Console.WriteLine( "String {0} yields {1}", s, UInt16.Parse(s, NumberStyles.AllowCurrencySymbol)); s = String.Format( "${0}", (UInt16.MaxValue).ToString()); Console.WriteLine( "String {0} yields {1}", s, UInt16.Parse(s, NumberStyles.AllowCurrencySymbol)); s = String.Format( "({0})", (UInt16.MinValue).ToString()); Console.WriteLine( "String {0} yields {1}", s, UInt16.Parse(s, NumberStyles.AllowParentheses)); s = String.Empty; Console.WriteLine("String {0} yields {1}", s, Int16.Parse(s, NumberStyles.Any)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = (UInt16.MaxValue + 1).ToString(); Console.WriteLine("String {0} yields {1}", s, UInt16.Parse(s, NumberStyles.Any));
B C D E F G H I J K L M N O P Q R S T U V W X Y Z
3543
Contents | Index
UInt16 Structure
System
Parse() Method
} catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A }
B }
C
}
D
The output is
E String $0 yields 0 String $65535 yields 65535 String (0) yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int16.Parse(String s, NumberStyles style, IFormatProvider provider) at System.Int16.Parse(String s, NumberStyles style) at Samples.UInt16Parse.Main() in C:\Books\BCL\Samples\System\UInt16\ Parse(System.String,System.Globalization.NumberStyles)\UInt16.cs:line 33 Exception: System.OverflowException: Value was either too large or too small for a UInt16. at System.UInt16.Parse(String s, NumberStyles style, IFormatProvider provider) at System.UInt16.Parse(String s, NumberStyles style) at Samples.UInt16Parse.Main() in C:\Books\BCL\Samples\System\UInt16\ Parse(System.String,System.Globalization.NumberStyles)\UInt16.cs:line 44
F G H I J K L M N O P
UInt16.Parse(System.String, System.Globalization.NumberStyles, System.IFormatProvider) Method
Q R
[ILASM]
.method public hidebysig static unsigned int16 Parse(string s, valuetype System.Globalization.NumberStyles style, class System.IFormatProvider provider)
S T
[C#]
public static ushort Parse(string s, NumberStyles style, IFormatProvider provider)
U V
Summary
W
Returns the specified System.String converted to a System.UInt16 value.
X Y Z
3544
Contents | Index
System
UInt16 Structure Parse() Method
Parameters Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Integer style.
A B C
provider
D E F
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
G H I
Return Value
J
The System.UInt16 value obtained from s.
K
Description
L
The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. This method is not CLS-compliant. For a CLS-compliant alternative use System.Int32.Parse(System.String, NumberStyles, System.IFormatProvider).
M N O P Q R
Exceptions
S T
Exception
Condition U
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.UInt16.MaxValue or less than System.UInt16.MinValue.
V W X Y Z
3545
Contents | Index
UInt16 Structure
System
Parse() Method
Example using System; using System.Globalization;
A namespace Samples { public class UInt16Parse { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; string s = String.Format(" ~{0}", UInt16.MaxValue); Console.WriteLine( "String {0} yields {1}", s, UInt16.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowLeadingSign, n)); s = "(0)"; Console.WriteLine( "String {0} yields {1}", s, UInt16.Parse(s, NumberStyles.AllowParentheses, n)); s = "!0"; Console.WriteLine( "Convert from String {0} yields {1}", s, UInt16.Parse(s, NumberStyles.Any, n)); } } }
B C D E F G H I J K L M N O P Q R S T U V
The output is
W String ~65535 yields 65535 String (0) yields 0 Convert from String !0 yields 0
X Y Z
3546
Contents | Index
System
UInt16 Structure Parse() Method
UInt16.Parse(System.String, System.IFormatProvider) Method [ILASM]
.method public hidebysig static unsigned int16 Parse(string s, class System.IFormatProvider provider)
A
[C#]
B
public static ushort Parse(string s, IFormatProvider provider)
C
Summary
D
Returns the specified System.String converted to a System.UInt16 value.
E F
Parameters
G
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Integer style.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
H I J K L M N
Return Value
O
The System.UInt16 value obtained from s.
P
Description
Q
This version of System.UInt16.Parse is equivalent to System.UInt16.Parse(s, NumberStyles.Integer, provider). The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. This method is not CLS-compliant. For a CLS-compliant alternative use System.Int32.Parse(System.String,System.IFormatProvider).
R S T U V W X Y Z
3547
Contents | Index
UInt16 Structure
System
Parse() Method
Exceptions Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.UInt16.MaxValue or less than System.UInt16.MinValue.
A B C D E F G
Example
H
using System; using System.Globalization;
I J
namespace Samples { public class UInt16Parse { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; try { s = "~0"; Console.WriteLine("String {0} yields {1}", s, UInt16.Parse(s, n)); s = (UInt16.MaxValue).ToString(); Console.WriteLine("String {0} yields {1}", s, UInt16.Parse(s, n)); s = "!0"; Console.WriteLine("String {0} yields {1}", s, UInt16.Parse(s, n)); s = String.Empty; Console.WriteLine("String {0} yields {1}", s, UInt16.Parse(s, n)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e);
K L M N O P Q R S T U V W X Y Z
3548
Contents | Index
System
UInt16 Structure ToString() Method
} try { s = (UInt16.MaxValue + 1).ToString(); Console.WriteLine("String {0} yields {1}", s, UInt16.Parse(s, n)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E
}
F
} }
G
The output is
H I
String ~0 yields 0 String 65535 yields 65535 String !0 yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseUInt32(String s, NumberStyles style, NumberFormatInfo info) at System.UInt16.Parse(String s, NumberStyles style, IFormatProvider provider) at System.UInt16.Parse(String s, IFormatProvider provider) at Samples.UInt16Parse.Main() in C:\Books\BCL\Samples\System\UInt16\ Parse(System.String,System.IFormatProvider)\UInt16.cs:line 27 Exception: System.OverflowException: Value was either too large or too small for a UInt16. at System.UInt16.Parse(String s, NumberStyles style, IFormatProvider provider) at System.UInt16.Parse(String s, IFormatProvider provider) at Samples.UInt16Parse.Main() in C:\Books\BCL\Samples\System\UInt16\ Parse(System.String,System.IFormatProvider)\UInt16.cs:line 37
J K L M N O P Q R S T
UInt16.ToString() Method
U
[ILASM]
V
.method public hidebysig virtual string ToString()
W
[C#]
public override string ToString()
X
Summary
Y
Returns a System.String representation of the value of the current instance.
Z
3549
Contents | Index
UInt16 Structure
System
ToString() Method
Return Value A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the current system culture. A B
Description
C
This version of System.UInt16.ToString is equivalent to System.UInt16.ToString(null, null). [Note: This method overrides System.Object.ToString.]
D E F
Example
G
using System; using System.Globalization;
H namespace Samples { public class UInt16ToString { public static void Main() { ushort max = ushort.MaxValue, min = ushort.MinValue; Console.WriteLine("{0}.ToString() yields {1}", max, max.ToString()); Console.WriteLine("{0}.ToString() yields {1}", min, min.ToString()); } } }
I J K L M N O P Q R
The output is
S
65535.ToString() yields 65535 0.ToString() yields 0
T U V
UInt16.ToString(System.String) Method
W
[ILASM]
X
.method public hidebysig instance string ToString(string format) [C#]
Y
public string ToString(string format)
Z
Summary Returns a System.String representation of the value of the current instance. 3550
Contents | Index
System
UInt16 Structure ToString() Method
Parameters Parameter
Description
format
A System.String that specifies the format of the returned string. [Note: For a list of valid values, see System.UInt16.ToString(System.String, System.IFormatProvider).]
A B C D
Return Value
E
A System.String representation of the current instance formatted as specified by format. The string takes into account the current system culture.
F G
Description
H
This method is equivalent to System.UInt16.ToString(format, null). If format is a null reference, the general format specifier “G” is used.
I J K
Exceptions
L
Exception
Condition
System.FormatException
format is invalid.
M N O P
Example
Q
using System; using System.Globalization;
R S
namespace Samples { public class UInt16ToString { public static void Main() { ushort max = ushort.MaxValue, min = ushort.MinValue; string[] formats = {"C", "c", "D", "d", "E", "e", "F", "f", "G", "g", "N", "n", "P", "p", "X", "x"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\") yields {2}", max, f, max.ToString(f)); foreach(string f in formats)
T U V W X Y Z
3551
Contents | Index
UInt16 Structure
System
ToString() Method
Console.WriteLine("{0}.ToString(\"{1}\") yields {2}", min, f, min.ToString(f)); } }
A
}
B
The output is
C 65535.ToString("C") yields $65,535.00 65535.ToString("c") yields $65,535.00 65535.ToString("D") yields 65535 65535.ToString("d") yields 65535 65535.ToString("E") yields 6.553500E+004 65535.ToString("e") yields 6.553500e+004 65535.ToString("F") yields 65535.00 65535.ToString("f") yields 65535.00 65535.ToString("G") yields 65535 65535.ToString("g") yields 65535 65535.ToString("N") yields 65,535.00 65535.ToString("n") yields 65,535.00 65535.ToString("P") yields 6,553,500.00 % 65535.ToString("p") yields 6,553,500.00 % 65535.ToString("X") yields FFFF 65535.ToString("x") yields ffff 0.ToString("C") yields $0.00 0.ToString("c") yields $0.00 0.ToString("D") yields 0 0.ToString("d") yields 0 0.ToString("E") yields 0.000000E+000 0.ToString("e") yields 0.000000e+000 0.ToString("F") yields 0.00 0.ToString("f") yields 0.00 0.ToString("G") yields 0 0.ToString("g") yields 0 0.ToString("N") yields 0.00 0.ToString("n") yields 0.00 0.ToString("P") yields 0.00 % 0.ToString("p") yields 0.00 % 0.ToString("X") yields 0 0.ToString("x") yields 0
D E F G H I J K L M N O P Q R S T U V W X
UInt16.ToString(System.String, System.IFormatProvider) Method
Y
[ILASM]
Z
.method public final hidebysig virtual string ToString(string format, class System.IFormatProvider provider) [C#]
public string ToString(string format, IFormatProvider provider)
3552
Contents | Index
System
UInt16 Structure ToString() Method
Summary Returns a System.String representation of the value of the current instance. A
Parameters
B
Parameter
Description
format
A System.String containing a character that specifies the format of the returned string.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo instance containing culture-specific formatting information.
C D E F G H
Return Value
I
A System.String representation of the current instance formatted as specified by format. The string takes into account the formatting information in the System.Globalization.NumberFormatInfo instance supplied by provider.
J K L
Description
M
If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. If format is a null reference, the general format specifier “G” is used. [Note: For a detailed description of formatting, see the System.IFormattable interface. This method is implemented to support the System.IFormattable interface.] The following table lists the characters that are valid for the System.UInt16 type.
N O P Q R
Format Characters
Description
S
"C", "c"
Currency format.
T
"D", "d"
Decimal format.
U
"E", "e"
Exponential notation format.
V
"F", "f"
Fixed-point format.
"G", "g"
General format.
"N", "n"
Number format.
"P", "p"
Percent format.
"X", "x"
Hexadecimal format.
W X Y Z
3553
Contents | Index
UInt16 Structure
System
ToString() Method
Exceptions Exception
Condition
System.FormatException
format is invalid.
A B C D
Example
E
using System; using System.Globalization;
F namespace Samples { public class UInt16ToString { public static void Main() { ushort max = ushort.MaxValue, min = ushort.MinValue; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; n.CurrencySymbol = "#"; string[] formats = {"C", "c", "D", "d", "E", "F", "f", "G", "g", "N", "P", "p", "X", "x"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\",n) max, f, max.ToString(f, foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\",n) min, f, min.ToString(f, } } }
G H I J K L M N O P Q R S T U V
"e", "n",
yields {2}", n)); yields {2}", n));
The output is
W
65535.ToString("C",n) 65535.ToString("c",n) 65535.ToString("D",n) 65535.ToString("d",n) 65535.ToString("E",n) 65535.ToString("e",n) 65535.ToString("F",n)
X Y Z
yields yields yields yields yields yields yields
#65,535.00 #65,535.00 65535 65535 6.553500E~004 6.553500e~004 65535.00
3554
Contents | Index
System
UInt16 Structure ToString() Method
65535.ToString("f",n) yields 65535.00 65535.ToString("G",n) yields 65535 65535.ToString("g",n) yields 65535 65535.ToString("N",n) yields 65,535.00 65535.ToString("n",n) yields 65,535.00 65535.ToString("P",n) yields 6,553,500.00 % 65535.ToString("p",n) yields 6,553,500.00 % 65535.ToString("X",n) yields FFFF 65535.ToString("x",n) yields ffff 0.ToString("C",n) yields #0.00 0.ToString("c",n) yields #0.00 0.ToString("D",n) yields 0 0.ToString("d",n) yields 0 0.ToString("E",n) yields 0.000000E~000 0.ToString("e",n) yields 0.000000e~000 0.ToString("F",n) yields 0.00 0.ToString("f",n) yields 0.00 0.ToString("G",n) yields 0 0.ToString("g",n) yields 0 0.ToString("N",n) yields 0.00 0.ToString("n",n) yields 0.00 0.ToString("P",n) yields 0.00 % 0.ToString("p",n) yields 0.00 % 0.ToString("X",n) yields 0 0.ToString("x",n) yields 0
A B C D E F G H I J K L M N O
UInt16.ToString(System.IFormatProvider) Method
P
[ILASM]
Q
.method public final hidebysig virtual string ToString(class System.IFormatProvider provider)
R
[C#]
S
public string ToString(IFormatProvider provider)
T
Summary
U
Returns a System.String representation of the value of the current instance.
V W
Parameters
X
Parameter
Description
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
Y Z
3555
Contents | Index
UInt16 Structure
System
ToString() Method
Return Value A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the formatting information in the System.Globalization.NumberFormatInfo instance supplied by provider.
A B
Description
C
This version of System.UInt16.ToString is equivalent to System.UInt16.ToString(“G”, provider). If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used.
D E F G
Example
H
using System; using System.Globalization;
I J
namespace Samples { public class UInt16ToString { public static void Main() { ushort max = ushort.MaxValue, min = ushort.MinValue; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; Console.WriteLine("{0}.ToString yields {1}", max, max.ToString(n)); Console.WriteLine("{0}.ToString yields {1}", min, min.ToString(n)); } } }
K L M N O P Q R S T U V
The output is
W 65535.ToString yields 65535 0.ToString yields 0
X Y Z
3556
Contents | Index
System
UInt16 Structure ToChar() Method
IConvertible.ToBoolean(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual bool System.IConvertible.ToBoolean(class System.IFormatProvider provider)
A
[C#]
B
bool IConvertible.ToBoolean(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToBoolean.]
E F G
IConvertible.ToByte(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual unsigned int8 System.IConvertible.ToByte(class System.IFormatProvider provider)
J
[C#]
K
byte IConvertible.ToByte(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToByte.]
N O P
IConvertible.ToChar(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual valuetype System.Char System.IConvertible.ToChar(class System.IFormatProvider provider)
S
[C#]
T
char IConvertible.ToChar(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToChar.]
W X Y Z
3557
Contents | Index
UInt16 Structure
System
ToDateTime() Method
IConvertible.ToDateTime(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual valuetype System.DateTime System.IConvertible.ToDateTime(class System.IFormatProvider provider)
B
[C#]
DateTime IConvertible.ToDateTime(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDateTime.]
F G H
IConvertible.ToDecimal(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual decimal System.IConvertible.ToDecimal(class System.IFormatProvider provider)
K
[C#]
decimal IConvertible.ToDecimal(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDecimal.]
O P Q
IConvertible.ToDouble(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual float64 System.IConvertible.ToDouble(class System.IFormatProvider provider)
T
[C#]
double IConvertible.ToDouble(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDouble.]
X Y Z
3558
Contents | Index
System
UInt16 Structure ToInt64() Method
IConvertible.ToInt16(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual int16 System.IConvertible.ToInt16(class System.IFormatProvider provider)
A
[C#]
B
short IConvertible.ToInt16(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt16.]
E F G
IConvertible.ToInt32(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual int32 System.IConvertible.ToInt32(class System.IFormatProvider provider)
J
[C#]
K
int IConvertible.ToInt32(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt32.]
N O P
IConvertible.ToInt64(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual int64 System.IConvertible.ToInt64(class System.IFormatProvider provider)
S
[C#]
T
long IConvertible.ToInt64(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt64.]
W X Y Z
3559
Contents | Index
UInt16 Structure
System
ToSByte() Method
IConvertible.ToSByte(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual int8 System.IConvertible.ToSByte(class System.IFormatProvider provider)
B
[C#]
sbyte IConvertible.ToSByte(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSByte.]
F G H
IConvertible.ToSingle(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual float32 System.IConvertible.ToSingle(class System.IFormatProvider provider)
K
[C#]
float IConvertible.ToSingle(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSingle.]
O P Q
IConvertible.ToType(System.Type, System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual object System.IConvertible.ToType(class System.Type type, class System.IFormatProvider provider)
T
[C#]
object IConvertible.ToType(Type type, IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToType.]
X Y Z
3560
Contents | Index
System
UInt16 Structure ToUInt64() Method
IConvertible.ToUInt16(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual unsigned int16 System.IConvertible.ToUInt16(class System.IFormatProvider provider)
A
[C#]
B
ushort IConvertible.ToUInt16(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt16.] This member is not CLS-compliant.
E F G
IConvertible.ToUInt32(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual unsigned int32 System.IConvertible.ToUInt32(class System.IFormatProvider provider)
J
[C#]
K
uint IConvertible.ToUInt32(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt32.] This member is not CLS-compliant.
N O P
IConvertible.ToUInt64(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual unsigned int64 System.IConvertible.ToUInt64(class System.IFormatProvider provider)
S
[C#]
T
ulong IConvertible.ToUInt64(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt64.] This member is not CLS-compliant.
W X Y Z
3561
Contents | Index
System UInt32 Structure
BCL
Object
A
ValueType
B
UInt32
C
IComparable IFormattable IConvertible
NotStandardized
D
Summary
E
Represents a 32-bit unsigned integer. This type is not CLS-compliant.
F
Type Summary
G
public struct UInt32 : IComparable, IFormattable, IConvertible { // Fields public const uint MaxValue = 4294967295; public const uint MinValue = 0;
H I J K L
// Methods public int CompareTo (object value); public override bool Equals (object obj); public override int GetHashCode (); MS public TypeCode GetTypeCode (); public static uint Parse (string s); public static uint Parse (string s, NumberStyles style); public static uint Parse (string s, NumberStyles style, IFormatProvider provider); CF public static uint Parse (string s, IFormatProvider provider); public override string ToString (); public string ToString (string format); public string ToString (string format, IFormatProvider provider); public string ToString (IFormatProvider provider);
M N O P Q R S T U
// MS MS MS MS MS MS MS MS MS MS
V W X Y Z
Explicit Interface Members bool IConvertible.ToBoolean(IFormatProvider provider); byte IConvertible.ToByte(IFormatProvider provider); char IConvertible.ToChar(IFormatProvider provider); DateTime IConvertible.ToDateTime(IFormatProvider provider); decimal IConvertible.ToDecimal(IFormatProvider provider); double IConvertible.ToDouble(IFormatProvider provider); short IConvertible.ToInt16(IFormatProvider provider); int IConvertible.ToInt32(IFormatProvider provider); long IConvertible.ToInt64(IFormatProvider provider); sbyte IConvertible.ToSByte(IFormatProvider provider);
3562
Contents | Index
System
UInt32 Structure UInt32 Structure
MS MS MS MS MS
float IConvertible.ToSingle(IFormatProvider provider); object IConvertible.ToType(Type type,IFormatProvider provider); ushort IConvertible.ToUInt16(IFormatProvider provider); uint IConvertible.ToUInt32(IFormatProvider provider); ulong IConvertible.ToUInt64(IFormatProvider provider);
A
}
B C
Description
D
The System.UInt32 data type represents integer values ranging from 0 to positive 4,294,967,295 (hexadecimal 0xFFFFFFFF).
E F
Example
G
using System;
H namespace Samples { public class UInt32Sample { public static void Main() { uint max = uint.MaxValue, min = uint.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); Console.WriteLine("Is {0} equal to {1}: {2}", max, max, max.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", max, min, max.Equals(min)); Console.WriteLine("{0} has hashcode of: {1}", max, max.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", min, min.GetHashCode()); string s = max.ToString(); Console.WriteLine("\"{0}\" parsed from string yields: {1}", s, UInt32.Parse(s)); s = min.ToString(); Console.WriteLine("\"{0}\" parsed from string yields: {1}", s, UInt32.Parse(s)); string[] formats = {"c", "d", "e", "f", "g", "n", "p", "x" }; foreach(string f in formats) Console.WriteLine("Format {0}: {1}", f, max.ToString(f)); } } }
I J K L M N O P Q R S T U V W X Y Z
3563
Contents | Index
UInt32 Structure
System
MaxValue Field
The output is MaxValue: 4294967295 MinValue: 0 Is 4294967295 equal to 4294967295: True Is 4294967295 equal to 0: False 4294967295 has hashcode of: -1 0 has hashcode of: 0 "4294967295" parsed from string yields: 4294967295 "0" parsed from string yields: 0 Format c: $4,294,967,295.00 Format d: 4294967295 Format e: 4.294967e+009 Format f: 4294967295.00 Format g: 4294967295 Format n: 4,294,967,295.00 Format p: 429,496,729,500.00 % Format x: ffffffff
A B C D E F G H I J K
UInt32.MaxValue Field
L
[ILASM]
M
.field public static literal unsigned int32 MaxValue [C#]
N
public const uint MaxValue = 4294967295
O P
Summary
Q
Contains the maximum value for the System.UInt32 type.
R
Description
S
The value of this constant is 4,294,967,295 (hexadecimal 0xFFFFFFFF).
T
Example
U
using System;
V
namespace Samples { public class UInt32MaxValue { public static void Main() { uint max = uint.MaxValue, min = uint.MinValue;
W X Y Z
3564
Contents | Index
System
UInt32 Structure MinValue Field
Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); } }
A
}
B
The output is
C
MaxValue: 4294967295 MinValue: 0
D E F
UInt32.MinValue Field
G
[ILASM]
H
.field public static literal unsigned int32 MinValue
I
[C#]
public const uint MinValue = 0
J
Summary
K
Contains the minimum value for the System.UInt32 type.
L M
Description
N
The value of this constant is 0.
O
Example
P
using System;
Q
namespace Samples { public class UInt32MinValue { public static void Main() { uint max = uint.MaxValue, min = uint.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); } } }
R S T U V W X Y Z
3565
Contents | Index
UInt32 Structure
System
CompareTo() Method
The output is MaxValue: 4294967295 MinValue: 0
A B C
UInt32.CompareTo(System.Object) Method
D
[ILASM]
.method public final hidebysig virtual int32 CompareTo(object value)
E
[C#]
public int CompareTo(object value)
F G
Summary
H
Returns the sort order of the current instance compared to the specified System.Object.
I
Parameters
J K
Parameter
Description
value
The System.Object to compare to the current instance.
L M N O
Return Value
P
A System.Int32 containing a value that reflects the sort order of the current instance as compared to value. The following table defines the conditions under which the return value is a negative number, zero, or a positive number.
Q R S
Return Value
Description
U
any negative number
Current instance < value.
V
zero
Current instance == value.
any positive number
Current instance > value, or value is a null reference.
T
W X Y
Description
Z
[Note: This method is implemented to support the System.IComparable interface.]
3566
Contents | Index
System
UInt32 Structure CompareTo() Method
Exceptions Exception
Condition
System.ArgumentException
value is not a System.UInt32 and is not a null reference.
A B C
Example
D
using System;
E
namespace Samples { public class UInt32CompareTo { private static string CompareUInt32s(uint u1, uint u2) { int i = u1.CompareTo(u2); if(0 == i) return String.Format("{0} is equal to {1}", u1, u2); if(i > 0) return String.Format("{0} is greater than {1}", u1, u2); else return String.Format("{0} is less than {1}", u1, u2); } public static void Main() { uint max = uint.MaxValue, min = uint.MinValue; Console.WriteLine(CompareUInt32s(min, min)); Console.WriteLine(CompareUInt32s(min, max)); Console.WriteLine(CompareUInt32s(max, min)); } } }
F G H I J K L M N O P Q R S T U
The output is
V 0 is equal to 0 0 is less than 4294967295 4294967295 is greater than 0
W X Y Z
3567
Contents | Index
UInt32 Structure
System
Equals() Method
UInt32.Equals(System.Object) Method [ILASM]
.method public hidebysig virtual bool Equals(object obj)
A
[C#]
public override bool Equals(object obj)
B C
Summary
D
Determines whether the current instance and the specified System.Object represent the same type and value.
E F
Parameters
G H
Parameter
Description
obj
The System.Object to compare to the current instance.
I J K
Return Value
L
true if obj represents the same type and value as the current instance. If obj is a null reference or is not an instance of System.UInt32, returns false.
M N
Description
O
[Note: This method overrides System.Object.Equals.]
P Q
Example
R
using System;
S
namespace Samples { public class UInt32Equals { public static void Main() { uint max = uint.MaxValue, min = uint.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); Console.WriteLine("Is {0} equal to {1}: {2}", max, max, max.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", max, min, max.Equals(min));
T U V W X Y Z
3568
Contents | Index
System
UInt32 Structure GetHashCode() Method
Console.WriteLine("Is {0} equal to {1}: {2}", min, max, min.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", min, min, min.Equals(min));
A
} }
B
}
C
The output is
D E
MaxValue: 4294967295 MinValue: 0 Is 4294967295 equal to 4294967295: True Is 4294967295 equal to 0: False Is 0 equal to 4294967295: False Is 0 equal to 0: True
F G H I J
UInt32.GetHashCode() Method
K [ILASM]
L
.method public hidebysig virtual int32 GetHashCode() [C#]
M
public override int GetHashCode()
N
Summary
O
Generates a hash code for the current instance.
P
Return Value
Q
A System.Int32 containing the hash code for the current instance.
R S
Description
T
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
U V
Example
W
using System;
X
namespace Samples { public class UInt32GetHashCode { public static void Main()
Y Z
3569
Contents | Index
UInt32 Structure
System
GetTypeCode() Method
{ uint max = uint.MaxValue, min = uint.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); Console.WriteLine("{0} has hashcode of: {1}", max, max.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", min, min.GetHashCode());
A B C D
} }
E }
F
The output is
G H
MaxValue: 4294967295 MinValue: 0 4294967295 has hashcode of: -1 0 has hashcode of: 0
I J K L
UInt32.GetTypeCode() Method
M
[ILASM]
N
.method public final hidebysig virtual valuetype System.TypeCode GetTypeCode() [C#]
O
public TypeCode GetTypeCode()
P
Summary
Q
Returns the System.TypeCode for value type System.UInt32.
R S T
UInt32.Parse(System.String) Method
U
[ILASM]
.method public hidebysig static unsigned int32 Parse(string s)
V
[C#]
public static uint Parse(string s)
W X
Summary
Y
Returns the specified System.String converted to a System.UInt32 value.
Z
3570
Contents | Index
System
UInt32 Structure Parse() Method
Parameters Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Integer style.
A B C D
Return Value
E
The System.UInt32 value obtained from s.
F
Description
G
This version of System.UInt32.Parse is equivalent to System.UInt32.Parse (s, System.Globalization.NumberStyles.Integer, null). The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.] This method is not CLS-compliant. For a CLS-compliant alternative use System.Int64.Parse(System.String).
H I J K L M
Exceptions Exception
N O
Condition
P System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.UInt32.MaxValue or less than System.UInt32.MinValue.
Q R S T U V
Example
W
using System;
X
namespace Samples { public class UInt32Parse { public static void Main() {
Y Z
3571
Contents | Index
UInt32 Structure
System
Parse() Method
string s; try { s = (UInt32.MaxValue).ToString(); Console.WriteLine("String {0} yields {1}", s, UInt32.Parse(s)); s = (UInt32.MinValue).ToString(); Console.WriteLine("String {0} yields {1}", s, UInt32.Parse(s)); s = String.Empty; Console.WriteLine("String {0} yields {1}", s, UInt32.Parse(s)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = ((Int64)UInt32.MaxValue + 1).ToString(); Console.WriteLine("String {0} yields {1}", s, UInt32.Parse(s)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E F G H I J K L M N O
} }
P }
Q
The output is
R S
String 4294967295 yields 4294967295 String 0 yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseUInt32(String s, NumberStyles style, NumberFormatInfo info) at System.UInt32.Parse(String s) at Samples.UInt32Parse.Main() in C:\Books\BCL\Samples\System\UInt32\ Parse(System.String)\UInt32.cs:line 19 Exception: System.OverflowException: Value was either too large or too small for a UInt32. at System.Number.ParseUInt32(String s, NumberStyles style, NumberFormatInfo info) at System.UInt32.Parse(String s) at Samples.UInt32Parse.Main() in C:\Books\BCL\Samples\System\UInt32\ Parse(System.String)\UInt32.cs:line 29
T U V W X Y Z
3572
Contents | Index
System
UInt32 Structure Parse() Method
UInt32.Parse(System.String, System.Globalization.NumberStyles) Method [ILASM]
.method public hidebysig static unsigned int32 Parse(string s, valuetype System.Globalization.NumberStyles style)
A
[C#]
B
public static uint Parse(string s, NumberStyles style)
C
Summary
D
Returns the specified System.String converted to a System.UInt32 value.
E F
Parameters
G
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Integer style.
H I J K L M N
Return Value
O
The System.UInt32 value obtained from s.
P Q
Description
R
This version of System.UInt32.Parse is equivalent to System.UInt32.Parse(s, style, null). The string is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.] This method is not CLS-compliant. For a CLS-compliant alternative use System.Int64.Parse(System.String, System.Globalization.NumberStyles).
S T U V W X Y Z
3573
Contents | Index
UInt32 Structure
System
Parse() Method
Exceptions Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.UInt32.MaxValue or less than System.UInt32.MinValue.
A B C D E F G
Example
H
using System; using System.Globalization;
I J
namespace Samples { public class UInt32Parse { public static void Main() { string s; try { s = "$0"; Console.WriteLine( "String {0} yields {1}", s, UInt32.Parse(s, NumberStyles.AllowCurrencySymbol)); s = String.Format( "${0}", (UInt32.MaxValue).ToString()); Console.WriteLine( "String {0} yields {1}", s, UInt32.Parse(s, NumberStyles.AllowCurrencySymbol)); s = String.Format( "({0})", (UInt32.MinValue).ToString()); Console.WriteLine( "String {0} yields {1}", s, UInt32.Parse(s, NumberStyles.AllowParentheses)); s = String.Empty;
K L M N O P Q R S T U V W X Y Z
3574
Contents | Index
System
UInt32 Structure Parse() Method
Console.WriteLine( "String {0} yields {1}", s, UInt32.Parse(s, NumberStyles.Any));
A
} catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = ((Int64) UInt32.MaxValue + 1).ToString(); Console.WriteLine("String {0} yields {1}", s, UInt32.Parse(s, NumberStyles.Any)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
B C D E F G H I J K
} }
L
}
M
The output is
N
String $0 yields 0 String $4294967295 yields 4294967295 String (0) yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseUInt32(String s, NumberStyles style, NumberFormatInfo info) at System.UInt32.Parse(String s, NumberStyles style) at Samples.UInt32Parse.Main() in C:\Books\BCL\Samples\System\UInt32\ Parse(System.String,System.Globalization.NumberStyles)\UInt32.cs:line 33 Exception: System.OverflowException: Value was either too large or too small for a UInt32. at System.Number.ParseUInt32(String s, NumberStyles style, NumberFormatInfo info) at System.UInt32.Parse(String s, NumberStyles style) at Samples.UInt32Parse.Main() in C:\Books\BCL\Samples\System\UInt32\ Parse(System.String,System.Globalization.NumberStyles)\UInt32.cs:line 45
O P Q R S T U V W X Y Z
3575
Contents | Index
UInt32 Structure
System
Parse() Method
UInt32.Parse(System.String, System.Globalization.NumberStyles, System.IFormatProvider) Method [ILASM]
A
.method public hidebysig static unsigned int32 Parse(string s, valuetype System.Globalization.NumberStyles style, class System.IFormatProvider provider)
B
[C#]
C
public static uint Parse(string s, NumberStyles style, IFormatProvider provider)
D
Summary
E
Returns the specified System.String converted to a System.UInt32 value.
F G
Parameters
H I J
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Integer style.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
K L M N O P Q R
Return Value
S
The System.UInt32 value obtained from s.
T
Description
U
The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. This method is not CLS-compliant. For a CLS-compliant alternative use System.Int64.Parse(System.String, System.Globalization.NumberStyles, System.IFormatProvider).
V W X Y Z
3576
Contents | Index
System
UInt32 Structure Parse() Method
Exceptions Exception
Condition
System.ArgumentNullException
s is a null reference.
B
System.FormatException
s is not in the correct style.
C
System.OverflowException
s represents a number greater than System.UInt32.MaxValue or less than System.UInt32.MinValue.
A
D E F
Example
G
using System; using System.Globalization;
H I
namespace Samples { public class UInt32Parse { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; string s = " ~0"; Console.WriteLine( "String {0} yields {1}", s, UInt32.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowLeadingSign, n)); s = "(0)"; Console.WriteLine( "String {0} yields {1}", s, UInt32.Parse(s, NumberStyles.AllowParentheses, n)); s = String.Format(" ~{0} ", UInt32.MaxValue); Console.WriteLine( "String {0} yields {1}", s, UInt32.Parse(s, NumberStyles.Any, n)); } } }
J K L M N O P Q R S T U V W X Y Z
3577
Contents | Index
UInt32 Structure
System
Parse() Method
The output is String ~0 yields 0 String (0) yields 0 String ~4294967295 yields 4294967295
A B C
UInt32.Parse(System.String, System.IFormatProvider) Method
D
[ILASM]
E
.method public hidebysig static unsigned int32 Parse(string s, class System.IFormatProvider provider)
F
[C#]
G
public static uint Parse(string s, IFormatProvider provider)
H
Summary
I
Returns the specified System.String converted to a System.UInt32 value.
J K
Parameters
L M N
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Integer style.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
O P Q R S
Return Value
T
The System.UInt32 value obtained from s.
U
Description
V
This version of System.UInt32.Parse is equivalent to System.UInt32.Parse(s, System.Globalization.NumberStyles.Integer, provider). The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. This method is not CLS-compliant. For a CLS-compliant alternative use System.Int64.Parse(System.String, System.IFormatProvider).
W X Y Z
3578
Contents | Index
System
UInt32 Structure Parse() Method
Exceptions Exception
Condition A
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.UInt32.MaxValue or less than System.UInt32.MinValue.
B C D E F G
Example
H
using System; using System.Globalization;
I J
namespace Samples { public class UInt32Parse { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; try { s = "~0"; Console.WriteLine("String {0} yields {1}", s, UInt32.Parse(s, n)); s = (UInt32.MaxValue).ToString(); Console.WriteLine("String {0} yields {1}", s, UInt32.Parse(s, n)); s = "!0"; Console.WriteLine("String {0} yields {1}", s, UInt32.Parse(s, n)); s = String.Empty; Console.WriteLine("String {0} yields {1}", s, UInt32.Parse(s, n)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); }
K L M N O P Q R S T U V W X Y Z
3579
Contents | Index
UInt32 Structure
System
ToString() Method
try { s = ((Int64)UInt32.MaxValue + 1).ToString(); Console.WriteLine("String {0} yields {1}", s, UInt32.Parse(s, n)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D }
E }
F
}
G
The output is
H String ~0 yields 0 String 4294967295 yields 4294967295 String !0 yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseUInt32(String s, NumberStyles style, NumberFormatInfo info) at System.UInt32.Parse(String s, IFormatProvider provider) at Samples.UInt32Parse.Main() in C:\Books\BCL\Samples\System\UInt32\ Parse(System.String,System.IFormatProvider)\UInt32.cs:line 27 Exception: System.OverflowException: Value was either too large or too small for a UInt32. at System.Number.ParseUInt32(String s, NumberStyles style, NumberFormatInfo info) at System.UInt32.Parse(String s, IFormatProvider provider) at Samples.UInt32Parse.Main() in C:\Books\BCL\Samples\System\UInt32\ Parse(System.String,System.IFormatProvider)\UInt32.cs:line 37
I J K L M N O P Q R S
UInt32.ToString() Method
T
[ILASM]
.method public hidebysig virtual string ToString()
U
[C#]
public override string ToString()
V W
Summary
X
Returns a System.String representation of the value of the current instance.
Y
Return Value
Z
A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the current system culture.
3580
Contents | Index
System
UInt32 Structure ToString() Method
Description This version of System.UInt32.ToString is equivalent to System.UInt32.ToString(null, null). [Note: This method overrides System.Object.ToString.]
A B
Example
C
using System; using System.Globalization;
D E
namespace Samples { public class UInt32ToString { public static void Main() { uint max = uint.MaxValue, min = uint.MinValue; Console.WriteLine("{0}.ToString() yields {1}", max, max.ToString()); Console.WriteLine("{0}.ToString() yields {1}", min, min.ToString()); } } }
F G H I J K L M N O
The output is
P 4294967295.ToString() yields 4294967295 0.ToString() yields 0
Q R S
UInt32.ToString(System.String) Method
T [ILASM]
U
.method public hidebysig instance string ToString(string format) [C#]
V
public string ToString(string format)
W
Summary
X
Returns a System.String representation of the value of the current instance.
Y Z
3581
Contents | Index
UInt32 Structure
System
ToString() Method
Parameters Parameter
Description
format
A System.String that specifies the format of the returned string. [Note: For a list of valid values, see System.UInt32.ToString(System.String, System.IFormatProvider).]
A B C D E
Return Value
F
A System.String representation of the current instance formatted as specified by format. The string takes into account the current system culture.
G H
Description
I
This method is equivalent to System.UInt32.ToString(format, null). If format is a null reference, the general format specifier “G” is used.
J K
Exceptions
L M N
Exception
Condition
System.FormatException
format is invalid.
O P
Example
Q
using System; using System.Globalization;
R S
namespace Samples { public class UInt32ToString { public static void Main() { uint max = uint.MaxValue, min = uint.MinValue; string[] formats = {"C", "c", "D", "d", "E", "e", "F", "f", "G", "g", "N", "n", "P", "p", "X", "x"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\") yields {2}", max, f, max.ToString(f)); foreach(string f in formats)
T U V W X Y Z
3582
Contents | Index
System
UInt32 Structure ToString() Method
Console.WriteLine("{0}.ToString(\"{1}\") yields {2}", min, f, min.ToString(f)); } }
A
}
B
The output is
C 4294967295.ToString("C") yields $4,294,967,295.00 4294967295.ToString("c") yields $4,294,967,295.00 4294967295.ToString("D") yields 4294967295 4294967295.ToString("d") yields 4294967295 4294967295.ToString("E") yields 4.294967E+009 4294967295.ToString("e") yields 4.294967e+009 4294967295.ToString("F") yields 4294967295.00 4294967295.ToString("f") yields 4294967295.00 4294967295.ToString("G") yields 4294967295 4294967295.ToString("g") yields 4294967295 4294967295.ToString("N") yields 4,294,967,295.00 4294967295.ToString("n") yields 4,294,967,295.00 4294967295.ToString("P") yields 429,496,729,500.00 % 4294967295.ToString("p") yields 429,496,729,500.00 % 4294967295.ToString("X") yields FFFFFFFF 4294967295.ToString("x") yields ffffffff 0.ToString("C") yields $0.00 0.ToString("c") yields $0.00 0.ToString("D") yields 0 0.ToString("d") yields 0 0.ToString("E") yields 0.000000E+000 0.ToString("e") yields 0.000000e+000 0.ToString("F") yields 0.00 0.ToString("f") yields 0.00 0.ToString("G") yields 0 0.ToString("g") yields 0 0.ToString("N") yields 0.00 0.ToString("n") yields 0.00 0.ToString("P") yields 0.00 % 0.ToString("p") yields 0.00 % 0.ToString("X") yields 0 0.ToString("x") yields 0
D E F G H I J K L M N O P Q R S T U V W
UInt32.ToString(System.String, System.IFormatProvider) Method
X
[ILASM]
Y
.method public final hidebysig virtual string ToString(string format, class System.IFormatProvider provider)
Z
[C#]
public string ToString(string format, IFormatProvider provider)
3583
Contents | Index
UInt32 Structure
System
ToString() Method
Summary Returns a System.String representation of the value of the current instance. A
Parameters
B C D
Parameter
Description
format
A System.String containing a character that specifies the format of the returned string.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo instance containing culture-specific formatting information.
E F G H
Return Value
I
A System.String representation of the current instance formatted as specified by format. The string takes into account the formatting information in the System.Globalization.NumberFormatInfo instance supplied by provider.
J K
Description
L
If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. If format is a null reference the general format specifier “G” is used. [Note: For a detailed description of formatting, see the System.IFormattable interface. This method is implemented to support the System.IFormattable interface.] The following table lists the characters that are valid for the System.UInt32 type.
M N O P Q R
Format Characters
Description
"C", "c"
Currency format.
"D", "d"
Decimal format.
"E", "e"
Exponential notation format.
W
"F", "f"
Fixed-point format.
X
"G", "g"
General format.
Y
"N", "n"
Number format.
Z
"P", "p"
Percent format.
"X", "x"
Hexadecimal format.
S T U V
3584
Contents | Index
System
UInt32 Structure ToString() Method
Exceptions Exception
Condition
System.FormatException
format is invalid.
A B C
Example
D
using System; using System.Globalization;
E F
namespace Samples { public class UInt32ToString { public static void Main() { uint max = uint.MaxValue, min = uint.MinValue; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; n.CurrencySymbol = "#"; string[] formats = {"C", "c", "D", "d", "E", "F", "f", "G", "g", "N", "P", "p", "X", "x"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\",n) max, f, max.ToString(f, foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\",n) min, f, min.ToString(f, } } }
G H I J K L M N "e", "n",
O P
yields {2}", c));
Q R
yields {2}", c));
S T U V
The output is 4294967295.ToString("C",n) 4294967295.ToString("c",n) 4294967295.ToString("D",n) 4294967295.ToString("d",n) 4294967295.ToString("E",n) 4294967295.ToString("e",n) 4294967295.ToString("F",n)
W yields yields yields yields yields yields yields
#4,294,967,295.00 #4,294,967,295.00 4294967295 4294967295 4.294967E~009 4.294967e~009 4294967295.00
X Y Z
3585
Contents | Index
UInt32 Structure
System
ToString() Method
4294967295.ToString("f",n) yields 4294967295.00 4294967295.ToString("G",n) yields 4294967295 4294967295.ToString("g",n) yields 4294967295 4294967295.ToString("N",n) yields 4,294,967,295.00 4294967295.ToString("n",n) yields 4,294,967,295.00 4294967295.ToString("P",n) yields 429,496,729,500.00 % 4294967295.ToString("p",n) yields 429,496,729,500.00 % 4294967295.ToString("X",n) yields FFFFFFFF 4294967295.ToString("x",n) yields ffffffff 0.ToString("C",n) yields #0.00 0.ToString("c",n) yields #0.00 0.ToString("D",n) yields 0 0.ToString("d",n) yields 0 0.ToString("E",n) yields 0.000000E~000 0.ToString("e",n) yields 0.000000e~000 0.ToString("F",n) yields 0.00 0.ToString("f",n) yields 0.00 0.ToString("G",n) yields 0 0.ToString("g",n) yields 0 0.ToString("N",n) yields 0.00 0.ToString("n",n) yields 0.00 0.ToString("P",n) yields 0.00 % 0.ToString("p",n) yields 0.00 % 0.ToString("X",n) yields 0 0.ToString("x",n) yields 0
A B C D E F G H I J K L M N O
UInt32.ToString(System.IFormatProvider) Method
P
[ILASM]
Q
.method public final hidebysig virtual string ToString(class System.IFormatProvider provider)
R
[C#]
S
public string ToString(IFormatProvider provider)
T
Summary
U
Returns a System.String representation of the value of the current instance.
V W
Parameters
X Y Z
Parameter
Description
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
3586
Contents | Index
System
UInt32 Structure ToString() Method
Return Value A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the formatting information in the System.Globalization.NumberFormatInfo instance supplied by provider.
A B
Description
C
This version of System.UInt32.ToString is equivalent to System.UInt32.ToString(“G”, provider). If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used.
D E F G
Example using System; using System.Globalization;
H
namespace Samples { public class UInt32ToString { public static void Main() { uint max = uint.MaxValue, min = uint.MinValue; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; Console.WriteLine("{0}.ToString yields {1}", max, max.ToString(n)); Console.WriteLine("{0}.ToString yields {1}", min, min.ToString(n)); } } }
J
I
K L M N O P Q R S T U V
The output is
W 4294967295.ToString yields 4294967295 0.ToString yields 0
X Y Z
3587
Contents | Index
UInt32 Structure
System
ToBoolean() Method
IConvertible.ToBoolean(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual bool System.IConvertible.ToBoolean(class System.IFormatProvider provider)
B
[C#]
bool IConvertible.ToBoolean(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToBoolean.]
F G H
IConvertible.ToByte(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual unsigned int8 System.IConvertible.ToByte(class System.IFormatProvider provider)
K
[C#]
byte IConvertible.ToByte(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToByte.]
O P Q
IConvertible.ToChar(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual valuetype System.Char System.IConvertible.ToChar(class System.IFormatProvider provider)
T
[C#]
char IConvertible.ToChar(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToChar.]
X Y Z
3588
Contents | Index
System
UInt32 Structure ToDouble() Method
IConvertible.ToDateTime(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual valuetype System.DateTime System.IConvertible.ToDateTime(class System.IFormatProvider provider)
A
[C#]
B
DateTime IConvertible.ToDateTime(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDateTime.]
E F G
IConvertible.ToDecimal(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual decimal System.IConvertible.ToDecimal(class System.IFormatProvider provider)
J
[C#]
K
decimal IConvertible.ToDecimal(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDecimal.]
N O P
IConvertible.ToDouble(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual float64 System.IConvertible.ToDouble(class System.IFormatProvider provider)
S
[C#]
T
double IConvertible.ToDouble(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDouble.]
W X Y Z
3589
Contents | Index
UInt32 Structure
System
ToInt16() Method
IConvertible.ToInt16(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual int16 System.IConvertible.ToInt16(class System.IFormatProvider provider)
B
[C#]
short IConvertible.ToInt16(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt16.]
F G H
IConvertible.ToInt32(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual int32 System.IConvertible.ToInt32(class System.IFormatProvider provider)
K
[C#]
int IConvertible.ToInt32(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt32.]
O P Q
IConvertible.ToInt64(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual int64 System.IConvertible.ToInt64(class System.IFormatProvider provider)
T
[C#]
long IConvertible.ToInt64(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt64.]
X Y Z
3590
Contents | Index
System
UInt32 Structure ToType() Method
IConvertible.ToSByte(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual int8 System.IConvertible.ToSByte(class System.IFormatProvider provider)
A
[C#]
B
sbyte IConvertible.ToSByte(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSByte.]
E F G
IConvertible.ToSingle(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual float32 System.IConvertible.ToSingle(class System.IFormatProvider provider)
J
[C#]
K
float IConvertible.ToSingle(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSingle.]
N O P
IConvertible.ToType(System.Type, System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual object System.IConvertible.ToType(class System.Type type, class System.IFormatProvider provider)
S
[C#]
T
object IConvertible.ToType(Type type, IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToType.]
W X Y Z
3591
Contents | Index
UInt32 Structure
System
ToUInt16() Method
IConvertible.ToUInt16(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual unsigned int16 System.IConvertible.ToUInt16(class System.IFormatProvider provider)
B
[C#]
ushort IConvertible.ToUInt16(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt16.] This member is not CLS-compliant.
F G H
IConvertible.ToUInt32(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual unsigned int32 System.IConvertible.ToUInt32(class System.IFormatProvider provider)
K
[C#]
uint IConvertible.ToUInt32(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt32.] This member is not CLS-compliant.
O P Q
IConvertible.ToUInt64(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual unsigned int64 System.IConvertible.ToUInt64(class System.IFormatProvider provider)
T
[C#]
ulong IConvertible.ToUInt64(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt64.] This member is not CLS-compliant.
X Y Z
3592
Contents | Index
System UInt64 Structure
BCL
Object ValueType UInt64
A
IComparable
B
IFormattable IConvertible
NotStandardized
C D
Summary
E
Represents a 64-bit unsigned integer. This type is not CLS-compliant.
F
Type Summary
G
public struct UInt64 : IComparable, IFormattable, IConvertible { // Fields public const ulong MaxValue = 18446744073709551615; public const ulong MinValue = 0;
H I J K L
// Methods public int CompareTo (object value); public override bool Equals (object obj); public override int GetHashCode (); MS public TypeCode GetTypeCode (); public static ulong Parse (string s); public static ulong Parse (string s, NumberStyles style); public static ulong Parse (string s, NumberStyles style, IFormatProvider provider); CF public static ulong Parse (string s, IFormatProvider provider); public override string ToString (); public string ToString (string format); public string ToString (string format, IFormatProvider provider); public string ToString (IFormatProvider provider); // MS MS MS MS MS MS MS MS MS MS
M N O P Q R S T U
Explicit Interface Members bool IConvertible.ToBoolean(IFormatProvider provider); byte IConvertible.ToByte(IFormatProvider provider); char IConvertible.ToChar(IFormatProvider provider); DateTime IConvertible.ToDateTime(IFormatProvider provider); decimal IConvertible.ToDecimal(IFormatProvider provider); double IConvertible.ToDouble(IFormatProvider provider); short IConvertible.ToInt16(IFormatProvider provider); int IConvertible.ToInt32(IFormatProvider provider); long IConvertible.ToInt64(IFormatProvider provider); sbyte IConvertible.ToSByte(IFormatProvider provider);
V W X Y Z
3593
Contents | Index
UInt64 Structure
System
UInt64 Structure
MS MS MS MS MS
A
float IConvertible.ToSingle(IFormatProvider provider); object IConvertible.ToType(Type type,IFormatProvider provider); ushort IConvertible.ToUInt16(IFormatProvider provider); uint IConvertible.ToUInt32(IFormatProvider provider); ulong IConvertible.ToUInt64(IFormatProvider provider);
}
B C
Description
D
The System.UInt64 data type represents integer values ranging from 0 to positive 18,446,744,073,709,551,615 (hexadecimal 0xFFFFFFFFFFFFFFFF).
E F
Example
G
using System;
H namespace Samples { public class UInt64Sample { public static void Main() { ulong max = ulong.MaxValue, min = ulong.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); Console.WriteLine("Is {0} equal to {1}: {2}", max, max, max.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", max, min, max.Equals(min)); Console.WriteLine("{0} has hashcode of: {1}", max, max.GetHashCode()); Console.WriteLine("{0} has hashcode of: {1}", min, min.GetHashCode()); string s = max.ToString(); Console.WriteLine("\"{0}\" parsed from string yields: {1}", s, UInt64.Parse(s)); s = min.ToString(); Console.WriteLine("\"{0}\" parsed from string yields: {1}", s, UInt64.Parse(s)); string[] formats = {"c", "d", "e", "f", "g", "n", "p", "x" }; foreach(string f in formats) Console.WriteLine("{0}: {1}", max, max.ToString(f)); } } }
I J K L M N O P Q R S T U V W X Y Z
3594
Contents | Index
System
UInt64 Structure MaxValue Field
The output is MaxValue: 18446744073709551615 MinValue: 0 Is 18446744073709551615 equal to 18446744073709551615: True Is 18446744073709551615 equal to 0: False 18446744073709551615 has hashcode of: 0 0 has hashcode of: 0 "18446744073709551615" parsed from string yields: 18446744073709551615 "0" parsed from string yields: 0 18446744073709551615: $18,446,744,073,709,551,615.00 18446744073709551615: 18446744073709551615 18446744073709551615: 1.844674e+019 18446744073709551615: 18446744073709551615.00 18446744073709551615: 18446744073709551615 18446744073709551615: 18,446,744,073,709,551,615.00 18446744073709551615: 1,844,674,407,370,955,161,500.00 % 18446744073709551615: ffffffffffffffff
A B C D E F G H I J K
UInt64.MaxValue Field
L
[ILASM]
.field public static literal unsigned int64 MaxValue
M
[C#]
N
public const ulong MaxValue = 18446744073709551615
O
Summary
P
Contains the maximum value for the System.UInt64 type.
Q R
Description
S
The value of this constant is 18,446,744,073,709,551,615 (hexadecimal 0xFFFFFFFFFFFFFFFF).
T
Example
U
using System;
V
namespace Samples { public class UInt64MaxValue { public static void Main() { ulong max = ulong.MaxValue, min = ulong.MinValue;
W X Y Z
3595
Contents | Index
UInt64 Structure
System
MinValue Field
Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); } }
A
}
B
The output is
C
MaxValue: 18446744073709551615 MinValue: 0
D E F
UInt64.MinValue Field
G H
[ILASM]
I
[C#]
.field public static literal unsigned int64 MinValue public const ulong MinValue = 0
J K
Summary
L
Contains the minimum value for the System.UInt64 type.
M
Description
N
The value of this constant is 0.
O P
Example
Q
using System;
R
namespace Samples { public class UInt64MinValue { public static void Main() { ulong max = ulong.MaxValue, min = ulong.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); } } }
S T U V W X Y Z
3596
Contents | Index
System
UInt64 Structure CompareTo() Method
The output is MaxValue: 18446744073709551615 MinValue: 0
A B
UInt64.CompareTo(System.Object) Method
C
[ILASM]
D
.method public final hidebysig virtual int32 CompareTo(object value)
E
[C#]
public int CompareTo(object value)
F G
Summary
H
Returns the sort order of the current instance compared to the specified System.Object.
I
Parameters
J
Parameter
Description
value
The System.Object to compare to the current instance.
K L M N
Return Value
O
A System.Int32 containing a value that reflects the sort order of the current instance as compared to value. The following table defines the conditions under which the return value is a negative number, zero, or a positive number.
P Q R S
Return Value
Description T
any negative number
Current instance < value.
U
zero
Current instance == value.
V
any positive number
Current instance > value, or value is a null reference.
W X Y
Description
Z
[Note: This method is implemented to support the System.IComparable interface.]
3597
Contents | Index
UInt64 Structure
System
Equals() Method
Exceptions Exception
Condition
System.ArgumentException
value is not a System.UInt64 and is not a null reference.
A B C
Example
D
using System;
E namespace Samples { public class UInt64CompareTo { private static string CompareUInt64s(ulong u1, ulong u2) { int i = u1.CompareTo(u2); if(0 == i) return String.Format("{0} is equal to {1}", u1, u2); if(i > 0) return String.Format("{0} is greater than {1}", u1, u2); else return String.Format("{0} is less than {1}", u1, u2); } public static void Main() { ulong max = ulong.MaxValue, min = ulong.MinValue; Console.WriteLine(CompareUInt64s(min, min)); Console.WriteLine(CompareUInt64s(max, min)); Console.WriteLine(CompareUInt64s(min, max)); } } }
F G H I J K L M N O P Q R S T
The output is
U
0 is equal to 0 18446744073709551615 is greater than 0 0 is less than 18446744073709551615
V W X
UInt64.Equals(System.Object) Method
Y
[ILASM]
Z
.method public hidebysig virtual bool Equals(object obj) [C#]
public override bool Equals(object obj)
3598
Contents | Index
System
UInt64 Structure Equals() Method
Summary Determines whether the current instance and the specified System.Object represent the same value and type. A
Parameters
B C
Parameter
Description
obj
The System.Object to compare to the current instance.
D E F
Return Value
G
true if obj represents the same value and type as the current instance. If obj is a null reference or is not an instance of System.UInt64, returns false.
H
Description
J
[Note: This method overrides System.Object.Equals.]
K
I
L
Example
M
using System;
N namespace Samples { public class UInt64Equals { public static void Main() { ulong max = ulong.MaxValue, min = ulong.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); Console.WriteLine("Is {0} equal to {1}: {2}", max, max, max.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", max, min, max.Equals(min)); Console.WriteLine("Is {0} equal to {1}: {2}", min, max, min.Equals(max)); Console.WriteLine("Is {0} equal to {1}: {2}", min, min, min.Equals(min)); } } }
O P Q R S T U V W X Y Z
3599
Contents | Index
UInt64 Structure
System
GetHashCode() Method
The output is MaxValue: 18446744073709551615 MinValue: 0 Is 18446744073709551615 equal to 18446744073709551615: True Is 18446744073709551615 equal to 0: False Is 0 equal to 18446744073709551615: False Is 0 equal to 0: True
A B C D E
UInt64.GetHashCode() Method
F [ILASM]
G
.method public hidebysig virtual int32 GetHashCode()
H
[C#]
public override int GetHashCode()
I J
Summary
K
Generates a hash code for the current instance.
L
Return Value
M
A System.Int32 containing the hash code for the current instance.
N O
Description
P
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
Q R
Example
S
using System;
T
namespace Samples { public class UInt64GetHashCode { public static void Main() { ulong max = ulong.MaxValue, min = ulong.MinValue; Console.WriteLine("MaxValue: {0}", max); Console.WriteLine("MinValue: {0}", min); Console.WriteLine("{0} has hashcode of: {1}", max, max.GetHashCode());
U V W X Y Z
3600
Contents | Index
System
UInt64 Structure Parse() Method
Console.WriteLine("{0} has hashcode of: {1}", min, min.GetHashCode()); } }
A
}
B
The output is
C
MaxValue: 18446744073709551615 MinValue: 0 18446744073709551615 has hashcode of: 0 0 has hashcode of: 0
D E F G
UInt64.GetTypeCode() Method
H
[ILASM]
I
.method public final hidebysig virtual valuetype System.TypeCode GetTypeCode()
J
[C#]
public TypeCode GetTypeCode()
K L
Summary
M
Returns the System.TypeCode for value type System.UInt64.
N O
UInt64.Parse(System.String) Method
P
[ILASM]
Q
.method public hidebysig static unsigned int64 Parse(string s) [C#]
R
public static ulong Parse(string s)
S
Summary
T
Returns the specified System.String converted to a System.UInt64 value.
U V
Parameters
W
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Integer style.
X Y Z
3601
Contents | Index
UInt64 Structure
System
Parse() Method
Return Value The System.UInt64 value obtained from s. A
Description
B
This version of System.UInt64.Parse is equivalent to System.UInt64.Parse(s, System.Globalization.NumberStyles.Integer, null). The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.] This method is not CLS-compliant. For a CLS-compliant alternative use System.Single.Parse(System.String).
C D E F G H
Exceptions
I J K
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.UInt64.MaxValue or less than System.UInt64.MinValue.
L M N O P
Example
Q
using System;
R namespace Samples { public class UInt64Parse { public static void Main() { string s; try { s = (UInt64.MaxValue).ToString(); Console.WriteLine("String {0} yields {1}", s, UInt64.Parse(s)); s = (UInt64.MinValue).ToString(); Console.WriteLine("String {0} yields {1}", s, UInt64.Parse(s));
S T U V W X Y Z
3602
Contents | Index
System
UInt64 Structure Parse() Method
s = String.Empty; Console.WriteLine("String {0} yields {1}", s, UInt64.Parse(s)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = String.Format("{0}1", UInt64.MaxValue); Console.WriteLine("String {0} yields {1}", s, UInt64.Parse(s)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A B C D E F G H I
}
J
}
K
}
L
The output is
M String 18446744073709551615 yields 18446744073709551615 String 0 yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseUInt64(String s, NumberStyles style, NumberFormatInfo info) at System.UInt64.Parse(String s) at Samples.UInt64Parse.Main() in C:\Books\BCL\Samples\System\UInt64\ Parse(System.String)\UInt64.cs:line 19 Exception: System.OverflowException: Value was either too large or too small for a UInt64. at System.Number.ParseUInt64(String s, NumberStyles style, NumberFormatInfo info) at System.UInt64.Parse(String s) at Samples.UInt64Parse.Main() in C:\Books\BCL\Samples\System\UInt64\ Parse(System.String)\UInt64.cs:line 29
N O P Q R S T U V
UInt64.Parse(System.String, System.Globalization.NumberStyles) Method
W
[ILASM]
X
.method public hidebysig static unsigned int64 Parse(string s, valuetype System.Globalization.NumberStyles style)
Y
[C#]
Z
public static ulong Parse(string s, NumberStyles style)
3603
Contents | Index
UInt64 Structure
System
Parse() Method
Summary Returns the specified System.String converted to a System.UInt64 value. A
Parameters
B C
Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Integer style.
D E F G H I
Return Value
J
The System.UInt64 value obtained from s.
K L
Description
M
This version of System.UInt64.Parse is equivalent to System.UInt64.Parse(s, style, null). The string s is parsed using the formatting information in a System.Globalization.NumberFormatInfo initialized for the current system culture. [Note: For more information, see System.Globalization.NumberFormatInfo.CurrentInfo.] This method is not CLS-compliant. For a CLS-compliant alternative use System.Single.Parse(System.String, System.Globalization.NumberStyles).
N O P Q R S
Exceptions
T U
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.UInt64.MaxValue or less than System.UInt64.MinValue.
V W X Y Z
3604
Contents | Index
System
UInt64 Structure Parse() Method
Example using System; using System.Globalization;
A namespace Samples { public class UInt64Parse { public static void Main() { string s; try { s = "$0"; Console.WriteLine( "String {0} yields {1}", s, UInt64.Parse(s, NumberStyles.AllowCurrencySymbol)); s = String.Format( "${0}", (Int64.MaxValue).ToString()); Console.WriteLine( "String {0} yields {1}", s, UInt64.Parse(s, NumberStyles.AllowCurrencySymbol)); s = String.Format( "({0})", (UInt64.MinValue).ToString()); Console.WriteLine( "String {0} yields {1}", s, UInt64.Parse(s, NumberStyles.AllowParentheses)); s = String.Empty; Console.WriteLine( "String {0} yields {1}", s, UInt64.Parse(s, NumberStyles.Any)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = String.Format("{0}1", Int64.MaxValue); Console.WriteLine("String {0} yields {1}", s, UInt64.Parse(s, NumberStyles.Any)); }
B C D E F G H I J K L M N O P Q R S T U V W X Y Z
3605
Contents | Index
UInt64 Structure
System
Parse() Method
catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); }
A
} }
B }
C
The output is
D E
String $0 yields 0 String $9223372036854775807 yields 9223372036854775807 String (0) yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseUInt64(String s, NumberStyles style, NumberFormatInfo info) at System.UInt64.Parse(String s, NumberStyles style) at Samples.UInt64Parse.Main() in C:\Books\BCL\Samples\System\UInt64\ Parse(System.String,System.Globalization.NumberStyles)\UInt64.cs:line 32 Exception: System.OverflowException: Value was either too large or too small for a UInt64. at System.Number.ParseUInt64(String s, NumberStyles style, NumberFormatInfo info) at System.UInt64.Parse(String s, NumberStyles style) at Samples.UInt64Parse.Main() in C:\Books\BCL\Samples\System\UInt64\ Parse(System.String,System.Globalization.NumberStyles)\UInt64.cs:line 44
F G H I J K L M N O P
UInt64.Parse(System.String, System.Globalization.NumberStyles, System.IFormatProvider) Method
Q R
[ILASM]
.method public hidebysig static unsigned int64 Parse(string s, valuetype System.Globalization.NumberStyles style, class System.IFormatProvider provider)
S T
[C#]
public static ulong Parse(string s, NumberStyles style, IFormatProvider provider)
U V
Summary
W
Returns the specified System.String converted to a System.UInt64 value.
X Y Z
3606
Contents | Index
System
UInt64 Structure Parse() Method
Parameters Parameter
Description
s
A System.String containing the value to convert. The string is interpreted using the style specified by style.
style
Zero or more System.Globalization.NumberStyles values that specify the style of s. Specify multiple values for style using the bitwise OR operator. If style is a null reference, the string is interpreted using the System.Globalization.NumberStyles.Integer style.
A B C
provider
D E F
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
G H I
Return Value
J
The System.UInt64 value obtained from s.
K
Description
L
The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. This method is not CLS-compliant. For a CLS-compliant alternative use System.Single.Parse(System.String, System.Globalization.NumberStyles, System.IFormatProvider).
M N O P Q R
Exceptions
S T
Exception
Condition U
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
System.OverflowException
s represents a number greater than System.UInt64.MaxValue or less than System.UInt64.MinValue.
V W X Y Z
3607
Contents | Index
UInt64 Structure
System
Parse() Method
Example using System; using System.Globalization;
A
namespace Samples { public class UInt64Parse { public static void Main() { CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; string s = " ~42"; Console.WriteLine( "String {0} yields {1}", s, UInt64.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowLeadingSign, n)); s = "(0)"; Console.WriteLine( "String {0} yields {1}", s, UInt64.Parse(s, NumberStyles.AllowParentheses, n)); s = " !0 "; Console.WriteLine("String {0} yields {1}", s, UInt64.Parse(s, NumberStyles.Any, n)); } } }
B C D E F G H I J K L M N O P Q R S
The output is
T
String ~42 yields 42 String (0) yields 0 String !0 yields 0
U V W X
UInt64.Parse(System.String, System.IFormatProvider) Method
Y
[ILASM]
.method public hidebysig static unsigned int64 Parse(string s, class System.IFormatProvider provider)
Z
[C#]
public static ulong Parse(string s, IFormatProvider provider)
3608
Contents | Index
System
UInt64 Structure Parse() Method
Summary Returns the specified System.String converted to a System.UInt64 value. A
Parameters
B
Parameter
Description
C
A System.String containing the value to convert. The string is interpreted using the System.Globalization.NumberStyles.Integer style.
D
s
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information about s.
F
provider
E
G H
Return Value
I
The System.UInt64 value obtained from s.
J K
Description
L
This version of System.UInt64.Parse is equivalent to System.UInt64.Parse(s, System.Globalization.NumberStyles.Integer, provider). The string s is parsed using the culture-specific formatting information from the System.Globalization.NumberFormatInfo instance supplied by provider. If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. This method is not CLS-compliant. For a CLS-compliant alternative use System.Single.Parse(System.String, System.IFormatProvider).
M N O P Q R S
Exceptions
T
Exception
Condition
System.ArgumentNullException
s is a null reference.
System.FormatException
s is not in the correct style.
X
System.OverflowException
s represents a number greater than System.UInt64.MaxValue or less than System.UInt64.MinValue.
Y
U V W
Z
3609
Contents | Index
UInt64 Structure
System
Parse() Method
Example using System; using System.Globalization;
A namespace Samples { public class UInt64Parse { public static void Main() { string s; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; try { s = "~42"; Console.WriteLine("String {0} yields {1}", s, UInt64.Parse(s, n)); s = (Int64.MaxValue).ToString(); Console.WriteLine("String {0} yields {1}", s, UInt64.Parse(s, n)); s = "!0"; Console.WriteLine("Convert from String {0} yields {1}", s, UInt64.Parse(s, n)); s = String.Empty; Console.WriteLine("Convert from String {0} yields {1}", s, UInt64.Parse(s, n)); } catch(FormatException e) { Console.WriteLine("Exception: {0}", e); } try { s = String.Format("{0}1", UInt64.MaxValue); Console.WriteLine("String {0} yields {1}", s, UInt64.Parse(s, n)); } catch(OverflowException e) { Console.WriteLine("Exception: {0}", e); } } } }
B C D E F G H I J K L M N O P Q R S T U V W X Y Z
3610
Contents | Index
System
UInt64 Structure ToString() Method
The output is String ~42 yields 42 String 9223372036854775807 yields 9223372036854775807 Convert from String !0 yields 0 Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseUInt64(String s, NumberStyles style, NumberFormatInfo info) at System.UInt64.Parse(String s, IFormatProvider provider) at Samples.UInt64Parse.Main() in C:\Books\BCL\Samples\System\UInt64\ Parse(System.String,System.IFormatProvider)\UInt64.cs:line 27 Exception: System.OverflowException: Value was either too large or too small for a UInt64. at System.Number.ParseUInt64(String s, NumberStyles style, NumberFormatInfo info) at System.UInt64.Parse(String s, IFormatProvider provider) at Samples.UInt64Parse.Main() in C:\Books\BCL\Samples\System\UInt64\ Parse(System.String,System.IFormatProvider)\UInt64.cs:line 37
A B C D E F G H I J K
UInt64.ToString() Method
L
[ILASM]
.method public hidebysig virtual string ToString()
M
[C#]
N
public override string ToString()
O
Summary
P
Returns a System.String representation of the value of the current instance.
Q R
Return Value
S
A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the current system culture.
T U
Description
V
This method is equivalent to System.UInt64.ToString(null, null). [Note: This method overrides System.Object.ToString.]
W X Y Z
3611
Contents | Index
UInt64 Structure
System
ToString() Method
Example using System; using System.Globalization;
A namespace Samples { public class UInt64ToString { public static void Main() { ulong max = ulong.MaxValue, min = ulong.MinValue; Console.WriteLine("{0}.ToString() yields {1}", max, max.ToString()); Console.WriteLine("{0}.ToString() yields {1}", min, min.ToString()); } } }
B C D E F G H I J K
The output is
L 18446744073709551615.ToString() yields 18446744073709551615 0.ToString() yields 0
M N O
UInt64.ToString(System.String) Method
P [ILASM]
Q
.method public hidebysig instance string ToString(string format)
R
[C#]
public string ToString(string format)
S T
Summary
U
Returns a System.String representation of the value of the current instance.
V
Parameters
W X
Parameter
Description
format
A System.String that specifies the format of the returned string. [Note: For a list of valid values, see System.UInt64.ToString(System.String, System.IFormatProvider).]
Y Z
3612
Contents | Index
System
UInt64 Structure ToString() Method
Return Value A System.String representation of the current instance formatted as specified by format. The string takes into account the current system culture. A
Description
B
This method is equivalent to System.UInt64.ToString(format, null). If format is a null reference, the general format specifier “G” is used.
C D E
Exceptions
F
Exception
Condition
System.FormatException
format is invalid.
G H I
Example
J
using System; using System.Globalization;
K
namespace Samples { public class UInt64ToString { public static void Main() { ulong max = ulong.MaxValue, min = ulong.MinValue; string[] formats = {"C", "c", "D", "d", "E", "e", "F", "f", "G", "g", "N", "n", "P", "p", "X", "x"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\") yields {2}", max, f, max.ToString(f)); foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\") yields {2}", min, f, min.ToString(f)); } } }
M
L
N O P Q R S T U V W X Y Z
3613
Contents | Index
UInt64 Structure
System
ToString() Method
The output is 18446744073709551615.ToString("C") yields 18446744073709551615.ToString("c") yields 18446744073709551615.ToString("D") yields 18446744073709551615.ToString("d") yields 18446744073709551615.ToString("E") yields 18446744073709551615.ToString("e") yields 18446744073709551615.ToString("F") yields 18446744073709551615.ToString("f") yields 18446744073709551615.ToString("G") yields 18446744073709551615.ToString("g") yields 18446744073709551615.ToString("N") yields 18446744073709551615.ToString("n") yields 18446744073709551615.ToString("P") yields 18446744073709551615.ToString("p") yields 18446744073709551615.ToString("X") yields 18446744073709551615.ToString("x") yields 0.ToString("C") yields $0.00 0.ToString("c") yields $0.00 0.ToString("D") yields 0 0.ToString("d") yields 0 0.ToString("E") yields 0.000000E+000 0.ToString("e") yields 0.000000e+000 0.ToString("F") yields 0.00 0.ToString("f") yields 0.00 0.ToString("G") yields 0 0.ToString("g") yields 0 0.ToString("N") yields 0.00 0.ToString("n") yields 0.00 0.ToString("P") yields 0.00 % 0.ToString("p") yields 0.00 % 0.ToString("X") yields 0 0.ToString("x") yields 0
A B C D E F G H I J K L M N O P Q R S
$18,446,744,073,709,551,615.00 $18,446,744,073,709,551,615.00 18446744073709551615 18446744073709551615 1.844674E+019 1.844674e+019 18446744073709551615.00 18446744073709551615.00 18446744073709551615 18446744073709551615 18,446,744,073,709,551,615.00 18,446,744,073,709,551,615.00 1,844,674,407,370,955,161,500.00 % 1,844,674,407,370,955,161,500.00 % FFFFFFFFFFFFFFFF ffffffffffffffff
T U
UInt64.ToString(System.String, System.IFormatProvider) Method
V [ILASM]
W
.method public final hidebysig virtual string ToString(string format, class System.IFormatProvider provider)
X
[C#]
public string ToString(string format, IFormatProvider provider)
Y Z
Summary Returns a System.String representation of the value of the current instance.
3614
Contents | Index
System
UInt64 Structure ToString() Method
Parameters Parameter
Description
format
A System.String containing a character that specifies the format of the returned string.
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo instance containing culture-specific formatting information.
A B C D E F
Return Value
G
A System.String representation of the current instance formatted as specified by format. The string takes into account the formatting information in the System.Globalization.NumberFormatInfo instance supplied by provider.
H I J
Description
K
If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used. If format is a null reference, the general format specifier “G” is used. [Note: For a detailed description of formatting, see the System.IFormattable interface. This method is implemented to support the System.IFormattable interface.] The following table lists the characters that are valid for the System.UInt64 type.
L M N O P
Format Characters
Description
Q
"C", "c"
Currency format.
R
"D", "d"
Decimal format.
"E", "e"
Exponential notation format.
"F", "f"
Fixed-point format.
"G", "g"
General format.
W
"N", "n"
Number format.
X
"P", "p"
Percent format.
Y
"X", "x"
Hexadecimal format.
S T U V
Z
3615
Contents | Index
UInt64 Structure
System
ToString() Method
Exceptions Exception
Condition
System.FormatException
format is invalid.
A B C D
Example
E
using System; using System.Globalization;
F namespace Samples { public class UInt64Int64ToString { public static void Main() { ulong max = ulong.MaxValue, min = ulong.MinValue; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; n.CurrencySymbol = "#"; string[] formats = {"C", "c", "D", "d", "E", "F", "f", "G", "g", "N", "P", "p", "X", "x"}; foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\",n) max, f, max.ToString(f, foreach(string f in formats) Console.WriteLine("{0}.ToString(\"{1}\",n) min, f, min.ToString(f, } } }
G H I J K L M N O P Q R S T U V
"e", "n",
yields {2}", n)); yields {2}", n));
The output is
W
18446744073709551615.ToString("C",n) 18446744073709551615.ToString("c",n) 18446744073709551615.ToString("D",n) 18446744073709551615.ToString("d",n) 18446744073709551615.ToString("E",n) 18446744073709551615.ToString("e",n) 18446744073709551615.ToString("F",n) 18446744073709551615.ToString("f",n)
X Y Z
yields yields yields yields yields yields yields yields
#18,446,744,073,709,551,615.00 #18,446,744,073,709,551,615.00 18446744073709551615 18446744073709551615 1.844674E~019 1.844674e~019 18446744073709551615.00 18446744073709551615.00
3616
Contents | Index
System
UInt64 Structure ToString() Method
18446744073709551615.ToString("G",n) yields 18446744073709551615.ToString("g",n) yields 18446744073709551615.ToString("N",n) yields 18446744073709551615.ToString("n",n) yields 18446744073709551615.ToString("P",n) yields 18446744073709551615.ToString("p",n) yields 18446744073709551615.ToString("X",n) yields 18446744073709551615.ToString("x",n) yields 0.ToString("C",n) yields #0.00 0.ToString("c",n) yields #0.00 0.ToString("D",n) yields 0 0.ToString("d",n) yields 0 0.ToString("E",n) yields 0.000000E~000 0.ToString("e",n) yields 0.000000e~000 0.ToString("F",n) yields 0.00 0.ToString("f",n) yields 0.00 0.ToString("G",n) yields 0 0.ToString("g",n) yields 0 0.ToString("N",n) yields 0.00 0.ToString("n",n) yields 0.00 0.ToString("P",n) yields 0.00 % 0.ToString("p",n) yields 0.00 % 0.ToString("X",n) yields 0 0.ToString("x",n) yields 0
18446744073709551615 18446744073709551615 18,446,744,073,709,551,615.00 18,446,744,073,709,551,615.00 1,844,674,407,370,955,161,500.00 % 1,844,674,407,370,955,161,500.00 % FFFFFFFFFFFFFFFF ffffffffffffffff
A B C D E F G H I J K L M N
UInt64.ToString(System.IFormatProvider) Method
O
[ILASM]
P
.method public final hidebysig virtual string ToString(class System.IFormatProvider provider)
Q
[C#]
R
public string ToString(IFormatProvider provider)
S
Summary
T
Returns a System.String representation of the value of the current instance.
U V
Parameters
W
Parameter
Description
provider
A System.IFormatProvider that supplies a System.Globalization.NumberFormatInfo containing culture-specific formatting information.
X Y Z
3617
Contents | Index
UInt64 Structure
System
ToBoolean() Method
Return Value A System.String representation of the current instance formatted using the general format specifier (“G”). The string takes into account the formatting information in the System.Globalization.NumberFormatInfo instance supplied by provider.
A B
Description
C
This version of System.UInt64.ToString is equivalent to System.UInt64.ToString(“G”, provider). If provider is null or a System.Globalization.NumberFormatInfo cannot be obtained from provider, the formatting information for the current system culture is used.
D E F G
Example
H
using System; using System.Globalization;
I namespace Samples { public class UInt64ToString { public static void Main() { ulong max = ulong.MaxValue, min = ulong.MinValue; CultureInfo c = new CultureInfo("en-AU"); NumberFormatInfo n = c.NumberFormat; n.PositiveSign = "~"; n.NegativeSign = "!"; Console.WriteLine("{0}.ToString yields {1}", max, max.ToString(n)); Console.WriteLine("{0}.ToString yields {1}", min, min.ToString(n)); } } }
J K L M N O P Q R S T
The output is
U V
18446744073709551615.ToString yields 18446744073709551615 0.ToString yields 0
W X
IConvertible.ToBoolean(System.IFormatProvider) Method
Y
[ILASM]
Z
.method private final hidebysig virtual bool System.IConvertible.ToBoolean(class System.IFormatProvider provider) [C#]
bool IConvertible.ToBoolean(IFormatProvider provider)
3618
Contents | Index
System
UInt64 Structure ToDateTime() Method
Summary Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToBoolean.] A B
IConvertible.ToByte(System.IFormatProvider) Method
C
[ILASM]
D
.method private final hidebysig virtual unsigned int8 System.IConvertible.ToByte(class System.IFormatProvider provider)
E
[C#]
F
byte IConvertible.ToByte(IFormatProvider provider)
G
Summary
H
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToByte.]
I J K
IConvertible.ToChar(System.IFormatProvider) Method
L
[ILASM]
M
.method private final hidebysig virtual valuetype System.Char System.IConvertible.ToChar(class System.IFormatProvider provider)
N
[C#]
O
char IConvertible.ToChar(IFormatProvider provider)
P
Summary
Q
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToChar.]
R S T
IConvertible.ToDateTime(System.IFormatProvider) Method
U
[ILASM]
V
.method private final hidebysig virtual valuetype System.DateTime System.IConvertible.ToDateTime(class System.IFormatProvider provider)
W
[C#]
X
DateTime IConvertible.ToDateTime(IFormatProvider provider)
Y
Summary
Z
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDateTime.]
3619
Contents | Index
UInt64 Structure
System
ToDecimal() Method
IConvertible.ToDecimal(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual decimal System.IConvertible.ToDecimal(class System.IFormatProvider provider)
B
[C#]
decimal IConvertible.ToDecimal(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDecimal.]
F G H
IConvertible.ToDouble(System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual float64 System.IConvertible.ToDouble(class System.IFormatProvider provider)
K
[C#]
double IConvertible.ToDouble(IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToDouble.]
O P Q
IConvertible.ToInt16(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual int16 System.IConvertible.ToInt16(class System.IFormatProvider provider)
T
[C#]
short IConvertible.ToInt16(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt16.]
X Y Z
3620
Contents | Index
System
UInt64 Structure ToSByte() Method
IConvertible.ToInt32(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual int32 System.IConvertible.ToInt32(class System.IFormatProvider provider)
A
[C#]
B
int IConvertible.ToInt32(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt32.]
E F G
IConvertible.ToInt64(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual int64 System.IConvertible.ToInt64(class System.IFormatProvider provider)
J
[C#]
K
long IConvertible.ToInt64(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToInt64.]
N O P
IConvertible.ToSByte(System.IFormatProvider) Method
Q
[ILASM]
R
.method private final hidebysig virtual int8 System.IConvertible.ToSByte(class System.IFormatProvider provider)
S
[C#]
T
sbyte IConvertible.ToSByte(IFormatProvider provider)
U
Summary
V
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSByte.]
W X Y Z
3621
Contents | Index
UInt64 Structure
System
ToSingle() Method
IConvertible.ToSingle(System.IFormatProvider) Method [ILASM]
A
.method private final hidebysig virtual float32 System.IConvertible.ToSingle(class System.IFormatProvider provider)
B
[C#]
float IConvertible.ToSingle(IFormatProvider provider)
C D
Summary
E
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToSingle.]
F G H
IConvertible.ToType(System.Type, System.IFormatProvider) Method
I
[ILASM]
J
.method private final hidebysig virtual object System.IConvertible.ToType(class System.Type type, class System.IFormatProvider provider)
K
[C#]
object IConvertible.ToType(Type type, IFormatProvider provider)
L M
Summary
N
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToType.]
O P Q
IConvertible.ToUInt16(System.IFormatProvider) Method
R
[ILASM]
S
.method private final hidebysig virtual unsigned int16 System.IConvertible.ToUInt16(class System.IFormatProvider provider)
T
[C#]
ushort IConvertible.ToUInt16(IFormatProvider provider)
U V
Summary
W
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt16.] This member is not CLS-compliant.
X Y Z
3622
Contents | Index
System
UInt64 Structure ToUInt64() Method
IConvertible.ToUInt32(System.IFormatProvider) Method [ILASM]
.method private final hidebysig virtual unsigned int32 System.IConvertible.ToUInt32(class System.IFormatProvider provider)
A
[C#]
B
uint IConvertible.ToUInt32(IFormatProvider provider)
C
Summary
D
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt32.] This member is not CLS-compliant.
E F G
IConvertible.ToUInt64(System.IFormatProvider) Method
H
[ILASM]
I
.method private final hidebysig virtual unsigned int64 System.IConvertible.ToUInt64(class System.IFormatProvider provider)
J
[C#]
K
ulong IConvertible.ToUInt64(IFormatProvider provider)
L
Summary
M
Implemented to support the System.IConvertible interface. [Note: For more information, see System.IConvertible.ToUInt64.] This member is not CLS-compliant.
N O P Q R S T U V W X Y Z
3623
Contents | Index
System UnauthorizedAccessException
BCL
Object
A
Exception
B
ISerializable
NotStandardized
SystemException UnauthorizedAccessException
C D
Summary
E
Represents the error that occurs when an I/O operation cannot be performed because of incompatible file access levels.
F G
Type Summary
H
public class UnauthorizedAccessException : SystemException { // Constructors public UnauthorizedAccessException (); public UnauthorizedAccessException (string message); public UnauthorizedAccessException (string message, Exception inner); MS CF protected UnauthorizedAccessException (SerializationInfo info, StreamingContext context); }
I J K L M N O
Description
P
System.UnauthorizedAccessException is typically thrown when a request is made to write to a read-only file, or a file I/O operation is requested on a directory.
Q R
Example
S
using System; using System.IO; using System.Security.Permissions;
T U
namespace Samples { public class UnauthorizedAccessExceptionConstructor { public static void Main() { try { string s = "readonly.txt"; FileStream fs = File.OpenWrite(s);
V W X Y Z
3624
Contents | Index
System
UnauthorizedAccessException UnauthorizedAccessException() Constructor
} catch(UnauthorizedAccessException e) { Console.WriteLine("Exception: {0}", e); }
A
}
B
}
C
}
D
The output is
E Exception: System.UnauthorizedAccessException: Access to the path "C:\Books\BCL\Samples\System\UnauthorizedAccessException\readonly.txt" is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String str) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean useAsync, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) at System.IO.File.OpenWrite(String path) at Samples.UnauthorizedAccessExceptionConstructor.Main() in C:\Books\BCL\ Samples\System\UnauthorizedAccessException\UnauthorizedAccessException.cs:line 14
F G H I J K L M
UnauthorizedAccessException() Constructor
N
[ILASM]
O
public rtspecialname specialname instance void .ctor()
P
[C#]
public UnauthorizedAccessException()
Q R
Summary
S
Constructs and initializes a new instance of the System.UnauthorizedAccessException class.
T U
Description
V
This constructor initializes the System.UnauthorizedAccessException.Message property of the new instance to a system-supplied message that describes the error, such as “Attempted to perform an unauthorized operation.” This message takes into account the current system culture. The System.UnauthorizedAccessException.InnerException property of the new instance is initialized to null.
W X Y Z
3625
Contents | Index
UnauthorizedAccessException
System
UnauthorizedAccessException() Constructor
UnauthorizedAccessException(System.String) Constructor [ILASM]
public rtspecialname specialname instance void .ctor(string message)
A
[C#]
public UnauthorizedAccessException(string message)
B C
Summary
D
Constructs and initializes a new instance of the System.UnauthorizedAccessException class.
E F
Parameters
G H
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
I J K L
Description
M
This constructor initializes the System.UnauthorizedAccessException.Message property of the new instance using message. If message is null, the System.UnauthorizedAccessException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. The System.UnauthorizedAccessException.InnerException property of the new instance is initialized to null.
N O P Q R S
UnauthorizedAccessException(System.String, System.Exception) Constructor
T U
[ILASM]
V
public rtspecialname specialname instance void .ctor(string message, class System.Exception inner)
W
[C#]
public UnauthorizedAccessException(string message, Exception inner)
X Y
Summary
Z
Constructs and initializes a new instance of the System.UnauthorizedAccessException class.
3626
Contents | Index
System
UnauthorizedAccessException UnauthorizedAccessException() Constructor
Parameters Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
A
inner
B C D
An instance of System.Exception that is the cause of the current exception. If inner is non-null, then the current exception was raised in a catch block handling inner.
E F G
Description
H
This constructor initializes the System.UnauthorizedAccessException.Message property of the new instance using message and the System.UnauthorizedAccessException.InnerException property using inner. If message is null, the System.UnauthorizedAccessException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For more information on inner exceptions, see System.Exception.InnerException.]
I J K L M N
UnauthorizedAccessException(System.Runtime.Serialization.Serialization Info, System.Runtime.Serialization.StreamingContext) Constructor
O P
[ILASM]
Q
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
R
[C#]
S
protected UnauthorizedAccessException(SerializationInfo info, StreamingContext context)
T U
Summary
V
Initializes a new instance of the System.UnauthorizedAccessException class with serialized data.
W X Y Z
3627
Contents | Index
UnauthorizedAccessException
System
UnauthorizedAccessException() Constructor
Parameters Parameter
Description
info
The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown.
context
The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination.
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
3628
Contents | Index
System.Globalization UnicodeCategory Enum
BCL
Object ValueType Enum UnicodeCategory
IComparable
A
IFormattable
B
IConvertible
C
NotStandardized
D
Summary
E
Designates the general Unicode category of a System.Char.
F G
Type Summary public enum UnicodeCategory { ClosePunctuation = 21, ConnectorPunctuation = 18, Control = 14, CurrencySymbol = 26, DashPunctuation = 19, DecimalDigitNumber = 8, EnclosingMark = 7, FinalQuotePunctuation = 23, Format = 15, InitialQuotePunctuation = 22, LetterNumber = 9, LineSeparator = 12, LowercaseLetter = 1, MathSymbol = 25, ModifierLetter = 3, ModifierSymbol = 27, NonSpacingMark = 5, OpenPunctuation = 20, OtherLetter = 4, OtherNotAssigned = 29, OtherNumber = 10, OtherPunctuation = 24, OtherSymbol = 28, ParagraphSeparator = 13, PrivateUse = 17, SpaceSeparator = 11, SpacingCombiningMark = 6, Surrogate = 16, TitlecaseLetter = 2, UppercaseLetter = 0, }
H I J K L M N O P Q R S T U V W X Y Z
3629
Contents | Index
UnicodeCategory Enum
System.Globalization
UnicodeCategory Enum
Description These categories conform to Version 3.1 of the Unicode Standard. [Note: For information on mapping specific Unicode characters to categories, see the UnicodeData.txt file in the Unicode Character Database at http://www.unicode.org/ Public/UNIDATA/UnicodeCharacterDatabase.html. The UnicodeData.txt file format is described at http://www.unicode.org/Public/3.1-Update/UnicodeData-3.1.0.html.] This enumeration is used to support System.Char methods such as System.Char.IsLetter, System.Char.IsUpper, etc.
A B C D E
Example
F
using System; using System.Globalization;
G H
namespace Samples { public class UnicodeCategorySample { public static void Main() { string s = "Pi is (\u03a0)!"; Console.WriteLine("In string: {0}", s); foreach(char c in s) Console.WriteLine( "Unicode category of Char '{0}' value: {1} is {2}", c, (int) c, Char.GetUnicodeCategory(c)); } } }
I J K L M N O P Q R
The output is
S
C In string: Pi is ()! Unicode category of Char Unicode category of Char Unicode category of Char Unicode category of Char Unicode category of Char Unicode category of Char Unicode category of Char Unicode category of Char Unicode category of Char Unicode category of Char
T U V W X Y
'P' value: 80 is UppercaseLetter 'i' value: 105 is LowercaseLetter ' ' value: 32 is SpaceSeparator 'i' value: 105 is LowercaseLetter 's' value: 115 is LowercaseLetter ' ' value: 32 is SpaceSeparator '(' value: 40 is OpenPunctuation '' value: 928 is UppercaseLetter ')' value: 41 is ClosePunctuation '!' value: 33 is OtherPunctuation
Z
3630
Contents | Index
System.Globalization
UnicodeCategory Enum CurrencySymbol Field
UnicodeCategory.ClosePunctuation Field [ILASM]
.field public static literal valuetype System.Globalization.UnicodeCategory ClosePunctuation
A
[C#]
B
ClosePunctuation = 21
C
Summary
D
Designates a Unicode ‘Pe’ (punctuation, close).
E F G
UnicodeCategory.ConnectorPunctuation Field
H
[ILASM]
.field public static literal valuetype System.Globalization.UnicodeCategory ConnectorPunctuation
I
[C#]
J
ConnectorPunctuation = 18
K
Summary
L
Designates a Unicode ‘Pc’ (punctuation, connector).
M N O
UnicodeCategory.Control Field
P [ILASM]
Q
.field public static literal valuetype System.Globalization.UnicodeCategory Control
R
[C#]
S
Control = 14
T
Summary
U
Designates a Unicode ‘Cc’ (other, control).
V W
UnicodeCategory.CurrencySymbol Field
X
[ILASM]
Y
.field public static literal valuetype System.Globalization.UnicodeCategory CurrencySymbol
Z
[C#]
CurrencySymbol = 26
3631
Contents | Index
UnicodeCategory Enum
System.Globalization
DashPunctuation Field
Summary Designates a Unicode ‘Sc’ (symbol, currency). A B
UnicodeCategory.DashPunctuation Field
C
[ILASM]
D
.field public static literal valuetype System.Globalization.UnicodeCategory DashPunctuation
E
[C#]
DashPunctuation = 19
F G
Summary
H
Designates a Unicode ‘Pd’ (punctuation, dash).
I J
UnicodeCategory.DecimalDigitNumber Field
K
[ILASM]
.field public static literal valuetype System.Globalization.UnicodeCategory DecimalDigitNumber
L M
[C#]
DecimalDigitNumber = 8
N O
Summary
P
Designates a Unicode ‘Nd’ (number, decimal digit).
Q R
UnicodeCategory.EnclosingMark Field
S [ILASM]
T
.field public static literal valuetype System.Globalization.UnicodeCategory EnclosingMark
U
[C#]
V
EnclosingMark = 7
W
Summary
X
Designates a Unicode ‘Me’ (mark, enclosing).
Y Z
3632
Contents | Index
System.Globalization
UnicodeCategory Enum LetterNumber Field
UnicodeCategory.FinalQuotePunctuation Field [ILASM]
.field public static literal valuetype System.Globalization.UnicodeCategory FinalQuotePunctuation
A
[C#]
B
FinalQuotePunctuation = 23
C
Summary
D
Designates a Unicode ‘Pf’ (punctuation, final quote).
E F G
UnicodeCategory.Format Field
H
[ILASM]
.field public static literal valuetype System.Globalization.UnicodeCategory Format
I
[C#]
J
Format = 15
K
Summary
L
Designates a Unicode ‘Cf’ (other, format).
M N
UnicodeCategory.InitialQuotePunctuation Field
O
[ILASM]
P
.field public static literal valuetype System.Globalization.UnicodeCategory InitialQuotePunctuation
Q
[C#]
R
InitialQuotePunctuation = 22
S
Summary
T
Designates a Unicode ‘Pi’ (punctuation, initial quote).
U V
UnicodeCategory.LetterNumber Field
W
[ILASM]
X
.field public static literal valuetype System.Globalization.UnicodeCategory LetterNumber
Y
[C#]
Z
LetterNumber = 9
3633
Contents | Index
UnicodeCategory Enum
System.Globalization
LineSeparator Field
Summary Designates a Unicode ‘Nl’ (number, letter). A B
UnicodeCategory.LineSeparator Field
C
[ILASM]
D
.field public static literal valuetype System.Globalization.UnicodeCategory LineSeparator
E
[C#]
LineSeparator = 12
F G
Summary
H
Designates a Unicode ‘Zl’ (separator, line).
I J
UnicodeCategory.LowercaseLetter Field
K
[ILASM]
.field public static literal valuetype System.Globalization.UnicodeCategory LowercaseLetter
L M
[C#]
LowercaseLetter = 1
N O
Summary
P
Designates a Unicode ‘Ll’ (letter, lowercase).
Q R
UnicodeCategory.MathSymbol Field
S [ILASM]
T
.field public static literal valuetype System.Globalization.UnicodeCategory MathSymbol
U
[C#]
V
MathSymbol = 25
W
Summary
X
Designates a Unicode ‘Sm’ (symbol, math).
Y Z
3634
Contents | Index
System.Globalization
UnicodeCategory Enum OpenPunctuation Field
UnicodeCategory.ModifierLetter Field [ILASM]
.field public static literal valuetype System.Globalization.UnicodeCategory ModifierLetter
A
[C#]
B
ModifierLetter = 3
C
Summary
D
Designates a Unicode ‘Lm’ (letter, modifier).
E F G
UnicodeCategory.ModifierSymbol Field
H
[ILASM]
.field public static literal valuetype System.Globalization.UnicodeCategory ModifierSymbol
I
[C#]
J
ModifierSymbol = 27
K
Summary
L
Designates a Unicode ‘Sk’ (symbol, modifier).
M N O
UnicodeCategory.NonSpacingMark Field
P [ILASM]
Q
.field public static literal valuetype System.Globalization.UnicodeCategory NonSpacingMark
R
[C#]
S
NonSpacingMark = 5
T
Summary
U
Designates a Unicode ‘Mn’ (mark, non-spacing).
V W
UnicodeCategory.OpenPunctuation Field
X
[ILASM]
Y
.field public static literal valuetype System.Globalization.UnicodeCategory OpenPunctuation
Z
[C#]
OpenPunctuation = 20
3635
Contents | Index
UnicodeCategory Enum
System.Globalization
OtherLetter Field
Summary Designates a Unicode ‘Ps’ (punctuation, open). A B
UnicodeCategory.OtherLetter Field
C
[ILASM]
D
.field public static literal valuetype System.Globalization.UnicodeCategory OtherLetter
E
[C#]
OtherLetter = 4
F G
Summary
H
Designates a Unicode ‘Lo’ (letter, other: not an uppercase letter, a lowercase letter, a titlecase letter, or a modifier letter).
I J K
UnicodeCategory.OtherNotAssigned Field
L
[ILASM]
M
.field public static literal valuetype System.Globalization.UnicodeCategory OtherNotAssigned
N
[C#]
OtherNotAssigned = 29
O P
Summary
Q
Designates a Unicode ‘Cn’ (other, not assigned).
R S
UnicodeCategory.OtherNumber Field
T
[ILASM]
U
.field public static literal valuetype System.Globalization.UnicodeCategory OtherNumber
V
[C#]
W
OtherNumber = 10
X
Summary
Y
Designates a Unicode ‘No’ (number, other: not a decimal digit number or a letter number).
Z
3636
Contents | Index
System.Globalization
UnicodeCategory Enum PrivateUse Field
UnicodeCategory.OtherPunctuation Field [ILASM]
.field public static literal valuetype System.Globalization.UnicodeCategory OtherPunctuation
A
[C#]
B
OtherPunctuation = 24
C
Summary
D
Designates a Unicode ‘Po’ (punctuation, other: not connector, dash, open, close, initial quote, or final quote punctuation).
E F G
UnicodeCategory.OtherSymbol Field
H
[ILASM]
I
.field public static literal valuetype System.Globalization.UnicodeCategory OtherSymbol
J
[C#]
K
OtherSymbol = 28
L
Summary
M
Designates a Unicode ‘So’ (symbol, other: not a math, currency, or modifier symbol).
N O
UnicodeCategory.ParagraphSeparator Field
P
[ILASM]
Q
.field public static literal valuetype System.Globalization.UnicodeCategory ParagraphSeparator
R
[C#]
S
ParagraphSeparator = 13
T
Summary
U
Designates a Unicode ‘Zp’ (separator, paragraph).
V W X
UnicodeCategory.PrivateUse Field
Y
[ILASM]
.field public static literal valuetype System.Globalization.UnicodeCategory PrivateUse
Z
[C#]
PrivateUse = 17
3637
Contents | Index
UnicodeCategory Enum
System.Globalization
SpaceSeparator Field
Summary Designates a Unicode ‘Co’ (other, private use). A B
UnicodeCategory.SpaceSeparator Field
C
[ILASM]
D
.field public static literal valuetype System.Globalization.UnicodeCategory SpaceSeparator
E
[C#]
SpaceSeparator = 11
F G
Summary
H
Designates a Unicode ‘Zs’ (separator, space).
I J
UnicodeCategory.SpacingCombiningMark Field
K
[ILASM]
.field public static literal valuetype System.Globalization.UnicodeCategory SpacingCombiningMark
L M
[C#]
SpacingCombiningMark = 6
N O
Summary
P
Designates a Unicode ‘Mc’ (mark, spacing combining).
Q R
UnicodeCategory.Surrogate Field
S [ILASM]
T
.field public static literal valuetype System.Globalization.UnicodeCategory Surrogate
U
[C#]
V
Surrogate = 16
W
Summary
X
Designates a Unicode ‘Cs’ (other, surrogate).
Y Z
3638
Contents | Index
System.Globalization
UnicodeCategory Enum UppercaseLetter Field
UnicodeCategory.TitlecaseLetter Field [ILASM]
.field public static literal valuetype System.Globalization.UnicodeCategory TitlecaseLetter
A
[C#]
B
TitlecaseLetter = 2
C
Summary
D
Designates a Unicode ‘Lt’ (letter, titlecase).
E F G
UnicodeCategory.UppercaseLetter Field
H
[ILASM]
.field public static literal valuetype System.Globalization.UnicodeCategory UppercaseLetter
I
[C#]
J
UppercaseLetter = 0
K
Summary
L
Designates a Unicode ‘Lu’ (letter, uppercase).
M N O P Q R S T U V W X Y Z
3639
Contents | Index
System.Text UnicodeEncoding
BCL
Object
A
Encoding
B
UnicodeEncoding
C
Summary
D
Represents a Unicode implementation of System.Text.Encoding.
E
Type Summary
F
public class UnicodeEncoding : Encoding { // Constructors public UnicodeEncoding (); public UnicodeEncoding (bool bigEndian, bool byteOrderMark);
G H I J K
// Fields MS public const int CharSize = 2;
L
// Methods public override bool Equals (object value); public override int GetByteCount (char[] chars, int index, int count); public override int GetByteCount (string s); public override int GetBytes (char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex); CF public override byte[] GetBytes (string s); public override int GetBytes (string chars, int charIndex, int charCount, byte[] bytes, int byteIndex); public override int GetCharCount (byte[] bytes, int index, int count); public override int GetChars (byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex);
M N O P Q R S T U V W X Y Z
3640
Contents | Index
System.Text
UnicodeEncoding UnicodeEncoding Class
public public public public public
override override override override override
Decoder GetDecoder (); int GetHashCode (); int GetMaxByteCount (int charCount); int GetMaxCharCount (int byteCount); byte[] GetPreamble ();
A
}
B C
JR Normally, there is no need for your application code to construct an Encodingderived object (such as UnicodeEncoding). Instead, you normally obtain an Encoding-derived object by calling one of the Encoding class’s static, read-only properties. Here is an example:
D E F G
UnicodeEncoding unicodeEncoding = Encoding.Unicode;
H
This is more efficient because it returns a reference to a single UnicodeEncoding object rather than creating new UnicodeEncoding objects.
I J K
Description
L
System.Text.UnicodeEncoding encodes each Unicode character in UTF-16, i.e., as two consecutive bytes. Both little-endian and big-endian encodings are supported. [Note: On little-endian platforms such as Intel machines, it is generally more efficient to store Unicode characters in little-endian. However, many other platforms can store Unicode characters in big-endian. Unicode files can be distinguished by the presence of the byte order mark (U+FEFF), which is written as either 0xfe 0xff or 0xff 0xfe. This System.Text.Encoding implementation can detect a byte order mark automatically and switch byte orders, based on a parameter specified in the constructor. ISO/IEC 10646 defines UCS-2 and UCS-4. UCS-4 is a four-byte (32-bit) encoding containing 231 code positions, divided into 128 groups of 256 planes. Each plane contains 216 code positions. UCS-2 is a two-byte (16-bit) encoding containing the 216 code positions of UCS-4 for which the upper two bytes are zero, known as Plane Zero or the Basic Multilingual Plane (BMP). For example, the code position for LATIN CAPITAL LETTER A in UCS-4 is 0x00000041 whereas in UCS-2 it is 0x0041. ISO/IEC 10646 also defines UTF-16, which stands for “UCS Transformation Format for 16 Planes of Group 00”. UTF-16 is a two-byte encoding that uses an extension mechanism to represent 221 code positions. UTF-16 represents code positions in Plane Zero by its UCS-2 code value and code positions in Planes 1 through 16 by a pair of special code values, called surrogates. UTF-16 is equivalent to the Unicode Standard. For a detailed description of UTF-16 and surrogates, see “The Unicode Standard Version 3.0” Appendix C.]
M N O P Q R S T U V W X Y Z
3641
Contents | Index
UnicodeEncoding
System.Text
UnicodeEncoding Class
Example using System; using System.Text;
A namespace Samples { public class UnicodeEncodingSample { public static void Main() { UnicodeEncoding u = (UnicodeEncoding) Encoding.Unicode; string s = "Pi is (\u03a0)"; int count = u.GetByteCount(s); Console.WriteLine("In string"); foreach(Int16 i in s) Console.Write("{0}, ", i); Console.WriteLine(); byte[] bytes = new byte[count]; bytes = u.GetBytes(s); Console.WriteLine("Converted to array of bytes"); foreach(Byte b in bytes) Console.Write("{0}, ", b); Console.WriteLine(); count = u.GetCharCount(bytes); char[] chars = new char[count]; u.GetChars(bytes, 0, bytes.Length, chars, 0); Console.WriteLine("Converted to array of chars"); foreach(Int16 c in chars) Console.Write("{0}, ", c); Console.WriteLine(); } } }
B C D E F G H I J K L M N O P Q R S
The output is
T U
In string 80, 105, 32, 105, 115, 32, 40, 928, 41, Converted to array of bytes 80, 0, 105, 0, 32, 0, 105, 0, 115, 0, 32, 0, 40, 0, 160, 3, 41, 0, Converted to array of chars 80, 105, 32, 105, 115, 32, 40, 928, 41,
V W X Y Z
3642
Contents | Index
System.Text
UnicodeEncoding UnicodeEncoding() Constructor
UnicodeEncoding() Constructor [ILASM]
public rtspecialname specialname instance void .ctor() [C#]
A
public UnicodeEncoding()
B C
Summary
D
Constructs and initializes a new instance of the System.Text.UnicodeEncoding class.
E
Description
F
The new instance uses little-endian encoding and includes the Unicode byte-order mark in conversions.
G H
Example
I
using System; using System.Text;
J K
namespace Samples { public class UnicodeEncodingConstructor { public static void Main() { UnicodeEncoding u = new UnicodeEncoding(); string s = "Pi is (\u03a0)"; int count = u.GetByteCount(s); byte[] bytes = new byte[count]; bytes = u.GetBytes(s); Console.WriteLine("Default Constructor"); foreach(Byte b in bytes) Console.Write("{0}, ", b); Console.WriteLine(); u = new UnicodeEncoding(true, false); count = u.GetByteCount(s); bytes = new byte[count]; bytes = u.GetBytes(s); Console.WriteLine("Parameterized Constructor"); foreach(Byte b in bytes) Console.Write("{0}, ", b); } } }
L M N O P Q R S T U V W X Y Z
3643
Contents | Index
UnicodeEncoding
System.Text
UnicodeEncoding() Constructor
The output is Default Constructor 80, 0, 105, 0, 32, 0, 105, 0, 115, 0, 32, 0, 40, 0, 160, 3, 41, 0, Parameterized Constructor 0, 80, 0, 105, 0, 32, 0, 105, 0, 115, 0, 32, 0, 40, 3, 160, 0, 41,
A B C D
UnicodeEncoding(System.Boolean, System.Boolean) Constructor
E
[ILASM]
public rtspecialname specialname instance void .ctor(bool bigEndian, bool byteOrderMark)
F G
[C#]
public UnicodeEncoding(bool bigEndian, bool byteOrderMark)
H I
Summary
J
Constructs and initializes a new instance of the System.Text.UnicodeEncoding class using the specified Boolean flags.
K L
Parameters
M N
Parameter
Description
bigEndian
A System.Boolean value that specifies the byte-ordering to use for the new instance. Specify true to use big-endian ordering; specify false to use little-endian ordering.
byteOrderMark
A System.Boolean value that specifies whether to include the Unicode byte-order mark in translated strings. Specify true to include the Unicode byte-order mark; otherwise, specify false.
O P Q R S T U
Example
V
using System; using System.Text;
W namespace Samples { public class UnicodeEncodingConstructor { public static void Main() { UnicodeEncoding u = new UnicodeEncoding();
X Y Z
3644
Contents | Index
System.Text
UnicodeEncoding CharSize Field
string s = "Pi is (\u03a0)"; int count = u.GetByteCount(s); byte[] bytes = new byte[count]; bytes = u.GetBytes(s); Console.WriteLine("Default Constructor"); foreach(Byte b in bytes) Console.Write("{0}, ", b); Console.WriteLine(); u = new UnicodeEncoding(true, false); count = u.GetByteCount(s); bytes = new byte[count]; bytes = u.GetBytes(s); Console.WriteLine("Parameterized Constructor"); foreach(Byte b in bytes) Console.Write("{0}, ", b);
A B C D E F G H
} }
I
}
J
The output is
K Default Constructor 80, 0, 105, 0, 32, 0, 105, 0, 115, 0, 32, 0, 40, 0, 160, 3, 41, 0, Parameterized Constructor 0, 80, 0, 105, 0, 32, 0, 105, 0, 115, 0, 32, 0, 40, 3, 160, 0, 41,
L M N O
UnicodeEncoding.CharSize Field
P
[ILASM]
Q
.field public static literal int32 CharSize
R
[C#]
public const int CharSize = 2
S
Summary
T
Represents the Unicode version 2.0 character size in bytes.
U V
Description
W
The value of this field is a 32-bit signed constant, with a value of two.
X
Example
Y
The following example demonstrates how to return the value of System.Text.UnicodeEncoding.CharSize and display it to the console.
Z
3645
Contents | Index
UnicodeEncoding
System.Text
Equals() Method
UnicodeEncoding.Equals(System.Object) Method [ILASM]
.method public hidebysig virtual bool Equals(object value)
A
[C#]
public override bool Equals(object value)
B C
Summary
D
Determines whether the current instance and the specified System.Object represent the same type and value.
E F
Parameters
G H
Parameter
Description
value
The System.Object to compare to the current instance.
I J K
Return Value
L
true if value represents the same type and value as the current instance. If value is a null reference or is not an instance of System.Text.UnicodeEncoding, returns false.
M N
Description
O
[Note: This method overrides System.Object.Equals.]
P Q
Example
R
using System; using System.Text;
S
namespace Samples { public class UnicodeEncodingEquals { public static void Main() { UnicodeEncoding u1 = new UnicodeEncoding(); UnicodeEncoding u2 = new UnicodeEncoding( true, false); Console.WriteLine("u1.Equals(u1): {0}", u1.Equals(u1)); Console.WriteLine("u1.Equals(u2): {0}", u1.Equals(u2));
T U V W X Y Z
3646
Contents | Index
System.Text
UnicodeEncoding GetByteCount() Method
Console.WriteLine("u2.Equals(u1): {0}", u2.Equals(u1)); } }
A
}
B
The output is
C
u1.Equals(u1): True u1.Equals(u2): False u2.Equals(u1): False
D E F G
UnicodeEncoding.GetByteCount(System.Char[], System.Int32, System.Int32) Method
H
[ILASM]
I
.method public hidebysig virtual int32 GetByteCount(class System.Char[] chars, int32 index, int32 count)
J
[C#]
K
public override int GetByteCount(char[] chars, int index, int count)
L
Summary
M
Determines the exact number of bytes required to encode the specified range of the specified array of characters as Unicode-encoded characters.
N O P
Parameters
Q
Parameter
Description
R
chars
A System.Char array to encode as Unicode-encoded characters.
S
index
A System.Int32 that specifies the first index of chars to encode.
count
A System.Int32 that specifies the number of elements in chars to encode.
T U V W
Return Value
X
A System.Int32 whose value equals the number of bytes required to encode the range in chars from index to index + count – 1 as Unicode-encoded characters.
Y Z
3647
Contents | Index
UnicodeEncoding
System.Text
GetByteCount() Method
Description [Note: This method overrides System.Text.Encoding.GetByteCount.] A
Exceptions
B C D
Exception
Condition
System.ArgumentNullException
chars is null.
E
index < 0.
F
-or-
G
System.ArgumentOutOfRangeException
count < 0. -or-
H
index and count do not specify a valid range in chars (i.e., (index + count) > chars.Length).
I J K
Example
L
using System; using System.Text;
M namespace Samples { public class UnicodeEncodingGetByteCount { public static void Main() { UnicodeEncoding u = (UnicodeEncoding) Encoding.Unicode; string s = "Pi is (\u03a0)"; char[] chars = s.ToCharArray(); int count = u.GetByteCount(chars, 0, chars.Length); Console.WriteLine("GetByteCount is {0}", count); byte[] bytes = new byte[count]; u.GetBytes(s, 0, s.Length, bytes, 0); foreach(Byte b in bytes) Console.Write("{0}, ", b); Console.WriteLine(); } } }
N O P Q R S T U V W X Y
The output is
Z
GetByteCount is 18 80, 0, 105, 0, 32, 0, 105, 0, 115, 0, 32, 0, 40, 0, 160, 3, 41, 0,
3648
Contents | Index
System.Text
UnicodeEncoding GetByteCount() Method
UnicodeEncoding.GetByteCount(System.String) Method [ILASM]
.method public hidebysig virtual int32 GetByteCount(string s) [C#]
A
public override int GetByteCount(string s)
B
Summary
C
Returns the number of bytes required to encode the specified string as Unicode-encoded characters.
D E F
Parameters
G
Parameter
Description
H
s
A System.String to encode as Unicode-encoded characters.
I J
Return Value
K
A System.Int32 containing the number of bytes needed to encode s as Unicode-encoded characters.
L M
Description
N
[Note: This method overrides System.Text.Encoding.GetByteCount.]
O P
Exceptions
Q
Exception
Condition
R
System.ArgumentNullException
s is null.
S T U
Example
V
using System; using System.Text;
W
namespace Samples { public class UnicodeEncodingGetByteCount { public static void Main() { UnicodeEncoding u = (UnicodeEncoding) Encoding.Unicode; string s = "Pi is (\u03a0)";
X Y Z
3649
Contents | Index
UnicodeEncoding
System.Text
GetBytes() Method
int count = u.GetByteCount(s); Console.WriteLine("GetByteCount is {0}", count); byte[] bytes = new byte[count]; u.GetBytes(s, 0, s.Length, bytes, 0); foreach(Byte b in bytes) Console.Write("{0}, ", b); Console.WriteLine();
A B }
C }
D
}
E
The output is
F GetByteCount is 18 80, 0, 105, 0, 32, 0, 105, 0, 115, 0, 32, 0, 40, 0, 160, 3, 41, 0,
G H I J
UnicodeEncoding.GetBytes(System.Char[], System.Int32, System.Int32, System.Byte[], System.Int32) Method
K
[ILASM]
L
.method public hidebysig virtual int32 GetBytes(class System.Char[] chars, int32 charIndex, int32 charCount, class System.Byte[] bytes, int32 byteIndex)
M
[C#]
N
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
O P
Summary
Q
Encodes the specified range of the specified character array into the specified range of the specified byte array as Unicode-encoded characters.
R
Parameters
S T
Parameter
Description
V
chars
A System.Char array of characters to encode as Unicode-encoded characters.
W
charIndex
A System.Int32 that specifies the first index of chars to encode.
charCount
A System.Int32 that specifies the number of elements in chars to encode.
bytes
A System.Byte array to encode into.
byteIndex
A System.Int32 that specifies the first index of bytes to encode into.
U
X Y Z
3650
Contents | Index
System.Text
UnicodeEncoding GetBytes() Method
Return Value A System.Int32 containing the number of bytes encoded into bytes as Unicode-encoded characters. A
Description
B
[Note: This method overrides System.Text.Encoding.GetBytes.System.Text.UnicodeEncoding.GetByteCount can be used to determine the exact number of bytes that will be produced for a given range of characters. Alternatively, System.Text.UnicodeEncoding.GetMaxByteCount can be used to determine the maximum number of bytes that will be produced for a given number of characters, regardless of the actual character values.]
C D E F G H
Exceptions
I
Exception
Condition
System.ArgumentException
bytes does not contain sufficient space to store the encoded characters.
J K L
chars is null. System.ArgumentNullException
M
-or-
N
bytes is null.
O
charIndex < 0.
P
-or-
System.ArgumentOutOfRangeException
charCount < 0.
Q
-or-
R
byteIndex < 0.
S
-or-
T
charIndex and charCount do not specify a valid range in chars (i.e., (charIndex + charCount) > chars.Length).
U
-or-
V
byteIndex > bytes.Length.
W X Y Z
3651
Contents | Index
UnicodeEncoding
System.Text
GetBytes() Method
Example using System; using System.Text;
A namespace Samples { public class UnicodeEncodingGetBytes { public static void Main() { UnicodeEncoding u = (UnicodeEncoding) Encoding.Unicode; string s = "Pi is (\u03a0)"; char[] chars = s.ToCharArray(); int count = u.GetByteCount(chars, 0, chars.Length); Console.WriteLine("GetByteCount is {0}", count); byte[] bytes = new byte[count]; u.GetBytes(chars, 0, chars.Length, bytes, 0); foreach(Byte b in bytes) Console.Write("{0}, ", b); Console.WriteLine(); } } }
B C D E F G H I J K L M
The output is
N
GetByteCount is 18 80, 0, 105, 0, 32, 0, 105, 0, 115, 0, 32, 0, 40, 0, 160, 3, 41, 0,
O P Q
UnicodeEncoding.GetBytes(System.String) Method
R
[ILASM]
S
.method public hidebysig virtual class System.Byte[] GetBytes(string s) [C#]
T
public override byte[] GetBytes(string s)
U V
Summary
W
Encodes the specified string as Unicode-encoded characters.
X
Parameters
Y Z
Parameter
Description
s
A System.String to encode as Unicode-encoded characters.
3652
Contents | Index
System.Text
UnicodeEncoding GetBytes() Method
Return Value A System.Byte array containing the encoded representation of s as Unicode-encoded characters. A
Description
B
[Note: This method overrides System.Text.Encoding.GetBytes.]
C D
Exceptions
E
Exception
Condition
System.ArgumentNullException
s is null.
F G H I
Example
J
using System; using System.Text;
K L
namespace Samples { public class UnicodeEncodingGetBytes { public static void Main() { UnicodeEncoding u = (UnicodeEncoding) Encoding.Unicode; string s = "Pi is (\u03a0)"; byte[] bytes = u.GetBytes(s); Console.WriteLine("bytes.Length is {0}", bytes.Length); foreach(Byte b in bytes) Console.Write("{0}, ", b); Console.WriteLine(); } } }
M N O P Q R S T U V W
The output is
X bytes.Length is 18 80, 0, 105, 0, 32, 0, 105, 0, 115, 0, 32, 0, 40, 0, 160, 3, 41, 0,
Y Z
3653
Contents | Index
UnicodeEncoding
System.Text
GetBytes() Method
UnicodeEncoding.GetBytes(System.String, System.Int32, System.Int32, System.Byte[], System.Int32) Method [ILASM]
A
.method public hidebysig virtual int32 GetBytes(string s, int32 charIndex, int32 charCount, class System.Byte[] bytes, int32 byteIndex)
B
[C#]
C
public override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex)
D E
Summary
F
Encodes the specified range of the specified string into the specified range of the specified array of bytes as Unicode-encoded characters.
G H
Parameters
I J
Parameter
Description
s
A System.String to encode as Unicode-encoded characters.
charIndex
A System.Int32 that specifies the first index of s from which to encode.
N
charCount
A System.Int32 that specifies the number of elements in s to encode.
O
bytes
A System.Byte array to encode into.
byteIndex
A System.Int32 that specifies the first index of bytes to encode into.
K L M
P Q R
Return Value
S
A System.Int32 whose value equals the number of bytes encoded into bytes as Unicodeencoded characters.
T U
Description
V
[Note: This method overrides System.Text.Encoding.GetBytes.]
W X Y Z
3654
Contents | Index
System.Text
UnicodeEncoding GetBytes() Method
Exceptions Exception
Condition
System.ArgumentException
bytes does not contain sufficient space to store the encoded characters.
System.ArgumentNullException
s is null. -orbytes is null.
System.ArgumentOutOfRangeException
charIndex < 0. -orcharCount < 0. -orbyteIndex < 0. -orcharIndex and charCount do not specify a valid range in s (i.e., (charIndex + charCount) > s.Length). -orbyteIndex >= bytes.Length.
A B C D E F G H I J K L M N
Example
O
using System; using System.Text;
P Q
namespace Samples { public class UnicodeEncodingGetBytes { public static void Main() { UnicodeEncoding u = (UnicodeEncoding) Encoding.Unicode; string s = "Pi is (\u03a0)"; int count = u.GetByteCount(s); Console.WriteLine("GetByteCount is {0}", count); byte[] bytes = new byte[count]; u.GetBytes(s, 0, s.Length, bytes, 0); foreach(Byte b in bytes) Console.Write("{0}, ", b); Console.WriteLine(); } } }
R S T U V W X Y Z
3655
Contents | Index
UnicodeEncoding
System.Text
GetCharCount() Method
The output is GetByteCount is 18 80, 0, 105, 0, 32, 0, 105, 0, 115, 0, 32, 0, 40, 0, 160, 3, 41, 0,
A B
D
UnicodeEncoding.GetCharCount(System.Byte[], System.Int32, System.Int32) Method
E
[ILASM]
F
.method public hidebysig virtual int32 GetCharCount(class System.Byte[] bytes, int32 index, int32 count)
C
[C#]
G
public override int GetCharCount(byte[] bytes, int index, int count)
H I
Summary
J
Determines the exact number of characters that will be produced by decoding the specified range of the specified array of bytes as Unicode-encoded characters.
K
Parameters
L M
Parameter
Description
O
bytes
A System.Byte array to decode as Unicode-encoded characters.
P
index
A System.Int32 that specifies the first index in bytes to decode.
count
A System.Int32 that specifies the number of elements in bytes to decode.
N
Q R S
Return Value
T
A System.Int32 whose value equals the number of characters a call to System.Text.UnicodeEncoding.GetChars will produce if presented with the specified range of bytes as Unicode-encoded characters.
U V W
Description
X
[Note: This method overrides System.Text.Encoding.GetCharCount.]
Y Z
3656
Contents | Index
System.Text
UnicodeEncoding GetCharCount() Method
Exceptions Exception
Condition
System.ArgumentNullException
bytes is null.
A
System.ArgumentOutOfRangeException
B
index < 0.
C
-or-
D
count < 0.
E
-or-
F
index and count do not specify a valid range in bytes (i.e., (index + count) > bytes.Length).
G H
Example
I
using System; using System.Text;
J K
namespace Samples { public class UnicodeEncodingGetCharCount { public static void Main() { UnicodeEncoding u = (UnicodeEncoding) Encoding.Unicode; string s = "Pi is (\u03a0)"; Byte[] bytes = u.GetBytes(s); foreach(Byte b in bytes) Console.Write("{0}, ", b); Console.WriteLine(); int count = u.GetCharCount(bytes, 0, bytes.Length); Console.WriteLine("GetCharCount is {0}", count); Char[] chars = new Char[count]; u.GetChars(bytes, 0, bytes.Length, chars, 0); foreach(Int16 i in chars) Console.Write("{0}, ", i); Console.WriteLine(); } } }
L M N O P Q R S T U V W X Y
The output is
Z 80, 0, 105, 0, 32, 0, 105, 0, 115, 0, 32, 0, 40, 0, 160, 3, 41, 0, GetCharCount is 9 80, 105, 32, 105, 115, 32, 40, 928, 41,
3657
Contents | Index
UnicodeEncoding
System.Text
GetChars() Method
UnicodeEncoding.GetChars(System.Byte[], System.Int32, System.Int32, System.Char[], System.Int32) Method [ILASM]
A
.method public hidebysig virtual int32 GetChars(class System.Byte[] bytes, int32 byteIndex, int32 byteCount, class System.Char[] chars, int32 charIndex)
B
[C#]
C
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
D E
Summary
F
Decodes the specified range of the specified array of bytes into the specified range of the specified array of characters as Unicode-encoded characters.
G H
Parameters
I J
Parameter
Description
bytes
A System.Byte array to decode as Unicode-encoded characters.
byteIndex
A System.Int32 that specifies the first index of bytes from which to decode.
N
byteCount
A System.Int32 that specifies the number of elements in bytes to decode.
O
chars
A System.Char array to decode into.
charIndex
A System.Int32 that specifies the first index of chars to store the decoded bytes.
K L M
P Q R S
Return Value
T
A System.Int32 containing the number of characters decoded into chars as Unicodeencoded characters.
U V
Description
W
[Note: This method overrides System.Text.Encoding.GetChars. System.Text.UnicodeEncoding.GetCharCount can be used to determine the exact number of characters that will be produced for a given range of bytes. Alternatively, System.Text.UnicodeEncoding.GetMaxCharCount can be used to determine the maximum number of characters that will be produced for a given number of bytes, regardless of the actual byte values.]
X Y Z
3658
Contents | Index
System.Text
UnicodeEncoding GetChars() Method
Exceptions Exception
Condition
System.ArgumentException
chars does not contain sufficient space to store the decoded characters.
A B C
chars is null. System.ArgumentNullException
D
-or-
E
bytes is null.
F
byteIndex < 0.
G
-or-
System.ArgumentOutOfRangeException
byteCount < 0.
H
-or-
I
charIndex < 0.
J
-or-
K
byteIndex and byteCount do not specify a valid range in bytes (i.e., (byteIndex + byteCount ) > bytes.Length).
L M
-or-
N
charIndex > chars.Length.
O P
Example
Q
using System; using System.Text;
R S
namespace Samples { public class UnicodeEncodingGetChars { public static void Main() { UnicodeEncoding u = (UnicodeEncoding) Encoding.Unicode; string s = "Pi is (\u03a0)"; Byte[] bytes = u.GetBytes(s); foreach(Byte b in bytes) Console.Write("{0}, ", b); Console.WriteLine(); int count = u.GetCharCount(bytes, 0, bytes.Length); Console.WriteLine("GetCharCount is {0}", count); Char[] chars = new Char[count];
T U V W X Y Z
3659
Contents | Index
UnicodeEncoding
System.Text
GetDecoder() Method
u.GetChars(bytes, 0, bytes.Length, chars, 0); foreach(Int16 i in chars) Console.Write("{0}, ", i); Console.WriteLine();
A
} }
B }
C
The output is
D E
80, 0, 105, 0, 32, 0, 105, 0, 115, 0, 32, 0, 40, 0, 160, 3, 41, 0, GetCharCount is 9 80, 105, 32, 105, 115, 32, 40, 928, 41,
F G H
UnicodeEncoding.GetDecoder() Method
I [ILASM]
J
.method public hidebysig virtual class System.Text.Decoder GetDecoder()
K
[C#]
public override Decoder GetDecoder()
L M
Summary
N
Returns a System.Text.Decoder object for the current instance.
O
Description
P
[Note: This method overrides System.Text.Encoding.GetDecoder. Unlike the System.Text.UnicodeEncoding.GetChars method, the System.Text.Decoder.GetChars method provided by a System.Text.Decoder object can convert partial sequences of bytes into partial sequences of characters by maintaining the appropriate state between the conversions. This implementation returns a decoder that simply forwards calls to System.Text.UnicodeEncoding.GetCharCount and System.Text.UnicodeEncoding.GetChars to the corresponding methods of the current instance. It is recommended that encoding implementations that require state to be maintained between successive conversions override this method and return an instance of an appropriate decoder implementation.]
Q R S T U V W X
Example
Y
using System; using System.Text;
Z
namespace Samples {
3660
Contents | Index
System.Text
UnicodeEncoding GetHashCode() Method
public class UnicodeEncodingGetDecoder { public static void Main() { UnicodeEncoding u = (UnicodeEncoding) Encoding.Unicode; Decoder d = u.GetDecoder(); Byte[] bytes1 = {80, 0, 105, 0, 32, 0, 105, 0, 115, 0, 32, 0, 40, 0, 160}; int size = u.GetMaxCharCount(bytes1.Length); Console.WriteLine("size is: {0}", size); Byte[] bytes2 = {3, 41, 0}; size += u.GetMaxCharCount(bytes2.Length); Console.WriteLine("size is: {0}", size); Char[] chars = new char[size]; int count = d.GetChars(bytes1, 0, bytes1.Length, chars, 0); Console.WriteLine("count: {0}", count); count += d.GetChars(bytes2, 0, bytes2.Length, chars, count); Console.WriteLine("count: {0}", count); for(int i = 0; i < count; i++) Console.Write("{0}, ", (int)chars[i]); Console.WriteLine(); } }
A B C D E F G H I J K L M N O
}
P Q
The output is
R
size is: 8 size is: 10 count: 7 count: 9 80, 105, 32, 105, 115, 32, 40, 928, 41,
S T U V
UnicodeEncoding.GetHashCode() Method
W
[ILASM]
X
.method public hidebysig virtual int32 GetHashCode() [C#]
Y
public override int GetHashCode()
Z
3661
Contents | Index
UnicodeEncoding
System.Text
GetMaxByteCount() Method
Summary Generates a hash code for the current instance. A
Return Value
B
A System.Int32 containing the hash code for the current instance.
C D
Description
E
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
F G
Example
H
using System; using System.Text;
I namespace Samples { public class UnicodeEncodingGetHashCode { public static void Main() { UnicodeEncoding u = (UnicodeEncoding) Encoding.Unicode; Console.WriteLine("u.GetHashCode: {0}", u.GetHashCode()); u = new UnicodeEncoding(true, false); Console.WriteLine("u.GetHashCode: {0}", u.GetHashCode()); } } }
J K L M N O P Q R S
The output is
T u.GetHashCode: 1200 u.GetHashCode: 1201
U V W
UnicodeEncoding.GetMaxByteCount(System.Int32) Method
X [ILASM]
Y
.method public hidebysig virtual int32 GetMaxByteCount(int32 charCount)
Z
[C#]
public override int GetMaxByteCount(int charCount)
3662
Contents | Index
System.Text
UnicodeEncoding GetMaxByteCount() Method
Summary Returns the maximum number of bytes required to encode the specified number of characters as Unicode-encoded characters, regardless of the actual character values. A
Parameters
B C
Parameter
Description
charCount
A System.Int32 whose value represents a number of characters to encode as Unicode-encoded characters.
D E F
Return Value
G
A System.Int32 containing the maximum number of bytes required to encode charCount characters as Unicode-encoded characters.
H
Description
J
[Note: This method overrides System.Text.Encoding.GetMaxByteCount. Use this method to determine an appropriate minimum buffer size for byte arrays passed to System.Text.UnicodeEncoding.GetBytes or System.Text.Encoder.GetBytes for the current instance. Using this minimum buffer size can help ensure that buffer overflow exceptions do not occur.]
K
I
L M N O
Exceptions
P
Exception
Condition
Q
System.ArgumentOutOfRangeException
charCount < 0.
R S
Example
T
using System; using System.Text;
U V
namespace Samples { public class UnicodeEncodingGetMaxByteCount { public static void Main() { UnicodeEncoding u = new UnicodeEncoding(); string s = "Pi is (\u03a0)"; int count = u.GetByteCount(s);
W X Y Z
3663
Contents | Index
UnicodeEncoding
System.Text
GetMaxCharCount() Method
Console.WriteLine("GetByteCount is {0}", count); count = u.GetMaxByteCount(s.Length); Console.WriteLine("GetMaxByteCount is {0}", count); }
A
} }
B
The output is
C D
GetByteCount is 18 GetMaxByteCount is 18
E F G
UnicodeEncoding.GetMaxCharCount(System.Int32) Method
H
[ILASM]
.method public hidebysig virtual int32 GetMaxCharCount(int32 byteCount)
I
[C#]
J
public override int GetMaxCharCount(int byteCount)
K
Summary
L
Returns the maximum number of characters produced by decoding the specified number of bytes as Unicode-encoded characters, regardless of the actual byte values.
M N
Parameters
O P
Parameter
Description
byteCount
A System.Int32 specifies the number of bytes to decode as Unicodeencoded characters.
Q R S T
Return Value
U
A System.Int32 containing the maximum number of characters that would be produced by decoding byteCount bytes as Unicode-encoded characters.
V W
Description
X
[Note: This method overrides System.Text.Encoding.GetMaxCharCount. Use this method to determine an appropriate minimum buffer size for byte arrays passed to System.Text.UnicodeEncoding.GetChars or System.Text.Encoding.GetChars for the current instance. Using this minimum buffer size can help ensure that no buffer overflow exceptions will occur.]
Y Z
3664
Contents | Index
System.Text
UnicodeEncoding GetMaxCharCount() Method
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
byteCount < 0.
A B C
Example
D
using System; using System.Text;
E F
namespace Samples { public class UnicodeEncodingGetMaxCharCount { public static void Main() { UnicodeEncoding u = (UnicodeEncoding) Encoding.Unicode; Byte[] bytes1 = {80, 0, 105, 0, 32, 0, 105, 0, 115, 0, 32, 0, 40, 0, 160}; Byte[] bytes2 = {3, 41, 0}; Console.WriteLine("GetMaxCharCount is {0}", u.GetMaxCharCount(bytes1.Length)); Console.WriteLine("GetCharCount is {0}", u.GetCharCount(bytes1, 0, bytes1.Length)); Console.WriteLine("GetMaxCharCount is {0}", u.GetMaxCharCount(bytes2.Length)); Console.WriteLine("GetCharCount is {0}", u.GetCharCount(bytes2, 0, bytes2.Length)); } } }
G H I J K L M N O P Q R S T
The output is GetMaxCharCount GetCharCount is GetMaxCharCount GetCharCount is
U is 8 7 is 2 1
V W X Y Z
3665
Contents | Index
UnicodeEncoding
System.Text
GetPreamble() Method
UnicodeEncoding.GetPreamble() Method [ILASM]
.method public hidebysig virtual class System.Byte[] GetPreamble()
A
[C#]
public override byte[] GetPreamble()
B C
Summary
D
Returns the bytes used at the beginning of a System.IO.Stream instance to determine which System.Text.Encoding implementation the stream was created with.
E F
Return Value
G
A System.Byte array that identifies the System.Text.Encoding implementation used to create a System.IO.Stream.
H I
Description
J
System.Text.UnicodeEncoding.GetPreamble returns the Unicode byte-order mark (U+FEFF) in either big-endian or little-endian order, according to the ordering that the current instance was initialized with. [Note: This method overrides System.Text.Encoding.GetPreamble.]
K L M N
Example
O
using System; using System.Text;
P Q
namespace Samples { public class UnicodeEncodingGetPreamble { public static void Main() { UnicodeEncoding u = (UnicodeEncoding) Encoding.Unicode; Byte[] bytes = u.GetPreamble(); foreach(Int16 i in bytes) Console.Write("{0}, ", i); Console.WriteLine(); } } }
R S T U V W X Y Z
The output is 255, 254,
3666
Contents | Index
System.Text UTF8Encoding
BCL
Object
A
Encoding
B
UTF8Encoding
C
Summary
D
Represents a UTF8 character System.Text.Encoding.
E
Type Summary
F
public class UTF8Encoding : Encoding { // Constructors public UTF8Encoding (); public UTF8Encoding (bool encoderShouldEmitUTF8Identifier); public UTF8Encoding (bool encoderShouldEmitUTF8Identifier, bool throwOnInvalidBytes);
G H I J K
// Methods public override bool Equals (object value); public override int GetByteCount (char[] chars, int index, int count); public override int GetByteCount (string str); public override int GetBytes (char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex); public override byte[] GetBytes (string s); public override int GetBytes (string s, int charIndex, int charCount, byte[] bytes, int byteIndex); public override int GetCharCount (byte[] bytes, int index, int count); public override int GetChars (byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex); public override Decoder GetDecoder (); public override Encoder GetEncoder ();
L M N O P Q R S T U V W X Y Z
3667
Contents | Index
UTF8Encoding
System.Text
UTF8Encoding Class
public public public public
A
override override override override
int GetHashCode (); int GetMaxByteCount (int charCount); int GetMaxCharCount (int byteCount); byte[] GetPreamble ();
}
B C
BA To adhere to our own guidelines completely, this should have been Utf8Encoding. Unfortunately we closed on the acronym casing rules too late in the product cycle to fix this class.
D E F
JR Normally, there is no need for your application code to construct an Encoding-
G
derived object (such as UTF8Encoding). Instead, you normally obtain an Encodingderived object by calling one of the Encoding class’s static, read-only properties. Here is an example:
H I
UTF8Encoding utf8Encoding = Encoding.UTF8;
J K
This is more efficient because it returns a reference to a single UTF8Encoding object rather than creating new UTF8Encoding objects.
L M N
Description
O
System.Text.UTF8Encoding encodes Unicode characters using the UTF-8 encoding (UCS Transformation Format, 8-bit form). This encoding supports all Unicode character values. [Note: UTF-8 encodes Unicode characters with a variable number of bytes per character. This encoding is optimized for the lower 127 ASCII characters, yielding an efficient mechanism to encode English in an internationalizable way. The UTF-8 identifier is the Unicode byte-order mark (0xFEFF) written in UTF-8 (0xEF 0xBB 0xBF). The byte-order mark is used to distinguish UTF-8 text from other encodings. This class offers an errorchecking feature that can be turned on when an instance of the class is constructed. Certain methods in this class check for invalid sequences of surrogate pairs. If error-checking is turned on and an invalid sequence is detected, System.ArgumentException is thrown. If error-checking is not turned on and an invalid sequence is detected, no exception is thrown and execution continues in a method-defined manner. For more information regarding surrogate pairs, see System.Globalization.UnicodeCategory.]
P Q R S T U V W X Y Z
3668
Contents | Index
System.Text
UTF8Encoding UTF8Encoding() Constructor
Example using System; using System.Text;
A namespace Samples { public class UTF8EncodingSample { public static void Main() { UTF8Encoding u = (UTF8Encoding) Encoding.UTF8; string s = "Pi is (\u03a0)"; Byte[] bytes = u.GetBytes(s); foreach(Int16 i in bytes) Console.Write("{0}, ", i); Console.WriteLine(); int count = u.GetCharCount(bytes, 0, bytes.Length); char[] chars = new char[count]; u.GetChars(bytes, 0, bytes.Length, chars, 0); foreach(Int16 i in chars) Console.Write("{0}, ", i); Console.WriteLine(); } } }
B C D E F G H I J K L M N O
The output is
P
80, 105, 32, 105, 115, 32, 40, 206, 160, 41, 80, 105, 32, 105, 115, 32, 40, 928, 41,
Q R
UTF8Encoding() Constructor
S
[ILASM]
T
public rtspecialname specialname instance void .ctor()
U
[C#]
V
public UTF8Encoding()
W
Summary
X
Constructs a new instance of the System.Text.UTF8Encoding class.
Y
Description
Z
This constructor is equivalent to System.Text.UTF8Encoding(false, false). [Note: By default, this constructor turns error-checking off for the new instance.] 3669
Contents | Index
UTF8Encoding
System.Text
UTF8Encoding() Constructor
Example using System; using System.Text;
A namespace Samples { public class UTF8EncodingConstructor { public static void Main() { UTF8Encoding u = new UTF8Encoding(); string s = "Pi is (\u03a0)"; Byte[] bytes = u.GetBytes(s); foreach(Int16 i in bytes) Console.Write("{0}, ", i); Console.WriteLine(); int count = u.GetCharCount(bytes, 0, bytes.Length); char[] chars = new char[count]; u.GetChars(bytes, 0, bytes.Length, chars, 0); foreach(Int16 i in chars) Console.Write("{0}, ", i); Console.WriteLine(); } } }
B C D E F G H I J K L M N O
The output is
P
80, 105, 32, 105, 115, 32, 40, 206, 160, 41, 80, 105, 32, 105, 115, 32, 40, 928, 41,
Q R S
UTF8Encoding(System.Boolean) Constructor
T
[ILASM]
U
public rtspecialname specialname instance void .ctor(bool encoderShouldEmitUTF8Identifier)
V
[C#]
W
public UTF8Encoding(bool encoderShouldEmitUTF8Identifier)
X
Summary
Y
Constructs a new instance of the System.Text.UTF8Encoding class with the specified System.Boolean that indicates whether the Unicode byte-order mark in UTF-8 is recognized or omitted when reading from or writing to a System.IO.Stream.
Z
3670
Contents | Index
System.Text
UTF8Encoding UTF8Encoding() Constructor
Parameters Parameter
Description
encoderShouldEmitUTF8Identifier
A System.Boolean that indicates whether the Unicode byte-order mark in UTF-8 is recognized or omitted when reading from or writing to a System.IO.Stream.
A B C D
Description
E
This constructor is equivalent to System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier, false). [Note: By default, this constructor turns error-checking off for the new instance.]
F G H
Example
I
using System; using System.Text;
J K
namespace Samples { public class UTF8EncodingConstructor { public static void Main() { UTF8Encoding u = new UTF8Encoding(true); string s = "Pi is (\u03a0)"; Byte[] bytes = u.GetBytes(s); foreach(Int16 i in bytes) Console.Write("{0}, ", i); Console.WriteLine(); int count = u.GetCharCount(bytes, 0, bytes.Length); char[] chars = new char[count]; u.GetChars(bytes, 0, bytes.Length, chars, 0); foreach(Int16 i in chars) Console.Write("{0}, ", i); Console.WriteLine(); } } }
L M N O P Q R S T U V W X Y
The output is
Z 80, 105, 32, 105, 115, 32, 40, 206, 160, 41, 80, 105, 32, 105, 115, 32, 40, 928, 41,
3671
Contents | Index
UTF8Encoding
System.Text
Equals() Constructor
UTF8Encoding.Equals(System.Boolean, System.Boolean) Constructor [ILASM]
A
public rtspecialname specialname instance void .ctor(bool encoderShouldEmitUTF8Identifier, bool throwOnInvalidBytes)
B
[C#]
C
public UTF8Encoding(bool encoderShouldEmitUTF8Identifier, bool throwOnInvalidBytes)
D
Summary
E
Constructs a new instance of the System.Text.UTF8Encoding class using the specified System.Boolean flags.
F G
Parameters
H I
Parameter
Description
encoderShouldEmitUTF8Identifier
A System.Boolean that indicates whether the Unicode byte-order mark in UTF-8 is recognized or omitted when reading from or writing to a System.IO.Stream.
throwOnInvalidBytes
A System.Boolean that indicates whether error-checking is turned on for the current instance.
J K L M N O P
UTF8Encoding.Equals(System.Object) Method
Q [ILASM]
R
.method public hidebysig virtual bool Equals(object value) [C#]
S
public override bool Equals(object value)
T U
Summary
V
Determines whether the current instance and the specified System.Object represent the same type and value.
W
Parameters
X Y Z
Parameter
Description
value
A System.Object to compare with the current instance.
3672
Contents | Index
System.Text
UTF8Encoding Equals() Method
Return Value true if value is a System.Text.UTF8Encoding and represents the same type and value as the current instance; otherwise, false. A
Description
B
[Note: This method overrides System.Object.Equals.]
C D
Example
E
using System; using System.Text;
F G
namespace Samples { public class UTF8EncodingEquals { public static void Main() { UTF8Encoding u1 = (UTF8Encoding) Encoding.UTF8; UTF8Encoding u2 = new UTF8Encoding(); UTF8Encoding u3 = new UTF8Encoding(true); UTF8Encoding u4 = new UTF8Encoding(true, true); Console.WriteLine("u1.Equals(u1): {0}", u1.Equals(u1)); Console.WriteLine("u1.Equals(u2): {0}", u1.Equals(u2)); Console.WriteLine("u1.Equals(u3): {0}", u1.Equals(u3)); Console.WriteLine("u1.Equals(u4): {0}", u1.Equals(u4)); } } }
H I J K L M N O P Q R S T
The output is u1.Equals(u1): u1.Equals(u2): u1.Equals(u3): u1.Equals(u4):
U
True False True True
V W X Y Z
3673
Contents | Index
UTF8Encoding
System.Text
GetByteCount() Method
UTF8Encoding.GetByteCount(System.Char[], System.Int32, System.Int32) Method [ILASM]
A
.method public hidebysig virtual int32 GetByteCount(class System.Char[] chars, int32 index, int32 count)
B
[C#]
C
public override int GetByteCount(char[] chars, int index, int count)
D E
Summary
F
Determines the number of bytes required to encode the specified range of characters in the specified Unicode character array as a System.Text.UTF8Encoding.
G
Parameters
H I
Parameter
Description
K
chars
The System.Char array to encode as a System.Text.UTF8Encoding.
L
index
A System.Int32 that specifies the first index of chars to encode.
count
A System.Int32 that specifies the number of characters to encode.
J
M N O
Return Value
P
A System.Int32 containing the number of bytes necessary to encode the range in chars from index to index + count – 1 as a System.Text.UTF8Encoding.
Q R
Description
S
If error-checking is turned off and an invalid surrogate sequence is detected, the invalid characters are ignored and do not affect the return value, and no exception is thrown. [Note: This method overrides System.Text.Encoder.GetByteCount.]
T U V W X Y Z
3674
Contents | Index
System.Text
UTF8Encoding GetByteCount() Method
Exceptions Exception
Condition
System.ArgumentNullException
chars is null.
System.ArgumentOutOfRangeException
The return value is greater than System.Int32.MaxValue. -orindex or count is less than zero. -orindex and count do not specify a valid range in chars (i.e., (index + count) > chars.Length).
A
System.ArgumentException
B C D E F G
Error-checking is turned on for the current instance and chars contains an invalid surrogate sequence.
H I J
Example
K
using System; using System.Text;
L M
namespace Samples { public class UTF8EncodingGetByteCount { public static void Main() { UTF8Encoding u = (UTF8Encoding) Encoding.UTF8; string s = "Pi is (\u03a0)"; Char[] chars = s.ToCharArray(); int count = u.GetByteCount(chars, 0, chars.Length); Console.WriteLine("Byte count: {0}", count); Byte[] bytes = new Byte[count]; u.GetBytes(s, 0, s.Length, bytes, 0); foreach(Int16 i in bytes) Console.Write("{0}, ", i); Console.WriteLine(); count = u.GetCharCount(bytes, 0, bytes.Length); chars = new char[count]; u.GetChars(bytes, 0, bytes.Length, chars, 0); foreach(Int16 i in chars) Console.Write("{0}, ", i); Console.WriteLine(); } } }
N O P Q R S T U V W X Y Z
3675
Contents | Index
UTF8Encoding
System.Text
GetByteCount() Method
The output is Byte count: 10 80, 105, 32, 105, 115, 32, 40, 206, 160, 41, 80, 105, 32, 105, 115, 32, 40, 928, 41,
A B C
UTF8Encoding.GetByteCount(System.String) Method
D
[ILASM]
E
.method public hidebysig virtual int32 GetByteCount(string chars)
F
[C#]
public override int GetByteCount(string chars)
G H
Summary
I
Determines the number of bytes required to encode the characters in the specified System.String as a System.Text.UTF8Encoding.
J K
Parameters
L M
Parameter
Description
N
chars
A System.String to encode as a System.Text.UTF8Encoding.
O P
Return Value
Q
A System.Int32 that specifies the number of bytes necessary to encode chars as a System.Text.UTF8Encoding.
R S
Description
T
If error-checking is turned off and an invalid surrogate sequence is detected, the invalid characters are ignored and do not affect the return value, and no exception is thrown. [Note: This method overrides System.Text.Encoding.GetByteCount.]
U V W X Y Z
3676
Contents | Index
System.Text
UTF8Encoding GetByteCount() Method
Exceptions Exception
Condition
System.ArgumentNullException
chars is null.
System.ArgumentException
Error-checking is turned on for the current instance and chars contains an invalid surrogate sequence.
System.ArgumentOutOfRangeException
The return value is greater than System.Int32.MaxValue.
A B C D E F
Example
G
using System; using System.Text;
H I
namespace Samples { public class UTF8EncodingGetByteCount { public static void Main() { UTF8Encoding u = (UTF8Encoding) Encoding.UTF8; string s = "Pi is (\u03a0)"; int count = u.GetByteCount(s); Console.WriteLine("Byte count: {0}", count); Byte[] bytes = new Byte[count]; u.GetBytes(s, 0, s.Length, bytes, 0); foreach(Int16 i in bytes) Console.Write("{0}, ", i); Console.WriteLine(); count = u.GetCharCount(bytes, 0, bytes.Length); char[] chars = new char[count]; u.GetChars(bytes, 0, bytes.Length, chars, 0); foreach(Int16 i in chars) Console.Write("{0}, ", i); Console.WriteLine(); } } }
J K L M N O P Q R S T U V W X Y
The output is
Z Byte count: 10 80, 105, 32, 105, 115, 32, 40, 206, 160, 41, 80, 105, 32, 105, 115, 32, 40, 928, 41,
3677
Contents | Index
UTF8Encoding
System.Text
GetBytes() Method
UTF8Encoding.GetBytes(System.Char[], System.Int32, System.Int32, System.Byte[], System.Int32) Method [ILASM]
A
.method public hidebysig virtual int32 GetBytes(class System.Char[] chars, int32 charIndex, int32 charCount, class System.Byte[] bytes, int32 byteIndex)
B
[C#]
C
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
D E
Summary
F
Encodes the specified range of the specified System.Char array into the specified range of the specified System.Byte array as a System.Text.UTF8Encoding.
G H
Parameters
I J
Parameter
Description
chars
The System.Char array to encode as a System.Text.UTF8Encoding.
charIndex
A System.Int32 that specifies the first index of chars to encode.
N
charCount
A System.Int32 that specifies the number of characters to encode.
O
bytes
The System.Byte array to encode into.
byteIndex
A System.Int32 that specifies the first index of bytes to encode into.
K L M
P Q R
Return Value
S
A System.Int32 that indicates the number of bytes encoded into bytes as a System.Text.UTF8Encoding.
T U
Description
V
If error-checking is turned off and an invalid surrogate sequence is detected, the invalid characters are ignored and are not encoded into bytes, and no exception is thrown. [Note: This method overrides System.Text.Encoding.GetBytes.System.Text.UTF8Encoding.GetByteCount can be used to determine the exact number of bytes that will be produced for a given range of characters. Alternatively, System.Text.UTF8Encoding.GetMaxByteCount can be used to determine the maximum number of bytes that will be produced for a specified number of characters, regardless of the actual character values.]
W X Y Z
3678
Contents | Index
System.Text
UTF8Encoding GetBytes() Method
Exceptions Exception
Condition A
System.ArgumentException
bytes does not contain sufficient space to store the encoded characters.
B
-or-
C
Error-checking is turned on for the current instance and chars contains an invalid surrogate sequence.
D E
System.ArgumentNullException
chars or bytes is null.
F G
charIndex, charCount, or byteIndex is less than zero.
H
-orSystem.ArgumentOutOfRangeException
(chars.Length – charIndex) < charCount.
I
-or-
J
byteIndex > bytes.Length.
K L
Example
M
using System; using System.Text;
N O
namespace Samples { public class UTF8EncodingGetBytes { public static void Main() { UTF8Encoding u = (UTF8Encoding) Encoding.UTF8; string s = "Pi is (\u03a0)"; Char[] chars = s.ToCharArray(); int count = u.GetByteCount(chars, 0, chars.Length); Byte[] bytes = new Byte[count]; u.GetBytes(chars, 0, s.Length, bytes, 0); foreach(Int16 i in bytes) Console.Write("{0}, ", i); Console.WriteLine(); count = u.GetCharCount(bytes, 0, bytes.Length); chars = new char[count]; u.GetChars(bytes, 0, bytes.Length, chars, 0); foreach(Int16 i in chars)
P Q R S T U V W X Y Z
3679
Contents | Index
UTF8Encoding
System.Text
GetBytes() Method
Console.Write("{0}, ", i); Console.WriteLine(); } }
A
}
B
The output is
C
80, 105, 32, 105, 115, 32, 40, 206, 160, 41, 80, 105, 32, 105, 115, 32, 40, 928, 41,
D E F
UTF8Encoding.GetBytes(System.String) Method
G H
[ILASM]
I
[C#]
.method public hidebysig virtual class System.Byte[] GetBytes(string s) public override byte[] GetBytes(string s)
J K
Summary
L
Encodes the specified System.String as a System.Text.UTF8Encoding.
M
Parameters
N O
Parameter
Description
s
The System.String to encode as a System.Text.UTF8Encoding.
P Q R
Return Value
S
A System.Byte array containing the values encoded from s as a System.Text.UTF8Encoding.
T U
Description
V
If error-checking is turned off and an invalid surrogate sequence is detected, the invalid characters are ignored and are not encoded into the returned System.Byte array, and no exception is thrown. [Note: This method overrides System.Text.Encoding.GetBytes.]
W X Y Z
3680
Contents | Index
System.Text
UTF8Encoding GetBytes() Method
Exceptions Exception
Condition
System.ArgumentException
Error-checking is turned on for the current instance and s contains an invalid surrogate sequence.
System.ArgumentNullException
s is null.
A B C D E
Example
F
using System; using System.Text;
G H
namespace Samples { public class UTF8EncodingGetBytes { public static void Main() { UTF8Encoding u = (UTF8Encoding) Encoding.UTF8; string s = "Pi is (\u03a0)"; Byte[] bytes = u.GetBytes(s); foreach(Int16 i in bytes) Console.Write("{0}, ", i); Console.WriteLine(); int count = u.GetCharCount(bytes, 0, bytes.Length); char[] chars = new char[count]; u.GetChars(bytes, 0, bytes.Length, chars, 0); foreach(Int16 i in chars) Console.Write("{0}, ", i); Console.WriteLine(); } } }
I J K L M N O P Q R S T U V
The output is
W 80, 105, 32, 105, 115, 32, 40, 206, 160, 41, 80, 105, 32, 105, 115, 32, 40, 928, 41,
X Y Z
3681
Contents | Index
UTF8Encoding
System.Text
GetBytes() Method
UTF8Encoding.GetBytes(System.String, System.Int32, System.Int32, System.Byte[], System.Int32) Method [ILASM]
A
.method public hidebysig virtual int32 GetBytes(string s, int32 charIndex, int32 charCount, class System.Byte[] bytes, int32 byteIndex)
B
[C#]
C
public override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex)
D E
Summary
F
Encodes the specified range of the specified System.String into the specified range of the specified System.Byte array as a System.Text.UTF8Encoding.
G H
Parameters
I J
Parameter
Description
s
The System.String to encode as a System.Text.UTF8Encoding.
charIndex
A System.Int32 that specifies the first index of s to encode.
N
charCount
A System.Int32 that specifies the number of characters to encode.
O
bytes
The System.Byte array to encode into.
byteIndex
A System.Int32 that specifies the first index of bytes to encode into.
K L M
P Q R
Return Value
S
A System.Int32 that indicates the number of bytes encoded into bytes as a System.Text.UTF8Encoding.
T U
Description
V
If error-checking is turned off and an invalid surrogate sequence is detected, the invalid characters are ignored and are not encoded into bytes, and no exception is thrown. [Note: This method overrides System.Text.Encoding.GetBytes.]
W X Y Z
3682
Contents | Index
System.Text
UTF8Encoding GetBytes() Method
Exceptions Exception
Condition
System.ArgumentException
bytes does not contain sufficient space to store the encoded characters. -orError-checking is turned on for the current instance and chars contains an invalid surrogate sequence.
D
System.ArgumentNullException
chars or bytes is null.
E
System.ArgumentOutOfRangeException
charIndex, charCount, or byteIndex is less than zero. -or(s.Length – charIndex) < charCount. -orbyteIndex >= bytes.Length.
A B C
F G H I J K
Example
L
using System; using System.Text;
M
namespace Samples { public class UTF8EncodingGetBytes { public static void Main() { UTF8Encoding u = (UTF8Encoding) Encoding.UTF8; string s = "Pi is (\u03a0)"; int count = u.GetByteCount(s); Byte[] bytes = new Byte[count]; u.GetBytes(s, 0, s.Length, bytes, 0); foreach(Int16 i in bytes) Console.Write("{0}, ", i); Console.WriteLine(); count = u.GetCharCount(bytes, 0, bytes.Length); char[] chars = new char[count]; u.GetChars(bytes, 0, bytes.Length, chars, 0); foreach(Int16 i in chars) Console.Write("{0}, ", i); Console.WriteLine(); } } }
N O P Q R S T U V W X Y Z
3683
Contents | Index
UTF8Encoding
System.Text
GetCharCount() Method
The output is 80, 105, 32, 105, 115, 32, 40, 206, 160, 41, 80, 105, 32, 105, 115, 32, 40, 928, 41,
A B
D
UTF8Encoding.GetCharCount(System.Byte[], System.Int32, System.Int32) Method
E
[ILASM]
F
.method public hidebysig virtual int32 GetCharCount(class System.Byte[] bytes, int32 index, int32 count)
C
[C#]
G
public override int GetCharCount(byte[] bytes, int index, int count)
H I
Summary
J
Returns the number of characters produced by decoding the specified range of the specified System.Byte array as a System.Text.UTF8Encoding.
K
Parameters
L M
Parameter
Description
O
bytes
The System.Byte array to decode as a System.Text.UTF8Encoding.
P
index
A System.Int32 that specifies the first index of bytes to decode.
count
A System.Int32 that specifies the number of bytes to decode.
N
Q R S
Return Value
T
A System.Int32 that indicates the number of characters produced by decoding the range in bytes from index to index + count – 1 as a System.Text.UTF8Encoding.
U V
Description
W
If error-checking is turned off and an invalid surrogate sequence is detected, the invalid bytes are ignored and do not affect the return value, and no exception is thrown. [Note: This method overrides System.Text.Encoding.GetCharCount.]
X Y Z
3684
Contents | Index
System.Text
UTF8Encoding GetCharCount() Method
Exceptions Exception
Condition A
System.ArgumentNullException
bytes is null.
B C
index or count is less than zero. System.ArgumentOutOfRangeException
System.ArgumentException
D
-orindex and count do not specify a valid range in bytes (i.e., (index + count) > bytes.Length).
E
Error-checking is turned on for the current instance and bytes contains an invalid surrogate sequence.
G
F
H I
Example
J
using System; using System.Text;
K L
namespace Samples { public class UTF8EncodingGetCharCount { public static void Main() { UTF8Encoding u = (UTF8Encoding) Encoding.UTF8; string s = "Pi is (\u03a0)"; Char[] chars = s.ToCharArray(); int count = u.GetByteCount(chars, 0, chars.Length); Byte[] bytes = new Byte[count]; u.GetBytes(s, 0, s.Length, bytes, 0); foreach(Int16 i in bytes) Console.Write("{0}, ", i); Console.WriteLine(); count = u.GetCharCount(bytes, 0, bytes.Length); chars = new char[count]; u.GetChars(bytes, 0, bytes.Length, chars, 0); foreach(Int16 i in chars) Console.Write("{0}, ", i); Console.WriteLine(); } } }
M N O P Q R S T U V W X Y Z
3685
Contents | Index
UTF8Encoding
System.Text
GetChars() Method
The output is 80, 105, 32, 105, 115, 32, 40, 206, 160, 41, 80, 105, 32, 105, 115, 32, 40, 928, 41,
A B
D
UTF8Encoding.GetChars(System.Byte[], System.Int32, System.Int32, System.Char[], System.Int32) Method
E
[ILASM]
F
.method public hidebysig virtual int32 GetChars(class System.Byte[] bytes, int32 byteIndex, int32 byteCount, class System.Char[] chars, int32 charIndex)
C
[C#]
G
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
H I
Summary
J
Decodes the specified range of the specified System.Byte array into the specified range of the specified System.Char array as a System.Text.UTF8Encoding.
K L
Parameters
M N
Parameter
Description
bytes
The System.Byte array to decode as a System.Text.UTF8Encoding.
Q
byteIndex
A System.Int32 that specifies the first index of bytes to decode.
R
byteCount
A System.Int32 that specifies the number of bytes to decode.
S
chars
The System.Char array to decode into.
charIndex
A System.Int32 that specifies the first index of chars to decode into.
O P
T U V
Return Value
W
The number of characters decoded into chars as a System.Text.UTF8Encoding.
X Y
Description
Z
If error-checking is turned off and an invalid surrogate sequence is detected, the invalid bytes are ignored and are not encoded into chars, and no exception is thrown.
3686
Contents | Index
System.Text
UTF8Encoding GetChars() Method
[Note: This method overrides System.Text.Encoding.GetChars.System.Text.UTF8Encoding.GetCharCount can be used to determine the exact number of characters that will be produced for a specified range of bytes. Alternatively, System.Text.UTF8Encoding.GetMaxCharCount can be used to determine the maximum number of characters that will be produced for a specified number of bytes, regardless of the actual byte values.]
A B C D
Exceptions
E
Exception
Condition
F
chars does not contain sufficient space to store the decoded characters. System.ArgumentException
System.ArgumentNullException
G H
-orError-checking is turned on for the current instance and bytes contains an invalid surrogate sequence.
I
bytes or chars is null.
K
J
L
byteIndex, byteCount, or charIndex is less than zero.
M
-orSystem.ArgumentOutOfRangeException
N
(bytes.Length – byteIndex) < byteCount. -or-
O
charIndex > chars.Length.
P Q
Example
R
using System; using System.Text;
S
namespace Samples { public class UTF8EncodingGetChars { public static void Main() { UTF8Encoding u = (UTF8Encoding) Encoding.UTF8; string s = "Pi is (\u03a0)"; Char[] chars = s.ToCharArray(); int count = u.GetByteCount(chars, 0, chars.Length); Byte[] bytes = new Byte[count];
U
T
V W X Y Z
3687
Contents | Index
UTF8Encoding
System.Text
GetDecoder() Method
u.GetBytes(chars, 0, s.Length, bytes, 0); foreach(Int16 i in bytes) Console.Write("{0}, ", i); Console.WriteLine(); count = u.GetCharCount(bytes, 0, bytes.Length); chars = new char[count]; u.GetChars(bytes, 0, bytes.Length, chars, 0); foreach(Int16 i in chars) Console.Write("{0}, ", i); Console.WriteLine();
A B C D E }
F
} }
G
The output is
H I
80, 105, 32, 105, 115, 32, 40, 206, 160, 41, 80, 105, 32, 105, 115, 32, 40, 928, 41,
J K L
UTF8Encoding.GetDecoder() Method
M
[ILASM]
N
.method public hidebysig virtual class System.Text.Decoder GetDecoder() [C#]
O
public override Decoder GetDecoder()
P
Summary
Q
Returns a System.Text.Decoder for the current instance.
R S
Description
T
[Note: This method overrides System.Text.Encoding.GetDecoder. Contrary to System.Text.UTF8Encoding.GetChars, a decoder can convert partial sequences of bytes into partial sequences of characters by maintaining the appropriate state between the conversions.]
U V W X
Example
Y
using System; using System.Text;
Z
namespace Samples { public class UTF8EncodingGetDecoder
3688
Contents | Index
System.Text
UTF8Encoding GetEncoder() Method
{ private const int limit = 512; public static void Main() { UTF8Encoding u = (UTF8Encoding) Encoding.UTF8; Decoder d = u.GetDecoder(); Byte[] bytes1 = new Byte[]{80, 105, 32, 105, 115, 32, 40, 206}; Byte[] bytes2 = new Byte[]{160, 41}; char[] chars = new char[limit]; int count = d.GetChars(bytes1, 0, bytes1.Length, chars, 0); count += d.GetChars(bytes2, 0, bytes2.Length, chars, count); for(int i = 0; i < count; i++) Console.Write("{0}, ", (int) chars[i]); Console.WriteLine();
A B C D E F G H I
}
J
}
K
}
L
The output is
M 80, 105, 32, 105, 115, 32, 40, 928, 41,
N O
UTF8Encoding.GetEncoder() Method
P
[ILASM]
Q
.method public hidebysig virtual class System.Text.Encoder GetEncoder()
R
[C#]
public override Encoder GetEncoder()
S
Summary
T
Returns a System.Text.Encoder for the current instance.
U V
Description
W
[Note: This method overrides System.Text.Encoding.GetEncoder. Contrary to System.Text.UTF8Encoding.GetBytes, an encoder can convert partial sequences of characters into partial sequences of bytes by maintaining the appropriate state between the conversions.]
X Y Z
3689
Contents | Index
UTF8Encoding
System.Text
GetHashCode() Method
Example using System; using System.Text;
A namespace Samples { public class UTF8EncodingGetEncoder { private const int limit = 512; public static void Main() { UTF8Encoding u = (UTF8Encoding) Encoding.UTF8; Encoder e = u.GetEncoder(); char[] chars1 = new char[]{'P', 'i', ' ', 'i', 's', ' '}; char[] chars2 = new char[]{'(', '\u03a0', ')'}; byte[] bytes = new byte[limit]; int count = e.GetBytes(chars1, 0, chars1.Length, bytes, 0, false); count += e.GetBytes(chars2, 0, chars2.Length, bytes, count, false); for(int i = 0; i < count; i++) Console.Write("{0}, ", (int) bytes[i]); Console.WriteLine(); } } }
B C D E F G H I J K L M N O
The output is
P
80, 105, 32, 105, 115, 32, 40, 206, 160, 41,
Q R S
UTF8Encoding.GetHashCode() Method
T
[ILASM]
.method public hidebysig virtual int32 GetHashCode()
U
[C#]
V
public override int GetHashCode()
W
Summary
X
Generates a hash code for the current instance.
Y
Return Value
Z
A System.Int32 value containing a hash code for the current instance.
3690
Contents | Index
System.Text
UTF8Encoding GetMaxByteCount() Method
Description The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.] A
Example
B
using System; using System.Text;
C D
namespace Samples { public class UTF8EncodingGetHashCode { public static void Main() { UTF8Encoding u1 = (UTF8Encoding) Encoding.UTF8; UTF8Encoding u2 = new UTF8Encoding(true); UTF8Encoding u3 = new UTF8Encoding(true); UTF8Encoding u4 = new UTF8Encoding(true, true); UTF8Encoding u5 = new UTF8Encoding(false, false); Console.WriteLine("u1.GetHashCode(): {0}", u1.GetHashCode()); Console.WriteLine("u2.GetHashCode(): {0}", u2.GetHashCode()); Console.WriteLine("u3.GetHashCode(): {0}", u3.GetHashCode()); Console.WriteLine("u4.GetHashCode(): {0}", u4.GetHashCode()); Console.WriteLine("u5.GetHashCode(): {0}", u5.GetHashCode()); } } }
E F G H I J K L M N O P Q R
The output is u1.GetHashCode(): u2.GetHashCode(): u3.GetHashCode(): u4.GetHashCode(): u5.GetHashCode():
S T
65002 65002 65002 65003 65001
U V W X
UTF8Encoding.GetMaxByteCount(System.Int32) Method
Y
[ILASM]
Z
.method public hidebysig virtual int32 GetMaxByteCount(int32 charCount) [C#]
public override int GetMaxByteCount(int charCount)
3691
Contents | Index
UTF8Encoding
System.Text
GetMaxByteCount() Method
Summary Returns the maximum number of bytes required to encode the specified number of characters as a System.Text.UTF8Encoding, regardless of the actual character values. A
Parameters
B C D E
Parameter
Description
charCount
A System.Int32 that specifies the number of characters to encode as a System.Text.UTF8Encoding.
F G
Return Value
H
A System.Int32 that specifies the maximum number of bytes required to encode charCount characters as a System.Text.UTF8Encoding.
I J
Description
K
[Note: This method overrides System.Text.Encoding.GetMaxByteCount. This method can be used to determine an appropriate buffer size for byte arrays passed to System.Text.UTF8Encoding.GetBytes. Using this minimum buffer size can help ensure that no buffer overflow exceptions will occur.]
L M N O
Exceptions
P Q R
Exception
Condition
System.ArgumentOutOfRangeException
charCount < 0.
S T
Example
U
using System; using System.Text;
V W
namespace Samples { public class UTF8EncodingGetMaxByteCount { public static void Main() { UTF8Encoding u = (UTF8Encoding) Encoding.UTF8; string s = "Pi is (\u03a0)";
X Y Z
3692
Contents | Index
System.Text
UTF8Encoding GetMaxCharCount() Method
Console.WriteLine("GetMaxByteCount: {0}", u.GetMaxByteCount(s.Length)); Console.WriteLine("GetByteCount: {0}", u.GetByteCount(s));
A
} }
B
}
C
The output is
D E
GetMaxByteCount: 36 GetByteCount: 10
F G
UTF8Encoding.GetMaxCharCount(System.Int32) Method
H
[ILASM]
I
.method public hidebysig virtual int32 GetMaxCharCount(int32 byteCount)
J
[C#]
public override int GetMaxCharCount(int byteCount)
K L
Summary
M
Returns the maximum number of characters produced by decoding the specified number of bytes as a System.Text.UTF8Encoding, regardless of the actual byte values.
N O
Parameters
P
Parameter
Description
byteCount
A System.Int32 that specifies the number of bytes to decode as a System.Text.UTF8Encoding.
Q R S T
Return Value
U
A System.Int32 that specifies the maximum number of characters produced by decoding byteCount bytes as a System.Text.UTF8Encoding.
V W X
Description
Y
[Note: This method overrides System.Text.Encoding.GetMaxCharCount. This method can be used to determine an appropriate minimum buffer size for character arrays passed to System.Text.UTF8Encoding.GetChars. Using this minimum buffer size can help ensure that no buffer overflow exceptions will occur.]
Z
3693
Contents | Index
UTF8Encoding
System.Text
GetPreamble() Method
Exceptions Exception
Condition
System.ArgumentOutOfRangeException
byteCount < 0.
A B C D
Example
E
using System; using System.Text;
F namespace Samples { public class UTF8EncodingGetMaxCharCount { public static void Main() { UTF8Encoding u = (UTF8Encoding) Encoding.UTF8; string s = "Pi is (\u03a0)"; byte[] bytes = u.GetBytes(s); Console.WriteLine("GetCharCount: {0}", u.GetCharCount(bytes, 0, bytes.Length)); Console.WriteLine("GetMaxCharCount: {0}", u.GetMaxCharCount( bytes.Length)); } } }
G H I J K L M N O P Q R
The output is
S GetCharCount: 9 GetMaxCharCount: 10
T U V
UTF8Encoding.GetPreamble() Method
W [ILASM]
X
.method public hidebysig virtual class System.Byte[] GetPreamble() [C#]
Y
public override byte[] GetPreamble()
Z
3694
Contents | Index
System.Text
UTF8Encoding GetPreamble() Method
Summary Returns the bytes used at the beginning of a stream to determine which encoding a file was created with. A
Return Value
B
A System.Byte array containing the UTF-8 encoding preamble.
C D
Description
E
[Note: This method overrides System.Text.Encoding.GetPreamble. System.Text.UTF8Encoding.GetPreamble returns the Unicode byte order mark (U+FEFF) written in UTF-8 (0xef, 0xbb, 0xbf) if this instance was constructed with a request to emit the UTF-8 identifier.]
F G H
Example
I
using System; using System.Text;
J K
namespace Samples { public class UTF8EncodingGetPreamble { public static void Main() { UTF8Encoding u = new UTF8Encoding(true, true); Byte[] bytes = u.GetPreamble(); foreach(Int16 i in bytes) Console.Write("{0}, ", i); Console.WriteLine(); } } }
L M N O P Q R S T
The output is
U V
239, 187, 191,
W X Y Z
3695
Contents | Index
System ValueType
BCL
Object IComparable
ValueType Enum
A
IFormattable AttributeTargets
IConvertible
B NotStandardized
C
DateTimeStyles
D
NumberStyles UnicodeCategory
E
FileAccess
F
FileMode
G
FileShare
H
SeekOrigin
I
EnvironmentPermissionAccess
J FileIOPermissionAccess
K
PermissionState SecurityAction
L
SecurityPermissionFlag
M
ThreadPriority
N
ThreadState
O
IComparable Boolean IConvertible
P
NotStandardized
Byte
Q
IComparable Char IConvertible
NotStandardized
DictionaryEntry
R
DateTime
S
Int16
T
Int32
U
Int64
IComparable
SByte
IFormattable
TimeSpan
IComparable
IConvertible
V W NotStandardized
X
UInt16
Y
UInt32
Z
UInt64 Decimal
ExtendedNumerics
Double
ExtendedNumerics
Single
ExtendedNumerics
3697
Contents | Index
ValueType
System
ValueType Class
Summary Provides support for value types. This class is the base class for all value types. A
Type Summary
B
public abstract class ValueType { // Constructors protected ValueType ();
C D E
// Methods public override bool Equals (object obj); public override int GetHashCode (); CF public override string ToString ();
F G }
H I
BA Notice we override Equals, GetHashCode, and ToString from System.Object in this class. We did this because the implementations inherited from Object rely on the object’s referential identity, so they make no sense for value types. We can also provide slightly more efficient implementations of those methods.
J K L M N
Description
O
[Note: Data types are separated into value types and reference types. Value types are either stack-allocated or allocated inline in a structure. Reference types are heap-allocated. Both reference and value types are derived from the ultimate base class System.Object. In cases where a value type needs to act like an object, a wrapper that makes the value type look like a reference object is allocated on the heap, and the value type’s value is copied into it. The wrapper is marked so that the system knows that it contains a value type. This process is known as boxing, and the reverse process is known as unboxing. Boxing and unboxing allow any type to be treated as an object.]
P Q R S T U
Example
V
using System;
W namespace Samples { public struct ValueTypeSample { private struct Point { private int xValue;
X Y Z
3698
Contents | Index
System
ValueType ValueType Class
private int yValue; public int X { get { return xValue;} set {xValue = public int Y { get { return yValue;} set {yValue = public override bool Equals(object o) { if(!(o is Point)) return false; Point p = (Point) o; return this.xValue == p.xValue && this.yValue == } public override string ToString() { return string.Format("Point: X: {0}, Y: {1}", X, } public override int GetHashCode() { return xValue ^ yValue; }
value;}} value;}}
A B C p.yValue;
D E F
Y);
G H I
} public static void Main() { Point p = new Point(); Console.WriteLine("p.ToString(): {0}", p.ToString()); Console.WriteLine("p.Equals(new Point()): {0}", p.Equals(new Point())); Console.WriteLine("p = {0}, p.GetHashCode(): {1}", p, p.GetHashCode()); p.X = 42; Console.WriteLine("p = {0}, p.GetHashCode(): {1}", p, p.GetHashCode()); p.Y = 42; Console.WriteLine("p = {0}, p.GetHashCode(): {1}", p, p.GetHashCode()); p.X = 0; Console.WriteLine("p = {0}, p.GetHashCode(): {1}", p, p.GetHashCode()); Console.WriteLine("p.Equals(new Point()): {0}", p.Equals(new Point())); }
J K L M N O P Q R S T U V
}
W
}
X
The output is
Y
p.ToString(): Point: X: 0, Y: 0 p.Equals(new Point()): True p = Point: X: 0, Y: 0, p.GetHashCode(): 0 p = Point: X: 42, Y: 0, p.GetHashCode(): 42
Z
3699
Contents | Index
ValueType
System
ValueType() Constructor
p = Point: X: 42, Y: 42, p.GetHashCode(): 0 p = Point: X: 0, Y: 42, p.GetHashCode(): 42 p.Equals(new Point()): False
A B
ValueType() Constructor
C
[ILASM]
D
family specialname instance void .ctor() [C#]
E
protected ValueType()
F
Summary
G
Constructs a new instance of the System.ValueType class.
H I J
ValueType.Equals(System.Object) Method
K
[ILASM]
.method public hidebysig virtual bool Equals(object obj)
L
[C#]
public override bool Equals(object obj)
M N
Summary
O
Determines whether the current instance and a specified System.Object represent the same value.
P Q
Parameters
R S T
Parameter
Description
obj
The System.Object to compare the current instance to.
U V
Return Value
W
true if obj and the current instance are of the same type and represent the same value; otherwise, false.
X Y
Description
Z
[Note: This method overrides System.Object.Equals.]
3700
Contents | Index
System
ValueType GetHashCode() Method
Example using System; namespace Samples { public class ValueTypeEquals { public static void Main() { int i = 0; Console.WriteLine("Is {0} equal to {1}: {2}", i, i, i.Equals(i)); Console.WriteLine("Is {0} equal to {1}: {2}", i, uint.MinValue, i.Equals(uint.MinValue)); Console.WriteLine("Is {0} equal to {1}: {2}", i, 0, i.Equals(0)); Console.WriteLine("Is {0} equal to {1}: {2}", i, 0f, i.Equals(0f)); } } }
A B C D E F G H I J K L M
The output is
N Is Is Is Is
0 0 0 0
equal equal equal equal
to to to to
0: 0: 0: 0:
True False True False
O P Q R
ValueType.GetHashCode() Method
S [ILASM]
.method public hidebysig virtual int32 GetHashCode()
T
[C#]
U
public override int GetHashCode()
V
Summary
W
Generates a hash code for the current instance.
X Y
Return Value
Z
A System.Int32 containing the hash code for the current instance.
3701
Contents | Index
ValueType
System
GetHashCode() Method
Description The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.] A B
Example
C
using System;
D
namespace Samples { public class ValueTypeGetHashCode { public static void Main() { Console.WriteLine("Value: {0}, GetHashCode(): {1}", short.MaxValue, short.MaxValue.GetHashCode()); Console.WriteLine("Value: {0}, GetHashCode(): {1}", int.MaxValue, int.MaxValue.GetHashCode()); Console.WriteLine("Value: {0}, GetHashCode(): {1}", long.MaxValue, long.MaxValue.GetHashCode()); Console.WriteLine("Value: {0}, GetHashCode(): {1}", ushort.MaxValue, ushort.MaxValue.GetHashCode()); Console.WriteLine("Value: {0}, GetHashCode(): {1}", uint.MaxValue, uint.MaxValue.GetHashCode()); Console.WriteLine("Value: {0}, GetHashCode(): {1}", ulong.MaxValue, ulong.MaxValue.GetHashCode()); Console.WriteLine("Value: {0}, GetHashCode(): {1}", ushort.MinValue, ushort.MinValue.GetHashCode()); Console.WriteLine("Value: {0}, GetHashCode(): {1}", uint.MinValue, uint.MinValue.GetHashCode()); Console.WriteLine("Value: {0}, GetHashCode(): {1}", ulong.MinValue, ulong.MinValue.GetHashCode()); } } }
E F G H I J K L M N O P Q R S T U
The output is
V Value: Value: Value: Value: Value: Value: Value: Value: Value:
W X Y Z
32767, GetHashCode(): 2147450879 2147483647, GetHashCode(): 2147483647 9223372036854775807, GetHashCode(): -2147483648 65535, GetHashCode(): 65535 4294967295, GetHashCode(): -1 18446744073709551615, GetHashCode(): 0 0, GetHashCode(): 0 0, GetHashCode(): 0 0, GetHashCode(): 0
3702
Contents | Index
System
ValueType ToString() Method
ValueType.ToString() Method [ILASM]
.method public hidebysig virtual string ToString() [C#]
A
public override string ToString()
B C
Summary
D
Returns a System.String representation of the fully qualified name of the type of the current instance.
E F
Description
G
[Note: This method overrides System.Object.ToString. This method returns the System.Type.FullName property.]
H I
Example
J
using System;
K namespace Samples { public class ValueTypeToString { public static void Main() { Console.WriteLine(int.MaxValue.ToString()); Console.WriteLine(long.MaxValue.ToString()); Console.WriteLine(uint.MinValue.ToString()); Console.WriteLine(ulong.MinValue.ToString()); Console.WriteLine(DateTime.Now.ToString()); } } }
L M N O P Q R S T
The output is
U V
2147483647 9223372036854775807 0 0 4/07/2003 12:50:55 PM
W X Y Z
3703
Contents | Index
System.Security VerificationException
BCL
Object
A
ISerializable
Exception
B
NotStandardized
SystemException VerificationException
C D
Summary
E
Represents the error that occurs when the security system requires code to be type-safe and the verification process is unable to verify that the code is type-safe.
F G
Type Summary
H
public class VerificationException : SystemException { // Constructors public VerificationException (); public VerificationException (string message); public VerificationException (string message, Exception innerException); MS CF protected VerificationException (SerializationInfo info, StreamingContext context); }
I J K L M N O
Description
P
[Note: The following IL instructions throw System.Security.VerificationException]
Q R
Example
S
using System; using System.Security; using System.Security.Permissions;
T U
[assembly: PermissionSetAttribute( SecurityAction.RequestRefuse, Name="SkipVerification")]
V W
namespace Samples { public class VerificationExceptionSample { unsafe public static void Main(string[] args) { string s = "damien";
X Y Z
3704
Contents | Index
System.Security
VerificationException VerificationException() Constructor
fixed(char *ptr = s) { for(int i = 0; i < s.Length; i++) Console.WriteLine(ptr[i]); }
A
}
B
}
C
}
D
The output is
E UnhandledException: System.Security.VerificationException: Operation could destabilize the runtime. at Samples.VerificationExceptionSample.Main(String[] args) in C:\Books\BCL\ Samples\System.Security\VerificationException\VerificationException.cs:line 15
F G H I
VerificationException() Constructor
J
[ILASM]
K
public rtspecialname specialname instance void .ctor()
L
[C#]
public VerificationException()
M
Summary
N
Constructs and initializes a new instance of the System.Security.VerificationException class.
O P Q
Description
R
This constructor initializes the System.Security.VerificationException.Message property of the new instance to a system-supplied message that describes the error, such as “Could not verify the code.” This message takes into account the current system culture. The System.Security.VerificationException.InnerException property is initialized to null.
S T U V W
VerificationException(System.String) Constructor
X [ILASM]
public rtspecialname specialname instance void .ctor(string message)
Y
[C#]
Z
public VerificationException(string message)
3705
Contents | Index
VerificationException
System.Security
VerificationException() Constructor
Summary Constructs and initializes a new instance of the System.Security.VerificationException. A
Parameters
B C D
Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
E F G H
Description
I
This constructor initializes the System.Security.VerificationException.Message property of the new instance using message. If message is null, the System.Security.VerificationException.Message property is initialized to the systemsupplied message provided by the constructor that takes no arguments. The System.Security.VerificationException.InnerException property is initialized to null.
J K L M N O
VerificationException(System.String, System.Exception) Constructor
P
[ILASM]
Q
public rtspecialname specialname instance void .ctor(string message, class System.Exception innerException)
R
[C#]
public VerificationException(string message, Exception innerException)
S T
Summary
U
Constructs and initializes a new instance of the System.Security.VerificationException class.
V W X Y Z
3706
Contents | Index
System.Security
VerificationException VerificationException() Constructor
Parameters Parameter
Description
message
A System.String that describes the error. The content of message is intended to be understood by humans. The caller of this constructor is required to ensure that this string has been localized for the current system culture.
innerException
An instance of System.Exception that is the cause of the current exception. If innerException is non-null, then the current exception was raised in a catch block handling innerException.
A B C D E F G
Description
H
This constructor initializes the System.Security.VerificationException.Message property of the new instance using message and the System.Security.VerificationException.InnerException property using innerException. If message is null, the System.Security.VerificationException.Message property is initialized to the system-supplied message provided by the constructor that takes no arguments. [Note: For more information on inner exceptions, see System.Exception.InnerException.]
I J K L M N O
VerificationException(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext) Constructor
P Q
[ILASM]
family rtspecialname specialname instance void .ctor(class System.Runtime.Serialization.SerializationInfo info, valuetype System.Runtime.Serialization.StreamingContext context)
R
[C#]
T
S
protected VerificationException(SerializationInfo info, StreamingContext context)
U
Summary
V
Initializes a new instance of the System.Security.VerificationException class with serialized data.
W X Y Z
3707
Contents | Index
VerificationException
System.Security
VerificationException() Constructor
Parameters Parameter
Description
info
The object that holds the serialized object data.
context
The contextual information about the source or destination.
A B C D E
Description
F
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream.
G H I J K L M N O P Q R S T U V W X Y Z
3708
Contents | Index
System Version
BCL
Object ICloneable
A
Version IComparable
B
Summary
C
Represents the version number of an assembly.
D E
Type Summary
F
public sealed class { // Constructors CF public Version public Version public Version public Version
Version : ICloneable, IComparable
G H
(); (int major, int minor); (int major, int minor, int build); (int major, int minor, int build, int revision); public Version (string version);
// Properties public int public int public int public int
I J K L
Build { get; } Major { get; } Minor { get; } Revision { get; }
M
// Methods public object Clone (); public int CompareTo (object version); public override bool Equals (object obj); public override int GetHashCode (); public static bool operator ==(Version v1, Version v2); public static bool operator >(Version v1, Version v2); public static bool operator >=(Version v1, Version v2); public static bool operator !=(Version v1, Version v2); public static bool operator <(Version v1, Version v2); public static bool operator <=(Version v1, Version v2); MS public override string ToString (); MS public string ToString (int fieldCount);
P
N O
Q R S T U V W X Y Z
}
3709
Contents | Index
Version
System
Version Class
Description System.Version numbers for an assembly consist of two to four components: major, minor, build, and revision. Components major and minor must be defined. Build and revision components are optional. Component revision may be used if and only if build is defined. All defined components must be a System.Int32 greater than or equal to zero.
A B C
Example
D
using System; using System.Reflection;
E
namespace Samples { public class VersionSample { public static void Main() { Type t = Typeof(String); Assembly a = Assembly.GetAssembly(t); AssemblyName an = a.GetName(); Version v = an.Version; Console.WriteLine("Version: {0}", v); Console.WriteLine("Major: {0}", v.Major); Console.WriteLine("Minor: {0}", v.Minor); Console.WriteLine("Build: {0}", v.Build); Console.WriteLine("Revision: {0}", v.Revision); v = Environment.Version; if(v.Major == 1 && v.Minor == 0) { Console.WriteLine ("You are running V1"); } else if(v.Major == 1 & v.Minor == 1) { Console.WriteLine ("You are running V1.1"); } else Console.WriteLine ("You are running an unknown version"); } } }
F G H I J K L M N O P Q R S T U V W
The output is
X
Version: 1.0.3300.0 Major: 1 Minor: 0 Build: 3300 Revision: 0 You are running V1
Y Z
3710
Contents | Index
System
Version Version() Constructor
Version() Constructor [ILASM]
public rtspecialname specialname instance void .ctor() [C#]
A
public Version()
B C
Summary
D
Constructs and initializes a new instance of the System.Version class.
E
Description
F
System.Version.Major and System.Version.Minor are set to zero. System.Version.Build and System.Version.Revision are unspecified.
G H
Example
I
using System;
J
namespace Samples { public class VersionConstructor { public static void Main() { Version v = new Version(); Console.WriteLine("Version: {0}", v); Console.WriteLine("Major: {0}", v.Major); Console.WriteLine("Minor: {0}", v.Minor); Console.WriteLine("Build: {0}", v.Build); Console.WriteLine("Revision: {0}", v.Revision); } } }
K L M N O P Q R S T
The output is
U V
Version: 0.0 Major: 0 Minor: 0 Build: -1 Revision: -1
W X Y Z
3711
Contents | Index
Version
System
Version() Constructor
Version(System.Int32, System.Int32) Constructor [ILASM]
public rtspecialname specialname instance void .ctor(int32 major, int32 minor)
A
[C#]
public Version(int major, int minor)
B C
Summary
D
Constructs and initializes a new instance of the System.Version class using the specified major and minor values.
E F
Parameters
G H I J
Parameter
Description
major
A System.Int32 specifying the major component.
minor
A System.Int32 specifying the minor component.
K L
Exceptions
M N
Exception
Condition
O
System.ArgumentOutOfRangeException
major or minor is less than zero.
P Q
Example
R
using System;
S
namespace Samples { public class VersionConstructor { public static void Main() { Version v = new Version(1, 2); Console.WriteLine("Version: {0}", v); Console.WriteLine("Major: {0}", v.Major); Console.WriteLine("Minor: {0}", v.Minor); Console.WriteLine("Build: {0}", v.Build); Console.WriteLine("Revision: {0}", v.Revision); } } }
T U V W X Y Z
3712
Contents | Index
System
Version Version() Constructor
The output is Version: 1.2 Major: 1 Minor: 2 Build: -1 Revision: -1
A B C D
Version(System.Int32, System.Int32, System.Int32) Constructor
E
[ILASM]
F
public rtspecialname specialname instance void .ctor(int32 major, int32 minor, int32 build)
G
[C#]
H
public Version(int major, int minor, int build)
I
Summary
J
Constructs and initializes a new instance of the System.Version class using the specified major, minor, and build values.
K L M
Parameters
N
Parameter
Description
major
A System.Int32 specifying the major component.
P
minor
A System.Int32 specifying the minor component.
Q
build
A System.Int32 specifying the build component.
O
R S T
Exceptions
U
Exception
Condition
System.ArgumentOutOfRangeException
major, minor, or build is less than zero.
V W X Y Z
3713
Contents | Index
Version
System
Version() Constructor
Example using System; namespace Samples { public class VersionConstructor { public static void Main() { Version v = new Version(1, 2, 3); Console.WriteLine("Version: {0}", v); Console.WriteLine("Major: {0}", v.Major); Console.WriteLine("Minor: {0}", v.Minor); Console.WriteLine("Build: {0}", v.Build); Console.WriteLine("Revision: {0}", v.Revision); } } }
A B C D E F G H I J
The output is
K L
Version: 1.2.3 Major: 1 Minor: 2 Build: 3 Revision: -1
M N O P
Version(System.Int32, System.Int32, System.Int32, System.Int32) Constructor
Q R
[ILASM]
S
public rtspecialname specialname instance void .ctor(int32 major, int32 minor, int32 build, int32 revision)
T
[C#]
U
public Version(int major, int minor, int build, int revision)
V
Summary
W
Constructs and initializes a new instance of the System.Version class with the specified major, minor, build, and revision numbers.
X Y Z
3714
Contents | Index
System
Version Version() Constructor
Parameters Parameter
Description
major
A System.Int32 specifying the major component.
minor
A System.Int32 specifying the minor component.
C
build
A System.Int32 specifying the build component.
D
revision
A System.Int32 specifying the revision component.
A B
E F G
Exceptions
H
Exception
Condition
System.ArgumentOutOfRangeException
major, minor, build, or revision is less than zero.
I J K L
Example
M
using System;
N namespace Samples { public class VersionConstructor { public static void Main() { Version v = new Version(1, 2, 3, 4); Console.WriteLine("Version: {0}", v); Console.WriteLine("Major: {0}", v.Major); Console.WriteLine("Minor: {0}", v.Minor); Console.WriteLine("Build: {0}", v.Build); Console.WriteLine("Revision: {0}", v.Revision); } } }
O P Q R S T U V W
The output is
X Y
Version: 1.2.3.4 Major: 1 Minor: 2 Build: 3 Revision: 4
Z
3715
Contents | Index
Version
System
Version() Constructor
Version(System.String) Constructor [ILASM]
public rtspecialname specialname instance void .ctor(string version)
A
[C#]
public Version(string version)
B C
Summary
D
Constructs and initializes a new instance of the System.Version class using the values represented by the specified System.String.
E F
Parameters
G H
Parameter
Description
version
A System.String that represents 2 to 4 System.Int32 integers separated by period characters ('.'). Each component delineated by a period character will be parsed to a System.Int32 with System.Int32.Parse(System.String). The numbers will be processed in the following order: major, minor, build, revision. If the revision or the revision and the build components are not represented by version, their values will be undefined.
I J K L M
[Note: The formatting of version must be as follows, with optional components shown in square brackets ('[' and']'): major.minor [.build[.revision]], where each component returns a System.Int32 with System.Int32.Parse(System.String).]
N O P
Exceptions
Q R
Exception
Condition
System.ArgumentException
version has fewer than 2 components or more than 4 components (i.e., fewer than 1 or more than 3 period characters).
System.ArgumentNullException
version is a null reference.
System.ArgumentOutOfRangeException
major, minor, build, or revision is less than zero.
System.FormatException
At least one component of version does not parse to a System.Int32 with System.Int32.Parse(System.String).
S T U V W X Y Z
3716
Contents | Index
System
Version Build Property
Example using System; namespace Samples { public class VersionConstructor { public static void Main() { Version v = new Version("1.2"); Console.WriteLine("Version: {0}", v); Console.WriteLine("Major: {0}", v.Major); Console.WriteLine("Minor: {0}", v.Minor); Console.WriteLine("Build: {0}", v.Build); Console.WriteLine("Revision: {0}", v.Revision); } } }
A B C D E F G H I J
The output is
K L
Version: 1.2 Major: 1 Minor: 2 Build: -1 Revision: -1
M N O P
Version.Build Property
Q
[ILASM]
R
.property int32 Build { public hidebysig specialname instance int32 get_Build() }
S
[C#]
public int Build { get; }
T
Summary
U
Gets the value of the build component of the current instance.
V W
Property Value
X
A System.Int32 specifying the build component, or –1 if the build component is undefined.
Y
Description
Z
[Note: If the version number is 6.1.2.4, the build component is 2. If the version number is 6.1, the build component is –1, which is considered to be undefined.] 3717
Contents | Index
Version
System
Major Property
Example using System; using System.Reflection;
A namespace Samples { public class VersionBuild { public static void Main() { Type t = Typeof(String); Assembly a = Assembly.GetAssembly(t); AssemblyName an = a.GetName(); Version v = an.Version; Console.WriteLine("Version: {0}", v); Console.WriteLine("Major: {0}", v.Major); Console.WriteLine("Minor: {0}", v.Minor); Console.WriteLine("Build: {0}", v.Build); Console.WriteLine("Revision: {0}", v.Revision); } } }
B C D E F G H I J K L M
The output is
N Version: 1.0.3300.0 Major: 1 Minor: 0 Build: 3300 Revision: 0
O P Q R S
Version.Major Property
T
[ILASM]
.property int32 Major { public hidebysig specialname instance int32 get_Major() }
U
[C#]
V
public int Major { get; }
W
Summary
X
Gets the value of the major component of the current instance.
Y
Property Value
Z
A System.Int32 specifying the major component. For example, if the version number is 6.1, the major version is 6. 3718
Contents | Index
System
Version Minor Property
Example using System; using System.Reflection;
A namespace Samples { public class VersionMajor { public static void Main() { Type t = Typeof(String); Assembly a = Assembly.GetAssembly(t); AssemblyName an = a.GetName(); Version v = an.Version; Console.WriteLine("Version: {0}", v); Console.WriteLine("Major: {0}", v.Major); Console.WriteLine("Minor: {0}", v.Minor); Console.WriteLine("Build: {0}", v.Build); Console.WriteLine("Revision: {0}", v.Revision); } } }
B C D E F G H I J K L M
The output is
N Version: 1.0.3300.0 Major: 1 Minor: 0 Build: 3300 Revision: 0
O P Q R
Version.Minor Property
S
[ILASM]
T
.property int32 Minor { public hidebysig specialname instance int32 get_Minor() }
U
[C#]
V
public int Minor { get; }
W
Summary
X
Gets the value of the minor component of the current instance.
Y
Property Value
Z
A System.Int32 specifying the minor component. For example, if the version number is 6.1, the minor component is 1. 3719
Contents | Index
Version
System
Revision Property
Example using System; using System.Reflection;
A namespace Samples { public class VersionMinor { public static void Main() { Type t = Typeof(String); Assembly a = Assembly.GetAssembly(t); AssemblyName an = a.GetName(); Version v = an.Version; Console.WriteLine("Version: {0}", v); Console.WriteLine("Major: {0}", v.Major); Console.WriteLine("Minor: {0}", v.Minor); Console.WriteLine("Build: {0}", v.Build); Console.WriteLine("Revision: {0}", v.Revision); } } }
B C D E F G H I J K L
The output is
M N
Version: 1.0.3300.0 Major: 1 Minor: 0 Build: 3300 Revision: 0
O P Q R S
Version.Revision Property
T
[ILASM]
U
.property int32 Revision { public hidebysig specialname instance int32 get_Revision() } [C#]
V
public int Revision { get; }
W
Summary
X
Gets the value of the revision component of the current instance.
Y Z
3720
Contents | Index
System
Version Clone() Method
Property Value A System.Int32 specifying the revision component, or –1 if the revision component is undefined. For example, if the version number is 6.1.2.4, the revision component is 4. If the version number is 6.1, the revision component is considered to be undefined.
A B
Example
C
using System; using System.Reflection;
D E
namespace Samples { public class VersionRevision { public static void Main() { Type t = Typeof(String); Assembly a = Assembly.GetAssembly(t); AssemblyName an = a.GetName(); Version v = an.Version; Console.WriteLine("Version: {0}", v); Console.WriteLine("Major: {0}", v.Major); Console.WriteLine("Minor: {0}", v.Minor); Console.WriteLine("Build: {0}", v.Build); Console.WriteLine("Revision: {0}", v.Revision); } } }
F G H I J K L M N O P
The output is
Q R
Version: 1.0.3300.0 Major: 1 Minor: 0 Build: 3300 Revision: 0
S T U V
Version.Clone() Method
W
[ILASM]
X
.method public final hidebysig virtual object Clone()
Y
[C#]
public object Clone()
Z
3721
Contents | Index
Version
System
Clone() Method
Summary Returns a new System.Object with values equal to the property values of the current instance. A B
Description
C
The System.Object returned by this method must be explicitly cast to a System.Version before it may be used as one. [Note: This method is implemented to support the System.ICloneable interface.]
D E F
Example
G
using System; using System.Reflection;
H namespace Samples { public class VersionClone { public static void Main() { Type t = Typeof(String); Assembly a = Assembly.GetAssembly(t); AssemblyName an = a.GetName(); Version v1 = an.Version; Version v2 = (Version) v1.Clone(); Console.WriteLine("Version: {0}", v2); Console.WriteLine("Major: {0}", v2.Major); Console.WriteLine("Minor: {0}", v2.Minor); Console.WriteLine("Build: {0}", v2.Build); Console.WriteLine("Revision: {0}", v2.Revision); } } }
I J K L M N O P Q R S T
The output is
U V
Version: 1.0.3300.0 Major: 1 Minor: 0 Build: 3300 Revision: 0
W X Y Z
3722
Contents | Index
System
Version CompareTo() Method
Version.CompareTo(System.Object) Method [ILASM]
.method public final hidebysig virtual int32 CompareTo(object version) [C#]
A
public int CompareTo(object version)
B C
Summary
D
Returns the sort order of the current instance compared to the specified System.Object.
E
Parameters
F
Parameter
Description
version
The System.Object to compare to the current instance.
G H I J
Return Value
K
A System.Int32 containing a value that reflects the sort order of the current instance as compared to version. The following table defines the conditions under which the returned value is a negative number, zero, or a positive number.
L M N O
Return Value
Description
any negative number
Current instance < version.
Q
zero
Current instance == version.
R
any positive number
Current instance > version, or version is a null reference.
P
S T U
Description
V
[Note: The components of System.Version in decreasing order of importance are major, minor, build, and revision. An undefined component is assumed to be older than any defined component. This method is implemented to support the System.IComparable interface.]
W X Y Z
3723
Contents | Index
Version
System
Equals() Method
Exceptions Exception
Condition
System.ArgumentException
version is not a System.Version and is not a null reference.
A B C D
Example
E
using System; using System.Reflection;
F G
namespace Samples { public class VersionCompareTo { public static void Main() { Type t = Typeof(String); Assembly a = Assembly.GetAssembly(t); AssemblyName an = a.GetName(); Version v1 = an.Version; Version v2 = (Version) v1.Clone(); Version v3 = new Version(); Console.WriteLine("v1.CompareTo(v1): {0}", v1.CompareTo(v1)); Console.WriteLine("v1.CompareTo(v2): {0}", v1.CompareTo(v2)); Console.WriteLine("v1.CompareTo(v3): {0}", v1.CompareTo(v3)); } } }
H I J K L M N O P Q R S T
The output is
U
v1.CompareTo(v1): 0 v1.CompareTo(v2): 0 v1.CompareTo(v3): 1
V W X Y
Version.Equals(System.Object) Method
Z
[ILASM]
.method public hidebysig virtual bool Equals(object obj) [C#]
public override bool Equals(object obj)
3724
Contents | Index
System
Version Equals() Method
Summary Determines whether the current instance and the specified System.Object represent the same type and value. A
Parameters
B C
Parameter
Description
obj
The System.Object to compare to the current instance.
D E F
Return Value
G
A System.Boolean where true indicates obj is the same type as the current instance and has equal System.Version.Major, System.Version.Minor, System.Version.Build, and System.Version.Revision properties as the current instance. If obj is a null reference or is not an instance of System.Version, returns false.
H I J K
Description
L
[Note: This method overrides System.Object.Equals.]
M
Example
N
using System; using System.Reflection;
O P
namespace Samples { public class VersionEquals { public static void Main() { Type t = Typeof(String); Assembly a = Assembly.GetAssembly(t); AssemblyName an = a.GetName(); Version v1 = an.Version; Version v2 = new Version(); Console.WriteLine("v1.Equals(v1): {0}", v1.Equals(v1)); Console.WriteLine("v1.Equals(v2): {0}", v1.Equals(v2)); } } }
Q R S T U V W X Y Z
3725
Contents | Index
Version
System
GetHashCode() Method
The output is v1.Equals(v1): True v1.Equals(v2): False
A B C
Version.GetHashCode() Method
D
[ILASM]
.method public hidebysig virtual int32 GetHashCode()
E
[C#]
public override int GetHashCode()
F G
Summary
H
Generates a hash code for the current instance.
I
Return Value
J
A System.Int32 containing the hash code for the current instance.
K L
Description
M
The algorithm used to generate the hash code is unspecified. [Note: This method overrides System.Object.GetHashCode.]
N O
Example
P
using System; using System.Reflection;
Q
namespace Samples { public class VersionGetHashCode { public static void Main() { Type t = Typeof(String); Assembly a = Assembly.GetAssembly(t); AssemblyName an = a.GetName(); Version v1 = an.Version; Version v2 = (Version) v1.Clone(); Version v3 = new Version(); Console.WriteLine("v1.GetHashCode(): {0}", v1.GetHashCode()); Console.WriteLine("v2.GetHashCode(): {0}", v2.GetHashCode());
R S T U V W X Y Z
3726
Contents | Index
System
Version op_Equality() Method
Console.WriteLine("v3.GetHashCode(): {0}", v3.GetHashCode()); } }
A
}
B
The output is
C
v1.GetHashCode(): 269369344 v2.GetHashCode(): 269369344 v3.GetHashCode(): 1048575
D E F G
Version.op_Equality(System.Version, System.Version) Method
H
[ILASM]
I
.method public hidebysig static specialname bool op_Equality(class System.Version v1, class System.Version v2)
J
[C#]
public static bool operator ==(Version v1, Version v2)
K L
Summary
M
Determines whether two instances of System.Version are equal.
N
Parameters
O
Parameter
Description
v1
An instance of the System.Version class.
v2
An instance of the System.Version class.
P Q R S T
Return Value
U
A System.Boolean where true indicates v1 and v2 have equal System.Version.Major, System.Version.Minor, System.Version.Build, and System.Version.Revision properties, or both v1 and v2 are null; otherwise, false.
V W X
Description
Y
The parts of the version number are compared independently starting with the System.Version.Major property and then the System.Version.Minor,
Z
3727
Contents | Index
Version
System
op_GreaterThan() Method
System.Version.Build, and System.Version.Revision properties, in order. This method returns as soon as one of the properties is determined not to be equal. A
Example
B
using System; using System.Reflection;
C namespace Samples { public class VersionOp_Equality { public static void Main() { Type t = Typeof(String); Assembly a = Assembly.GetAssembly(t); AssemblyName an = a.GetName(); Version v1 = an.Version; Version v2 = new Version(); Console.WriteLine("v1 == v1: {0}", v1 == v1); Console.WriteLine("v1 == v2: {0}", v1 == v2); } } }
D E F G H I J K L M N O
The output is
P v1 == v1: True v1 == v2: False
Q R S
Version.op_GreaterThan(System.Version, System.Version) Method
T
[ILASM]
U
.method public hidebysig static specialname bool op_GreaterThan(class System.Version v1, class System.Version v2)
V
[C#]
W
public static bool operator >(Version v1, Version v2)
X
Summary
Y
Determines whether the first instance of System.Version is greater than the second instance of System.Version.
Z
3728
Contents | Index
System
Version op_GreaterThan() Method
Parameters Parameter
Description
v1
An instance of the System.Version class.
v2
An instance of the System.Version class.
A B C D
Return Value
E
A System.Boolean where true indicates v1 is greater than v2; otherwise, false. If v1 is null, false is returned.
F G
Description
H
The parts of the version number are compared independently starting with the System.Version.Major property and then the System.Version.Minor, System.Version.Build, and System.Version.Revision properties, in order. This method returns as soon as one of the properties is determined not to be equal.
I J K L
Exceptions
M
Exception
Condition
System.ArgumentNullException
v2 is a null reference.
N O P Q
Example
R
using System; using System.Reflection;
S T
namespace Samples { public class VersionOp_GreaterThan { public static void Main() { Type t = Typeof(String); Assembly a = Assembly.GetAssembly(t); AssemblyName an = a.GetName(); Version v1 = an.Version; Version v2 = new Version(); Console.WriteLine("v1 > v1: {0}", v1 > v1);
U V W X Y Z
3729
Contents | Index
Version
System
op_GreaterThanOrEqual() Method
Console.WriteLine("v1 > v2: {0}", v1 > v2); } }
A
}
B
The output is
C v1 > v1: False v1 > v2: True
D E F
Version.op_GreaterThanOrEqual(System.Version, System.Version) Method
G [ILASM]
H
.method public hidebysig static specialname bool op_GreaterThanOrEqual(class System.Version v1, class System.Version v2)
I
[C#]
public static bool operator >=(Version v1, Version v2)
J K
Summary
L
Determines whether the first instance of System.Version is greater than or equal to the second instance of System.Version.
M N
Parameters
O P Q
Parameter
Description
v1
An instance of the System.Version class.
v2
An instance of the System.Version class.
R S T U
Return Value
V
A System.Boolean where true indicates v1 is greater than or equal to v2; otherwise, false. If v1 is null, false is returned.
W X
Description
Y
The parts of the version number are compared independently starting with the System.Version.Major property and then the System.Version.Minor, System.Version.Build, and System.Version.Revision properties, in order. This method returns as soon as one of the properties is determined not to be equal.
Z
3730
Contents | Index
System
Version op_Inequality() Method
Exceptions Exception
Condition
System.ArgumentNullException
v2 is a null reference.
A B C
Example
D
using System; using System.Reflection;
E F
namespace Samples { public class VersionOp_GreaterThanOrEqual { public static void Main() { Type t = Typeof(String); Assembly a = Assembly.GetAssembly(t); AssemblyName an = a.GetName(); Version v1 = an.Version; Version v2 = new Version(); Console.WriteLine("v1 >= v1: {0}", v1 >= v1); Console.WriteLine("v1 >= v2: {0}", v1 >= v2); } } }
G H I J K L M N O P Q
The output is
R S
v1 >= v1: True v1 >= v2: True
T U
Version.op_Inequality(System.Version, System.Version) Method
V
[ILASM]
W
.method public hidebysig static specialname bool op_Inequality(class System.Version v1, class System.Version v2)
X
[C#]
Y
public static bool operator !=(Version v1, Version v2)
Z
Summary Determines whether two instances of System.Version are not equal. 3731
Contents | Index
Version
System
op_Inequality() Method
Parameters Parameter
Description
v1
An instance of the System.Version class.
v2
An instance of the System.Version class.
A B C D E
Return Value
F
A System.Boolean where true indicates v1 and v2 have at least one unequal property; otherwise, false. If v1 and v2 are both null, returns false; if one is null but not the other, returns true.
G H I
Description
J
The parts of the version number are compared independently starting with the System.Version.Major property and then the System.Version.Minor, System.Version.Build, and System.Version.Revision properties, in order. This method returns as soon as one of the properties is determined not to be equal.
K L M
Example
N
using System; using System.Reflection;
O P
namespace Samples { public class VersionOp_Inequality { public static void Main() { Type t = Typeof(String); Assembly a = Assembly.GetAssembly(t); AssemblyName an = a.GetName(); Version v1 = an.Version; Version v2 = new Version(); Console.WriteLine("v1 != v1: {0}", v1 != v1); Console.WriteLine("v1 != v2: {0}", v1 != v2); } } }
Q R S T U V W X Y Z
3732
Contents | Index
System
Version op_LessThan() Method
The output is v1 != v1: False v1 != v2: True
A B
Version.op_LessThan(System.Version, System.Version) Method
C
[ILASM]
D
.method public hidebysig static specialname bool op_LessThan(class System.Version v1, class System.Version v2)
E
[C#]
F
public static bool operator <(Version v1, Version v2)
G
Summary
H
Determines whether the first instance of System.Version is less than the second instance of System.Version.
I
Parameters
K
J
L
Parameter
Description
M
v1
An instance of the System.Version class.
N
v2
An instance of the System.Version class.
O P Q
Return Value
R
A System.Boolean where true indicates v1 is less than v2; otherwise, false. If v2 is null, false is returned.
S T
Description
U
The parts of the version number are compared independently starting with the System.Version.Major property and then the System.Version.Minor, System.Version.Build, and System.Version.Revision properties, in order. This method returns as soon as one of the properties is determined not to be equal.
V W X Y Z
3733
Contents | Index
Version
System
op_LessThanOrEqual() Method
Exceptions Exception
Condition
System.ArgumentNullException
v1 is a null reference.
A B C D
Example
E
using System; using System.Reflection;
F namespace Samples { public class VersionOp_LessThan { public static void Main() { Version v1 = new Version(); Type t = Typeof(String); Assembly a = Assembly.GetAssembly(t); AssemblyName an = a.GetName(); Version v2 = an.Version; Console.WriteLine("v1 < v1: {0}", v1 < v1); Console.WriteLine("v1 < v2: {0}", v1 < v2); } } }
G H I J K L M N O P Q R
The output is
S v1 < v1: False v1 < v2: True
T U V
Version.op_LessThanOrEqual(System.Version, System.Version) Method
W [ILASM]
X
.method public hidebysig static specialname bool op_LessThanOrEqual(class System.Version v1, class System.Version v2)
Y
[C#]
public static bool operator <=(Version v1, Version v2)
Z
3734
Contents | Index
System
Version op_LessThanOrEqual() Method
Summary Determines whether the first instance of System.Version is less than or equal to the second instance of System.Version. A
Parameters Parameter
B C
Description
D
v1
An instance of the System.Version class.
E
v2
An instance of the System.Version class.
F G
Return Value
H
A System.Boolean where true indicates v1 is less than or equal to v2; otherwise, false. If v2 is null, false is returned.
I
Description
K
The parts of the version number are compared independently starting with the System.Version.Major property and then the System.Version.Minor, System.Version.Build, and System.Version.Revision properties, in order. This method returns as soon as one of the properties is determined not to be equal.
L
J
M N O
Exceptions
P
Exception
Condition
System.ArgumentNullException
v1 is a null reference.
Q R S T
Example
U
using System; using System.Reflection;
V W
namespace Samples { public class VersionOp_LessThanOrEqual { public static void Main() { Version v1 = new Version(); Type t = Typeof(String);
X Y Z
3735
Contents | Index
Version
System
ToString() Method
Assembly a = Assembly.GetAssembly(t); AssemblyName an = a.GetName(); Version v2 = an.Version; Console.WriteLine("v1 <= v1: {0}", v1 <= v1); Console.WriteLine("v1 <= v2: {0}", v1 <= v2);
A B }
C }
D
}
E
The output is
F
v1 <= v1: True v1 <= v2: True
G H I
Version.ToString() Method
J
[ILASM]
.method public hidebysig virtual string ToString()
K
[C#]
public override string ToString()
L M
Summary
N
Converts the value of this instance to its equivalent System.String representation.
O
Return Value
P
The System.String representation of the values of the major, minor, build, and revision components of this instance, as depicted in the following format. Each component is separated by a period character (’.’). Square brackets (’[’ and ’]’) indicate a component that will not appear in the return value if the component is not defined:
Q R S T
major.minor[.build[.revision]]
U
For example, if you create an instance of System.Version using the constructor Version(1,1), the returned string is “1.1”. If you create an instance of System.Version using the constructor Version(1,3,4,2), the returned string is “1.3.4.2”.
V W X
Version.ToString(System.Int32) Method
Y
[ILASM]
Z
.method public hidebysig instance string ToString(int32 fieldCount) [C#]
public string ToString(int fieldCount)
3736
Contents | Index
System
Version ToString() Method
Summary Converts the value of this instance to its equivalent System.String representation. A specified count indicates the number of components to return. A
Parameters
B C
Parameter
Description D
fieldCount
The number of components to return. The fieldCount ranges from 0 to 4.
E F
Return Value
G
The System.String representation of the values of the major, minor, build, and revision components of this instance, each separated by a period character (’.’). The fieldCount parameter determines how many components are returned.
H I J K
fieldCount
Return Value
0
An empty string ("")
1
major
N
2
major.minor
O
3
major.minor.build
4
major.minor.build.revision
L M
P Q R S
For example, if you create an instance of Version using the constructor Version(1,3,5), ToString(2) returns “1.3” and ToString(4) throws an exception.
T U
Exceptions Exception
V W
Condition
X fieldCount is less than 0, or more than 4. System.ArgumentException
Y
-orZ
fieldCount is more than the number of components defined in this instance.
3737
Contents | Index
System.Threading WaitHandle
BCL
Object
A
MarshalByRefObject WaitHandle
B
IDisposable
C
Summary
D
Encapsulates operating-system specific objects that wait for exclusive access to shared resources.
E F
Type Summary
G
public abstract class WaitHandle : MarshalByRefObject, IDisposable { // Constructors public WaitHandle ();
H I J K
// Fields MS protected static readonly IntPtr InvalidHandle = new IntPtr (-1); MS CF public const int WaitTimeout = 258;
L M
// Properties MS public virtual IntPtr Handle { set; get; }
N O
MS
MS
MS
MS
MS
// Methods public virtual void Close (); CF protected virtual void Dispose (bool explicitDisposing); ~WaitHandle () {} CF public static bool WaitAll (WaitHandle[] waitHandles); CF public static bool WaitAll (WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext); CF public static bool WaitAll (WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext); CF public static int WaitAny (WaitHandle[] waitHandles); CF public static int WaitAny (WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext); CF public static int WaitAny (WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext); public virtual bool WaitOne (); CF public virtual bool WaitOne (int millisecondsTimeout, bool exitContext);
P Q R S T U V W X Y Z
3739
Contents | Index
WaitHandle
System.Threading
WaitHandle Class
MS CF public virtual bool WaitOne (TimeSpan timeout, bool exitContext); // Explicit Interface Members CF void IDisposable.Dispose ();
A }
B C
JR The parameter-less WaitOne method will always return true. Therefore, there is not a need to test its return value; it should have been prototyped with a void return value.
D E F G
Description
H
[Note: This class is typically used as a base class for synchronization objects. Classes derived from System.Threading.WaitHandle define a signaling mechanism to indicate taking or releasing exclusive access to a shared resource, but use the inherited System.Threading.WaitHandle methods to block while waiting for access to shared resources. The static methods of this class are used to block a System.Threading.Thread until one or more synchronization objects receive a signal.]
I J K L M N
Example
O
using System; using System.Threading;
P
namespace Samples { public class WaitHandle { static AutoResetEvent threadDone = new AutoResetEvent(false); public static void StartHere() { Console.WriteLine("Starting thread"); Thread.Sleep(1000); threadDone.Set(); Console.WriteLine("Finishing thread"); }
Q R S T U V W X
public static void Main() { Console.WriteLine("Starting Main"); Thread t = new Thread( new ThreadStart(StartHere));
Y Z
3740
Contents | Index
System.Threading
WaitHandle WaitHandle() Constructor
t.Start(); threadDone.WaitOne(); threadDone.Close(); Console.WriteLine("Finishing Main");
A
} }
B
}
C
The output is
D
Starting Main Starting thread Finishing Main Finishing thread
E F G H
WaitHandle() Constructor
I
[ILASM]
J
public rtspecialname specialname instance void .ctor()
K
[C#]
public WaitHandle()
L M
Summary
N
Constructs and initializes a new instance of the System.Threading.WaitHandle class.
O
Example
P
using System; using System.Threading;
Q R
namespace Samples { public class WaitHandleConstructor { static AutoResetEvent threadDone = new AutoResetEvent(false); public static void StartHere() { Console.WriteLine("Starting thread"); Thread.Sleep(1000); threadDone.Set(); Console.WriteLine("Finishing thread"); }
S T U V W X Y Z
public static void Main() {
3741
Contents | Index
WaitHandle
System.Threading
InvalidHandle Field
Console.WriteLine("Starting Main"); Thread t = new Thread( new ThreadStart(StartHere)); t.Start(); threadDone.WaitOne(); threadDone.Close(); Console.WriteLine("Finishing Main");
A B C
} }
D
}
E
The output is
F
Starting Main Starting thread Finishing Main Finishing thread
G H I J K
WaitHandle.InvalidHandle Field
L
[ILASM]
.field family static initOnly valuetype System.IntPtr InvalidHandle
M
[C#]
protected static readonly IntPtr InvalidHandle = new IntPtr ()
N O
Summary
P
Represents an invalid native operating system handle.
Q
Description
R
Used internally to initialize the System.Threading.WaitHandle.Handle property. You can use this value to determine whether the System.Threading.WaitHandle.Handle property contains a valid native operating system handle. This member must be implemented if the Runtime Infrastructure Library is present in the implementation.
S T U V W X
WaitHandle.WaitTimeout Field
Y
[ILASM]
.field public static literal int32 WaitTimeout
Z
[C#]
public const int WaitTimeout = 258
3742
Contents | Index
System.Threading
WaitHandle Handle Property
Summary Indicates that a System.Threading.WaitHandle.WaitAny operation timed out before any of the wait handles were signaled. This field is constant. A
Description
B
This field is one of the possible return values of WaitAny.
C D
WaitHandle.Handle Property
E
[ILASM]
F
.property valuetype System.IntPtr Handle { public hidebysig virtual specialname valuetype System.IntPtr get_Handle() public hidebysig virtual specialname void set_Handle(valuetype System.IntPtr value) }
G H
[C#]
I
public virtual IntPtr Handle { get; set; }
J
Summary
K
Gets or sets the native operating system handle.
L
Property Value
M
An IntPtr representing the native operating system handle. The default is the value of the System.Threading.WaitHandle.InvalidHandle property.
N O P
Exceptions
Q
Exception
Condition
System.Security.SecurityException
The caller does not have the required permission.
R S T U
Permissions
V
Permission
Description
W
System.Security.Permissions.SecurityPermissionAttribute
For access to unmanaged code. Associated enumeration: System.Security.Permissions.SecurityPermissionFlag. UnmanagedCode.
X Y Z
3743
Contents | Index
WaitHandle
System.Threading
Close() Method
WaitHandle.Close() Method [ILASM]
.method public hidebysig virtual void Close()
A
[C#]
public virtual void Close()
B C
Summary
D
Releases all resources held by the current instance.
E
Description
F
This method is the public version of the System.IDisposable.Dispose method implemented to support the System.IDisposable interface.
G H
Behaviors
I
This method releases any unmanaged resources held by the current instance. This method can, but is not required to, suppress finalization during garbage collection by calling the System.GC.SuppressFinalize method.
J K L
How and When to Override
M
Override this property to release resources allocated in subclasses.
N O
Usage
P
Use this method to release all resources held by an instance of WaitHandle. Once this method is called, references to the current instance cause undefined behavior.
Q R
Example
S
using System; using System.Threading;
T namespace Samples { public class WaitHandleClose { static AutoResetEvent threadDone = new AutoResetEvent(false); public static void StartHere() { Console.WriteLine("Starting thread"); Thread.Sleep(1000); threadDone.Set(); Console.WriteLine("Finishing thread");
U V W X Y Z
3744
Contents | Index
System.Threading
WaitHandle Dispose() Method
} public static void Main() { Console.WriteLine("Starting Main"); Thread t = new Thread( new ThreadStart(StartHere)); t.Start(); threadDone.WaitOne(); threadDone.Close(); Console.WriteLine("Finishing Main"); }
A B C D E F
} }
G
The output is
H I
Starting Main Starting thread Finishing Main Finishing thread
J K L M
WaitHandle.Dispose(System.Boolean) Method
N [ILASM]
O
.method family hidebysig virtual void Dispose(bool explicitDisposing) [C#]
P
protected virtual void Dispose(bool explicitDisposing)
Q
Summary
R
Releases the unmanaged resources used by the System.Threading.WaitHandle and optionally releases the managed resources.
S T
Parameters
U V
Parameter
Description
explicitDisposing
true to release both managed and unmanaged resources; false to release only unmanaged resources.
W X Y Z
3745
Contents | Index
WaitHandle
System.Threading
Finalize() Method
Behaviors This method releases all unmanaged resources held by the current instance. When the explicitDisposing parameter is true, this method releases all resources held by any managed objects referenced by the current instance. This method invokes the Dispose() method of each referenced object.
A B C
How and When to Override
D
Override this method to dispose of resources allocated by types derived from System.Threading.WaitHandle. When overriding Dispose(System.Boolean), be careful not to reference objects that have been previously disposed in an earlier call to Dispose or Close. Dispose can be called multiple times by other objects.
E F G H
Usage
I
This method is called by the public System.Threading.WaitHandle.Dispose method and the System.Object.Finalize method. Dispose() invokes this method with the explicitDisposing parameter set to true. System.Object.Finalize invokes Dispose with explicitDisposing set to false.
J K L M
WaitHandle.Finalize() Method
N [ILASM]
O
.method family hidebysig virtual void Finalize() [C#]
P
~WaitHandle()
Q R
Summary
S
Releases the resources held by the current instance.
T
Description
U
[Note: Application code does not call this method; it is automatically invoked during garbage collection unless finalization by the garbage collector has been disabled. For more information, see System.GC.SuppressFinalize, and System.Object.Finalize. This method overrides System.Object.Finalize.]
V W X Y Z
3746
Contents | Index
System.Threading
WaitHandle WaitAll() Method
WaitHandle.WaitAll(System.Threading.WaitHandle[]) Method [ILASM]
.method public hidebysig static bool WaitAll(class System.Threading.WaitHandle[] waitHandles)
A
[C#]
B
public static bool WaitAll(WaitHandle[] waitHandles)
C
Summary
D
Waits for all of the elements in the specified array to receive a signal.
E F
Parameters
G H
Parameter
Description
waitHandles
A System.Threading.WaitHandle array containing the objects for which the current instance will wait. This array cannot contain multiple references to the same object (duplicates).
I J K L
Return Value
M
Returns true when every element in waitHandles has received a signal. If the current thread receives a request to abort before the signals are received, this method returns false. The maximum number of objects specified in the waitHandles array is system defined.
N O P
Exceptions
Q R
Exception
Condition
System.ArgumentNullException
waitHandles is null or one or more elements in the waitHandles array is null. waitHandles contains elements that are duplicates.
U
System.DuplicateWaitObjectException
The number of objects in waitHandles is greater than the system permits.
W
System.NotSupportedException
S T
V
X Y Z
3747
Contents | Index
WaitHandle
System.Threading
WaitAll() Method
Example using System; using System.Threading;
A
namespace Samples { public class WaitHandleWaitAll { public const int THREADS = 10; public static Thread[] threads = new Thread[THREADS]; public static AutoResetEvent[] threadsDone = new AutoResetEvent[THREADS]; public int threadNumber; public void StartHere() { Console.WriteLine("Starting thread {0}", threadNumber); Thread.Sleep(10000); Console.WriteLine("Finishing thread {0}", threadNumber); threadsDone[threadNumber].Set(); } public static void StartThreads() { for(int i = 0; i < THREADS; i++) { WaitHandleWaitAll whs = new WaitHandleWaitAll(); whs.threadNumber = i; threads[i] = new Thread( new ThreadStart(whs.StartHere)); } for(int i = 0; i < THREADS; i++) threads[i].Start(); } public static void SetupAutoResetEvents() { for(int i = 0; i < THREADS; i++) { threadsDone[i] = new AutoResetEvent(false); } } public static void Main() { Console.WriteLine("Starting Main"); SetupAutoResetEvents(); StartThreads(); WaitHandle.WaitAll(threadsDone); Console.WriteLine("Finishing Main"); } } }
B C D E F G H I J K L M N O P Q R S T U V W X Y Z
3748
Contents | Index
System.Threading
WaitHandle WaitAll() Method
The output is Starting Main Starting thread 0 Starting thread 1 Starting thread 2 Starting thread 3 Starting thread 4 Starting thread 5 Starting thread 6 Starting thread 7 Starting thread 8 Starting thread 9 Finishing thread 0 Finishing thread 1 Finishing thread 2 Finishing thread 3 Finishing thread 4 Finishing thread 5 Finishing thread 6 Finishing thread 7 Finishing thread 8 Finishing thread 9 Finishing Main
A B C D E F G H I J K L M N
WaitHandle.WaitAll(System.Threading.WaitHandle[], System.Int32, System.Boolean) Method
O
[ILASM]
Q
.method public hidebysig static bool WaitAll(class System.Threading.WaitHandle[] waitHandles, int32 millisecondsTimeout, bool exitContext)
R
[C#]
S
public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext)
T
P
U
Summary
V
Waits for all the elements in the specified array to receive a signal, using a System.Int32 value to measure the time interval and specifying whether to exit the synchronization domain before the wait.
W X Y Z
3749
Contents | Index
WaitHandle
System.Threading
WaitAll() Method
Parameters Parameter
Description
waitHandles
A WaitHandle array containing the objects for which the current instance will wait. This array cannot contain multiple references to the same object (duplicates).
millisecondsTimeout
The number of milliseconds to wait for the thread to receive a signal.
exitContext
true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
A B C D E F G H
Return Value
I
true to exit the synchronization domain before the wait; otherwise, false.
J
Description
K
Returns when the wait terminates, which means either when all the handles are signaled or when time-out occurs. On some implementations, if more than 64 handles are passed, a System.NotSupportedException is thrown. If there are duplicates in the array, the call will fail.
L M N O
Exceptions
P Q R
Exception
Condition
System.ArgumentNullException
The waitHandles parameter is null or one or more of the objects in the waitHandles array is null.
System.DuplicateWaitObjectException
The waitHandles array contains elements that are duplicates.
System.NotSupportedException
The number of objects in waitHandles is greater than the system permits.
S T U V W X Y Z
3750
Contents | Index
System.Threading
WaitHandle WaitAll() Method
WaitHandle.WaitAll(System.Threading.WaitHandle[], System.TimeSpan, System.Boolean) Method [ILASM]
A
.method public hidebysig static bool WaitAll(class System.Threading.WaitHandle[] waitHandles, valuetype System.TimeSpan timeout, bool exitContext)
B
[C#]
C
public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext)
D E
Summary
F
Waits for all the elements in the specified array to receive a signal, using a System.TimeSpan value to measure the time interval and specifying whether to exit the synchronization domain before the wait.
G H I
Parameters
J
Parameter
Description
K
A WaitHandle array containing the objects for which the current instance will wait. This array cannot contain multiple references to the same object (duplicates).
L
waitHandles
timeout
The number of milliseconds to wait for the thread to receive a signal.
exitContext
true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
M N O P Q R
Return Value
S
true if the method exited the synchronization domain before the wait; otherwise, false.
T
Description
U
Returns when the wait terminates, which means either all the handles are signaled or a timeout occurs. On some implementations, if more than 64 handles are passed, a System.NotSupportedException is thrown. If the array contains duplicates, the call will fail.
V W X Y Z
3751
Contents | Index
WaitHandle
System.Threading
WaitAny() Method
Exceptions Exception
Condition
System.ArgumentNullException
The waitHandles parameter is null or one or more of the objects in the waitHandles array is null.
System.DuplicateWaitObjectException
The waitHandles array contains elements that are duplicates.
System.NotSupportedException
The number of objects in waitHandles is greater than the system permits.
A B C D E F G H
WaitHandle.WaitAny(System.Threading.WaitHandle[]) Method
I
[ILASM]
J
.method public hidebysig static int32 WaitAny(class System.Threading.WaitHandle[] waitHandles)
K
[C#]
L
public static int WaitAny(WaitHandle[] waitHandles)
M
Summary
N
Waits for any of the elements in the specified array to receive a signal.
O P
Parameters
Q R
Parameter
Description
waitHandles
A System.Threading.WaitHandle array containing the objects for which the current instance will wait. This array cannot contain multiple references to the same object (duplicates).
S T U V
Return Value
W
Returns a System.Int32 set to the index of the element in waitHandles that received a signal. The maximum number of objects specified in the waitHandles array is system defined.
X Y Z
3752
Contents | Index
System.Threading
WaitHandle WaitAny() Method
Exceptions Exception
Condition
System.ArgumentNullException
waitHandles is null or one or more elements in the waitHandles array is null.
System.DuplicateWaitObjectException
waitHandles contains elements that are duplicates.
System.NotSupportedException
The number of objects in waitHandles is greater than the system permits.
A B C D E F G
Example
H
using System; using System.Threading;
I J
namespace Samples { public class WaitHandleWaitAny { public const int THREADS = 10; public static Thread[] threads = new Thread[THREADS]; public static AutoResetEvent[] threadsDone = new AutoResetEvent[THREADS]; public int threadNumber; public void StartHere() { Console.WriteLine("Starting thread {0}", threadNumber); Monitor.Enter(threadsDone); Thread.Sleep(1000); Monitor.Exit(threadsDone); Console.WriteLine("Finishing thread {0}", threadNumber); threadsDone[threadNumber].Set(); } public static void StartThreads() { for(int i = 0; i < THREADS; i++) { WaitHandleWaitAny whs = new WaitHandleWaitAny(); whs.threadNumber = i; threads[i] = new Thread( new ThreadStart(whs.StartHere)); }
K L M N O P Q R S T U V W X Y Z
3753
Contents | Index
WaitHandle
System.Threading
WaitAny() Method
for(int i = 0; i < THREADS; i++) threads[i].Start(); } public static void SetupAutoResetEvents() { for(int i = 0; i < THREADS; i++) { threadsDone[i] = new AutoResetEvent(false); } } public static void Main() { Console.WriteLine("Starting Main"); SetupAutoResetEvents(); StartThreads(); for(int i = 0; i < THREADS; i++) { WaitHandle.WaitAny(threadsDone); Console.WriteLine("One thread done"); } Console.WriteLine("Finishing Main"); }
A B C D E F G H I J K L
} }
M N
The output is
O Starting Main Starting thread 0 Starting thread 1 Starting thread 2 Starting thread 3 Starting thread 4 Starting thread 5 Starting thread 6 Starting thread 7 Starting thread 8 Starting thread 9 Finishing thread 0 One thread done Finishing thread 1 One thread done Finishing thread 2 One thread done Finishing thread 3 One thread done Finishing thread 4 One thread done
P Q R S T U V W X Y Z
3754
Contents | Index
System.Threading
WaitHandle WaitAny() Method
Finishing thread One thread done Finishing thread One thread done Finishing thread One thread done Finishing thread One thread done Finishing thread One thread done Finishing Main
5 6
A
7
B 8
C 9
D E F
WaitHandle.WaitAny(System.Threading.WaitHandle[], System.Int32, System.Boolean) Method
H
[ILASM]
I
.method public hidebysig static int32 WaitAny(class System.Threading.WaitHandle[] waitHandles, int32 millisecondsTimeout, bool exitContext)
J
G
[C#]
K
public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext)
L M
Summary
N
Waits for any of the elements in the specified array to receive a signal, using a 32-bit signed integer to measure the time interval, and specifying whether to exit the synchronization domain before the wait.
O P Q
Parameters
R
Parameter
Description
S
A WaitHandle array containing the objects for which the current instance will wait. This array cannot contain multiple references to the same object (duplicates).
T
waitHandles millisecondsTimeout
The number of milliseconds to wait for the thread to receive a signal.
exitContext
true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
U V W X Y Z
3755
Contents | Index
WaitHandle
System.Threading
WaitAny() Method
Return Value The array index of the object that satisfied the wait, or System.Threading.WaitHandle.WaitTimeout if no object satisfied the wait and a time interval equivalent to millisecondsTimeout has passed.
A B
Description
C
This method returns when the wait terminates, either when any of the handles are signaled or when a time-out occurs. If more than one object becomes signaled during the call, the return value is the array index of the signaled object with the smallest index value of all the signaled objects. On some implementations, if more than 64 handles are passed, a System.NotSupportedException is thrown. If the array contains duplicates, the call will fail. If a thread exits or aborts without explicitly releasing a System.Threading.Mutex, and that Mutex is included in a WaitAny on another thread, the index returned by WaitAny will be the correct value plus 128. To guard against this, check the index before using it, with C# code such as if (index >= 128) index -= 128; or Visual Basic code such as If index >= 128 Then index -= 128.
D E F G H I J K
Exceptions
L M
Exception
Condition
System.ArgumentNullException
The waitHandles parameter is null or one or more of the objects in the waitHandles array is null.
System.DuplicateWaitObjectException
The waitHandles array contains elements that are duplicates.
System.NotSupportedException
The number of objects in waitHandles is greater than the system permits.
N O P Q R S T U
WaitHandle.WaitAny(System.Threading.WaitHandle[], System.TimeSpan, System.Boolean) Method
V W
[ILASM]
X
.method public hidebysig static int32 WaitAny(class System.Threading.WaitHandle[] waitHandles, valuetype System.TimeSpan timeout, bool exitContext)
Y
[C#]
public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext)
Z
3756
Contents | Index
System.Threading
WaitHandle WaitAny() Method
Summary Waits for any of the elements in the specified array to receive a signal, using a System.TimeSpan to measure the time interval and specifying whether to exit the synchronization domain before the wait.
A B
Parameters
C
Parameter
Description
waitHandles
A WaitHandle array containing the objects for which the current instance will wait. This array cannot contain multiple references to the same object (duplicates).
timeout
The number of milliseconds to wait for the thread to receive a signal.
exitContext
true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
D E F G H I J K
Return Value
L
The array index of the object that satisfied the wait, or System.Threading.WaitHandle.WaitTimeout if no object satisfied the wait and a time interval equivalent to timeout has passed.
M N
Description
O
This method returns when the wait terminates, either when any of the handles are signaled or when a time-out occurs. If more than one object becomes signaled during the call, the return value is the array index of the signaled object with the smallest index value of all the signaled objects. On some implementations, if more than 64 handles are passed, a System.NotSupportedException is thrown. If the array contains duplicates, the call will fail. If a thread exits or aborts without explicitly releasing a System.Threading.Mutex, and that Mutex is included in a WaitAny on another thread, the index returned by WaitAny will be the correct value plus 128. To guard against this, check the index before using it, with C# code such as if (index >= 128) index -= 128; or Visual Basic code such as If index >= 128 Then index -= 128.
P Q R S T U V W X Y Z
3757
Contents | Index
WaitHandle
System.Threading
WaitOne() Method
Exceptions Exception
Condition
System.ArgumentNullException
The waitHandles parameter is null or one or more of the objects in the waitHandles array is null.
System.DuplicateWaitObjectException
The waitHandles array contains elements that are duplicates.
System.NotSupportedException
The number of objects in waitHandles is greater than the system permits.
A B C D E F G H
WaitHandle.WaitOne() Method
I
[ILASM]
J
.method public hidebysig virtual bool WaitOne() [C#]
K
public virtual bool WaitOne()
L
Summary
M
Blocks the current thread until the current instance receives a signal.
N O
Return Value
P
Returns true when the current instance receives a signal.
Q
Behaviors
R
The caller of this method blocks indefinitely until a signal is received by the current instance.
S T
Usage
U
Use this method to block until a WaitHandle receives a signal from another thread, such as is generated when an asynchronous operation completes. For more information, see the System.IAsyncResult interface.
V W X
Exceptions
Y Z
Exception
Condition
System.ObjectDisposedException
The current instance has already been disposed.
3758
Contents | Index
System.Threading
WaitHandle WaitOne() Method
Example using System; using System.Threading;
A namespace Samples { public class WaitHandleWaitOne { static AutoResetEvent threadDone = new AutoResetEvent(false); public static void StartHere() { Console.WriteLine("Starting thread"); Thread.Sleep(1000); threadDone.Set(); Console.WriteLine("Finishing thread"); }
B C D E F G H I J
public static void Main() { Console.WriteLine("Starting Main"); Thread t = new Thread( new ThreadStart(StartHere)); t.Start(); threadDone.WaitOne(); threadDone.Close(); Console.WriteLine("Finishing Main"); }
K L M N O P
} }
Q
The output is
R S
Starting Main Starting thread Finishing Main Finishing thread
T U V W
WaitHandle.WaitOne(System.Int32, System.Boolean) Method
X [ILASM]
Y
.method public hidebysig virtual bool WaitOne(int32 millisecondsTimeout, bool exitContext)
Z
[C#]
public virtual bool WaitOne(int millisecondsTimeout, bool exitContext)
3759
Contents | Index
WaitHandle
System.Threading
WaitOne() Method
Summary When overridden in a derived class, blocks the current thread until the current System.Threading.WaitHandle receives a signal, using 32-bit signed integer to measure the time interval and specifying whether to exit the synchronization domain before the wait.
A B
Parameters
C D
Parameter
Description
millisecondsTimeout
The number of milliseconds to wait for the thread to receive a signal.
exitContext
true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
E F G H I
Return Value
J
true if the current instance receives a signal; otherwise, false.
K L
Description
M
The caller of this method blocks indefinitely until the current instance receives a signal. Use this method to block until a System.Threading.WaitHandle receives a signal from another thread, such as is generated when an asynchronous operation completes. For more information, see the System.IAsyncResult interface. Override this method to customize the behavior of derived classes.
N O P Q
Exceptions
R S T
Exception
Condition
System.ObjectDisposedException
The current instance has already been disposed.
U V W
WaitHandle.WaitOne(System.TimeSpan, System.Boolean) Method
X
[ILASM]
Y
.method public hidebysig virtual bool WaitOne(valuetype System.TimeSpan timeout, bool exitContext)
Z
[C#]
public virtual bool WaitOne(TimeSpan timeout, bool exitContext)
3760
Contents | Index
System.Threading
WaitHandle Dispose() Method
Summary When overridden in a derived class, blocks the current thread until the current instance receives a signal, using a System.TimeSpan to measure the time interval and specifying whether to exit the synchronization domain before the wait.
A B
Parameters
C D
Parameter
Description
timeout
The number of milliseconds to wait for the thread to receive a signal.
exitContext
true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false.
E F G H
Return Value
I
true if the current instance receives a signal; otherwise, false.
J K
Description
L
The caller of this method blocks indefinitely until the current instance receives a signal. Use this method to block until a System.Threading.WaitHandle receives a signal from another thread, such as is generated when an asynchronous operation completes. For more information, see the System.IAsyncResult interface. Override this method to customize the behavior of derived classes.
M N O P
Exceptions
Q
Exception
Condition
System.ObjectDisposedException
The current instance has already been disposed.
R S T U
IDisposable.Dispose() Method
V
[ILASM]
W
.method private final hidebysig virtual void System.IDisposable.Dispose()
X
[C#]
void IDisposable.Dispose()
Y
Summary
Z
Implemented to support the System.IDisposable interface. [Note: For more information, see System.IDisposable.Dispose.] 3761
Contents | Index
Annotations Index A
H
Abrams, Brad 47, 53, 68–69, 283, 289, 313, 369–370, 377, 401, 425, 487–488, 493, 497, 523, 529–530, 597, 994, 1098–1099, 1165, 1296, 1341, 1404, 1448, 1460, 1497, 1504, 1551, 1604, 1611, 1629, 1634, 1693, 1737, 1753, 1767–1768, 1831, 1852, 1923, 1950–1951, 1954–1955, 1957, 1982–1983, 2039, 2100, 2145, 2152, 2329, 2388, 2399, 2430, 2538, 2695, 2811, 2957, 3130, 3310, 3668, 3698
Hejlsberg, Anders xxii, 497, 530, 597–598, 1337, 2811
C
R
Cwalina, Krzysztof 33, 598, 1853, 1901, 1916, 2695, 2957, 3214
Richter, Jeffrey 33, 48, 70, 194, 289, 309, 313, 370, 384, 425, 493, 523–524, 598, 995, 1165, 1296, 1337, 1461, 1505, 1604, 1612, 1769, 1839, 1901, 1911, 1916, 1923, 1946, 1951, 2039–2040, 2100, 2278, 2400, 2812, 2957, 3075, 3199, 3641, 3668, 3740
G George, Kit 530, 598, 994–995, 1165, 1405, 1768, 1912, 2125, 2448, 2519, 2695, 2736, 2775, 2812, 2957, 3237 Grunkemeyer, Brian 69–70, 193–194, 289, 377, 488, 523, 530, 1099, 1165, 1341, 1404–1405, 1461, 1504, 1551, 1608, 1612, 1629, 1696–1697, 1768, 1831, 1852–1853, 1915, 1927, 1978, 2039, 2278, 2649, 2812, 3042
L Lin, Yung-Shin 1460
M Marcey, Joel 69, 193, 1165, 1839, 2400, 2448, 3130
3763
Contents | Index
Index A Abbreviated names days of the week 1108, 1139 months 1110, 1141 Access 206–207, 1371 code permissions 496 dates/time 1656 environment variables 1574, 1581 EnvironmentPermissionAccess AllAccess field 1595–1596 NoAccess field 1596 Read field 1596 Write field 1596 files 1369 adding 1706 configuring date and time 1685 security 1696 security actions 1597 System.IO.FileAccess.Enum 1693–1694, 1695 System.MarshalByRefObject 2145–2146 constructor 2146 Actions security 1597 SecurityAction.Enum 2568–2569 Assert field 2569–2571 Demand field 2571–2577 Deny field 2572–2574 InheritanceDemand field 2574–2576 LinkDemand field 2576–2580 PermitOnly field 2577–2579 RequestMinimum field 2579–2581 RequestOptional field 2580–2582 RequestRefuse field 2581
Adding access for specified files 1706 attributes (SecurityElement) 2591 children (SecurityElement) 2592 instances 209–210 ranges 211–212 Addresses, URL 1619 Advancing current instances 491 Aligning enumerators 121 AllAccess field 1724 Ancestors, searching 367 ANSI code page, encoding 1466 Append field 1724–1725 Appending UTF-8 encoded text 1635 Applications console 528–531 Console.Error property 532 Console.In property 533 Console.OpenStandardError() method 535–536 Console.OpenStandardInput() method 536–538 Console.OpenStandardOutput() method 538–540 Console.Out property 534 Console.Read() method 540–541 Console.ReadLine() method 541–542 Console.SetError() method 542–544 Console.SetIn() method 544–545 Console.SetOut() method 546–547 Console.Write() method 547–563 Console.WriteLine() method 564–566 execution 33 System.ApplicationException 33–37
3765
Contents | Index
ArgumentException
■
Attributes
ArgumentException class 38–46 GetObjectData() method 45, 46 Message property 44–45 ParamName property 45 ArgumentNullException 47–51 ArgumentOutOfRangeException ActualValue property 58 class 53–54 GetObjectBack() method 60 Message property 59 Arguments environments 1567 methods, invoking delegates 1319 null 54 paths 1636 System.Event.Args class 1604–1606 System.Int32 71 Arithmetic operations 61–64 See also Mathematical functions System.OverflowException 2443–2444, 2444–2446 Arrays bytes 1454 characters 567 converting 609 decoding 1293 indexes of 228 subsets 604 System.ArrayList class ArrayList.Capacity property 199–200 ArrayList.Count property 200–201 ArrayList.GetEnumerator() method 237–239 ArrayList.GetRange() method 240–241 ArrayList.IndexOf() method 241–244 ArrayList.Insert() method 246–248 ArrayList.InsertRange() method 248–250 ArrayList.LastIndexOf() method 250–255 ArrayList.ReadOnly() method 255–257 ArrayList.Remove() method 258–259 ArrayList.RemoveAt() method 259–261 ArrayList.RemoveRange() method 261–263 ArrayList.Repeat() method 263–264 ArrayList.Reverse() method 264–267 ArrayList.SetRange() method 267–269 ArrayList.Sort() method 271–275 ArrayList.Synchronized() method 275–277 ArrayList.ToArray() method 278–280 ArrayList.TrimToSize() method 281–282
System.Collections.ArrayList class 191–195 ArrayList() constructor 195–199 ArrayList.Adapter() method 199–209 ArrayList.Add() method 209–210 ArrayList.AddRange() method 211–212 ArrayList.BinarySearch() method 212–222 ArrayList.Clear() method 222–224 ArrayList.Clone() method 224–225 ArrayList.Contains() method 225–227 ArrayList.CopyTo() method 228–234 ArrayList.FixedSize() method 234–235 ArrayTypeMismatchException 283–285 constructor 285–287 ASCII Encoding.ASCII property 1464 Text.ASCIIEncoding class 288–289 ASCIIEncoding constructor 289–290 GetByteCount() method 290–293 GetBytes() method 293–297 GetCharCount() method 297–299 GetChars() method 299–302 GetMaxByte() method 302–303 GetMaxCharCount() method 303–305 GetString() method 305–308 Asynchronous operations, objects 1901 Asynchronous read and write operations 1766–1771 Atomic operations, System.Threading.Interlocked 2100–2102 Interlocked.CompareExchange() method 2102–2106 Interlocked.Decrement() method 2106–2110 Interlocked.Exchange() method 2110–2113 Interlocked.Increment() method 2113–2115 Attributes 311–315 Attribute() constructor 315 Attribute.Equals() method 316 Attribute.GetCustomAttribute() method 317–330 Attribute.GetCustomAttributes() method 330–354 Attribute.GetHashCode() method 354–355 Attribute.IsDefaultAttribute() method 355 Attribute.IsDefined() method 355–367 Attribute.Match() method 367–368 CLSCompliantAttribute() constructor 495 CLSCompliantAttribute.IsCompliant property 495 CodeAccessSecurityAttribute() constructor 515 FileIOPermissionAttribute 1727 files 1679 namespaces 4–5
3766
Contents | Index
Base classes
SecurityElement AddAttribute() method 2591 Attribute() method 2593 IsValidAttributeName() method 2596 property 2589 SecurityPermissionAttribute 2628–2630 Assertion property 2631 constructor 2630 System.AttributeTarget Enum class 369–375 System.AttributeUsageAttribute class 376–381 System.CLSCompliantAttribute 493–494 System.Diagnostics.ConditionalAttribute class 525 System.FlagsAttribute 1831–1832 constructor 1833 System.ObsoleteAttribute.Class 2430–2431 constructors 2431–2435 IsError property 2435–2437 Message property 2437–2438 System.Security.Permission.SecurityAttribute Action property 2585 CreatePermission() method 2586 System.Security.Permissions.SecurityAttribute 2583–2584 System.Security.Permisson.SecurityAttribute constructor 2584 Unrestricted property 2585
B Base classes See also Classes System.ApplicationException 33–37 System.EventArgs class 1604 Base data types, System.Convert class 589–599 Convert.ChangeType() method 600–603 Convert.FromBase64CharArray() method 604–606 Convert.GetTypeCode() method 606 Convert.IsDBNull() method 607 Convert.ToBase64CharArray() method 607–609 Convert.ToBase64String() method 610 Convert.ToBoolean() method 611–631 Convert.ToByte() method 631–658 Convert.ToChar() method 658–678 Convert.ToDateTime() method 678–692 Convert.ToDecimal() method 693–716 Convert.ToDouble() method 719–736 Convert.ToInt16() method 739–766 Convert.ToInt32() method 766–791 Convert.ToInt64() method 791–816 Convert.ToSByte() method 816–844
■
Bytes
Convert.ToSingle() method 844–866 Convert.ToString() method 866–910 Convert.ToUInt16() method 910–937 Convert.ToUInt32() method 937–964 Convert.ToUInt64() method 964–990 Behavior, attributes 376–381 Big-endian byte order, Unicode characters 1464 Binary searches 81–91 See also Searching ArrayList.BinarySearch() method 212–222 Bit-fields, declaring 1831 Blocks of characters, converting into bytes 1453 Boolean structure 383–384 Boolean.CompareTo() method 386–387 Boolean.Equals() method 388–389 Boolean.FalseString field 384–385 Boolean.GetHashCode() method 389–390 Boolean.GetTypeCode() method 390 Boolean.Parse() method 390–392 Boolean.ToString() method 393–394 Boolean.TrueString field 385–386 Boolean values 616 Browsers See also Interfaces encoding 1467 saving 1467 Building strings. See StringBuilder class Bytes ASCIIEncoding GetByteCount() method 290–293 GetBytes() method 293–297 GetMaxByte() method 302–303 GetMaxCharCount() method 303–305 GetString() method 305–308 Big-endian 1464 characters 1453 little-endian byte order 1469 maximum number of, returning 1493 number of, determining 1454 structure 400–402 Byte.CompareTo() method 404–405 Byte.Equals() method 405–406 Byte.GetHashCode() method 407 Byte.GetTypeCode() method 408 Byte.MaxValue field 402 Byte.MinValue field 403 Byte.Parse() method 408–413 Byte.ToString() method 415–422 System.IO.Stream, returning 1494
3767
Contents | Index
Call stacks
■
Characters
C Call stacks 507 state of 1558 Callable methods 523 Char CompareTo() method 428–429 Equals() method 430–431 GetHashCode() method 431–432 GetNumericValue() method 432–435 GetTypeCode() method 435–476 GetUnicodeCategory() method 435–438 IsControl() method 438–441 IsDigit() method 441–444 IsLetter() method 444–447 IsLetterOrDigit() method 447–450 IsLower() method 450–453 IsNumber() method 453–456 IsPunctuation() method 456–459 IsSeparator() method 459–462 IsSurrogate() method 462–464 IsSymbol() method 465–467 IsUpper() method 467–470 IsWhiteSpace() method 470–473 MaxValue field 426–427 MinValue field 427 Parse() method 473–474 ToLower() method 475–476 ToString() method 477–479 ToUpper() method 479–481 Characters See also ASCII arrays 567 ASCIIEncoding GetByteCount() method 290–293 GetBytes() method 293–297 GetCharCount() method 297–299 GetChars() method 299–302 GetMaxByte() method 302–303 GetMaxCharCount() method 303–305 GetString() method 305–308 bytes converting into 1453 determining number of 1454 decoding 1293 encoding 1458 maximum number of, returning 1494 positioning 440 reading 540–541, 541–542
repositioning 491 subarrays 568 System.Char Structure 423–426 Char.CompareTo() method 428–429 Char.Equals() method 430–431 Char.GetHashCode() method 431–432 Char.GetNumericValue() method 432–435 Char.GetTypeCode() method 435–476 Char.GetUnicodeCategory() method 435–438 Char.IsControl() method 438–441 Char.IsDigit() method 441–444 Char.IsLetter() method 444–447 Char.IsLetterOrDigit() method 447–450 Char.IsLower() method 450–453 Char.IsNumber() method 453–456 Char.IsPunctuation() method 456–459 Char.IsSeparator() method 459–462 Char.IsSurrogate() method 462–464 Char.IsSymbol() method 465–467 Char.IsUpper() method 467–470 Char.IsWhiteSpace() method 470–473 Char.MaxValue field 426–427 Char.MinValue field 427 Char.Parse() method 473–474 Char.ToLower() method 475–476 Char.ToString() method 477–479 Char.ToUpper() method 479–481 System.CharEnumerator 487–489 System.Text.StringBuilder 2955–2959 Append() method 2970–2994 AppendFormat() method 2994–3002 Capacity property 2965–2967 Chars property 2967–2968 constructor 2959–2965 EnsureCapacity() method 3002–3004 Equals() method 3004–3005 Insert() method 3005–3032 Length property 2968–2970 MaxCapacity property 2970 Remove() method 3032–3033 Replace() method 3034–3039 ToString() method 3039–3041 troubleshooting Console.Error property 532 Console.In property 533 Console.Out property 534 Console.Set.In() method 544–545 Console.Set.Out() method 546–547
3768
Contents | Index
CharEnumerator
Console.SetError() method 542–544 Console.Write() method 547–563 Console.WriteLine() method 564–566 Unicode 459 See also Unicode characters white space 1157 CharEnumerator Clone() method 489–490 CurrentProperty() method 489 MoveNext() method 491 Reset() method 491 Children SecurityElement property 2589 SecurityElement.AddChild() method 2592 Classes See also individual classes ArgumentException 38–46 ArgumentNullException 47–51 ArgumentOutOfRange 53–54 Array 65–72 Array() constructor 73 Array.BinarySearch() method 81–91 Array.Clear() method 91–92 Array.Clone() method 93–94 Array.Copy() method 94–104 Array.CopyTo() method 104–107 Array.CreateInstance() method 108–120 Array.GetEnumerator() method 121–123 Array.GetLength() method 123 Array.GetLongLength() method 124 Array.GetLowerBound() method 125–126 Array.GetUpperBound() method 126–127 Array.GetValue() method 128–137 Array.IndexOf() method 138–143 Array.Initialize() method 143–149 Array.IsFixedSize property 73–74 Array.LastIndexOf() method 144–149 Array.Length property 75 Array.LongLength property 76 Array.Rank property 76–77 Array.Reverse() method 150–152 Array.SetValue() method 153–160, 160–164 Array.Sort() method 165–181 Array.SyncRoot property 77 Array.System.Collections.ICollection.Count property 189 Array.System.Collections.IList.Add() method 182 Array.System.Collections.IList.Clear() method 183
■
Classes
Array.System.Collections.IList.Contains() method 184–185 Array.System.Collections.IList.IndexOf() method 185–186 Array.System.Collections.IList.Insert() method 186–187 Array.System.Collections.IList.Item property 190 Array.System.Collections.IList.Remove() method 187–188 Array.System.Collections.IList.RemoveAt() method 188–189 ArrayTypeMismatchException 287 DateTimeFormatInfo 1098–1106 System.ApplicationException 33–37 System.ArithmeticException 61–64 System.Attribute 311–315 Attribute() constructor 315 Attribute.Equals() method 316 Attribute.GetCustomAttribute() method 317–330 Attribute.GetCustomAttributes() method 330–354 Attribute.GetHashCode() method 354–355 Attribute.IsDefaultAttribute() method 355 Attribute.IsDefined() method 355–367 Attribute.Match() method 367–368 System.AttributeTarget Enum 369–375 System.AttributeUsageAttribute 376–381 System.Collections.ArrayList 191–195 ArrayList() constructor 195–199 ArrayList.Adapter() method 199–209 ArrayList.Add() method 209–210 ArrayList.AddRange() method 211–212 ArrayList.BinarySearch() method 212–222 ArrayList.Capacity property 199–200 ArrayList.Clear() method 222–224 ArrayList.Clone() method 224–225 ArrayList.Contains() method 225–227 ArrayList.CopyTo() method 228–234 ArrayList.Count property 200–201 ArrayList.FixedSize() method 234–235, 236 ArrayList.GetEnumerator() method 237–239 ArrayList.GetRange() method 240–241 ArrayList.IndexOf() method 241–244 ArrayList.Insert() method 246–248 ArrayList.InsertRange() method 248–250 ArrayList.IsReadOnly property 202–203 ArrayList.IsSynchronized property 203–204 ArrayList.Item property 205–206 ArrayList.LastIndexOf() method 250–255
3769
Contents | Index
Classes
■
Classes
ArrayList.ReadOnly() method 255–257 ArrayList.Remove() method 258–259 ArrayList.RemoveAt() method 259–261 ArrayList.RemoveRange() method 261–263 ArrayList.Repeat() method 263–264 ArrayList.Reverse() method 264–267 ArrayList.SetRange() method 267–269 ArrayList.Sort() method 271–275 ArrayList.Synchronized() method 275–277 ArrayList.SyncRoot property 206–207 ArrayList.ToArray() method 278–280 ArrayList.TrimToSize() method 281–282 System.Collections.Comparer 517 Comparer.Compare() method 520–522 Comparer.Default field 519 System.Console 528–531 Console.Error property 532 Console.In property 533 Console.OpenStandardError() method 535–536 Console.OpenStandardInput() method 536–538 Console.OpenStandardOutput() method 538–540 Console.Out property 534 Console.Read() method 540–541 Console.ReadLine() method 541–542 Console.SetError() method 542–544 Console.SetIn() method 544–545 Console.SetOut() method 546–547 Console.Write() method 547–563 Console.WriteLine() method 564–566 System.Convert 589–599 Convert.ChangeType() method 600–603 Convert.FromBase64CharArray() method 604–606 Convert.GetTypeCode() method 606 Convert.IsDBNull() method 607 Convert.ToBase64CharArray() method 607–609 Convert.ToBase64String() method 610 Convert.ToBoolean() method 611–631 Convert.ToByte() method 631–658 Convert.ToChar() method 658–678 Convert.ToDateTime() method 678–692 Convert.ToDecimal() method 693–716 Convert.ToDouble() method 719–736 Convert.ToInt16() method 739–766 Convert.ToInt32() method 766–791 Convert.ToInt64() method 791–816 Convert.ToSByte() method 816–844 Convert.ToSingle() method 844–866 Convert.ToString() method 866–910
Convert.ToUInt16() method 910–937 Convert.ToUInt32() method 937–964 Convert.ToUInt64() method 964–990 System.Diagnostics.ConditionalAttribute 523–525 System.Diganostics.ConditionalAttribute ConditionalAttribute() constructor 525–526 ConditionalAttribute.ConditionString property 526–527 System.Enum 1502–1506 Enum.CompareTo() method 1507–1508 Enum.Equals() method 1509–1510 Enum.Format() method 1510–1512 Enum.GetHashCode() method 1512–1513 Enum.GetName() method 1513–1516 Enum.GetTypeCode() method 1516–1517 Enum.GetUnderlyingType() method 1517–1518 Enum.GetValues() method 1518–1519 Enum.IsDefined() method 1519–1521 Enum.Parse() method 1521–1524 Enum.ToObject() method 1525–1538 Enum.ToString() method 1539–1544 System.Environment 1550–1552 Environment.CommandLine property 1552–1553 Environment.CurrentDirectory property 1553–1554 Environment.Exit() method 1564–1566 Environment.ExitCode property 1555 Environment.ExpandEnvironmentVariables() method 1566–1567 Environment.GetCommandLineArgs() method 1567–1568 Environment.GetEnvironmentVariable() method 1568–1570 Environment.GetEnvironmentVariables() method 1570–1572 Environment.GetFolderPath() method 1572 Environment.GetLogicalDrives() method 1573 Environment.HasShutDownStarted property 1556 Environment.MachineName property 1556–1557 Environment.NewLine property 1557 Environment.OSversion property 1558 Environment.StackTrace property 1558–1559 Environment.SystemDirectory property 1559 Environment.TickCount property 1560–1561 Environment.UserDomainName property 1561 Environment.UserInteractive property 1562 Environment.UserName property 1563 Environment.Version property 1563–1564 Environment.WorkingSet property 1564
3770
Contents | Index
Cleanup
System.EventArgs 1604–1606 EventArgs() constructor 1606 EventArgs.Empty field 1606–1607 System.EventHandler.Delegate 1608–1609 System.Exception 1611–1615 Exception() constructor 1615–1619 Exception.ToString() method 1628 GetBaseException() 1625–1626 GetObjectData() 1627 HelpLink property 1619 HResult property 1619–1620 InnerException property 1620–1621 Message property 1621–1623 Source property 1623 StackTrace property 1623–1624 TargetSite property 1625 System.ExecutionEngineException 1629–1632 System.IO.EndOfStreamException 1497–1501 System.ObsoleteAttribute.Class 2430–2431 constructor 2431–2435 IsError property 2435–2437 Message property 2437–2438 System.Security.CodeAccessPermission 496–499 System.Security.Permissions EnviromentPermission 1574–1576 EnviromentPermissionAccess.Enum 1594–1595 EnviromentPermissionAttribute 1597–1598 SecurityAttribute 514–515 System.Text Encoder 1453 Encode constructor() 1453–1454 Encode.GetByteCount() method 1454–1455 Encode.GetBytes() method 1455–1457 System.Text Encoding 1458–1463 Encoding() constructor 1463–1464 Encoding.ASCII property 1464 Encoding.BigEndianUnicode property 1464–1465 Encoding.BodyName property 1465 Encoding.CodePage property 1465 Encoding.Convert() method 1471–1472 Encoding.Default property 1466 Encoding.EncodingName property 1466 Encoding.Equal() method 1473 Encoding.GetByteCount() method 1473–1476 Encoding.GetBytes() method 1476–1482 Encoding.GetCharCount() method 1482–1484 Encoding.GetChars() method 1485–1488 Encoding.GetDecoder() method 1488–1489 Encoding.GetEncoder() method 1489
■
Code
Encoding.GetEncoding() method 1491–1492 Encoding.GetHashCode() method 1492 Encoding.GetMaxByte() method 1493 Encoding.GetMaxCharCount() method 1494 Encoding.GetPreamble() method 1494–1495 Encoding.GetString() method 1495–1496 Encoding.HeaderName property 1466 Encoding.IsBrowserDisplay property 1467 Encoding.IsBrowserSave property 1467 Encoding.IsMailNewsDisplay property 1468 Encoding.IsMailNewsSave property 1468 Encoding.Unicode property 1469 Encoding.UTF7 property 1469 Encoding.UTF8 property 1470 Encoding.WebName property 1470 Encoding.WindowsCodePage property 1470 Text.ASCIIEncoding 288–289 Cleanup, resources 1950 Clients browsers 1467 mail/news encoding 1468 saving 1468 Cloning CharEnumerator.Clone() method 489 current instances 224 delegates 1303–1305 CLS (Common Language Specification) 314 CLSCompliantAttribute() constructor 495 CLSCompliantAttribute.IsCompliant property 495 System.CLSCompliantAttribute 493–494 CLS-compliant current instances 495 CLSCompliantAttribute.IsCompliant property 495 Code access permissions 496 CodeAccessPermission class 496–499 exit 1555 page identifiers 1465 security attributes 514 Unicode characters 435 CodeAccessPermission class CodeAccessPermission.Assert() method constructor 499–500 CodeAccessPermission.Copy() method constructor 501 CodeAccessPermission.Demand() method constructor 501–502 CodeAccessPermission.Deny() method constructor 503
3771
Contents | Index
CodeAccessSecurityAttribute() constructor
■
Constructors
CodeAccessPermission.FromXml() method constructor 504 CodeAccessPermission.Intersect() method constructor 504–505 CodeAccessPermission.IsSubsetOf() method constructor 505–506 CodeAccessPermission.PermitOnly() method constructor 506–507 CodeAccessPermission.RevertAll() method constructor 508 CodeAccessPermission.RevertAssert() method constructor 508–509 CodeAccessPermission.RevertPermitOnly() method constructor 510 CodeAccessPermission.ToString() method constructor 510 CodeAccessPermission.ToXml() method constructor 510–511 CodeAccessPermission.Union() method constructor 511–512 constructor 499 CodeAccessSecurityAttribute() constructor 515 Collections namespaces 11–12 permissions 2481 sorting 1927–1928 Common Language Specification. See CLS Common mathematical functions 2150 Comparer.Compare() method 520–522 Comparer.Default field 519 Comparers 82 null references 175 System.Collections.IComparer implementation 88 Comparing sort orders 386 Compilers, callable methods 523 Concatenation, invocation lists 1309 ConditionalAttribute() constructor 525–526 ConditionalAttribute.ConditionString property 526–527 Configuration attributes 1679 creation date and time 1681 directories 1342 first day of the week 1120 keys 1339 long date patterns 1124 patterns 1136 Consoles 528–531 Console.Error property 532 Console.In property 533
Console.OpenStandardError() method 535–536 Console.OpenStandardInput() method 536–538 Console.OpenStandardOutput() method 538–540 Console.Out property 534 Console.Read() method 540–541 Console.ReadLine() method 541–542 Console.SetError() method 542–544 Console.SetIn() method 544–545 Console.SetOut() method 546–547 Console.Write() method 547–563 Console.WriteLine() method 564–566 Constants, System.Date.Time structure 1010 Constructors ApplicationException() 35–37 ArgumentException() 39–41 ArgumentNullException() 49–52 ArgumentOutOfRange() 55–56 ArithmeticException() 62–64 Array() 73 Array.Initialize() method 143–149 ArrayList() 195–199 ArrayTypeMismatchException() 285–287 ASCIIEncoding() 289–290 Attribute() 315 AttributeUsageAttribute() 379 CLSCompliantAttribute() 495 CodeAccessPermission() 499 CodeAccessSecurityAttribute() 515 ConditionalAttribute() 525–526 DateTime() 997, 1004–1008 DateTimeFormatInfo() 1107 Decimal() 1168–1178 Decoder() 1291 Delegate() 1298–1300 DictionaryEntry() 1338 DirectoryNotFoundException() 1395–1397 DivideByZeroException() 1400 DuplicateWaitObjectException() 1449–1452 Encoder() 1453–1454 Encoding() 1463–1464 EndOfStreamException() 1498–1501 EnviromentPermissionAttribute() 1598–1599 EnvironmentPermission() 1577–1581 EventArgs() 1606 Exception() 1615–1619 ExecutionEngineException() 1630–1632 FileIOPermission 1700–1705 FileIOPermissionAttribute 1728–1729 FileLoadException() 1739–1743
3772
Contents | Index
Control characters
FileNotFound() 1754–1758 FileStream 1771–1792 FormatException() 1835–1837 Hashtable() 1855–1871 InvalidCastException() 2117–2119 InvalidOperationException() 2121–2124 InvalidProgramException() 2125–2127 IOException() 2129–2132 MarshalByRefObject() 2146 MemoryStream() 2236–2250 NotFiniteNumberException() 2314 NotImplementedException() 2321–2323 NotSupportedException() 2325–2328 NullReferenceException() 2330–2333 NumberFormatInfo() 2337 ObjectDisposedException() 2425–2427 ObsoleteAttribute() 2431–2435 OutOfMemoryException() 2440–2442 OverflowException() 2444–2446 PathTooLongException() 2477–2480 PermissionSet() 2486–2489 Random() 2521–2523 RankException() 2533–2535 SecurityAttribute() 2584 SecurityPermission() 2613–2617 SecurityPermissionAttribute() 2630 StackOverflowException() 2691–2693 Stream() 2699 StreamReader() 2738–2758 StreamWriter() 2776–2792 String() 2815–2826 StringBuilder() 2959–2965 StringReader() 3043–3044 StringWriter() 3055–3060 SynchronizationLockException() 3070 System.IndexOutOfRangeException 2005–2007 System.Object() 2401–2402 SystemException() 2602–2606, 3076–3078 TextReader() 3080–3081 TextWriter() 3091–3092 Thread() 3132–3133 ThreadStateException() 3208–3211 Timer() 3216–3222 TimeSpan() 3239–3245 Type() 3314 UnauthorizedAccessException() 3625–3628 UnicodeEncoding() 3643–3645 UTF8Encoding() 3669–3672 ValueType 3700
■
Conversion
VerificationException() 3705–3708 Version() 3711–3717 WaitHandle() 3741–3742 Control characters positioning 440 Unicode characters 438 Control over resource cleanup 1950 Conversion arrays 604 date and time 1067 enumeration type 1521 integers 609 lowercase letters 475 OLE Automation Dates 1080 String representations 478 System.ArrayTypeMismatchException 283 System.Convert class 589–599 Convert.ChangeType() method 600–603 Convert.FromBase64CharArray() method 604–606 Convert.GetTypeCode() method 606 Convert.IsDBNull() method 607 Convert.ToBase64CharArray() method 607–609 Convert.ToBase64String() method 610 Convert.ToBoolean() method 611–631 Convert.ToByte() method 631–658 Convert.ToChar() method 658–678 Convert.ToDateTime() method 678–692 Convert.ToDecimal() method 693–716 Convert.ToDouble() method 719–736 Convert.ToInt16() method 739–766 Convert.ToInt32() method 766–791 Convert.ToInt64() method 791–816 Convert.ToSByte() method 816–844 Convert.ToSingle() method 844–866 Convert.ToString() method 866–910 Convert.ToUInt16() method 910–937 Convert.ToUInt32() method 937–964 Convert.ToUInt64() method 964–990 System.DateTime structure formats 1045 values 1061 time 1082 universal time 1155 uppercase letters 479 UTC 1077 values 390–392 Boolean 616 strings 393–394 subsets 608
3773
Contents | Index
Coordinated universal time (UTC)
■
Dates
Coordinated universal time (UTC) 1043, 1077 converting 1077 creation time of directories 1351 directories, accessing 1371 returning creation date and time 1655 Copying Array.Clone() method 93–94 Array.Copy() method 94–104 Array.CopyTo() method 104–107 arrays 65–72 CharEnumerator.Clone() method 489 current instances 224 delegates 1303–1305 environment permissions 1582 files 1638 permissions 1708 range of elements 228 Count number of elements 263 Creation date and time, configuring 1681 Current directories, paths to 1553 Current frames, overriding 508 Current instances 222 Array.Clone() method 93–94 Array.GetEnumerator() method 121–123 Array.GetLowerBound() method 125–126 Array.GetUpperBound() method 126–127 Array.GetValue() method 128–137 CharEnumerator.Clone() method 489 CharEnumerator.MoveNext() method 491 CLS-compliant 495 copying 224 elements 261–263 hash codes. See Hash codes memory 281 One-dimensional arrays 104 rank of 76–77 removing 258–259 repositioning 491 searching 250–255 security 1603 sort orders 386–387 subsets 506 System.String 477 Unicode characters 428 unions 511 values 316 XML 510 Custom Attributes. See Attributes
Customization collections 1927–1928 hash functions 1978–1980 strings 1968–1976 System.IO.File 1634
D Dates accessing 1656 Convert.ToDateTime() method 690 converting 1067 creating 1653 creation time of files or directories 1349 creation time, configuring 1681 DateTimeStyles.NoCurrentDateDefault field 1159–1160 long patterns, configuring 1124 OLE Automation 1080 System.DateTime structure 991–1004 DateTime() constructor 1004–1008 DateTime.Add property 1022–1023 DateTime.AddDays() method 1023–1024 DateTime.AddHours() method 1025 DateTime.AddMilliseconds() method 1026–1028 DateTime.AddMinutes() method 1028–1029 DateTime.AddMonths() method 1029–1031 DateTime.AddSeconds() method 1031–1032 DateTime.AddTicks() method 1032–1033 DateTime.AddYears() method 1034–1035 DateTime.Compare() method 1035–1036 DateTime.CompareTo() method 1037–1038 DateTime.DayOfWeek property 1012 DateTime.DayOfYear property 1013 DateTime.DaysInMonth() method 1039–1040 DateTime.Equals() method 1040–1042 DateTime.FromFileTime() method 1042 DateTime.FromFileTimeUtc() method 1043 DateTime.FromOADate() method 1044 DateTime.GetDateTimeFormats() method 1045–1047 DateTime.GetHashCode() method 1048 DateTime.GetTypeCode() method 1049 DateTime.Hour property 1014 DateTime.IsLeapYear() method 1049–1050 DateTime.MaxValue field 1009 DateTime.Millisecond property 1014–1016 DateTime.Minute property 1015 DateTime.MinValue field 1010–1012
3774
Contents | Index
Days
DateTime.Month property 1016–1017 DateTime.Now property 1017 DateTime.op_Addition() method 1050–1051 DateTime.op_Equality() method 1051–1052 DateTime.op_GreaterThan() method 1053 DateTime.op_GreaterThanOrEqual() method 1054 DateTime.op_Inequality() method 1055–1056 DateTime.op_LessThan() method 1056–1057 DateTime.op_LessThanOrEqual() method 1057–1058 DateTime.op_Subtraction() method 1059–1061 DateTime.Parse() method 1061–1067 DateTime.ParseExact() method 1067–1074 DateTime.Second property 1018 DateTime.Subtract() method 1074–1076 DateTime.Ticks property 1018 DateTime.TimeOfDay property 1019 DateTime.Today property 1020 DateTime.ToFileTime() method 1076 DateTime.ToFileTimeUtc() method 1077 DateTime.ToLocalTime() method 1077–1078 DateTime.ToLongDateString() method 1078–1079 DateTime.ToLongTimeString() method 1079–1080 DateTime.ToOADate() method 1080–1081 DateTime.ToShortDateString() method 1081–1082 DateTime.ToShortTimeString() method 1082–1083 DateTime.ToString() method 1083–1090 DateTime.ToUniversalTime() method 1090–1091 DateTime.UtcNow property 1021 DateTime.Year property 1021–1022 DateTimeFormatInfo class 1098–1106 DateTimeFormatInfo() constructor 1107 Days See also System.DateTime structure number of, adding 1023 Decimals System.Decimal.Structure 1162–1167 Add() method 1183–1184 Compare() method 1185–1186 CompareTo() method 1186–1188 constructor 1168–1178 Divide() method 1188–1189 Equals() method 1190–1192 Floor() method 1192–1193 FromOACurrency() method 1193–1194 GetBits() method 1194–1196 GetHashCode() method 1197–1198 GetTypeCode() method 1198
■
Decimals
MaxValue field 1178–1179 MinusOne field 1179–1180 MinValue field 1180–1181 Multiply() method 1198–1200 Negate() method 1200–1201 One field 1181–1182 op_Addition() method 1201–1203 op_Decrement() method 1203–1204 op_Division() method 1205–1206 op_Equality() method 1206–1208 op_Explicit() method 1208–1227 op_GreaterThan() method 1227–1228 op_GreaterThanOrEqual() method 1229–1230 op_Implicit() method 1230–1239 op_Increment() method 1239–1241 op_Inequality() method 1241–1242 op_LessThan() method 1242–1243 op_LessThanOrEqual() method 1244–1245 op_Modulus() method 1245–1246 op_Multiply() method 1247–1248 op_Subtraction() method 1248–1250 op_UnaryNegotiation() method 1250–1251 op_UnaryPlus() method 1251–1253 Parse() method 1253–1263 Remainder() method 1263–1265 Round() method 1265–1266 Subtract() method 1267–1268 ToByte() method 1268–1269 ToDouble() method 1269 ToInt16() method 1270 ToInt32() method 1271 ToInt64() method 1272 ToOACurrency() method 1272 ToSByte() method 1273 ToSingle() method 1274 ToString() method 1274–1281 ToUInt16() method 1281 ToUInt32() method 1282 ToUInt64() method 1283 Truncate() method 1284–1285 Zero field 1182–1183 System.Double.Structure 1403–1407 CompareTo() method 1414–1415 Epsilon field 1407 Equals() method 1416–1417 GetHashCode() method 1417–1418 GetTypeCode() method 1418 IsInfinity() method 1418–1419
3775
Contents | Index
Declarations
■
Directories
IsNaN() method 1420–1421 IsNegativeInfinity() method 1421–1422 IsPositiveInfinity() method 1422–1424 MaxValue field 1408 MinValue field 1409 NaN field 1410–1411 NegativeInfinity field 1412 Parse() method 1424–1434 PositiveInfinity field 1413 ToString() method 1434–1440 TryParse() method 1441–1442 System.String 448 Unicode characters 441, 443, 447 Declarations bit-fields 1831 security actions 1597 Decoder constructor 1291 GetCharCount() method 1291–1292 GetChars() method 1293–1294 Decoding ASCIIEncoding.GetCharCount() method 297–299 ASCIIEncoding.GetChars() method 299–302 System.Text.Decoder 1488 Defaults attributes 355 dates 1159 Defining attributes 376–381 pre-processing identifiers 523 shape of methods 1608 Delegate Clone() method 1303–1305 Combine() method 1305–1309 CombineImpl() method 1309–1310 constructor 1298–1300 CreateDelegate() method 1311–1319 DynamicInvoke() method 1319–1321 DynamicInvokeImpl() method 1321–1323 Equals() method 1323–1324 GetHashCode() method 1325 GetInvocationList() method 1326–1327 GetMethodImpl() method 1327–1328 GetObjectData() method 1328 Method property 1301 op_Equality() method 1329–1335 Remove() method 1332 RemoveAll() method 1334
RemoveImpl() method 1335 Target property 1302 Delegation namespaces 6 System.Threading.ThreadStart.Delegate 3199–3200 System.Threading.TimerCallback.Delegate 3234–3235 Deleting current frames 508 directories 1344 files 1648 invocation lists 1335 Deserialization 64 See also Serialization Destination arrays Array.CopyTo() method 104–107 parameters 95, 97, 100 Diagnostics 525 namespaces 14 Dictionaries 1337–1339 DictionaryEntry() constructor 1338 DictionaryEntry.Key property 1339 DictionaryEntry.Value property 1339 System.Collections.IDictionary.Interface 1931–1932 Add() method 1938–1940 Clear() method 1940–1941 Contains() method 1941–1942 GetEnumerators() method 1942–1943 IsFixedSize property 1933–1934 IsReadOnly property 1934–1935 Item property 1935–1936 Keys property 1936–1937 Remove() method 1944–1945 Values property 1937–1938 System.Collections.IDictionaryEnumerator.Interface 1946–1947 Entry property 1947–1948 Key property 1948–1949 Value property 1949 Digits See also Decimals Unicode characters 443, 447 Dimensions, rank of 76–77 Directories access 1369 creating 1342 date/time 1653
3776
Contents | Index
DivideByZeroException
DirectoryNotFoundException() constructor 1395–1397 moving 1378 paths, configuring to 1553, 1559 searching 1367 security 1696 System.IO 1340–1342 Directory.CreateDirectory() method 1342–1343 Directory.Delete() method 1344–1347 Directory.Exists() method 1347 Directory.GetCreationTime() method 1349–1351 Directory.GetCreationTimeUtc() method 1351–1352 Directory.GetCurrentDirectory() method 1352 Directory.GetDirectories() method 1353–1358 Directory.GetDirectoryRoot() method 1358–1360 Directory.GetFiles() method 1360–1364 Directory.GetFileSystemEntries() method 1364–1369 Directory.GetLastAccessTime() method 1369–1371 Directory.GetLastAccessTimeUTC() method 1371–1372 Directory.GetLastWriteTime() method 1372–1374 Directory.GetLastWriteTimeUtc() method 1374–1375 Directory.GetLogicalDrives() method 1376 Directory.GetParent() method 1376–1377 Directory.Move() method 1378–1380 Directory.SetCreationTime() method 1380–1382 Directory.SetCreationTimeUtc() method 1382–1384 Directory.SetCurrentDirectory() method 1384–1385 Directory.SetLastAccessTime() method 1386–1388 Directory.SetLastAccessTimeUTC() method 1388–1389 Directory.SetLastWriteTime() method 1389–1391 Directory.SetLastWriteTimeUTC() method 1392–1393 System.IO.Path 2447–2452 AltDirectorySeparatorChar field 2453–2454 ChangeExtension() method 2457–2458 Combine() method 2458–2460 DirectorySeparatorChar field 2454–2455 GetDirectoryName() method 2460–2461 GetExtension() method 2462–2463 GetFileName() method 2463–2465 GetFileNameWithoutExtension() method 2465–2466 GetFullPath() method 2466–2468 GetPathRoot() method 2468–2470 GetTempFileName() method 2470–2471
■
Empty directories
GetTempFilePath() method 2471–2472 HasExtension() method 2472–2473 InvalidPathChars field 2455 IsPathRooted() method 2474–2475 PathSeparator 2456 VolumeSeparatorChar 2457 DivideByZeroException 1399–1402 Domains, names associated with users 1561 DuplicateWaitObjectException() constructor 1449–1452
E Elements 71 ancestors 367 Array.Clear() method 91–92 Array.CopyTo() method 104–107 count number of 263 Current instances 491 initializing 143–149 integers 123, 124 keys 171 lists 234 memory 281 positioning 489 ranges 228 removing 259–261 reversing sequences 150–152 sequences 264 sorting 271–275 storing 199 System.Security.SecurityElement 2587–2588 AddAttribute() method 2591 AddChild() method 2592 Attribute() method 2593–2594 Attributes property 2589 Children property 2589 Equal() method 2594 Escape() method 2595 IsValidAttributeName() method 2596 IsValidAttributeTag() method 2597 IsValidAttributeText() method 2597–2599 IsValidAttributeValue() method 2596–2598 SearchForTextOfTag() method 2598–2599 Tag property 2590 Text property 2591 ToString() method 2599–2601 values 153–160 elementType objects 110 Empty directories, deleting 1344
3777
Contents | Index
Empty instances
■
Enumeration
Empty instances 196 Encoder constructor 1453–1454 GetByteCount() method 1454–1455 GetBytes() method 1455–1457 Encoding ASCII property 1464 BigEndianUnicode property 1464–1465 BodyName property 1465 CodePage property 1465 constructor 1463–1464 Convert() method 1471–1472 Default property 1466 EncodingName property 1466 Equal() method 1473 GetByteCount() method 1473–1476 GetBytes() method 1476–1482 GetCharCount() method 1482–1484 GetChars() method 1485–1488 GetDecoder() method 1488–1489 GetEncoder() method 1489 GetEncoding() method 1491–1492 GetHashCode() method 1492 GetMaxByte() method 1493 GetMaxCharCount() method 1494 GetPreamble() method 1494–1495 GetString() method 1495–1496 HeaderName property 1466 IsBrowserDisplay property 1467 IsBrowserSave property 1467 IsMailNewsDisplay property 1468 IsMailNewsSave property 1468 object security 2587 permissions 1709 StreamReader 2735–2737 BaseStream property 2758 Close() method 2761–2762 constructor 2738–2758 CurrentEncoding property 2760 DiscardBufferedData() method 2762–2764 Dispose() method 2764–2766 Null field 2758 Peek() method 2765 Read() method 2766–2770 ReadLine() method 2770–2772 ReadToEnd() method 2772–2773 Text.ASCIIEncoding class 288–289 Unicode property 1469 UTF8 characters 3667–3669
constructor 3669–3672 Equals() method 3672–3673 GetByteCount() method 3674–3677 GetBytes() 3678–3684 GetCharCount() 3684–3688 GetDecoder() 3688–3689 GetEncoder() 3689–3690 GetHashCode() 3690–3691 GetMaxByteCount() 3691–3693 GetMaxCharCount() 3693–3694 GetPreamble() 3694–3695 UTF8 property 1470 WebName property 1470 WindowsCodePage property 1470 XML 1583, 1719 Encoding.UTF7 property 1469 EndOfStreamException() constructor 1498–1501 Entries, dictionaries 1337–1339 DictionaryEntry() constructor 1338 DictionaryEntry.Key property 1339 DictionaryEntry.Value property 1339 Enum CompareTo() method 1507–1508 Equals() method 1509–1510 Format() method 1510–1512 GetHashCode() method 1512–1513 GetName() method 1513–1516 GetTypeCode() method 1516–1517 GetUnderlyingType() method 1517–1518 GetValues() method 1518–1519 IsDefined() method 1519–1521 Parse() method 1521–1524 ToObject() method 1525–1538 ToString() method 1539–1544 Enumeration System.Enum class 1502–1506 Enum.CompareTo() method 1507–1508 Enum.Equals() method 1509–1510 Enum.Format() method 1510–1512 Enum.GetHashCode() method 1512–1513 Enum.GetName() method 1513–1516 Enum.GetTypeCode() method 1516–1517 Enum.GetUnderlyingType() method 1517–1518 Enum.GetValues() method 1518–1519 Enum.IsDefined() method 1519–1521 Enum.Parse() method 1521–1524 Enum.ToObject() method 1525–1538 Enum.ToString() method 1539–1544 System.IO.File 1634
3778
Contents | Index
Enumerators
Enumerators Array.GetEnumerator() method 121–123 ArrayList.GetEnumerator() method 237–239 System.AttributeTarget Enum class 369–375 System.CharEnumerator 487–489 CharEnumerator.Clone() method 489–490 CharEnumerator.CurrentProperty() method 489 CharEnumerator.MoveNext() method 491 CharEnumerator.Reset() method 491 Environment CommandLine property 1552–1553 CurrentDirectory property 1553–1554 Exit() method 1564–1566 ExitCode property 1555 ExpandEnvironmentVariables() method 1566–1567 GetCommandLineArgs() method 1567–1568 GetEnvironmentVariable() method 1568–1570 GetEnvironmentVariables() method 1570–1572 GetFolderPath() method 1572 GetLogicalDrives() method 1573 HasShutDownStarted property 1556 MachineName property 1556–1557 NewLine property 1557 OSVersion property 1558 StackTrace property 1558–1559 System.Environment class 1550–1552 SystemDirectory property 1559 TickCount property 1560–1561 UserDomainName property 1561 UserInteractive property 1562 UserName property 1563 Version property 1563–1564 WorkingSet property 1564 EnvironmentPermission AddPathList() method 1581 constructor 1577–1581 Copy() method 1582–1583 FromXml() method 1583–1584 GetPathList() method 1584–1585 Intersect() method 1586–1587 IsSubsetOf() method 1587–1589 IsUnrestricted() method 1589 SetPathList() method 1590 ToXml() method 1590–1591 Union() method 1592–1593 EnvironmentPermissionAccess All Access field 1595–1596 No Access field 1596
■
Exceptions
Read field 1596 Write field 1596 EnvironmentPermissionAttribute All property 1600–1601 constructor 1598–1599 CreatePermission() method 1602 Read property 1601–1602 Write property 1602 Equality delegates 1329 System.DateTime structure 1051 Errors See also Troubleshooting execution engines 1629 messages 44 streams 528, 1497 output streams 532 returning 535 System.Exception class 1611 Events, System.EventArgs class 1604–1606 Exceptions ArgumentException 38–46 ArgumentNullException 47–51 ArgumentOutOfRange 53–54 ArrayTypeMismatchException class 283 DirectoryNotFoundException 1394 DirectoryNotFoundException() constructor 1395–1397 DivideByZeroException 1399–1402 EndOfStreamException() constructor 1498–1501 FileLoadException 1737–1739 constructor 1739–1743 FileName property 1743–1744 FusionLog property 1744 GetObjectData() method 1745–1746 Message property 1745 ToString() method 1746–1747 FileNotFoundException 1752–1754 constructor 1754–1758 FileName property 1758 FusionLog property 1759 GetObjectData() method 1760 Message property 1759–1760 ToString() method 1760 namespaces 7–8 NotFiniteNumberException 2313–2314 constructor 2314–2318 GetObjectData() method 2319 OffendingNumber property 2318
3779
Contents | Index
Execution
■
Extended numerics
PathTooLongException 2476–2477 constructor 2477–2480 StackOverFlowException 2690–2691 constructor 2691–2693 System.ApplicationException 33–37 System.ArithmeticException class 61–64 System.DuplicateWaitObjectException 1448–1449 System.Exception class 1611–1615 Exception() constructor 1615–1619 Exception.GetBaseException() 1625–1626 Exception.GetObjectData() 1627 Exception.HelpLink property 1619 Exception.HResult property 1619–1620 Exception.InnerException property 1620–1621 Exception.Message property 1621–1623 Exception.Source property 1623 Exception.StackTrace property 1623–1624 Exception.TargetSite property 1625 Exception.ToString() method 1628 System.ExecutionEngineException class 1629–1632 System.IndexOutOfRangeException 2004–2005 constructor 2005–2007 System.InvalidCastException 2116–2117 constructor 2117–2119 System.InvalidOperationException 2120–2121 constructor 2121–2124 System.InvalidProgramException 2125 constructor 2125–2127 System.IO.EndOfStreamException 1497–1501 System.IO.IOException 2128–2129 constructor 2129–2132 System.NotImplementedException 2320–2321 constructor 2321–2323 System.NotSupportedException 2324–2325 constructor 2325–2328 System.NullReferenceException 2329–2330 constructor 2330–2333 System.ObjectDisposedException 2424–2425 constructor 2425–2427 Message property 2427–2428 ObjectName property 2428, 2428 System.OutOfMemoryException 2439–2440 constructor 2440–2442 System.OverflowException 2443–2444 constructors 2444–2446 System.RankException 2532–2533 constructor 2533–2535 System.Security.SystemException 2600–2601 constructor 2602–2606
GetObjectData() method 2609–2610 GrantedSet property 2606–2607 PermissionState property 2607–2608 PermissionType property 2608 RefusedSet property 2608–2609 ToString() method 2610 System.Security.VerificationException 3704–3705 constructor 3705–3708 System.SystemException 3075–3076 constructor 3076–3078 System.Threading.SynchronizationLockException 3069–3070 constructor 3070–3073 System.Threading.ThreadStateException 3207–3208 constructor 3208–3211 System.UnauthorizedAccessException 3624–3625 constructor 3625–3628 SystemFormatException 1834–1835 constructor 1835–1837 ThreadAbortException 3192–3193 ExceptionState property 3193–3194 TypeInitializationException 3528–3529 GetObjectData property 3530 TypeName property 3529 Execution engines, troubleshooting 1629 environments 1550 System.Exception class 1611 troubleshooting 33 Existing files 1650 opening 1673 Exit code configuring 1555 current process, terminating 1565 Explicit conversion System.InvalidCastException 2116–2117 System.InvalidCastException constructor 2117–2119 Extended numerics System.Decimal.Structure 1162–1167 Add() method 1183–1184 Compare() method 1185–1186 CompareTo() method 1186–1188 constructor 1168–1178 Divide() method 1188–1189 Equals() method 1190–1192 Floor() method 1192–1193
3780
Contents | Index
Extensible Markup Language
FromOACurrency() method 1193–1194 GetBits() method 1194–1196 GetHashCode() method 1197–1198 GetTypeCode() method 1198 MaxValue field 1178–1179 MinusOne field 1179–1180 MinValue field 1180–1181 Multiply() method 1198–1200 Negate() method 1200–1201 One field 1181–1182 op_Addition() method 1201–1203 op_Decrement() method 1203–1204 op_Division() method 1205–1206 op_Equality() method 1206–1208 op_Explicit() method 1208–1227 op_GreaterThan() method 1227–1228 op_GreaterThanOrEqual() method 1229–1230 op_Implicit() method 1230–1239 op_Increment() method 1239–1241 op_Inequality() method 1241–1242 op_LessThan() method 1242–1243 op_LessThanOrEqual() method 1244–1245 op_Modulus() method 1245–1246 op_Multiply() method 1247–1248 op_Subtraction() method 1248–1250 op_UnaryNegotiation() method 1250–1251 op_UnaryPlus() method 1251–1253 Parse() method 1253–1263 Remainder() method 1263–1265 Round() method 1265–1266 Subtract() method 1267–1268 ToByte() method 1268–1269 ToDouble() method 1269 ToInt16() method 1270 ToInt32() method 1271 ToInt64() method 1272 ToOACurrency() method 1272 ToSByte() method 1273 ToSingle() method 1274 ToString() method 1274–1281 ToUInt16() method 1281 ToUInt32() method 1282 ToUInt64() method 1283 Truncate() method 1284–1285 Zero field 1182–1183 System.Double.Structure 1403–1407 CompareTo() method 1414–1415 Epsilon field 1407 Equals() method 1416–1417
■
Fields
GetHashCode() method 1417–1418 GetTypeCode() method 1418 IsInfinity() method 1418–1419 IsNaN() method 1420–1421 IsNegativeInfinity() method 1421–1422 IsPositiveInfinity() method 1422–1424 MaxValue field 1408 MinValue field 1409 NaN field 1410–1411 NegativeInfinity field 1412 Parse() method 1424–1434 PositiveInfinity field 1413 ToString() method 1434–1440 TryParse() method 1441–1442 System.Math 2232 System.NotFiniteNumberException 2313–2314 constructor 2314–2318 GetObjectData() method 2319 OffendingNumber property 2318 System.Single.Structure 2648–2651 CompareTo() method 2658–2659 Epsilon field 2651–2652 Equals() method 2660–2661 GetHashCode() method 2661–2662 GetTypeCode() method 2662 IsInfinity() method 2662–2664 IsNaN() method 2664–2665 IsNegativeInfinity() method 2665–2666 IsPositiveInfinity() method 2667–2668 MaxValue field 2652–2653 MinValue field 2653–2654 NaN field 2654–2655 NegativeInfinity field 2656–2657 Parse() method 2668–2678 PositiveInfinity field 2657–2658 ToString() method 2678–2684 Extensible Markup Language. See XML
F False Array.Clear method 91–92 current instances 222 Fields bit-fields 1831 Boolean.FalseString 384–385 Boolean.TrueString 385–386 Byte.MaxValue 402 Byte.MinValue 403 Char.MaxValue 426–427
3781
Contents | Index
Fields
■
Fields
Char.MinValue 427 Comparer.Default 519 DateTime.MaxValue 1009 DateTime.MinValue 1010–1012 DateTimeStyles.AdjustToUniversal 1155–1156 DateTimeStyles.AllowInnerWhite 1156 DateTimeStyles.AllowLeadingWhite 1157 DateTimeStyles.AllowTrailingWhite 1158 DateTimeStyles.AllowWhiteSpaces 1158 DateTimeStyles.NoCurrentDateDefault 1159–1160 DateTimeStyles.None 1160 Decimal.MaxValue 1178–1179 Decimal.MinusOne 1179–1180 Decimal.MinValue 1180–1181 Decimal.One 1181–1182 Decimal.Zero 1182–1183 Double.Epsilon 1407 Double.MaxValue 1408 Double.MinValue 1409 Double.NaN 1410–1411 Double.NegativeInfinity 1412 Double.PositiveInfinity 1413 EnvironmentPermissionAccess.AllAccess 1595–1596 EnvironmentPermissionAccess.NoAccess 1596 EnvironmentPermissionAccess.Read 1596 EnvironmentPermissionAccess.Write 1596 EventArgs.Empty 1606–1607 FileAccess.Read 1695 FileAccess.ReadWrite 1695 FileAccess.Write 1695 FileIOPermissionAccess.AllAccess 1724 FileIOPermissionAccess.Append 1724–1725 FileIOPermissionAccess.NoAccess 1725 FileIOPermissionAccess.PathDiscovery 1725 FileIOPermissionAccess.Read 1725–1726 FileIOPermissionAccess.Write 1726 FileMode.Append 1749–1750 FileMode.Create 1750 FileMode.CreateNew 1750 FileMode.Open 1750 FileMode.OpenOrCreate 1751 FileMode.Truncate 1751 FileShare.Inheritable 1764 FileShare.None 1764 FileShare.Read 1764 FileShare.ReadWrite 1764–1765 FileShare.Write 1765
Int16.MaxValue 2010 Int16.MinValue 2011 Int32.MaxValue 2041–2042 Int32.MinValue 2042 Int64.MaxValue 2071 Int64.MinValue 2072 Math.PI 2153 NumberStyles.AllowCurrencyStyles 2391 NumberStyles.AllowDecimalPoint 2391 NumberStyles.AllowHexSpecifier 2392 NumberStyles.AllowLeadingSign 2393 NumberStyles.AllowLeadingWhite 2393 NumberStyles.AllowParentheses 2393 NumberStyles.AllowThousands 2393 NumberStyles.AllowTrailingSign 2394 NumberStyles.AllowTrailingWhite 2394 NumberStyles.Any 2395 NumberStyles.Currency 2395 NumberStyles.Float 2396 NumberStyles.HexNumber 2396 NumberStyles.Integer 2396 NumberStyles.None 2397 NumberStyles.Number 2397 Path.AltDirectorySeparatorChar 2453 Path.DirectorySeparatorChar 2454 Path.InvalidPathChars 2455 Path.PathSeparator 2456 Path.VolumeSeparatorChar 2457 PermissionState.None 2518 PermissionState.Unrestricted 2518 SByte.MaxValue 2539–2540 SecurityAction.Assert 2569–2571 SecurityAction.Demand 2571–2577 SecurityAction.Deny 2572–2574 SecurityAction.InheritanceDemand 2574–2576 SecurityAction.LinkDemand 2576–2580 SecurityAction.PermitOnly 2577–2579 SecurityAction.RequestMinimum 2579–2581 SecurityAction.RequestOptional 2580–2582 SecurityAction.RequestRefuse 2581 SecurityPermissionFlag.AllFlags 2639–2640 SecurityPermissionFlag.Assertion 2640 SecurityPermissionFlag.BindingRedirects 2640 SecurityPermissionFlag.ControlAppDomain 2640 SecurityPermissionFlag.ControlDomainPolicy 2641 SecurityPermissionFlag.ControlEvidence 2641 SecurityPermissionFlag.ControlPolicy 2641 SecurityPermissionFlag.ControlPrincipal 2642 SecurityPermissionFlag.ControlThread 2642
3782
Contents | Index
Fields
SecurityPermissionFlag.Execution 2642 SecurityPermissionFlag.Infrastructure 2643 SecurityPermissionFlag.NoFlags 2643 SecurityPermissionFlag.RemotingConfiguration 2643 SecurityPermissionFlag.SerializationFormatter 2643 SecurityPermissionFlag.SkipVerification 2644 SecurityPermissionFlag.UnmanagedCode 2644 SeekOrigin.Begin 2646 SeekOrigin.Current 2646 SeekOrigin.End 2647 Single.Epsilon 2651–2652 Single.MaxValue 2652–2653 Single.MinValue 2653–2654 Single.NaN 2654–2655 Single.NegativeInfinity 2656–2657 Single.PositiveInfinity 2657–2658 Stream.Null 2700 StreamReader.Null field 2758 StreamWriter.Null 2792 String.Empty 2826–2827 TextReader.Null 3081 TextWriter.CoreNewLine 3092 TextWriter.Null 3092–3093 ThreadPriority.AboveNormal 3197 ThreadPriority.BelowNormal 3197 ThreadPriority.Highest 3197 ThreadPriority.Lowest 3197 ThreadPriority.Normal 3198 ThreadState.Aborted 3204 ThreadState.AbortRequest 3204 ThreadState.Background 3204 ThreadState.Running 3204 ThreadState.Stopped 3205 ThreadState.StopRequested 3205 ThreadState.Suspended 3205 ThreadState.SuspendRequested 3206 ThreadState.Unstarted 3206 ThreadState.WaitSleepJoin 3206 Timeout.Infinite 3213 TimeSpan.MaxValue 3245–3246 TimeSpan.MinValue 3246–3247 TimeSpan.TicksPerDay 3248–3249 TimeSpan.TicksPerHour 3249–3250 TimeSpan.TicksPerMillisecond 3250–3251 TimeSpan.TicksPerMinute 3251–3252 TimeSpan.TicksPerSecond 3252–3253 TimeSpan.Zero 3253–3254
■
FileAccess
Type.Delimiter 3314–3315 Type.EmptyTypes 3315–3316 Type.FilterAttribute 3316–3317 Type.FilterName 3317 Type.FilterNameIgnoreCase 3317–3318 Type.Missing 3318–3319 UInt16.MaxValue 3533–3534 UInt16.MinValue 3534–3535 UInt32.MaxValue 3564–3565 UInt32.MinValue 3565–3566 UInt64.MaxValue 3595–3596 UInt64.MinValue 3596–3597 UnicodeCategory.ClosePunctuation 3631 UnicodeCategory.ConnectorPunctuation 3631 UnicodeCategory.Control 3631 UnicodeCategory.CurrencySymbol 3631 UnicodeCategory.DashPunctuation 3632 UnicodeCategory.DecimalDigitNumber 3632 UnicodeCategory.EnclosingMark 3632 UnicodeCategory.FinalQuotePunctuation 3633 UnicodeCategory.Format 3633 UnicodeCategory.InitialQuotePunctuation 3633 UnicodeCategory.LetterNumber 3633 UnicodeCategory.LineSeparator 3634 UnicodeCategory.LowercaseLetter 3634 UnicodeCategory.MathSymbol 3634 UnicodeCategory.ModifierLetter 3635 UnicodeCategory.ModifierSymbol 3635 UnicodeCategory.NonSpacingMark 3635 UnicodeCategory.OpenPunctuation 3635 UnicodeCategory.OtherLetter 3636 UnicodeCategory.OtherNotAssigned 3636 UnicodeCategory.OtherNumber 3636 UnicodeCategory.OtherPunctuation 3637 UnicodeCategory.OtherSymbol 3637 UnicodeCategory.ParagraphSeparator 3637 UnicodeCategory.PrivateUse 3637 UnicodeCategory.SpaceSeparator 3638 UnicodeCategory.SpacingCombiningMark 3638 UnicodeCategory.Surrogate 3638 UnicodeCategory.TitlecaseLetter 3639 UnicodeCategory.UppercaseLetter 3639 UnicodeEncoding.CharSize 3645 WaitHandle.InvalidHandle 3742 WaitHandle.WaitTimeout 3742–3743 FileAccess Read field 1695 ReadWrite field 1695 Write field 1695
3783
Contents | Index
FileIOPermissionAttribute
■
FileStream
FileIOPermissionAttribute 1727–1728 AllProperty 1730–1731 Append property 1731–1732 constructor 1728–1729 CreatePermission() method 1736 PathDiscovery property 1732–1733 Read property 1734–1735 Write property 1735–1736 FileLoadException 1737–1739 constructor 1739–1743 FileName property 1743–1744 FusionLog property 1744 GetObjectData() method 1745–1746 Message property 1745 ToString() method 1746–1747 FileMode.Enum Append field 1749–1750 Create field 1750 CreateNew field 1750 Open field 1750 OpenOrCreate field 1751 Truncate field 1751 FileNotFoundException 1752–1754 constructor 1754–1758 FileName property 1758 FusionLog property 1759 GetObjectData() Method 1760 Message property 1759–1760 ToString() Method 1760 Files access 1369, 1706 copying 1638 creating 1642 creation time of 1349 deleting 1648 existing 1650, 1673 moving 1378, 1663 opening 1646, 1665, 1748–1749 searching 1367 security 1696 sharing 1762–1763 System.IO File 1633–1635 File.AppendText() method 1635–1637 File.Copy() method 1637–1642 File.Create() method 1642–1646 File.CreateText() method 1646–1648 File.Delete() method 1648–1650 File.Exists() method 1650–1651 File.GetAttributes() method 1651–1653
File.GetCreationTime() method 1653–1655 File.GetCreationTimeUtc() method 1655–1656 File.GetLastAccessTime() method 1656–1658 File.GetLastAccessTimeUtc() method 1658–1659 File.GetLastWriteTime() method 1659–1661 File.GetLastWriteTimeUtc() method 1662–1663 File.Move() method 1663–1665 File.Open() method 1665–1673 File.OpenRead() method 1673–1675 File.OpenText() method 1675–1677 File.OpenWrite() method 1677–1679 File.SetAttributes() method 1679–1680 File.SetCreationTime() method 1681–1683 File.SetCreationTimeUtc() method 1683–1684 File.SetLastAccessTime() method 1684–1686 File.SetLastAccessTimeUtc() method 1687–1688 File.SetLastWriteTime() method 1688–1690 File.SetLastWriteTimeUtc() method 1690–1692 System.IO.FileAccess.Enum 1693–1694, 1695 System.IO.Path 2447–2452 AltDirectorySeparatorChar field 2453–2454 ChangeExtension() method 2457–2458 Combine() method 2458–2460 DirectorySeparatorChar field 2454–2455 GetDirectoryName() method 2460–2461 GetExtension() method 2462–2463 GetFileName() method 2463–2465 GetFileNameWithoutExtension() method 2465–2466 GetFullPath() method 2466–2468 GetPathRoot() method 2468–2470 GetTempFileName() method 2470–2471 GetTempPath() method 2471–2472 HasExtension() method 2472–2473 InvalidPathChars field 2455 IsPathRooted() method 2474–2475 PathSeparator field 2456 VolumeSeparatorChar field 2457 UTF-8 encoded text, appending 1635 writing 1677 FileShare Inheritable field 1764 None field 1764 Read field 1764 ReadWrite field 1764–1765 Write field 1765 FileStream BeginRead() 1803–1805
3784
Contents | Index
Finalizers
BeginWrite() 1806–1808 CanRead property 1792–1794 CanSeek property 1794–1795 CanWrite property 1795–1797 Close() 1808–1810 constructor 1771–1792 Dispose() 1810 EndRead() 1811–1813 EndWrite() 1813–1815 Finalize() 1815–1816 Flush() 1816–1817 Handle property 1797–1798 IsAsync property 1798–1799 Length property 1799–1800 Lock() 1817–1818 Name property 1801 Position property 1801–1803 Read() 1818–1821 ReadByte() 1821–1822 Seek() 1823–1824 SetLength() 1824–1826 Unlock() 1826 Write() 1827–1828 WriteByte() 1829–1830 Finalizers 1840 First day of the week, configuring 1120 Fixed size wrappers 236 Flags security permissions 2617 SecurityPermissionAttribute.Flags property 2634 System.FlagsAttribute 1831–1832 System.FlagsAttribute constructor 1833 FlagsAttribute() constructor 1833 Folders, paths 1572 Formatting See also Configuration Array.CreateInstance() method 108–120 arrays 65–72 dates/time 1653 directories 1342 enumeration 1510 enumerators 121 files 1642 leap year 1049 little-endian byte order 1469 services 1964–1965 strings 584 System.DateTime structure, converting 1045 System.FormatException 1834–1835
■
GMT (Greenwich mean time)
System.FormatException constructor 1835–1837 System.Globalization.NumberFormatInfo 2334–2337 System.Globalization.NumberFormatInfo constructor 2337 System.Globalization.NumberStyles.Enum 2388–2391 AllowCurrencyStyles field 2391 AllowDecimalPoint field 2391–2392 AllowExponent field 2392 AllowHexSpecifier field 2392 AllowLeadingSign field 2393 AllowLeadingWhite field 2393 AllowParentheses field 2393 AllowThousands field 2394 AllowTrailingSign field 2394 AllowTrailingWhite field 2394 Any field 2395 Currency field 2395 Float field 2396 HexNumber field 2396 Integer field 2396 None field 2397 Number field 2397 Frames, overriding 508 Full access, securing 1600
G Garbage Collector GC.Collect() method 1842–1843 GC.GetGeneration() method 1843–1844 GC.GetTotalMemory() method 1845 GC.KeepAlive() method 1845 GC.MaxGeneration property 1841–1842 GC.ReRegisterForFinalize() method 1846–1848 GC.SuppressFinalize() method 1848–1849 GC.WaitForPendingFinalizers() method 1849–1850 System.GC 1839–1841 Generating See also Hash codes hash codes 354–355 Boolean 389–390 Char.GetHashCode() method 431 Globalization namespaces 15 System.Globalization namespace 1003 Unicode characters 437 GMT (Greenwich mean time), converting 1155
3785
Contents | Index
Hash codes
■
IList
H Hash codes 431 Boolean 389–390 Byte.GetHashCode() method 407 encoding 1493 enumeration 1512 generating 354–355 System.DateTime.GetHashCode() 1048 Hash functions, customizing 1978–1980 Hashtables System.Collections.HashTable 1851–1855 Add() method 1882–1883 Clear() method 1883–1884 Clone() method 1885–1886 Comparer property 1871 constructor 1855–1871 Contains() method 1886–1887 ContainsKey() method 1887–1888 ContainsValue() method 1889–1890 CopyTo() method 1890–1892 Count property 1872 GetEnumerator() method 1892–1893 GetHash() method 1893–1894 GetObjectData() method 1894 hcp property 1873 IsFixedSize property 1873–1874 IsReadOnly property 1874–1875 IsSynchronized property 1875–1876 Item property 1877–1878 KeyEquals() method 1895–1896 Keys property 1878–1879 OnDeserialization() method 1896 Remove() method 1896–1898 Synchronized() method 1898–1899 SyncRoot property 1880–1881 Values property 1881–1882 Headers, mail agent tags 1466 Help See also Troubleshooting Exception.HelpLink property 1619 Hours, adding number of 1025 HRESULT 1619 Human-readable description of the encoding 1466
I I/O operations namespaces 17–19 System.IO.IOException 2128–2129 System.IO.IOException constructor 2129–2132
IANA (Internet Assigned Numbers Authority) 1470 ICloneable.Clone() method 1913–1914 ICollection CopyTo property 1920–1921 Count property 1917 IsSynchronized property 1918 SynchRoot property 1919 IComparable.CompareTo() method 1925–1926 IComparer.Compare() method 1929–1930 IConvertible ToBoolean() method 2949, 3588, 3618 ToByte() method 2950, 3588, 3619 ToChar() method 2950, 3588, 3619 ToDateTime() method 2950, 3589, 3619 ToDecimal() method 2951, 3589, 3620 ToDouble() method 2951, 3589, 3620 ToInt16() method 2951, 3559, 3590, 3620 ToInt32() method 2952, 3559, 3590, 3621 ToInt64() method 2952, 3559, 3590, 3621 ToSByte() method 2952, 3560, 3591, 3621 ToSingle() method 2953, 3560, 3591, 3622 ToType() method 2953, 3560, 3591, 3622 ToUInt16() method 2953, 3561, 3592, 3622 ToUInt32() method 2954, 3561, 3592, 3623 ToUInt64() method 2954, 3561, 3592, 3623 Identifiers, pre-processing 523 IDeserializationCallback.OnDeserialization() method 2516 IDisposable.Dispose() method 1953, 2734, 3088, 3127, 3761 IEnumerable.GetEnumerator() method 1956, 2949 IEnumerator Current property 1958–1960 MoveNext() method 1960–1961 Reset() method 1962–1963 IFormatProvider.GetFormat() method 1965–1966 IFormattable.ToString() method 1976–1977 IHashCodeProvider.GetHashCode() method 1980–1981 IList Add() method 1993–1994 Clear() method 1994–1995 Contains() method 1996–1997 IndexOf() method 1997–1998 Insert() method 1998–2000 IsFixedSize property 1987–1989 IsReadOnly property 1989–1991 Remove() method 2000–2002 RemoveAt() method 2002–2003
3786
Contents | Index
Implementation
Implementation System.Collections.IComparer 88 System.Collections.IComparer interface 517 Indexes 71 Array.Copy() method 94 Array.IndexOf() method 138–143 Array.LastIndexOf() method 144–149 ArrayList.IndexOf() method 241–244 arrays 228 elements 259–261 returning 241, 250–255 System.IndexOutOfRangeException 2004–2005 constructor 2005–2007 values 105 Initialization instances 35, 1006 null messages 40 System.IO.EndOfStreamException class 1500 Initialization, Array.Initialize() method 143–149 Input streams 528 characters 540 Console.In property 533 Console.OpenStandardInput() method 536 Inserting See also Adding ArrayList.Insert() method 246–248 elements 248–250 Instances See also Current instances adding 209–210 Array.Clone() method 93–94 Array.CreateInstance() method 108–120 date and time 1006 day of the week, retrieving 1012 empty 196 hours, retrieving 1014 initializing 35 iteration over 1954 milliseconds component, retrieving 1014 minute components, retrieving 1015 month components, retrieving 1016 one-dimensional arrays 104 searching 241 second components, retrieving 1018 System.Exception class 1615 System.IO.EndOfStreamException class 1500 System.Text.Encoding class 1463 values 388–389 year components, retrieving 1021
■
Integers
Int16 2008–2010 CompareTo() method 2012–2013 Equals() method 2013–2014 GetHashCode() method 2015 GetTypeCode() method 2016 MaxValue field 2010 MinValue field 2011 Parse() method 2016–2025 ToString() method 2025–2033 Int32 2038–2041 CompareTo() method 2043–2044 Equals() method 2044–2045 GetHashType() method 2046 GetTypeCode() method 2047 MaxValue field 2041–2042 MinValue field 2042 Parse() method 2047–2056 ToString() method 2056–2064 Int64 2069–2071 CompareTo() method 2073–2074 Equals() method 2074–2076 GetHashCode() method 2076–2077 GetTypeCode() method 2077 MaxValue field 2071–2072 MinValue field 2073 Parse() method 2077–2086 ToString() method 2086–2094 Integers byte structure 400–402 Byte.CompareTo method() 404–405 Byte.Equals() method 405–406 Byte.GetHashCode() method 407 Byte.GetTypeCode() method 408 Byte.MaxValue field 402 Byte.MinValue field 403 Byte.Parse() method 408–413 Byte.ToString() method 415–422 elements 123, 124 System.Int16.Structure 2008–2010 Int16.CompareTo() method 2012–2013 Int16.Equals() method 2013–2014 Int16.GetHashCode() method 2015 Int16.GetTypeCode() method 2016 Int16.MaxValue field 2010 Int16.MinValue field 2011 Int16.Parse() method 2016–2025 Int16.ToString() method 2025–2033 System.Int32.Structure 2038–2041 Int32.CompareTo() method 2043–2044
3787
Contents | Index
Interfaces
■
Interfaces
Int32.Equals() method 2044–2045 Int32.GetHashCode() method 2046 Int32.GetTypeCode() method 2047 Int32.MaxValue field 2041–2042 Int32.MinValue field 2042 Int32.Parse() method 2047–2056 Int32.ToString() method 2056–2064 System.Int64.Structure 2069–2071 Int64.CompareTo() method 2073–2074 Int64.Equals() method 2074–2076 Int64.GetHashCode() method 2076–2077 Int64.GetTypeCode() method 2077 Int64.MaxValue field 2071 Int64.MinValue field 2072 Int64.Parse() method 2077–2086 Int64.ToString() method 2086–2094 System.SByte.Structure 2537–2539 CompareTo() method 2541–2542 Equals() method 2542–2543 GetTypeCode() method 2544–2548 HashCode() method 2543–2544 MaxValue field 2539–2540 MinValue field 2540 Parse() method 2545–2554 ToString() method 2554–2562 UInt16.Structure 3531–3533 CompareTo() method 3535–3536 Equals() method 3536–3538 GetHashCode() method 3538–3539 GetTypeCode() method 3539 MaxValue field 3533–3534 MinValue field 3534–3535 Parse() method 3539–3549 ToBoolean() method 3557 ToByte() method 3557 ToChar() method 3557 ToDateTime() method 3558 ToDecimal() method 3558 ToDouble() method 3558 ToString() method 3549–3556 UInt32.Structure 3562–3564 CompareTo() method 3566–3567 Equals() method 3568–3569 GetHashCode() method 3569–3570 GetTypeCode() method 3570 MaxValue field 3564–3565 MinValue field 3565–3566 Parse() method 3570–3580 ToString() method 3580–3587 UInt64.Structure 3593–3595
CompareTo() method 3597–3598 Equals() method 3598–3600 GetHashCode() method 3600–3601 GetTypeCode() method 3601 MaxValue field 3595–3596 MinValue field 3596–3597 Parse() method 3601–3611 ToString() method 3611–3618 values 609 Interfaces 1901–1903, 1909–1910 encoding 1467 namespaces 6 saving 1467 System.Collections.ICollection.Interface 1915–1917 CopyTo property 1920–1921 Count property 1917 IsSynchronized property 1918 SynchRoot property 1919 System.Collections.IComparer.Interface 517, 1927–1928 IComparer.Compare() method 1929–1930 System.Collections.IDictionary.Interface 1931–1932 Add() method 1938–1940 Clear() method 1940–1941 Contains() method 1941–1942 GetEnumerators() method 1942–1943 IsFixedSize property 1933–1934 IsReadOnly property 1934–1935 Item property 1935–1936 Keys property 1936–1937 Remove() method 1944–1945 Values property 1937–1938 System.Collections.IDictionaryEnumerator.Interface 1946–1947 Entry property 1947–1948 Key property 1948–1949 Value property 1949 System.Collections.IEnumerable.Interface 1954–1956 GetEnumerator() method 1956 System.Collections.IEnumerator.Interface 492, 1957–1958 Current property 1958–1960 Move.Next() method 1960–1961 Reset() method 1962–1963 System.Collections.IHashCodeProvider.Interface 1978–1980 GetHashCode() method 1980–1981
3788
Contents | Index
Internal errors
System.Collections.IList.Interface 1982–1987 Add() method 1993–1994 Clear() method 1994–1995 Contains() method 1996–1997 IndexOf() method 1997–1998 Insert() method 1998–2000 IsFixedSize property 1987–1989 IsReadOnly property 1989–1991 Item property 1991–1992 Remove() method 2000–2002 RemoveAt() method 2002–2003 System.FormatProvider.Interface 1964–1965 GetFormat() method 1965–1966 System.ICloneable.Interface 1911–1913 Clone() method 1913–1914 System.IComparable.Interface 1923–1925 CompareTo() method 1925–1926 System.IDisposable.Interface 1950–1952 Dispose() method 1953 System.IFormattable.Interface 1968–1976 ToString() method 1976–1977 System.Security.IPermision IPermission.Copy() method 2135 IPermission.Demand() method 2136–2137 IPermission.Intersect() method 2138–2139 IPermission.IsSubsetOf() method 2140–2142 IPermission.Union() method 2142–2144 System.Security.IPermission 2133–2134 Internal errors 1629 Internet Assigned Numbers Authority ( IANA) 1470 Intersections 504 environment permissions 1586 permissions 505, 1712 Invariants 1122 Invocation lists concatenating 1309 deleting 1335 Invoking methods 1319 Items 175 ArrayList.Item property 205–206 property 1991–1992 Iteration over instances 1954 System.CharEnumerator 487–489
K Keys 175 configuring 1339 elements 171
■
MarshalByRefObject
L Leading, white space 1157 Leap year, formatting 1049 Length of arrays 71, 112, 115 Array.GetLength() method 123 Array.GetLongLength() method 124 Array.Length property 75 Array.LongLength property 76 Letters See also Unicode characters lowercase converting 476 System.String 451 System.String 445 Unicode characters 444, 447 converting lowercase 475 converting uppercase 479 lowercase 450 uppercase 469 uppercase 468 Lines formatted strings 583 terminators 563, 579 Lists, references 234 Little-endian byte order, formatting 1469 Logarithmic functions 2150 Logical drive names 1573 Logical true values 385–386 Long date patterns, configuring 1124 Lower bound Array.GetLowerBound() method 125–126 of dimensions 71 Lowercase letters converting 476 System.String 451 Unicode characters 450, 475
M Mail agents body tags 1465 header tags 1466 Mail clients encoding 1468 saving 1468 Margins leading 1157 Unicode characters 470, 472 MarshalByRefObject constructor 2146 CreateObjRef() method 2146–2147
3789
Contents | Index
Matching instances and objects
■
Methods
GetLifetimeService() method 2147–2148 InitializeLifetimeService() method 2148–2149 Matching instances and objects 367–368 Mathematical functions 2150–2152 Math.Abs() method 2153–2163 Math.Acs() method 2163–2164 Math.Asin() method 2165–2166 Math.Atan() method 2166–2167 Math.Atan2() method 2167–2169 Math.BigMul() method 2169–2170 Math.Ceiling() method 2170–2171 Math.Cos() method 2171–2172 Math.Cosh() method 2172–2173 Math.DivRem() method 2174–2176 Math.Exp() method 2175–2177 Math.Floor() method 2176–2180 Math.IEEERemainder() method 2177–2179 Math.Log() method 2179–2181 Math.Log10() method 2182–2184 Math.Max() method 2183–2196 Math.Min() method 2197–2210 Math.PI field 2153 Math.Pow() method 2210–2212 Math.Round() method 2212–2216 Math.Sign() method 2217–2226 Math.Sin() method 2226–2227 Math.Sinh() method 2227–2228 Math.Sqrt() method 2229–2230 Math.Tan() method 2230–2231 Math.Tanh() method 2231–2232 Maximum code points 426 Memory mapped to process context 1564 minimizing 281 System.IO.MemoryStream 2233–2236 CanRead property 2250–2251 CanSeek property 2251–2253 CanWrite property 2253–2254 Capacity property 2254–2256 Close() method 2260–2261 constructor 2236–2250 Flush() method 2261 GetBuffer() method 2262–2263 Length property 2257–2258 Position property 2258–2260 Read() method 2263–2265 ReadByte() method 2265–2266 Seek() method 2267–2268 SetLength() method 2268–2270
ToArray() method 2271–2272 Write() method 2272–2274 WriteByte() method 2274–2276 WriteTo() method 2276–2277 System.OutOfMemoryException 2439–2440 constructor 2440–2442 MemoryStream CanRead property 2250–2251 CanSeek property 2251–2253 CanWrite property 2253–2254 Capacity property 2254–2256 Close() method 2260–2261 constructor 2236–2250 Flush() method 2261 GetBuffer() method 2262–2263 Length property 2257–2258 Position property 2258–2260 Read() method 2263–2265 ReadByte() method 2265–2266 Seek() method 2267–2268 SetLength() method 2268–2270 ToArray() method 2271–2272 Write() method 2272–2274 WriteByte() method 2274–2276 WriteTo() method 2276–2277 Messages ArgumentException.Message property 44–45 errors. See Errors null 40 Metadata, attributes 355–367 Methods ArgumentException.GetObjectData() 46 ArgumentOutOfRangeException.GetObjectBack() 60 Array.BinarySearch() 81–91 Array.Clear() 91–92 Array.Clone() 93–94 Array.Copy() 94–104 Array.CopyTo() 104–107 Array.CreateInstance() 108–120 Array.GetEnumerator() 121–123 Array.GetLength() 123 Array.GetLongLength() 124 Array.GetLowerBound() 125–126 Array.GetUpperBound() 126–127 Array.GetValue() 128–137 Array.IndexOf() 138–143 Array.Initialize() 143–149 Array.LastIndexOf() 144–149
3790
Contents | Index
Methods
Array.Reverse() 150–152 Array.SetValue() 153–160, 160–164 Array.Sort() 165–181 Array.System.Collections.IList.Add() 182 Array.System.Collections.IList.Clear() 183 Array.System.Collections.IList.Contains() 184–185 Array.System.Collections.IList.IndexOf() 185–186 Array.System.Collections.IList.Insert() 186–187 Array.System.Collections.IList.Remove() 187–188 Array.System.Collections.IList.RemoveAt() 188–189 ArrayList.Adapter() 199–209 ArrayList.Add() 209–210 ArrayList.AddRange() 211–212 ArrayList.BinarySearch() 212–222 ArrayList.Clear() 222–224 ArrayList.Clone() 224–225 ArrayList.Contains() 225–227 ArrayList.CopyTo() 228–234 ArrayList.FixedSize() 234–235, 236 ArrayList.GetEnumerator() 237–239 ArrayList.GetRange() 240–241 ArrayList.IndexOf() 241–244 ArrayList.Insert() 246–248 ArrayList.InsertRange() 248–250 ArrayList.LastIndexOf() 250–255 ArrayList.ReadOnly() 255–257 ArrayList.Remove() 258–259 ArrayList.RemoveAt() 259–261 ArrayList.RemoveRange() 261–263 ArrayList.Repeat() 263–264 ArrayList.Reverse() 264–267 ArrayList.SetRange() 267–269 ArrayList.Sort() 271–275 ArrayList.Synchronized() 275–277 ArrayList.ToArray() 278–280 ArrayList.TrimToSize() 281–282 ASCIIEncoding.GetByteCount() 290–293 ASCIIEncoding.GetBytes() 293–297 ASCIIEncoding.GetCharCount() 297–299 ASCIIEncoding.GetChars() 299–302 ASCIIEncoding.GetMaxByte() 302–303 ASCIIEncoding.GetMaxCharCount() 303–305 ASCIIEncoding.GetString() 305–308 Attribute.Equals() 316 Attribute.GetCustomAttribute() 317–330 Attribute.GetCustomAttributes() 330–354 Attribute.GetHashCode() 354–355 Attribute.IsDefaultAttribute() 355
■
Methods
Attribute.IsDefined() 355–367 Attribute.Match() 367–368 Boolean.CompareTo 386–387 Boolean.Equals() 388–389 Boolean.GetHashCode() 389–390 Boolean.GetTypeCode() 390 Boolean.Parse() 390–392 Boolean.ToString() 393–394 Byte.CompareTo() 404–405 Byte.Equals() 405–406 Byte.GetHashCode() 407 Byte.GetTypeCode() 408 Byte.Parse() 408–413 Byte.ToString() 415–422 callable 523 Char.CompareTo() 428–429 Char.Equals() 430–431 Char.GetHashCode() 431–432 Char.GetNumericValue() 434 Char.GetTypeCode() 435–476 Char.GetUnicodecategory() 437 Char.IsControl() method 438–441 Char.IsDigit() method 441–444 Char.IsLetter() method 444–447 Char.IsLetterOrDigit() 447 Char.IsLower() 450–453 Char.IsNumber() 453–456 Char.IsPunctuation() 456–459 Char.IsSeparator() 459–462 Char.IsSurrogate() 462–464 Char.IsSymbol() 465–467 Char.IsUpper() 467–470 Char.IsWhiteSpace() 470–473 Char.Parse() 473–474 Char.ToLower() 475–476 Char.ToString() 477–479 Char.ToUpper() 479–481 CharEnumerator.Clone() 489–490 CharEnumerator.CurrentProperty() 489 CharEnumerator.MoveNext() 491 CharEnumerator.Reset() 491 CodeAccessPermission.Assert() 499–500 CodeAccessPermission.Copy() 501 CodeAccessPermission.Demand() 501–502 CodeAccessPermission.Deny() 503 CodeAccessPermission.FromXml() 504 CodeAccessPermission.Intersect() 504–505 CodeAccessPermission.IsSubsetOf() 505–506 CodeAccessPermission.PermitOnly() 506–507
3791
Contents | Index
Methods
■
Methods
CodeAccessPermission.RevertAll() 508 CodeAccessPermission.RevertAssert() 508–509 CodeAccessPermission.RevertPermitOnly() 510 CodeAccessPermission.ToString() 510 CodeAccessPermission.ToXml() 510–511 CodeAccessPermission.Union() 511–512 Comparer.Compare() 520–522 Console.OpenStandardError() 535 Console.OpenStandardInput() 536 Console.OpenStandardOutput 538 Convert.ChangeType() 600–603 Convert.GetTypeCode() 606 Convert.IsDBNull() 607 Convert.ToBase64CharArray() 607 Convert.ToBase64String() 610 Convert.ToBoolean() 611–631 Convert.ToInt16() 739–766 Convert.ToInt32() 766–791 Convert.ToInt64() 791–816 Convert.ToSByte() 816–844 Convert.ToSingle() 844–866 Convert.ToUInt16() 910–937 Convert.ToUInt32() 937–964 Convert.ToUInt64() 964–990 DateTime.AddDays() 1023–1024 DateTime.AddHours() 1025 DateTime.AddMilliseconds() 1026–1028 DateTime.AddMinutes() 1028–1029 DateTime.AddMonths() 1029–1031 DateTime.AddSeconds() 1031–1032 DateTime.AddTicks() 1032–1033 DateTime.AddYears() 1034–1035 DateTime.Compare() 1035–1036 DateTime.CompareTo() 1037–1038 DateTime.DaysInMonth() 1039–1040 DateTime.Equals() 1040–1042 DateTime.FromFileTime() 1042 DateTime.FromFileTimeUtc() 1043 DateTime.FromOADate() 1044 DateTime.GetDateTimeFormats() 1045 DateTime.GetHashCode() 1048 DateTime.GetTypeCode() 1049 DateTime.IsLeapYear() 1049–1050 DateTime.op_Addition() 1050–1051 DateTime.op_Equality() 1051–1052 DateTime.op_GreaterThan() 1053 DateTime.op_GreaterThanOrEqual() 1054 DateTime.op_Inequality() 1055–1056 DateTime.op_LessThan() 1056–1057
DateTime.op_LessThanOrEqual() 1057–1058 DateTime.op_Subtraction() 1059–1061 DateTime.Parse() 1061–1067 DateTime.ParseExact() 1067–1074 DateTime.Subtract() 1074–1076 DateTime.ToFileTime() 1076 DateTime.ToFileTimeUtc() 1077 DateTime.ToLocalTime() 1077–1078 DateTime.ToLongDateString() 1078–1079 DateTime.ToLongTimeString() 1079–1080 DateTime.ToOADate() 1080–1081 DateTime.ToShortDateString() 1081–1082 DateTime.ToShortTimeString() 1082–1083 DateTime.ToString() 1083–1090 DateTime.ToUniversalTime() 1090–1091 DateTimeFormatInfo.Clone() 1138 DateTimeFormatInfo.GetAbbreviatedDayName() 1139–1140 DateTimeFormatInfo.GetAbbreviatedMonthName() 1141–1143 DateTimeFormatInfo.GetAllDateTimePatterns() 1143–1144 DateTimeFormatInfo.GetDayName() 1144–1145 DateTimeFormatInfo.GetEra() 1145–1146 DateTimeFormatInfo.GetEraName() 1146–1148 DateTimeFormatInfo.GetFormat() 1148–1149 DateTimeFormatInfo.GetInstance() 1149–1150 DateTimeFormatInfo.GetMonthName() 1150–1152 DateTimeFormatInfo.ReadOnly() 1152 Decimal.Add() 1183–1184 Decimal.Compare() 1185–1186 Decimal.CompareTo() 1186–1188 Decimal.Divide() 1188–1189 Decimal.Equals() 1190–1192 Decimal.Floor() 1192–1193 Decimal.FromOACurrency() 1193–1194 Decimal.GetBits() 1194–1196 Decimal.GetHashCode() 1197–1198 Decimal.GetTypeCode() 1198 Decimal.Multiply() 1198–1200 Decimal.Negate() 1200–1201 Decimal.op_Addition() 1201–1203 Decimal.op_Decrement() 1203–1204 Decimal.op_Division() 1205–1206 Decimal.op_Equality() 1206–1208 Decimal.op_Explicit() 1208–1227 Decimal.op_GreaterThan() 1227–1228 Decimal.op_GreaterThanOrEqual() 1229–1230
3792
Contents | Index
Methods
Decimal.op_Implicit() 1230–1239 Decimal.op_Increment() 1239–1241 Decimal.op_Inequality() 1241–1242 Decimal.op_LessThan() 1242–1243 Decimal.op_LessThanOrEqual() 1244–1245 Decimal.op_Modulus() 1245–1246 Decimal.op_Multiply() 1247–1248 Decimal.op_Subtraction() 1248–1250 Decimal.op_UnaryNegotiation() 1250–1251 Decimal.op_UnaryPlus() 1251–1253 Decimal.Parse() 1253–1263 Decimal.Remainder() 1263–1265 Decimal.Round() 1265–1266 Decimal.Subtract() 1267–1268 Decimal.ToByte() 1268–1269 Decimal.ToDouble() 1269 Decimal.ToInt16() 1270 Decimal.ToInt32() 1271 Decimal.ToInt64() 1272 Decimal.ToOACurrency() 1272 Decimal.ToSByte() 1273 Decimal.ToSingle() 1274 Decimal.ToString() 1274–1281 Decimal.ToUInt16() 1281 Decimal.ToUInt32() 1282 Decimal.ToUInt64() 1283 Decimal.Truncate() 1284–1285 Decoder.GetCharCount() 1291–1292 Decoder.GetChars() 1293–1294 Delegate.Clone() 1303–1305 Delegate.Combine() 1305–1309 Delegate.CombineImpl() 1309–1310 Delegate.CreateDelegate() 1311–1319 Delegate.DynamicInvoke() 1319–1321 Delegate.DynamicInvokeImpl() 1321–1323 Delegate.Equals() 1323–1324 Delegate.GetHashCode() 1325 Delegate.GetInvocationList() 1326–1327 Delegate.GetMethodImpl() 1327–1328 Delegate.GetObjectData() 1328 Delegate.op_Equality() 1329–1335 Delegate.Remove() 1332 Delegate.RemoveImpl() 1335 delegates, invoking 1319 Directory.CreateDirectory() 1342–1343 Directory.Delete() 1344–1347 Directory.Exists() 1347 Directory.GetCreationTime() 1349–1351 Directory.GetCreationTimeUtc() 1351–1352
■
Methods
Directory.GetCurrentDirectory() 1352 Directory.GetDirectories() 1353–1358 Directory.GetDirectoryRoot() 1358–1360 Directory.GetFiles() 1360–1364 Directory.GetFileSystemEntries() 1364–1369 Directory.GetLastAccessTime() 1369–1371 Directory.GetLastAccessTimeUTC() 1371–1372 Directory.GetLastWriteTime() 1372–1374 Directory.GetLastWriteTimeUtc() 1374–1375 Directory.GetLogicalDrives() 1376 Directory.GetParent() 1376–1377 Directory.Move() 1378–1380 Directory.SetCreationTime() 1380–1382 Directory.SetCreationTimeUtc() 1382–1384 Directory.SetCurrentDirectory() 1384–1385 Directory.SetLastAccessTime() 1386–1388 Directory.SetLastAccessTimeUTC() 1388–1389 Directory.SetLastWriteTime() 1389–1391 Directory.SetLastWriteTimeUTC() 1392–1393 Double.CompareTo() 1414–1415 Double.Equals() 1416–1417 Double.GetHashCode() 1417–1418 Double.GetTypeCode() 1418 Double.IsInfinity() 1418–1419 Double.IsNaN() 1420–1421 Double.IsNegativeInfinity() 1421–1422 Double.IsPositiveInfinity() 1422–1424 Double.Parse() 1424–1434 Double.ToString() 1434–1440 Double.TryParse() 1441–1442 Encoder.GetByteCount() 1454–1455 Encoder.GetBytes() 1455–1457 Encoding.Convert() 1471–1472 Encoding.Equal() 1473 Encoding.GetByteCount() 1473 Encoding.GetBytes() 1476–1482 Encoding.GetCharCount() 1482 Encoding.GetChars() 1485–1488 Encoding.GetDecoder() 1488–1489 Encoding.GetEncoder() 1489 Encoding.GetEncoding() 1491–1492 Encoding.GetHashCode() 1492 Encoding.GetMaxByteCount() 1493 Encoding.GetMaxCharCount() 1494 Encoding.GetPreamble() 1494 Enum.CompareTo() 1507–1508 Enum.Equals() 1509–1510 Enum.Format() 1510–1512 Enum.GetHashCode() 1512–1513
3793
Contents | Index
Methods
■
Methods
Enum.GetName() 1513–1516 Enum.GetTypeCode() 1516–1517 Enum.GetUnderlyingType() 1517–1518 Enum.GetValues() 1518–1519 Enum.IsDefined() 1519–1521 Enum.Parse() 1521–1524 Enum.ToObject() 1525–1538 Enum.ToString() 1539–1544 EnviromentPermissionAttribute.CreatePermission() 1602 Environment.Exit() 1564–1566 Environment.ExpandEnvironmentVariables() 1566 Environment.GetCommandLineArgs() 1567 Environment.GetEnvironmentVariables() 1570 Environment.GetFolderPath() 1572 Environment.GetLogicalDrives() 1573 EnvironmentPermission.AddPathList() 1581 EnvironmentPermission.Copy() 1582–1583 EnvironmentPermission.FromXml() 1583–1584 EnvironmentPermission.GetPathList() 1584–1585 EnvironmentPermission.Intersect() 1586–1587 EnvironmentPermission.IsSubsetOf() 1587–1589 EnvironmentPermission.IsUnrestricted() 1589 EnvironmentPermission.SetPathList() 1590 EnvironmentPermission.ToXml() 1590–1591 EnvironmentPermission.Union() 1592–1593 Exception.GetBaseException() 1625–1626 Exception.GetObjectData() 1627 Exception.ToString() 1628 FileIOPermission.AddPathList() 1706–1707 FileIOPermission.Copy() 1708–1709 FileIOPermission.FromXml() 1709–1710 FileIOPermission.GetPathList() 1711–1712 FileIOPermission.Intersection() 1712–1714 FileIOPermission.IsSubsetOf() 1714–1716 FileIOPermission.IsUnrestricted() 1716–1717 FileIOPermission.SetPathList() 1717–1719 FileIOPermission.ToXml() 1719–1720 FileIOPermission.Union() 1721–1722 FileIOPermissionAttribute.CreatePermission() 1736 FileLoadException.GetObjectData() 1745–1746 FileLoadException.ToString() 1746–1747 FileNotFoundException.GetObjectData() 1760 FileNotFoundException.ToString() 1760 FileStream.BeginRead() 1803–1805 FileStream.BeginWrite() 1806–1808 FileStream.Close() 1808–1810 FileStream.Dispose() 1810 FileStream.EndRead() 1811–1813
FileStream.EndWrite() 1813–1815 FileStream.Finalize() 1815–1816 FileStream.Flush() 1816–1817 FileStream.Lock() 1817–1818 FileStream.Read() 1818–1821 FileStream.ReadByte() 1821–1822 FileStream.Seek() 1823–1824 FileStream.SetLength() 1824–1826 FileStream.Unlock() 1826 FileStream.Write() 1827–1828 FileStream.WriteByte() 1829–1830 FromBase64CharArray() 604 GC.Collect() 1842–1843 GC.GetGeneration() 1843–1844 GC.GetTotalMemory() 1845 GC.KeepAlive() 1845 GC.ReRegisterForFinalize() 1846–1848 GC.SuppressFinalize() 1848–1849 GC.WaitForPendingFinalizers() 1849–1850 Hashtable.Add() 1882–1883 Hashtable.Clear() 1883–1884 Hashtable.Clone() 1885–1886 Hashtable.Contains() 1886–1887 Hashtable.ContainsKey() 1887–1888 Hashtable.ContainsValue() 1889–1890 Hashtable.CopyTo() 1890–1892 Hashtable.GetEnumerator() 1892–1893 Hashtable.GetHash() 1893–1894 Hashtable.GetObjectData() 1894 Hashtable.KeyEquals() 1895–1896 Hashtable.OnDeserialization() 1896 Hashtable.Remove() 1896–1898 Hashtable.Synchronized() 1898–1899 ICloneable.Clone() 1913–1914 IComparable.CompareTo() 1925–1926 IComparer.Compare() 1929–1930 IConvertible.ToBoolean() 2949, 3588, 3618 IConvertible.ToByte() 2950, 3588, 3619 IConvertible.ToChar() 2950, 3588, 3619 IConvertible.ToDateTime() 2950, 3589, 3619 IConvertible.ToDecimal() 2951, 3589, 3620 IConvertible.ToDouble() 2951, 3589, 3620 IConvertible.ToInt16() 2951, 3559, 3590, 3620 IConvertible.ToInt32() 2952, 3559, 3590, 3621 IConvertible.ToInt64() 2952, 3559, 3590, 3621 IConvertible.ToSByte() 2952, 3560, 3591, 3621 IConvertible.ToSingle() 2953, 3560, 3591, 3622 IConvertible.ToType() 2953, 3560, 3591, 3622 IConvertible.ToUInt16() 2953, 3561, 3592, 3622
3794
Contents | Index
Methods
IConvertible.ToUInt32() 2954, 3561, 3592, 3623 IConvertible.ToUInt64() 2954, 3561, 3592, 3623 IDeserializationCallBack.OnDeserialization() 2516 IDisposable.Dispose 3761 IDisposable.Dispose() 1953, 2734, 3088, 3127 IEnumerable.GetEnumerator() 1956, 2949 IEnumerator.MoveNext() 1960–1961 IEnumerator.Reset() 1962–1963 IFormatProvider.GetFormat() 1965–1966 IFormattable.ToString() 1976–1977 IHashCodeProvider.GetHashCode() 1980–1981 IList.Add() 1993–1994 IList.Clear() 1994–1995 IList.Contains() 1996–1997 IList.IndexOf() 1997–1998 IList.Insert() 1998–2000 IList.Remove() 2000–2002 IList.RemoveAt() 2002–2003 Int16.CompareTo() 2012–2013 Int16.Equals() 2013–2014 Int16.GetHashCode() 2015 Int16.GetTypeCode() 2016 Int16.Parse() 2016–2025 Int16.ToString() 2025–2033 Int32.CompareTo() 2043–2044 Int32.Equals() 2044–2045 Int32.GetHashCode() 2046 Int32.GetTypeCode() 2047 Int32.Parse() 2047–2056 Int32.ToString() 2056–2064 Int64.CompareTo() 2073–2074 Int64.Equals() 2074–2076 Int64.GetHashCode() 2076–2077 Int64.GetTypeCode() 2077 Int64.Parse() 2077–2086 Int64.ToString() 2086–2094 Interlocked.CompareExchange() 2102 Interlocked.Decrement() 2106 Interlocked.Exchange() 2110 Interlocked.Increment() 2113 IPermission.Copy() 2135 IPermission.Demand() 2136–2137 IPermission.Intersect() 2138 IPermission.Union() 2142–2144 MarshalByRefObject.CreatObjRef() 2146–2147 MarshalByRefObject.GetLifetimeService() 2147–2148 MarshalByRefObject.InitializeLifetimeService() 2148–2149
■
Methods
Math.Abs() 2153–2163 Math.Acs() 2163–2164 Math.Asin() 2165–2166 Math.Atan() 2166–2167 Math.Atan2() 2167–2169 Math.BigMul() 2169–2170 Math.Ceiling() 2170–2171 Math.Cos() 2171–2172 Math.Cosh() 2172–2173 Math.DivRem() 2174–2176 Math.Exp() 2175–2177 Math.Floor() 2176–2180 Math.IEEERemainder() 2177–2179 Math.Log() 2179–2181 Math.Log10() 2182–2184 Math.Max() 2183–2196 Math.Min() 2197–2210 Math.Pow() 2210–2212 Math.Round() 2212–2216 Math.Sign() 2217–2226 Math.Sin() 2226–2227 Math.Sinh() 2227–2228 Math.Sqrt() 2229–2230 Math.Tan() 2230–2231 Math.Tanh() 2231–2232 MemoryStream.Close() 2260–2261 MemoryStream.Flush() 2261 MemoryStream.GetBuffer() 2262–2263 MemoryStream.Read() 2263–2265 MemoryStream.ReadByte() 2265–2266 MemoryStream.Seek() 2267–2268 MemoryStream.SetLength() 2268–2270 MemoryStream.ToArray() 2271–2272 MemoryStream.Write() 2272–2274 MemoryStream.WriteByte() 2274–2276 MemoryStream.WriteTo() 2276–2277 Monitor.Enter() 2283–2285 Monitor.Exit() 2285–2287 Monitor.Pulse() 2287–2289 Monitor.PulseAll() 2289–2292 Monitor.TryEnter() 2292–2299 Monitor.Wait() 2299–2311 NotFiniteNumberException() 2319 NumberFormatInfo.Clone() 2384 NumberFormatInfo.GetFormat() 2384 NumberFormatInfo.ReadOnly() 2386–2387 ObjectDisposedException.GetObjectData() 2428 Path.ChangeExtension() 2457–2458 Path.Combine() 2458–2460
3795
Contents | Index
Methods
■
Methods
Path.GetAFullPath() 2466–2468 Path.GetDirectoryName() 2460–2461 Path.GetExtension() 2462–2463 Path.GetFileName() 2463–2465 Path.GetFileNameWithoutExtension() 2465 Path.GetPathRoot() 2468–2470 Path.GetTempFileName() 2470–2471 Path.GetTempPath() 2471–2472 Path.HasExtension() 2472–2473 Path.IsPathRooted() 2474–2475 PermissionSet.AddPermission() 2491–2493 PermissionSet.Assert() 2493–2495 PermissionSet.ContainsNonCodeAccessPermissions() 2495 PermissionSet.ConvertPermissionSet() 2495 PermissionSet.Copy() 2496–2497 PermissionSet.CopyTo() 2497–2500 PermissionSet.Demand() 2500–2501 PermissionSet.Deny() 2502–2503 PermissionSet.FromXml() 2504–2506 PermissionSet.GetEnumerator() 2506–2507 PermissionSet.IsSubsetOf() 2507–2509 PermissionSet.PermitOnly() 2509–2511 PermissionSet.ToString() 2511–2512 PermissionSet.ToXml() 2512–2514 PermissionSet.Union() 2514–2516 Random.Next() 2524–2528 Random.NextBytes() 2528–2529 Random.NextDouble() 2529–2530 Random.Sample() 2531 RemoveAll() 1334 SByte.CompareTo() 2541–2542 SByte.Equals() 2542–2543 SByte.GetTypeCode() 2544–2548 SByte.HashCode() 2543–2544 SByte.Parse() 2545–2554 SByte.ToString() 2554–2562 Security.Attribute.CreatePermission() 2586 SecurityElement.AddAttribute() 2591 SecurityElement.AddChild() 2592 SecurityElement.Attribute() 2593 SecurityElement.Equal() 2594 SecurityElement.Escape() 2595 SecurityElement.IsValidAttributeName() 2596 SecurityElement.IsValidAttributeValue() 2596 SecurityElement.IsValidTag() 2597 SecurityElement.IsValidText() 2597 SecurityElement.SearchForTextOfTag() 2598 SecurityElement.ToString() 2599
SecurityPermission.Copy() 2618–2619 SecurityPermission.FromXml() 2619–2620 SecurityPermission.Intersect() 2621–2622 SecurityPermission.IsSubsetOf() 2622–2624 SecurityPermission.IsUnrestricted() 2624 SecurityPermission.ToXml() 2625 SecurityPermission.Union() 2626–2627 SecurityPermissionAttribute.CreatePermission() 2636 shape of, defining 1608 Single.CompareTo() 2658–2659 Single.Equals() 2660–2661, 2661–2662 Single.IsInfinity() 2662–2664 Single.IsNaN() 2664–2665 Single.IsNegativeInfinity() 2665–2666 Single.IsPositiveInfinity() 2667–2668 Single.Parse() 2668–2678 Single.ToString() 2678–2684 Stream.BeginRead() 2708–2711 Stream.BeginWrite() 2711–2714 Stream.Close() 2714–2715 Stream.CreateWaitHandle() 2715 Stream.EndRead() 2716–2718 Stream.EndWrite() 2718–2720 Stream.Flush() 2720–2722 Stream.Read() 2722–2726 Stream.Seek() 2726–2728 Stream.SetLength() 2728–2730 Stream.Write() 2730–2732 Stream.WriteByte() 2732–2733 StreamReader.Close() 2761–2762 StreamReader.DiscardBufferedData() 2762–2764 StreamReader.Dispose() 2764–2766 StreamReader.Peek() 2765 StreamReader.Read() 2766–2770 StreamReader.ReadLine() 2770–2772 StreamReader.ReadToEnd() 2772–2773 StreamWriter.Close() 2796–2798 StreamWriter.Dispose() 2798 StreamWriter.Finalize() 2799 StreamWriter.Flush() 2799–2800 StreamWriter.Write() 2800–2806 String.Clone() 2829–2830 String.Compare() 2830–2843 String.CompareOrdinal() 2843–2847 String.CompareTo() 2847–2850 String.Concat() 2850–2859 String.Copy() 2860–2861 String.CopyTo() 2861–2863
3796
Contents | Index
Methods
String.EndsWith() 2863–2864 String.Equals() 2865–2868 String.Format() 2868–2877 String.GetEnumerator() 2877–2878 String.GetHashCode() 2878–2879 String.GetTypeCode() 2879 String.IndexOf() 2879–2890 String.IndexOfAny() 2890–2895 String.Insert() 2895–2896 String.Intern() 2896–2898 String.IsInterned() 2898–2899 String.Join() 2900–2902 String.LastIndexOf() 2902–2913 String.LastIndexOfAny() 2913–2918 String.op_Equality() 2918–2920 String.op_Inequality() 2920–2921 String.PadLeft() 2921–2924 String.PadRight() 2924–2926 String.Remove() 2926–2928 String.Replace() 2928–2930 String.Split() 2930–2933 String.StartsWith() 2933–2935 String.Substring() 2935–2938 String.ToCharArray() 2938–2940 String.ToLower() 2940–2942 String.ToString() 2942–2943 String.ToUpper() 2943–2945 String.Trim() 2945–2947 String.TrimEnd() 2947–2948 String.TrimStart() 2948–2949 StringBuilder.Append() 2970–2994 StringBuilder.AppendFormat() 2994–3002 StringBuilder.EnsureCapacity() 3002–3004 StringBuilder.Equals() 3004–3005 StringBuilder.Insert() 3005–3032 StringBuilder.Remove() 3032–3033 StringBuilder.Replace() 3034–3039 StringBuilder.ToString() 3039–3041 StringReader.Close() 3044–3045 StringReader.Dispose() 3046 StringReader.Peek() 3046–3048 StringReader.Read() 3048–3051 StringReader.ReadLine() 3051–3052 StringReader.ReadToEnd() 3052–3053 StringWriter.Close() 3061–3062 StringWriter.Dispose() 3062 StringWriter.GetStringBuilder() 3063 StringWriter.ToString() 3064 StringWriter.Write() 3065–3068
■
Methods
System.IO File 1634 Copy() 1637–1642 Create() 1642–1646 CreateText() 1646–1648 Delete() 1648–1650 Exists() 1650–1651 File.AppendText() 1635–1637 File.Move() 1663–1665 File.Open() 1665–1673 File.OpenRead() 1673–1675 File.OpenText() 1675–1677 File.OpenWrite() 1677–1679 File.SetAttributes() 1679–1680 File.SetCreationTime() 1681–1683 File.SetCreationTimeUtc() 1683–1684 File.SetLastAccessTime() 1684–1686 File.SetLastAccessTimeUtc() 1687–1688 File.SetLastWriteTime() 1688–1690 File.SetLastWriteTimeUtc() 1690–1692 GetAttributes() 1651–1653 GetCreationTime() 1653–1655 GetCreationTimeUtc() 1655–1656 GetLastAccessTime() 1656–1658 GetLastAccessTimeUtc() 1658–1659 GetLastWriteTime() 1659–1661 GetLastWriteTimeUtc() 1662–1663 System.Object.Equals() 142, 2402–2411 System.Object.Finalize() 2411–2412 System.Object.GetHashCode() 2412–2417 System.Object.GetType() 2417–2418 System.Object.MemberwiseClone() 2418–2420 System.Object.ReferenceEquals() 2421–2422 System.Object.ToString() 2422–2423 SystemException.GetObjectData() 2609–2610 SystemException.ToString() 2610 TextReader.Close() 3081–3082 TextReader.Dispose() 3082 TextReader.Peek() 3082–3083 TextReader.Read() 3083–3085 TextReader.ReadBlock() 3085–3086 TextReader.ReadLine() 3086 TextReader.ReadToEnd() 3087 TextReader.Synchronized() 3087–3088 TextWriter.Close() 3094 TextWriter.Dispose() 3095 TextWriter.Flush() 3095 TextWriter.Synchronized() 3096 TextWriter.Write() 3097–3111 TextWriter.WriteLine() 3112–3127
3797
Contents | Index
Methods
■
Methods
Thread.Abort() 3144–3149 Thread.AllocateDataSlot() 3149 Thread.AllocateNamedDataSlot() 3149–3150 Thread.Finalize() 3150 Thread.FreeNamedDataSlot() 3150–3151 Thread.GetData() 3151–3152 Thread.GetDomain() 3152 Thread.GetDomainID() 3153 Thread.GetNamedDataSlot() 3153–3154 Thread.Interrupt() 3154 Thread.Join() 3154–3160 Thread.MemoryBarrier() 3160 Thread.ResetAbort() 3160–3162 Thread.Resume() 3162–3163 Thread.SetData() 3163 Thread.Sleep() 3164–3166 Thread.SpinWait() 3167 Thread.Start() 3167–3168 Thread.Suspend() 3169 Thread.VolatileRead() 3169–3179 Thread.VolatileWrite() 3180–3191 Timer.Change() 3222–3230 Timer.Dispose() 3230–3233 Timer.Finalize() 3233 TimeSpan.Add() 3267–3268 TimeSpan.Compare() 3268–3270 TimeSpan.CompareTo() 3270–3271 TimeSpan.Duration() 3272 TimeSpan.Equals() 3272–3275 TimeSpan.FromDays() 3275–3276 TimeSpan.FromHours() 3277–3278 TimeSpan.FromMilliseconds() 3278–3280 TimeSpan.FromMinutes() 3280–3281 TimeSpan.FromSeconds() 3282–3283 TimeSpan.FromTicks() 3283–3284 TimeSpan.GetHashCode() 3285–3286 TimeSpan.Negate() 3286–3287 TimeSpan.op_Addition() 3287–3288 TimeSpan.op_Equality() 3288–3289 TimeSpan.op_GreaterThan() 3289–3290 TimeSpan.op_GreaterThanOrEqual() 3291–3292 TimeSpan.op_Inequality() 3292–3293 TimeSpan.op_LessThan() 3293–3294 TimeSpan.op_LessThanOrEqual() 3294–3295 TimeSpan.op_Subtraction() 3296–3297 TimeSpan.op_UnaryNegation() 3297–3298 TimeSpan.op_UnaryPlus() 3298–3299 TimeSpan.Parse() 3299–3301 TimeSpan.Subtract() 3301–3303
TimeSpan.ToString() 3303–3304 troubleshooting 38–46 Type.Equals() 3374–3376 Type.FindInterfaces() 3376–3377 Type.FindMembers() 3378–3380 Type.GetArrayRank() 3380–3381 Type.GetAttributeFlagsImpl() 3381–3382 Type.GetConstructor() 3382–3397 Type.GetDefaultMembers() 3397–3398 Type.GetElementType() 3398–3399 Type.GetEvent() 3399–3403 Type.GetEvents() 3403–3406 Type.GetField() 3406–3410 Type.GetFields() 3410–3413 Type.GetHashCode() 3413–3414 Type.GetInterface() 3414–3417 Type.GetInterfaceMap() 3417–3418 Type.GetInterfaces() 3419 Type.GetMember() 3420–3426 Type.GetMembers() 3426–3429 Type.GetMethod() 3429–3445 Type.GetMethodImpl() 3445–3448 Type.GetMethods() 3448–3451 Type.GetNestedType() 3452–3455 Type.GetNestedTypes() 3456–3459 Type.GetProperties() 3459–3462 Type.GetProperty() 3462–3477 Type.GetPropertyImpl() 3477–3479 Type.GetType() 3479–3486 Type.GetTypeArray() 3486–3488 Type.GetTypeCode() 3488 Type.GetTypeFromCLSID() 3488–3492 Type.GetTypeFromHandle() 3492–3494 Type.GetTypeFromProgID() 3494–3500 Type.GetTypeHandle() 3500–3501 Type.HasElementTypeImpl() 3501–3502 Type.InvokeMembers() 3502–3517 Type.IsArrayImpl() 3517–3518 Type.IsAssignableFrom() 3518–3519 Type.IsByRefImpl() 3519–3520 Type.IsCOMObjectImpl() 3520 Type.IsContextfulImpl() 3520–3521 Type.IsInstanceOfType() 3521–3522 Type.IsMarshalByRefImpl() 3523 Type.IsPointerImpl() 3523 Type.IsPrimitiveImpl() 3524 Type.IsSubclassOf() 3524–3526 Type.IsValueTypeImpl() 3526 Type.ToString() 3527
3798
Contents | Index
Milliseconds
UInt16.CompareTo() 3535–3536 UInt16.Equals() 3536–3538 UInt16.GetHashCode() 3538–3539 UInt16.GetTypeCode() 3539 UInt16.Parse() 3539–3549 UInt16.ToBoolean() 3557 UInt16.ToByte() 3557 UInt16.ToChar() 3557 UInt16.ToDateTime() 3558 UInt16.ToDecimal() 3558 UInt16.ToDouble() 3558 UInt16.ToString() 3549–3556 UInt32.CompareTo() 3566–3567 UInt32.Equals() 3568–3569 UInt32.GetHashCode() 3569–3570 UInt32.GetTypeCode() 3570 UInt32.Parse() 3570–3580 UInt32.ToString() 3580–3587 UInt64.CompareTo() 3597–3598 UInt64.Equals() 3598–3600 UInt64.GetHashCode() 3600–3601 UInt64.GetTypeCode() 3601 UInt64.Parse() 3601–3611 UInt64.ToString() 3611–3618 UnicodeEncoding.Equals() 3646–3647 UnicodeEncoding.GetByteCount() 3647–3650 UnicodeEncoding.GetBytes() 3650–3656 UnicodeEncoding.GetCharCount() 3656–3657 UnicodeEncoding.GetChars() 3658–3660 UnicodeEncoding.GetDecoder() 3660–3661 UnicodeEncoding.GetHashCode() 3661–3662 UnicodeEncoding.GetMaxByteCount() 3662–3664 UnicodeEncoding.GetMaxCharCount() 3664–3665 UnicodeEncoding.GetPreamble() 3666 UTF8Encoding.Equals() 3672–3673, 3674–3677 ValueType.Equals() 3700–3701 ValueType.GetHashCode() 3701–3702 ValueType.ToString() 3703 Version.Clone() 3721–3722 Version.CompareTo() 3723–3724 Version.Equals() 3724–3726 Version.GetHashCode() 3726–3727 Version.op_Equality() 3727–3728 Version.op_GreaterThan() 3728–3730 Version.op_GreaterThanOrEqual() 3730–3731 Version.op_Inequality() 3731–3733 Version.op_LessThan() 3733–3734 Version.op_LessThanOrEqual() 3734–3736 Version.ToString() 3736–3737
■
Names
WaitHandle.Close() 3744–3745 WaitHandle.Dispose() 3745–3746 WaitHandle.Finalize() 3746 WaitHandle.WaitAll() 3747–3752 WaitHandle.WaitAny() 3752–3758 WaitHandle.WaitOne() 3758–3761 Milliseconds number of since system started 1560 number of, adding 1026 retrieving 1014 Minimizing memory 281 Minimum code points 427 Minute components, retrieving 1015 Modification arrays 65–72 lists 234 Monitor Enter() method 2283–2285 Exit() method 2285–2287 Pulse() method 2287–2289 PulseAll() method 2289–2292 TryEnter() method 2292–2299 Wait() method 2299–2311 Months 1006, 1128 names 1128 number of, adding 1029 patterns 1136 retrieving 1016 Moving files 1378, 1663 permissions 1708 Multicast (combinable) delegates 1309 Multidimensional arrays 117
N Names 1128 days of the week 1118 domains 1561 enumeration 1513 IANA 1470 logical drives 1573 mail agent body tags 1465 NetBIOS 1556 parameters 45 replacing 1566 searching 1367 subdirectories 1356 URN 1619 users 1563
3799
Contents | Index
Namespaces
■
Numbers
Namespaces attributes 4–5 collections 11–12 delegates 6 diagnostics 14 Exceptions 7–8 globalization 15 I/O operations 17–19 interfaces 6 permissions 22 security 21–24 System 3–4 System.Globalization 1003 text 25 threading 27–30 utility objects 5 Nanosecond units 995 NetBIOS names 1556 Newline strings 1557 News clients encoding 1468 saving 1468 NoAccess field 1725 NotFiniteNumberException constructor 2314 GetObjectData() method 2319 OffendingNumber property 2318 NotImplementedException() constructor 2321–2323 NotSupportedException() constructor 2325–2328 Null arguments 54 Null fields StreamReader.Null field 2758 streams 2700 TextReader 3081 TextWriter 3092–3093 Null messages 40 Null methods, troubleshooting 47–51 Null references 91–92 binary searches 217 comparers 175 current instances 222 NullReferenceException() constructor 2330–2333 NumberFormatInfo 2334–2337 Clone() method 2384 constructor 2337 CurrencyDecimalDigits property 2338–2339 CurrencyDecimalSeparator property 2339–2340 CurrencyGroupSeparator property 2340–2341
CurrencyGroupSizes property 2342–2343 CurrencyNegativePattern property 2343–2345 CurrencyPositivePattern property 2346–2347 CurrencySymbol property 2348–2349 CurrentInfo property 2349–2351 GetFormat() method 2384 InvariantInfo property 2351–2355 IsReadOnly property 2356–2357 NaNSymbol property 2357–2358 NegativeInfinitySymbol property 2358–2359 NegativeSign property 2360–2361 NumberDecimalDigits property 2361–2362 NumberDecimalSeparator property 2362–2363 NumberGroupSeparator property 2364–2365 NumberGroupSizes property 2365–2367 NumberNegativePattern property 2367–2368 PercentDecimalDigits property 2369–2370 PercentDecimalSeparator property 2370–2371 PercentGroupSeparator property 2371–2372 PercentGroupSizes property 2373–2374 PercentNegativePattern property 2374–2376 PercentPositivePattern property 2376–2378 PercentSymbol property 2378–2379 PerMilleSymbol property 2380–2381 PositiveInfinitySymbol property 2381–2382 PositiveSign property 2382–2383 ReadOnly() method 2386–2387 Numbers See also Decimals System.Globalization,NumberFormatInfo constructor 2337 System.Globalization.NumberFormatInfo 2334–2337 System.Globalization.NumberStyles.Enum 2388–2391 AllowCurrencyStyles field 2391 AllowDecimalPoint field 2391–2392 AllowExponent field 2392 AllowHexSpecifier field 2392 AllowLeadingSign field 2393 AllowLeadingWhite field 2393 AllowParentheses field 2393 AllowThousands field 2394 AllowTrailingSign field 2394 AllowTrailingWhite field 2394 Any field 2395 Currency field 2395 Float field 2396 HexNumber field 2396
3800
Contents | Index
Numeric type
Integer field 2396 None field 2397 Number field 2397 System.Random 2519–2521 constructor 2521–2523 Next() method 2524–2528 NextBytes() method 2528–2529 NextDouble() method 2529–2530 Sample() method 2531 System.String 454 Unicode characters 453 Numeric type, converting 599 Numeric values, Unicode characters 432, 434 Numerics. See Extended numerics
O Objects ArgumentException.GetObjectData() 46 ArgumentOutOfRangeException.GetObjectBack() method 60 asynchronous operations 1901 elementType 110 output streams 534 security, encoding 2587 services 1964–1965 sort orders 404–405 sorting 165–181 strings 1968–1976 subsets 505, 1714 System.MarshalByRefObject 2145–2146 System.Object 2399–2401 constructor 2401–2402 Equals() method 2402–2411 Finalize() method 2411–2412 GetHashCode() method 2412–2417 GetType() method 2417–2418 MemberwiseClone() method 2418–2420 ReferenceEquals() method 2421–2422 ToString() method 2422–2423 System.ObjectDisposedException 2424–2425 constructor 2425–2427 GetObjectData() method 2428 Message property 2427–2428 ObjectName property 2428 text representations 577 unions 511 utility 5 OLE Automation Dates, converting 1080 One-dimensional arrays 104
■
Output streams
Array.IndexOf() method 138–143 values 160–164 One-dimensional instances, elements 153–160 Opening existing files 1673 files 1646, 1665, 1748–1749 text 1675 Operating systems identifying 1558 timestamps 1043 Operations System.InvalidOperationException 2120–2121 constructor 2121–2124 System.IO File 1633–1635 File.AppendText() method 1635–1637 File.Copy() method 1637–1642 File.Create() method 1642–1646 File.CreateText() method 1646–1648 File.Delete() method 1648–1650 File.Exists() method 1650–1651 File.GetAttributes() method 1651–1653 File.GetCreationTime() method 1653–1655 File.GetCreationTimeUtc() method 1655–1656 File.GetLastAccessTime() method 1656–1658 File.GetLastAccessTimeUtc() method 1658–1659 File.GetLastWriteTime() method 1659–1661 File.GetLastWriteTimeUtc() method 1662–1663 File.Move() method 1663–1665 File.Open() method 1665–1673 File.OpenRead() method 1673–1675 File.OpenText() method 1675–1677 File.OpenWrite() method 1677–1679 File.SetAttributes() method 1679–1680 File.SetCreationTime() method 1681–1683 File.SetCreationTimeUtc() method 1683–1684 File.SetLastAccessTime() method 1684–1686 File.SetLastAccessTimeUtc() method 1687–1688 File.SetLastWriteTime() method 1688–1690 File.SetLastWriteTimeUtc() method 1690–1692 System.IO.IOException 2128–2129 constructor 2129–2132 System.NotImplementedException 2320–2321 constructor 2321–2323 System.NotSupportedException 2324–2325 constructor 2325–2328 Output streams 528 Console.OpenStandardOutput() method 538 Console.Out property 534 errors 532
3801
Contents | Index
OverflowException() constructor
■
Permissions
OverflowException() constructor 2446 Overflows StackOverflowException 2690–2691 StackOverflowException constructor 2691–2693 Overriding frames 508 Overwriting files 1642
P Parameters destinationArray 97 names 45 provider 393, 418 sourceArray 97 Parsing Boolean.Parse() method 390–392 Byte.Parse() method 408–413 enumeration type 1521 System.DateTime values 1061 Unicode characters 473–474 PathDiscovery field 1725 Paths arguments 1636 directories, creating 1342 folders 1572 System.IO.File Attributes 1652 System.IO.Path 2447–2452 AltDirectorySeparatorChar field 2453–2454 ChangeExtension() method 2457–2458 Combine() method 2458–2460 DirectorySeparatorChar field 2454–2455 GetDirectoryName() method 2460–2461 GetExtension() method 2462–2463 GetFileName() method 2463–2465, 2465–2466 GetFullPath() method 2466–2468 GetPathRoot() method 2468–2470 GetTempFileName() method 2470–2471 GetTempPath() method 2471–2472 HasExtension() method 2472–2473 InvalidPathChars field 2455 IsPathRooted() method 2474–2475 PathSeparator field 2456 VolumeSeparatorChar field 2457 System.IO.PathTooLongException 2476–2477 constructor 2477–2480 Patterns long date, configuring 1124 months 1136 RFC 1123 1131 years 1136
Permissions See also Access See also Security code access 496 copying 1708 EnvironmentPermission AddPathList() method 1581 Copy() method 1582–1583 FromXml() 1583–1584 GetPathList() 1584–1585 Intersect() 1586–1587 IsRestricted() 1589 IsSubsetOf() 1587–1589 SetPathList() 1590 ToXml() 1590–1591 Union() 1592–1593 intersections 505, 1712 namespaces 22 SecurityPermission 2611–2613 constructor 2613–2617 Copy() method 2618–2619 Flags property 2617 FromXml() method 2619–2620 Intersect() method 2621–2622 IsSubsetOf() method 2622–2624 IsUnrestricted() method 2624 ToXml() method 2625 Union() method 2626–2627 SecurityPermissionAttribute 2628–2630 Assertion property 2631 constructor 2630 ControlAppDomain property 2631 ControlDomainPolicy property 2631–2632 ControlEvidence property 2632 ControlPolicy property 2632 ControlPrincipal property 2633 ControlThread property 2633 CreatePermission() method 2636–2637 Execution property 2633–2634 Flags property 2634 Infrastructure property 2634 RemotingConfiguration property 2635 SerializationFormatter property 2635 SkipVerification property 2635 UnmanagedCode property 2636 System.Security.IPermission.Interface 2133–2134 IPermssion.Copy() method 2135 IPermssion.Demand() method 2136–2137 IPermssion.Intersect() method 2138–2139
3802
Contents | Index
PermissionState
IPermssion.IsSubsetOf() method 2140–2142 IPermssion.Union() method 2142–2144 System.Security.Permissions.PermissionState.Enum 2517–2518 System.SecurityPermissionSet 2481–2486 AddPermission() method 2491–2493 Assert() method 2493–2495 constructor 2486–2489 ContainsNonCodeAccessPermissions() method 2495 ConvertPermissionSet() method 2495 Copy() method 2496–2497 CopyTo() method 2497–2500 Count property 2489–2490 Demand() method 2500–2501 Deny() method 2502–2503 FromXml() method 2504–2506 GetEnumerator() method 2506–2507 IsReadOnly property 2490 IsSubsetOf() method 2507–2509 IsSynchronized property 2490–2491 PermitOnly() method 2509–2511 SynchRoot property 2491 ToString() method 2511–2512 ToXml() method 2512–2514 Union() method 2514–2516 unions 1721 unrestricted 1716 XML 1709 PermissionState None field 2518 Unrestricted field 2518 Physical memory, mapped to process context 1564 Positioning Array.GetValue() method 128–137 control characters 440 current instances 491 decimal digits 443, 447 elements 153–160, 489 enumerators 121 Unicode characters 434 globalization 437 values 160–164 Pre-processing identifiers, defining 523 Priorities, System.Threading.ThreadPriority.Enum 3195 Programming See also Code System.GC 1839–1841
■
Properties
Collect() method 1842–1843 GetGeneration() method 1843–1844 GetTotalMemory() method 1845 KeepAlive() method 1845 MaxGeneration property 1841–1842 ReRegisterForFinalize() method 1846–1848 SuppressFinalize() method 1848–1849 WaitForPendingFinalizers() method 1849–1850 Programs See also Applications System.InvalidProgramException 2125 System.InvalidProgramException constructor 2125–2127 Properties ArgumentException.Message 44–45 ArgumentException.ParamName 45 ArgumentOutOfRangeException.ActualValue 58 ArgumentOutOfRangeException.Message 59 Array.IsFixedSize 73–74 Array.Length 75 Array.LongLength 76 Array.Rank 76–77 Array.SyncRoot 77 Array.System.Collections.ICollection.Count 189 Array.System.Collections.IList.Item 190 ArrayList.Capacity 199–200 ArrayList.Count 200–201 ArrayList.ICollection.IsReadOnly 202–203 ArrayList.ICollection.IsSynchronized 203–204 ArrayList.ICollection.Item 205–206 ArrayList.ICollection.SyncRoot 206–207 AttributeUsageAttribute.AllowMultiple 380 AttributeUsageAttribute.Inherited 380 AttributeUsageAttribute.Valid 381 CLSCompliantAttribute.IsCompliant 495 ConditionalAttribute.ConditionString 526 Console.Error 532 Console.In 533 Console.Out 534 DateTime.Add 1022–1023 DateTime.DayOfWeek 1012 DateTime.DayOfYear 1013 DateTime.Hour 1014 DateTime.Millisecond 1014–1016 DateTime.Minute 1015 DateTime.Month 1016–1017 DateTime.Now 1017 DateTime.Second 1018 DateTime.Ticks 1018
3803
Contents | Index
Properties
■
Properties
DateTime.TimeOfDay 1019 DateTime.Today 1020 DateTime.UtcNow 1021 DateTime.Year 1021–1022 DateTimeFormatInfo.AbbreviatedDayNames 1108 DateTimeFormatInfo.AbbreviatedMonthNames 1110 DateTimeFormatInfo.AMDesignator 1112–1113 DateTimeFormatInfo.Calendar 1114–1115 DateTimeFormatInfo.CalendarWeekRule 1115 DateTimeFormatInfo.CurrentInfo 1116–1117 DateTimeFormatInfo.DateSeparator 1117 DateTimeFormatInfo.DayNames 1118 DateTimeFormatInfo.FirstDayOfWeek 1120 DateTimeFormatInfo.FullDateTimePattern 1121–1122 DateTimeFormatInfo.InvariantInfo 1122–1123 DateTimeFormatInfo.IsReadOnly 1123–1124 DateTimeFormatInfo.LongDatePattern 1124–1125 DateTimeFormatInfo.LongTimePattern 1125–1126 DateTimeFormatInfo.MonthDayPattern 1127 DateTimeFormatInfo.MonthNames 1128–1129 DateTimeFormatInfo.PMDesignator 1130–1131 DateTimeFormatInfo.RFC1123Pattern 1131 DateTimeFormatInfo.ShortDateTimePattern 1132–1133 DateTimeFormatInfo.ShortTimePattern 1133–1134 DateTimeFormatInfo.SortableDateTimePattern 1134 DateTimeFormatInfo.TimeSeparator 1135 DateTimeFormatInfo.UniversalSortableDateTimePattern 1136 DateTimeFormatInfo.YearMonthPattern 1136–1137 Delegate.Method 1301 Delegate.Target 1302 DictionaryEntry.Key 1339 DictionaryEntry.Value 1339 Encoding.ASCII 1464 Encoding.BigEndianUnicode 1464 Encoding.BodyName 1465 Encoding.CodePage 1465 Encoding.Default 1466 Encoding.EncodingName 1466 Encoding.HeaderName 1466 Encoding.IsBrowserDisplay 1467 Encoding.IsMailNewsDisplay 1468 Encoding.IsMailNewsSave 1468 Encoding.Unicode 1469 Encoding.UTF7 1469
Encoding.UTF8 1470 Encoding.WindowsCodePage 1470 EnviromentPermissionAttribute.All 1600–1601 EnviromentPermissionAttribute.Read 1601–1602 EnviromentPermissionAttribute.Write 1602 Environment.CommandLine 1552–1553 Environment.CurrentDirectory 1553–1554 Environment.ExitCode 1555 Environment.HasShutdownStarted 1556 Environment.MachineName 1556–1557 Environment.NewLine 1557 Environment.OSVersion 1558 Environment.StackTrace 1558–1559 Environment.SystemDirectory 1559 Environment.TickCount 1560–1561 Environment.UserDomainName 1561 Environment.UserInteractive 1562 Environment.UserName 1563 Environment.Version 1563–1564 Environment.WorkingSet 1564 Exception.HelpLink 1619 Exception.HResult 1619–1620 Exception.InnerException 1620–1621 Exception.Message 1621–1623 Exception.Source 1623 Exception.StackTrace 1623–1624 Exception.TargetSite 1625 FileIOPermissionAttribute.AllProperty 1730–1731 FileIOPermissionAttribute.Append 1731–1732 FileIOPermissionAttribute.PathDiscovery 1732–1733 FileIOPermissionAttribute.Read 1734–1735 FileIOPermissionAttribute.Write 1735–1736 FileLoadException.FileName 1743–1744 FileLoadException.FusionLog 1744 FileLoadException.Message 1745 FileNotFoundException.FileName 1758 FileNotFoundException.FusionLog 1759 FileNotFoundException.Message 1759–1760 FileStream.CanRead 1792–1794 FileStream.CanSeek 1794–1795 FileStream.CanWrite 1795–1797 FileStream.Handle 1797–1798 FileStream.IsAsync 1798–1799 FileStream.Length 1799–1800 FileStream.Name 1801 FileStream.Position 1801–1803 GC.MaxGeneration 1841–1842 Hashtable.Comparer 1871
3804
Contents | Index
Properties
Hashtable.Count 1872 Hashtable.hcp 1873 Hashtable.IsFixedSize 1873–1874 Hashtable.IsReadOnly 1874–1875 Hashtable.IsSynchronized 1875–1876 Hashtable.Item 1877–1878 Hashtable.Keys 1878–1879 Hashtable.SyncRoot 1880–1881 Hashtable.Values 1881–1882 IAsyncResult.IsCompleted 1909–1910 ICollection.CopyTo 1920–1921 ICollection.Count 1917 ICollection.IsSynchronized 1918 ICollection.SynchRoot 1919 IEnumerator.Current 1958–1960 IList.IsFixedSize 1987–1989 IList.IsReadOnly 1989–1991 IList.Item 1991–1992 MemoryStream.CanRead 2250–2251 MemoryStream.CanSeek 2251–2253 MemoryStream.CanWrite 2253–2254 MemoryStream.Capacity 2254–2256 MemoryStream.Length 2257–2258 MemoryStream.Position 2258–2260 NotFiniteNumberException.OffendingNumber 2318 NumberFormatInfo.CurrencyDecimalDigits 2338–2339 NumberFormatInfo.CurrencyDecimalSeparator 2339–2340 NumberFormatInfo.CurrencyGroupSeparator 2340–2341 NumberFormatInfo.CurrencyGroupSizes 2342–2343 NumberFormatInfo.CurrencyNegativePattern 2343–2345 NumberFormatInfo.CurrencyPositivePattern 2346–2347 NumberFormatInfo.CurrencySymbol 2348–2349 NumberFormatInfo.CurrentInfo 2349–2351 NumberFormatInfo.InvariantInfo 2351–2355 NumberFormatInfo.IsReadOnly 2356–2357 NumberFormatInfo.NaNSymbol 2357–2358 NumberFormatInfo.NegativeInfinitySymbol 2358–2359 NumberFormatInfo.NegativeSign 2360–2361 NumberFormatInfo.NumberDecimalDigits 2361–2362 NumberFormatInfo.NumberDecimalSeparator 2362–2363
■
Properties
NumberFormatInfo.NumberGroupSeparator 2364–2365 NumberFormatInfo.NumberGroupSizes 2365–2367 NumberFormatInfo.NumberNegativePattern 2367–2368 NumberFormatInfo.PercentDecimalDigits 2369–2370 NumberFormatInfo.PercentDecimalSeparator 2370–2371 NumberFormatInfo.PercentGroupSeparator 2371–2372 NumberFormatInfo.PercentGroupSizes 2373–2374 NumberFormatInfo.PercentNegativePattern 2374–2376 NumberFormatInfo.PercentPositivePattern 2376–2378 NumberFormatInfo.PercentSymbol 2378–2379 NumberFormatInfo.PerMilleSymbol 2380–2381 NumberFormatInfo.PositiveInfinitySymbol 2381–2382 NumberFormatInfo.PositiveSign 2382–2383 ObjectDisposedException.Message 2427–2428 ObjectDisposedException.ObjectName 2428 ObsoleteAttribute.IsError 2435–2437 ObsoleteAttribute.Message 2437–2438 PermissionSet.Count 2489–2490 PermissionSet.IsReadOnly 2490 PermissionSet.IsSynchronized 2490–2491 PermissionSet.SynchRoot 2491 SecurityAttribute.Action 2585 SecurityAttribute.Unrestricted 2585 SecurityElement.Attributes 2589 SecurityElement.Children 2589 SecurityElement.Tag 2590 SecurityElement.Text 2591 SecurityPermission.Flags 2617 SecurityPermissionAttribute.ControlAppDomain 2631 SecurityPermissionAttribute.ControlDomainPolicy 2631 SecurityPermissionAttribute.ControlEvidence 2632 SecurityPermissionAttribute.ControlPrincipal 2633 SecurityPermissionAttribute.ControlThread 2633 SecurityPermissionAttribute.Execution 2633–2634 SecurityPermissionAttribute.Flags 2634 SecurityPermissionAttribute.Infrastructure 2634
3805
Contents | Index
Properties
■
Properties
SecurityPermissionAttribute.RemotingConfiguration 2635 SecurityPermissionAttribute.SerializationFormatter 2635 SecurityPermissionAttribute.SkipVerification 2635 SecurityPermissionAttribute.UnmanagedCode 2636 Stream.CanRead 2700 Stream.CanSeek 2701 Stream.CanWrite 2703 Stream.Length 2705 Stream.Position 2706 StreamReader.BaseStream 2758 StreamReader.CurrentEncoding 2760 StreamWriter.AutoFlush 2792 StreamWriter.BaseStream 2794 StreamWriter.Encoding 2795 String.Chars 2827–2828 String.Length 2828–2829 StringBuilder.Capacity 2965–2967 StringBuilder.Chars 2967–2968 StringBuilder.Length 2968–2970 StringBuilder.MaxCapacity 2970 StringWriter.Encoding 3060 SystemException.GrantedSet 2606–2607 SystemException.PermissionState 2607–2608 SystemException.PermissionType 2608 SystemException.RefusedSet 2608–2609 SystemPermissionAttribute.Assertion 2631 TextWriter.Encoding 3093 TextWriter.FormatProvider 3093–3094 TextWriter.NewLine 3094 Thread.ApartmentState 3133–3134 Thread.CurrentContext 3134 Thread.CurrentPrincipal 3135 Thread.CurrentThread 3135–3136 Thread.IsAlive 3136–3137 Thread.IsBackground 3138–3139 Thread.IsThreadPoolThread 3139 Thread.Name 3139–3141 Thread.Priority 3141–3142 Thread.ThreadState 3143–3144 ThreadAbortException.ExceptionState 3193–3194 TimeSpan.Days 3254–3255 TimeSpan.Hours 3255–3256 TimeSpan.Milliseconds 3256–3257 TimeSpan.Minutes 3257–3258 TimeSpan.Seconds 3258 TimeSpan.Ticks 3259 TimeSpan.TotalDays 3260–3262
TimeSpan.TotalHours 3262–3263 TimeSpan.TotalMilliseconds 3263–3264 TimeSpan.TotalMinutes 3264–3265 TimeSpan.TotalSeconds 3266–3267 Type.Assembly 3319–3320 Type.AssemblyQualifiedName 3320–3322 Type.Attributes 3322–3324 Type.BaseType 3324–3325 Type.DeclaringType 3325–3326 Type.DefaultBinder 3326–3328 Type.FullName 3328–3329 Type.GUID 3330 Type.HasElementType 3330–3331 Type.IsAbstract 3331–3332 Type.IsAnsiClass 3333 Type.IsArray 3333–3334 Type.IsAutoClass 3334–3335 Type.IsAutoLayout 3335–3336 Type.IsByRef 3336–3337 Type.IsClass 3337–3338 Type.IsCOMObject 3339 Type.IsContextful 3339 Type.IsEnum 3340–3341 Type.IsExplicitLayout 3341–3342 Type.IsImport 3342–3343 Type.IsInterface 3343–3344 Type.IsLayoutSequential 3344–3346 Type.IsMarshalByRef 3346–3347 Type.IsNestedAssembly 3347–3348 Type.IsNestedFamANDAssem 3349–3350 Type.IsNestedFamily 3350–3351 Type.IsNestedFamOrAssem 3352–3353 Type.IsNestedPrivate 3353–3354 Type.IsNestedPublic 3355–3356 Type.IsNotPublic 3356–3357 Type.IsPointer 3358–3359 Type.IsPrimitive 3359–3360 Type.IsPublic 3360–3361 Type.IsSealed 3361–3362 Type.IsSerializable 3363 Type.IsSpecialName 3363–3364 Type.IsUnicodeClass 3364–3365 Type.IsValueType 3365–3366 Type.MemberType 3366 Type.Module 3366–3367 Type.Namespace 3368–3369 Type.ReflectedType 3369–3370 Type.TypeHandle 3370–3371 Type.TypeInitializer 3371–3372
3806
Contents | Index
Provider parameter
Type.UnderlyingSystemType 3373–3374 TypeInitializationException.GetObjectData 3530 TypeInitializationException.TypeName 3529 Version.Build 3717–3718 Version.Major 3718–3719 Version.Minor 3719–3720 Version.Revision 3720–3721 WaitHandle.Handle 3743 Provider parameter 393, 418 Pseudo-random numbers 2519–2521 Random() constructor 2521–2523 Random.Next() method 2524–2528 Random.NextBytes() method 2528–2529 Random.NextDouble() method 2529–2530 Random.Sample() method 2531 Punctuation marks System.String 457 Unicode characters 456
R Random numbers 2519–2521 Random() constructor 2521–2523 Random.Next() method 2524–2528 Random.NextBytes() method 2528–2529 Random.NextDouble() method 2529–2530 Random.Sample() method 2531 Ranges adding 211–212 ArgumentOutOfRange class 53–54 Array.Clear() method 91–92 Array.IndexOf() method 138–143 ArrayList.GetRange() method 240–241 arrays, decoding 1293 ASCIIEncoding GetByteCount() method 290–293 GetBytes() method 293–297 GetCharCount() method 297–299 GetChars() method 299–302 characters, encoding 1455 elements copying 228 inserting 248–250 objects, sorting 165–181 removing 261–263 RankException() constructor 2533–2535 Ranks of arrays 71 of current instances 76–77 Read field 1725–1726
■
Returning
Reading characters 540–542 end of streams 1497 strings. See StringReader class Read-only access, System.CharEnumerator 487–489 Read-only wrappers, returning 255–257 Reference lists 234 Registration, IANA 1470 Removing current frames 508 current instances 258–259 elements 259–261 ranges 261–263 Replacing names 1566 Repositioning current instances 491 Representations System.Object 430 text writing 564 writing to objects 577 XML 510 Resources, cleanup 1950 Retrieving attributes 338 day of the week 1012 hours 1014 milliseconds components 1014 minute components 1015 month components 1016 second components 1018 year components 1021 Returning bytes ASCIIEncoding.GetMaxByte() method 302–303 ASCIIEncoding.GetMaxCharCount() method 303–305 ASCIIEncoding.GetString() method 305–308 delegates 1315 error streams 535 existing files 1650 indexes 241 numeric values 434 read-only wrappers 255–257 sort orders of current instances 386–387 specified strings 898 System.Object 600 wrappers 275 XML 510, 1719
3807
Contents | Index
Reverses
■
Security
Reverses elements 150–152 sequences 264 RFC 1123 1131 Runtime ArgumentException() constructor 43 ArgumentNullException() constructor 51–52 ArgumentOutOfRangeException.GetObjectBack() method 60 ArithmeticException() constructor 64 ArrayTypeMismatchException 287
S Saving browsers 1467 mail/news clients 1468 SByte CompareTo() method 2541–2542 Equals() method 2542–2543 GetTypeCode() method 2544–2548 HashCode() method 2543–2544 MaxValue field 2539–2540 MinValue field 2540 Parse() method 2545–2554 ToString() method 2554–2562 Scheduling System.Threading.ThreadPriority.Enum 3195 Searching ancestors 367 ArrayList.BinarySearch() method 212–222 arrays 65–72 binary 81–91 current instances 250–255 files 1367 instances 241 subdirectories 1356 System.Int32 88 troubleshooting 148 Seconds number of, adding 1031 retrieving 1018 Security actions 1597 CodeAccessPermission 496–499 Assert() method 499–500 constructor 499 Copy() method 501 Demand() method 501–502 Deny() method 503
FromXml() method 504 Intersect() method 504–505 IsSubsetOf() method 505–506 PermitOnly() method 506–507 RevertAll() method 508 RevertAssert() method 508–509 RevertPermitOnly() method 510 ToString() method 510 ToXml() method 510–511 Union() method 511–512 CodeAccessSecurityAttribute() constructor 515 environment variables 1574 FileIOPermissionAccess.Enum 1723–1724 fields 1724, 1724–1725, 1725–1726 files 1696 namespaces 21–24 SecurityAttribute 2583–2584 Action property 2585 constructor 2584 CreatePermission() method 2586 Unrestricted property 2585 System.Security.Permissions.FileIOPermissions 1696–1700 FileIOPermission constructor 1700–1705 FileIOPermission.AddPathList() method 1706–1707 FileIOPermission.Copy() method 1708–1709 FileIOPermission.FomXml() method 1709–1710 FileIOPermission.GetPathList() method 1711–1712 FileIOPermission.Intersection() method 1712–1714 FileIOPermission.IsSubsetOf() method 1714–1716 FileIOPermission.IsUnrestricted() method 1716–1717 FileIOPermission.SetPathList() method 1717–1719 FileIOPermission.ToXml() method 1719–1720 FileIOPermission.Union() method 1721–1722 System.Security.SecurityElement 2587–2588 AddAttribute() method 2591 AddChild() method 2592 Attribute() method 2593–2594 Attributes property 2589 Children property 2589 Equal() method 2594 Escape() method 2595 IsvalidAttributeName() method 2596
3808
Contents | Index
SecurityAction.Enum
IsvalidAttributeTag() method 2597 IsvalidAttributeText() method 2597–2599 IsvalidAttributeValue() method 2596–2598 SearchForTextOfTag() method 2598–2599 Tag property 2590 Text property 2591 ToString() method 2599–2601 SecurityAction.Enum 2568–2569 Assert field 2569–2571 Demand field 2571–2577 Deny field 2572–2574 InheritanceDemand field 2574–2576 LinkDemand field 2576–2580 PermitOnly field 2577–2579 RequestMinimum field 2579–2581 RequestOptional field 2580–2582 RequestRefuse field 2581 SecurityException 2600–2601 constructor 2602–2606 GetObjectData() method 2609–2610 GrantedSet property 2606–2607 PermissionState property 2607–2608 PermissionType property 2608 RefusedSet property 2608–2609 ToString() method 2610 SecurityPermission 2611–2613 constructor 2613–2617 Copy() method 2618–2619 Flags property 2617 FromXml() method 2619–2620 Intersect() method 2621–2622 IsSubsetOf() method 2622–2624 IsUnrestricted() method 2624 ToXml() method 2625 Union() method 2626–2627 SecurityPermissionAttribute 2628–2630 Assertion property 2631 constructor 2630 ControlAppDomain property 2631 ControlDomainPolicy property 2631–2632 ControlPolicy property 2632 ControlPrincipal property 2633 ControlThread property 2633 CreatePermission() method 2636–2637 Execution property 2633–2634 Flags property 2634 Infrastructure property 2634 RemotingConfiguration property 2635 SerializationFormatter property 2635
■
Signed integers
SkipVerification property 2635 UnmanagedCode property 2636 SecurityPermissionFlag AllFlags field 2639–2640 Assertion field 2640 BindingRedirects field 2640 ControlAppDomain field 2640 ControlEvidence field 2641 ControlPolicy field 2641 ControlPolicyDomain field 2641 ControlPrincipal field 2642 ControlThread field 2642 Execution field 2642 Infrastructure field 2643 NoFlags field 2643 RemotingConfiguration field 2643 SerializationFormatter field 2643 SkipVerification field 2644 UnmanagedCode field 2644 Seeking references 2645–2646 SeekOrigin Begin field 2646 Current field 2646 End field 2647 Separator characters 460 Unicode 459 Sequences of elements 150–152 reversing 264 Sequential threads. See System.Threading.Thread class Serialization ArgumentException() constructor 43 ArgumentException.GetObjectData method() 46 ArgumentNullException() constructor 51–52 ArgumentOutOfRangeException.GetObjectBack() method 60 ArithmeticException() constructor 64 ArrayTypeMismatchException 287 Services, formatting 1964–1965 SetValue() Method 161, 162 Shape of methods, defining 1608 Sharing files 1762–1763 Short date values 1132 Short time System.String representation, converting 1082 Shut down values 1556 Signed integers, System.SByte.Structure 2537–2539 CompareTo() method 2541–2542
3809
Contents | Index
Single
■
StreamWriter
Equals() method 2542–2543 GetTypeCode() method 2544–2548 HashCode() method 2543–2544 MaxValue field 2539–2540 MinValue field 2540 Parse() method 2545–2554 ToString() method 2554–2562 Single CompareTo() method 2658–2659 Epsilon field 2651–2652 Equals() method 2660–2661 GetHashCode() method 2661–2662 GetTypeCode() method 2662 IsInfinity() method 2662–2664 IsNaN() method 2664–2665 IsNegativeInfinity() method 2665–2666 IsPositiveInfinity() method 2667–2668 MaxValue field 2652–2653 MinValue field 2653–2654 NaN field 2654–2655 NegativeInfinity field 2656–2657 Parse() method 2668–2678 PositiveInfinity field 2657–2658 ToString() method 2678–2684 Single-precision floating-point number 2648 Sorting arrays 65–72, 82 collections 1927–1928 dates and time 1134 elements 271–275 objects 165–181 orders 386–387 System.DateTime structure 1035 Unicode characters 428 sourceArray parameter 95, 97, 100 Specified search criteria, searching 1367 Specified strings, returning 898 StackOverflowException 2690–2691 constructor 2691–2693 Stacks call, state of 1558 permissions 507 Standard error streams, returning 536 Standard input streams, returning 536, 537 Standard output streams, returning 538, 539 startIndex 142 State of call stacks 1558 Static methods, delegates 1327 Storing elements 199
Streaming context ArgumentException() constructor 43 ArgumentNullException() constructor 51–52 ArgumentOutOfRangeException.GetObjectBack() method 60 ArithmeticException() constructor 64 ArrayTypeMismatchException 287 StreamReader 2735–2737 BaseStream property 2758 Close() method 2761–2762 constructor 2738–2758 CurrentEncoding property 2760 DiscardBufferedData() method 2762–2764 Dispose() method 2764–2766 Null field 2758 Peek() method 2765 Read() method 2766–2770 ReadLine() method 2770–2772 ReadToEnd() method 2772–2773 Streams 2694–2699 See also System.IO.MemoryStream BeginRead() method 2708–2711 BeginWrite() method 2711–2714 CanRead property 2700 CanSeek property 2701 CanWrite property 2703 Close() method 2714–2715 constructor 2699 CreateWaitHandle() method 2715 EndRead() method 2716–2718 EndWrite() method 2718–2720 Flush() method 2720–2722 Length property 2705 Null field 2700 Position property 2706 Read() method 2722–2726 Seek() method 2726–2728 SetLength() method 2728–2730 Write() method 2730–2732 WriteByte() method 2732–2733 Streams, reading 1497 StreamWriter 2774–2776 AutoFlush property 2792 BaseStream property 2794 Close() method 2796–2798 constructor 2776–2792 Dispose() method 2798 Encoding property 2795 Finalize() method 2799
3810
Contents | Index
StringBuilder
Flush() method 2799–2800 Null field 2792 Write() method 2800–2806 StringBuilder 2955–2959 Append() method 2970–2994 AppendFormat() method 2994–3002 Capacity property 2965–2967 Chars property 2967–2968 Constructor 2959–2965 EnsureCapacity() method 3002–3004 Equals() method 3004–3005 Insert() method 3005–3032 Length property 2968–2970 MaxCapacity property 2970 Remove() method 3032–3033 Replace() method 3034–3039 ToString() method 3039–3041 StringReader 3042–3043 Close() method 3044–3045 constructor 3043–3044 Dispose() method 3046 Peek() method 3046–3048 Read() method 3048–3051 ReadLine() method 3051–3052 ReadToEnd() method 3052–3053 Strings Byte.ToString() method 415–422 ConditionalAttribute.ConditionString property 526 Convert.ToBase64String() method 610 customizing 1968–1976 enumerating 1539 false values 384–385 formatting 584 names 1566 newline 1557 representations 478 System.String 2807–2815 Chars property 2827–2828 Clone() method 2829–2830 Compare() method 2830–2843 CompareOrdinal() method 2843–2847 CompareTo() method 2847–2850 Concat() method 2850–2859 constructor 2815–2826 Copy() method 2860–2861 CopyTo() method 2861–2863 Empty field 2826–2827 EndsWith() method 2863–2864
■
Subsets
Equals() method 2865–2868 Format() method 2868–2877 GetEnumerator() method 2877–2878 GetHashCode() method 2878–2879 GetTypeCode() method 2879 IndexOf() method 2879–2890 IndexOfAny() method 2890–2895 Insert() method 2895–2896 Intern() method 2896–2898 IsInterned() method 2898–2899 Join() method 2900–2902 LastIndexOf() method 2902–2913 LastIndexOfAny() method 2913–2918 Length property 2828–2829 op_Equality() method 2918–2920 op_Inequality() method 2920–2921 PadLeft() method 2921–2924 PadRight() method 2924–2926 Remove() method 2926–2928 Replace() method 2928–2930 Split() method 2930–2933 StartsWith() method 2933–2935 Substring() method 2935–2938 ToCharArray() method 2938–2940 ToLower() method 2940–2942 ToString() method 2942–2943 ToUpper() method 2943–2945 Trim() method 2945–2947 TrimEnd() method 2947–2948 TrimStart() method 2948–2949 true values 385–386 values 393–394 StringWriter 3054–3055 Close() method 3061–3062 constructor 3055–3060 Dispose() method 3062 Encoding property 3060 GetStringBuilder() method 3063 ToString() method 3064 Write() method 3065–3068 Structure, System.Char Structure 423–426 Subarrays See also Arrays characters 568 Subdirectories 1356 creating 1342 Subsets arrays 604 objects 505, 1714
3811
Contents | Index
Subtraction
■
System.Byte
targets 1715 values 608 Subtraction 1075 Surrogate characters 462, 463 Symbols System.String 466 Unicode characters 465 Synchronization 206–207 access 206–207 output streams 534 SynchronizationLockException() constructor 3070 Synchronous read and write operations 1766–1771 System directory, path to 1559 System namespace 3–4 System.ApplicationException class 33–37 System.ArithmeticException class 61–64 System.Array class 65–72 Array() constructor 73 Array.BinarySerach() method 81–91 Array.Clear() method 91–92 Array.Clone() method 93–94 Array.Copy() method 94–104 Array.CopyTo() method 104–107 Array.CreateInstance() method 108–120 Array.GetEnumerator() method 121–123 Array.GetLength() method 123 Array.GetLongLength() method 124 Array.GetLowerBound() method 125–126 Array.GetUpperBound() method 126–127 Array.GetValue() method 128–137 Array.IndexOf() method 138–143 Array.Initialize() method 143–149 Array.IsFixedSize property 73–74 Array.LastIndexOf() method 144–149 Array.Length property 75 Array.LongLength property 76 Array.Rank property 76–77 Array.Reverse() method 150–152 Array.SetValue() method 153–160, 160–164 Array.Sort() method 165–181 Array.SyncRoot property 77 Array.System.Collections.ICollection.Count property 189 Array.System.Collections.IList.Add() method 182 Array.System.Collections.IList.Clear() method 183 Array.System.Collections.IList.Contains() method 184–185 Array.System.Collections.IList.IndexOf() method 185–186
Array.System.Collections.IList.Insert() method 186–187 Array.System.Collections.IList.Item property 190 Array.System.Collections.IList.Remove() method 187–188 Array.System.Collections.IList.RemoveAt() method 188–189 System.ArrayTypeMismatchException. See ArrayTypeMismatchException System.AsyncCallback Delegate 309–310 System.AsyncResult.Interface 1901–1903 IAsyncResult.IsCompleted property 1909–1910 System.Attribute class 311–315 Attribute() constructor 315 Attribute.Equals() method 316 Attribute.GetCustomAttribute() method 317–330 Attribute.GetCustomAttributes() method 330–354 Attribute.GetHashCode() method 354–355 Attribute.IsDefaultAttribute() method 355 Attribute.IsDefined() method 355–367 Attribute.Match() method 367–368 System.AttributeTarget Emun class 369–375 System.AttributeUsageAttribute class 376–381 System.Boolean CLS-compliant current instances 495 converting to System.Boolean 611 converting to System.Byte 631 converting to System.Decimal 693 converting to System.Double 717 converting to System.Int16 739 converting to System.Int32 766 converting to System.Int64 791 converting to System.SByte 816 converting to System.Single 844 converting to System.ToString 867 converting to System.UInt16 910 converting to System.UInt32 937 converting to System.UInt64 964 DateTime.Equals() method 1040 Directory.Exists() method 1347 enumerating 1520 existing files 1650 text representations 547 System.Byte converting to System.Boolean 612 converting to System.Byte 632 converting to System.Char 659 converting to System.Decimal 694 converting to System.Double 718
3812
Contents | Index
System.Byte array
converting to System.Int16 740 converting to System.Int32 767 converting to System.Int64 792 converting to System.SByte 817 converting to System.Single 845 converting to System.String 868, 870 converting to System.UInt16 911 converting to System.UInt32 938 converting to System.UInt64 965 System.Byte array decoding 1485, 1495 encoding 1482 returning enumeration type 1525 System.Char array, encoding 1473, 1477 System.Char structure 423–426 Char.CompareTo() method 428–429 Char.Equals() method 430–431 Char.GetHashCode() method 431–432 Char.GetNumericValue() method 432–435 Char.GetTypeCode() method 435–476 Char.IsControl() method 438–441 Char.IsDigit() method 441–444 Char.IsLetter() method 444–447 Char.IsLetterOrDigit() method 447–450 Char.IsLower() method 450–453 Char.IsNumber() method 453–456 Char.IsPunctuation() method 456–459 Char.IsSeparator() method 459–462 Char.IsSurrogate() method 462–464 Char.IsSymbol() method 465–467 Char.IsUpper() method 467–470 Char.IsWhiteSpace() method 470–473 Char.MaxValue field 426–427 Char.MinValue field 427 Char.Parse() method 473–474 Char.ToLower() method 475–476 Char.ToString() method 477–479 Char.ToUpper() method 479–481 Char.UnicodeCategory() method 435–438 converting to System.Byte 633 converting to System.Char 660 converting to System.Int16 741 converting to System.Int32 768 converting to System.Int64 793 converting to System.SByte 819 converting to System.String 871 converting to System.UInt16 912 converting to System.UInt32 940 converting to System.UInt64 966
■
System.Collections.DictionaryEntry structure
System.CharEnumerator 487–489 CharEnumerator.Clone() method 489–490 CharEnumerator.CurrentProperty() method 489 CharEnumerator.MoveNext() method 491 CharEnumerator.Reset() method 491 System.CLSCompliantAttribute 493–494 constructor 495 System.Collections.ArrayList class 191–195 ArrayList() constructor 195–199 ArrayList.Adapter() method 199–209 ArrayList.Add() method 209–210 ArrayList.AddRange() method 211–212 ArrayList.BinarySearch() method 212–222 ArrayList.Capacity property 199–200 ArrayList.Clear() method 222–224 ArrayList.Clone() method 224–225 ArrayList.Contains() method 225–227 ArrayList.CopyTo() method 228–234 ArrayList.Count property 200–201 ArrayList.FixedSize() method 234–235, 236 ArrayList.GetEnumerator() method 237–239 ArrayList.GetRange() method 240–241 ArrayList.IndexOf() method 241–244 ArrayList.Insert() method 246–248 ArrayList.InsertRange() method 248–250 ArrayList.IsReadOnly property 202–203 ArrayList.IsSynchronized property 203–204 ArrayList.Item property 205–206 ArrayList.LastIndexOf() method 250–255 ArrayList.ReadOnly() method 255–257 ArrayList.Remove() method 258–259 ArrayList.RemoveAt() method 259–261 ArrayList.RemoveRange() method 261–263 ArrayList.Repeat() method 263–264 ArrayList.Reverse() method 264–267 ArrayList.SetRange() method 267–269 ArrayList.Sort() method 271–275 ArrayList.Synchronized() method 275–277 ArrayList.SyncRoot property 206–207 ArrayList.ToArray() method 278–280 ArrayList.TrimToSize() method 281–282 System.Collections.Comparer class 517 Comparer.Compare() method 520–522 Comparer.Default field 519 System.Collections.Comparer, returning 519 System.Collections.DictionaryEntry structure 1337–1339 DictionaryEntry.Key property 1339 DictionaryEntry.Value property 1339
3813
Contents | Index
System.Collections.DictionaryEntry() constructor
■
System.Console.OutSystem.IO.TextWriter
System.Collections.DictionaryEntry() constructor DictionaryEntry() constructor 1338 System.Collections.Hashtable 1851–1855 Add() method 1882–1883 Clear() method 1883–1884 Clone() method 1885–1886 Comparer property 1871 constructor 1855–1871 Contains() method 1886–1887 ContainsKey() method 1887–1888 ContainsValue() method 1889–1890 CopyTo() method 1890–1892 Count property 1872 GetEnumerator() method 1892–1893 GetHash() method 1893–1894 GetObjectData() method 1894 hcp property 1873 IsFixedSize property 1873–1874 IsReadOnly property 1874–1875 IsSynchronized property 1875–1876 Item property 1877–1878 KeyEquals() method 1895–1896 Keys property 1878–1879 OnDeserialization() method 1896 Remove() method 1896–1898 Synchronized() method 1898–1899 SyncRoot property 1880–1881 Values property 1881–1882 System.Collections.ICollection.Interface 1915–1917 CopyTo property 1920–1921 Count property 1917 IsSynchronized property 1918 SyncRoot property 1919 System.Collections.IComparer.Interface 1927–1928 IComparer.Compare() method 1929–1930 System.Collections.IDictionary.Interface 1931–1932 Add() method 1938–1940 Clear() method 1940–1941 Contains() method 1941–1942 GetEnumerators() method 1942–1943 IsFixedSize property 1933–1934 IsReadOnly property 1934–1935 Item property 1935–1936 Keys property 1936–1937 Remove() method 1944–1945 Values property 1937–1938 System.Collections.IDictionaryEnumerator.Interface 1946–1947 Entry property 1947–1948
Key property 1948–1949 Value property 1949 System.Collections.IEnumerable.GetEnumerator 1900 System.Collections.IEnumerable.Interface 1954–1956 GetEnumerator() method 1956 System.Collections.IEnumerator.Interface 492, 1957–1958 Current property 1958–1960 MoveNext() method 1960–1961 Reset() method 1962–1963 System.Collections.IHashCodeProvider.Interface 1978–1980 GetHashCode() method 1980–1981 System.Collections.IList.Interface 1982–1987 Add() method 1993–1994 Clear() method 1994–1995 Contains() method 1996–1997 IndexOf() method 1997–1998 Insert() method 1998–2000 IsFixedSize property 1987–1989 IsReadOnly property 1989–1991 Items property 1991–1992 Remove() method 2000–2002 RemoveAt() method 2002–2003 System.CollectionsIComparer implementation 88 System.Console class 528–531 Console.Error property 532 Console.In property 533 Console.OpenRead() method 540–541 Console.OpenReadLine() method 541–542 Console.OpenStandardError() method 535–536 Console.OpenStandardInput() method 536–538 Console.OpenStandardOutput() method 538–540 Console.Out property 534 Console.SetError() method 542–544 Console.SetIn() method 544–545 Console.SetOut() method 546–547 Console.Write() method 547–563 Console.WriteLine() method 564–566 text representations 555 System.Console.Error property, configuring 542 System.Console.In property, configuring 544 System.Console.Out property, configuring 546 System.Console.OutSystem.IO.TextWriter arrays 549 characters 548 line terminators 565
3814
Contents | Index
System.Console.OutSystem.IO.TextWriter
strings 556 subarrays of characters 550 System.Console.OutSystem.IO.TextWriter, writing formatted strings to 557, 558, 559, 560 System.Convert class 589–599, 606, 937–964 Convert.ToByte() method 631–658 Convert.ToChar() method 658–678 Convert.ToDateTime() method 678–692 Convert.ToDecimal() method 693–716 Convert.ToDouble() method 719–736 Convert.ToString() method 866–910 System.DateTime structure 991–1004, 1653 DateTime() constructor 1004–1008 DateTime.Add property 1022–1023 DateTime.AddDays() method 1023–1024 DateTime.AddHours() method 1025 DateTime.AddMilliseconds() method 1026–1028 DateTime.AddMinutes() method 1028–1029 DateTime.AddMonths() method 1029–1031 DateTime.AddSeconds() method 1031–1032 DateTime.AddTicks() method 1032–1033 DateTime.AddYears() method 1034–1035 DateTime.Compare() method 1035–1036 DateTime.CompareTo() method 1037–1038 DateTime.DayOfWeek property 1012 DateTime.DayOfYear property 1013 DateTime.DaysInMonth() method 1039–1040 DateTime.Equals() method 1040–1042 DateTime.FromFileTime() method 1042 DateTime.FromFileTimeUtc() method 1043 DateTime.FromOADate() method 1044 DateTime.GetDateTimeFormats() method 1045–1047 DateTime.GetHashCode() method 1048 DateTime.GetTypeCode() method 1049 DateTime.Hour property 1014 DateTime.IsLeapYear() method 1049–1050 DateTime.MaxValue field 1009 DateTime.Millisecond property 1014–1016 DateTime.Minute property 1015 DateTime.MinValue field 1010–1012 DateTime.Month property 1016–1017 DateTime.Now property 1017 DateTime.op_Addition() method 1050–1051 DateTime.op_Equality() method 1051–1052 DateTime.op_GreaterThan() method 1053 DateTime.op_GreatherThanOrEqual() method 1054 DateTime.op_Inequality() method 1055–1056 DateTime.op_LessThan() method 1056–1057
■
System.DateTime structure
DateTime.op_LessThanOrEqual() method 1057–1058 DateTime.op_Subtraction() method 1059–1061 DateTime.Parse() method 1061–1067 DateTime.ParseExact() method 1067–1074 DateTime.Second property 1018 DateTime.Subtract() method 1074–1076 DateTime.Ticks property 1018 DateTime.TimeOfDay property 1019 DateTime.Today property 1020 DateTime.ToFileTime() method 1076 DateTime.ToFileTimeUtc() method 1077 DateTime.ToLocalTime() method 1077–1078 DateTime.ToLongDateString() method 1078–1079 DateTime.ToLongTimeString() method 1079–1080 DateTime.ToOADate() method 1080–1081 DateTime.ToShortDateString() method 1081–1082 DateTime.ToShortTimeString() method 1082–1083 DateTime.ToString() method 1083–1090 DateTime.ToUniversalTime() method 1090–1091 DateTime.UtcNow property 1021 DateTime.Year property 1021–1022 DateTimeFormatInfo class 1098–1106 DateTimeFormatInfo() constructor 1107 DateTimeFormatInfo.AbbreviatedDayNames property 1108 DateTimeFormatInfo.AbbreviatedMonthNames property 1110 DateTimeFormatInfo.AMDesignator property 1112–1113 DateTimeFormatInfo.Calendar property 1114–1115 DateTimeFormatInfo.CalendarWeekRule property 1115 DateTimeFormatInfo.Clone() method 1138 DateTimeFormatInfo.CurrentInfo property 1116–1117 DateTimeFormatInfo.DateSeparator property 1117 DateTimeFormatInfo.DayNames property 1118 DateTimeFormatInfo.FirstDayOfWeek property 1120 DateTimeFormatInfo.FullDateTimePattern property 1121–1122 DateTimeFormatInfo.GetAbbreviatedDayName() method 1139–1140 DateTimeFormatInfo.GetAbbreviatedMonthName() method 1141–1143 DateTimeFormatInfo.GetAllDateTimePatterns() method 1143–1144 DateTimeFormatInfo.GetDayName() method 1144–1145
3815
Contents | Index
System.DateTime to System.DateTime
■
System.Decimal.Structure
DateTimeFormatInfo.GetEra() method 1145–1146 DateTimeFormatInfo.GetEraName() method 1146–1148 DateTimeFormatInfo.GetFormat() method 1148–1149 DateTimeFormatInfo.GetInstance() method 1149–1150 DateTimeFormatInfo.GetMonthName() method 1150–1152 DateTimeFormatInfo.InvariantInfo property 1122–1123 DateTimeFormatInfo.IsReadOnly property 1123–1124 DateTimeFormatInfo.LongDatePattern property 1124–1125 DateTimeFormatInfo.LongTimePattern property 1125–1126 DateTimeFormatInfo.MonthDayPattern property 1127 DateTimeFormatInfo.MonthNames property 1128–1129 DateTimeFormatInfo.PMDesignator property 1130–1131 DateTimeFormatInfo.ReadOnly() method 1152 DateTimeFormatInfo.RFC1123Pattern property 1131 DateTimeFormatInfo.ShortDateTimePattern property 1132–1133 DateTimeFormatInfo.ShortTimePattern property 1133–1134 DateTimeFormatInfo.SortableDateTimePattern property 1134 DateTimeFormatInfo.TimeSeparator property 1135 DateTimeFormatInfo.UniversalSortableDateTimePattern property 1136 DateTimeFormatInfo.YearMonthPattern property 1136–1137 MinValue field 1653 System.DateTime to System.DateTime, converting 690 System.DateTime value to System.String, converting 900, 901 System.Decimal.Structure 1162–1167 Add() method 1183–1184 Compare() method 1185–1186 CompareTo() method 1186–1188 constructor 1168–1178 converting to System.Boolean 614 converting to System.Byte 635 converting to System.Decimal 696 converting to System.Double 719
converting to System.Int16 743 converting to System.Int32 769 converting to System.Int64 794 converting to System.SByte 821 converting to System.Single 847 converting to System.String 873, 875 converting to System.UInt16 914 converting to System.UInt32 941 converting to System.UInt64 968 Divide() method 1188–1189 Equals() method 1190–1192 Floor() method 1192–1193 FromOACurrency() method 1193–1194 GetBits() method 1194–1196 GetHashCode() method 1197–1198 GetTypeCode() method 1198 MaxValue field 1178–1179 MinusOne field 1179–1180 MinValue field 1180–1181 Multiply() method 1198–1200 Negate() method 1200–1201 One field 1181–1182 op_Addition() method 1201–1203 op_Decrement() method 1203–1204 op_Division() method 1205–1206 op_Equality() method 1206–1208 op_Explicit() method 1208–1227 op_GreaterThan() method 1227–1228 op_GreaterThanOrEqual() method 1229–1230 op_Implicit() method 1230–1239 op_Increment() method 1239–1241 op_Inequality() method 1241–1242 op_LessThan() method 1242–1243 op_LessThanOrEqual() method 1244–1245 op_Modulus() method 1245–1246 op_Multiply() method 1247–1248 op_Subtraction() method 1248–1250 op_UnaryNegotiation() method 1250–1251 op_UnaryPlus() method 1251–1253 Parse() method 1253–1263 Remainder() method 1263–1265 Round() method 1265–1266 Subtract() method 1267–1268 text representations 551, 570 ToByte() method 1268–1269 ToDouble() method 1269 ToInt16() method 1270 ToInt32() method 1271 ToInt64() method 1272
3816
Contents | Index
System.Delegate
ToOACurrency() method 1272 ToSByte() method 1273 ToSingle() method 1274 ToString() method 1274–1281 ToUInt16() method 1281 ToUInt32() method 1282 ToUInt64() method 1283 Truncate() method 1284–1285 Zero field 1182–1183 System.Delegate 1295, 1298 System.Diagnostics.ConditionalAttribute class 523–525 ConditionalAttribute() constructor 525–526 ConditionalAttribute.ConditionString property 526–527 System.DivideByZeroException 1399–1402 System.Double.Structure 1403–1407 CompareTo() method 1414–1415 converting to System.Boolean 615 converting to System.Byte 637 converting to System.Decimal 697 converting to System.Double 721 converting to System.Int16 744 converting to System.Int32 771 converting to System.Int64 796 converting to System.SByte 822 converting to System.Single 848 converting to System.String 876, 878 converting to System.UInt16 915 converting to System.UInt32 942 converting to System.UInt64 969 Epsilon field 1407 Equals() method 1416–1417 GetHashCode() method 1417–1418 GetTypeCode() method 1418 IsInfinity() method 1418–1419 IsNaN() method 1420–1421 IsNegativeInfinity() method 1421–1422 IsPositiveInfinity() method 1422–1424 MaxValue field 1408 MinValue field 1409 NaN field 1410–1411 NegativeInfinity field 1412 Parse() method 1424–1434 PositiveInfinity field 1413 text representations 552, 571 ToString() method 1434–1440 TryParse() method 1441–1442 System.DuplicateWaitObjectException 1448–1449
■
System.Exception class
System.Enum class 1502–1506 Enum.CompareTo() method 1507–1508 Enum.Equals() method 1509–1510 Enum.Format() method 1510–1512 Enum.GetHashCode() method 1512–1513 Enum.GetName() method 1513–1516 Enum.GetTypeCode() method 1516–1517 Enum.GetUnderlyingType() method 1517–1518 Enum.GetValues() method 1518–1519 Enum.IsDefined() method 1519–1521 Enum.Parse() method 1521–1524 Enum.ToObject() method 1525–1538 Enum.ToString() method 1539–1544 System.Environment class 1550–1552 Environment.CommandLine property 1552–1553 Environment.CurrentDirectory property 1553–1554 Environment.Exit() method 1564–1566 Environment.ExitCode property 1555 Environment.ExpandEnvironmentVariables() method 1566–1567 Environment.GetCommandLineArgs() method 1567–1568 Environment.GetEnvironmentVariable() method 1568–1570 Environment.GetEnvironmentVariables() method 1570–1572 Environment.GetFolderPath() method 1572 Environment.GetLogicalDrives() method 1573 Environment.HasShutDownStarted property 1556 Environment.MachineName property 1556–1557 Environment.NewLine property 1557 Environment.OSVersion property 1558 Environment.StackTrace property 1558–1559 Environment.SystemDirectory property 1559 Environment.TickCount property 1560–1561 Environment.UserDomainName property 1561 Environment.UserInteractive property 1562 Environment.UserName property 1563 Environment.Version property 1563–1564 Environment.WorkingSet property 1564 System.EventArgs class 1604–1606 EventArgs() constructor 1606 EventArgs.Empty field 1606–1607 System.EventHandler.Delegate class 1608–1609 System.Exception class 1611–1615 Exception() constructor 1615–1619 Exception.GetBaseException() method 1625–1626 Exception.GetObjectData() method 1627
3817
Contents | Index
System.ExecutionEngineException class
■
System.IConvertible
Exception.HelpLink property 1619 Exception.HResult property 1619–1620 Exception.InnerException property 1620–1621 Exception.Message property 1621–1623 Exception.Source property 1623 Exception.StackTrace property 1623–1624 Exception.TargetSite property 1625 Exception.ToString() method 1628 System.ExecutionEngineException class 1629–1632 System.FlagsAttribute 1831–1832 constructor 1833 System.FormatException 1834–1835 constructor 1835–1837 System.GC 1839–1841 GC.Collect() method 1842–1843 GC.GetGeneration() method 1843–1844 GC.GetTotalMemory() method 1845 GC.KeepAlive() method 1845 GC.MaxGeneration property 1841–1842 GC.ReRegisterForFinalize() method 1846–1848 GC.SuppressFinalize() method 1848–1849 GC.WaitForPendingFinalizers() method 1849–1850 System.Globalization 2337, 2384 DateTimeFormatInfo class, constructing 1107 DateTimeStyles 1154 DateTimeStyles.AdjustToUniversal field 1155–1156 DateTimeStyles.AllowInnerWhite field 1156 DateTimeStyles.AllowLeadingWhite field 1157 DateTimeStyles.AllowTrailingWhite field 1158 DateTimeStyles.AllowWhiteSpaces field 1158 DateTimeStyles.NoCurrentDateDefault field 1159–1160 DateTimeStyles.None field 1160 namespace 1003 System.Globalization.NumberStyles.Enum 2388–2391 AllowCurrencySymbol field 2391 AllowDecimalPoint field 2391–2392 AllowExponent field 2392 AllowHexSpecifier field 2392 AllowLeadingSign field 2393 AllowLeadingWhite field 2393 AllowParentheses field 2393 AllowThousands field 2394 AllowTrailingSign field 2394 AllowTrailingWhite field 2394 Any field 2395 Currency field 2395 Float field 2396
HexNumber field 2396 Integer field 2396 None field 2397 Number field 2397 System.Globalization.UnicodeCategory 436, 437 System.Globalization.UnicodeCategory.Enum 3629–3630 ClosePunctuation field 3631 ConnectorPunctuation field 3631 Control field 3631 CurrencySymbol field 3631 DashPunctuation field 3632 DecimalDigitNumber field 3632 EnclosingMark field 3632 FinalQuotePunctuation field 3633 Format field 3633 InitialQuotePunctuation field 3633 LetterNumber field 3633 LineSeparator field 3634 LowercaseLetter field 3634 MathSymbol field 3634 ModifierLetter field 3635 ModifierSymbol field 3635 NonSpacingMark field 3635 OpenPunctuation field 3635 OtherLetter field 3636 OtherNotAssigned field 3636 OtherNumber field 3636 OtherPunctuation field 3637 OtherSymbol field 3637 ParagraphSeparator field 3637 PrivateUse field 3637 SpaceSeparator field 3638 SpacingCombiningMark field 3638 Surrogate field 3638 TitlecaseLetter field 3639 UppercaseLetter field 3639 System.ICloneable.Interface 1911–1913 Clone() method 1913–1914 System.IComparable.Interface 1923–1925 CompareTo() method 1925–1926 System.IConvertible ToBoolean 1442, 2562 ToByte 1442, 2562 ToChar 1443, 2563 ToDateTime 1443, 2563 ToDecimal 1443, 2563 ToDouble 1444, 2564 ToInt16 1444, 2564
3818
Contents | Index
System.IDisposable.Interface
ToInt32 1444, 2564 ToInt64 1445, 2565 ToSByte 1445, 2565 ToSingle 1445, 2565 ToType 1446, 2566 ToUInt16 1446 ToUInt32 1446, 2566 ToUInt64 1447, 2567 System.IDisposable.Interface 1950–1952 Dispose() method 1953 System.IFormatProvider.Interface 1964–1965 GetFormat() method 1965–1966 System.IFormattable.Interface 1968–1976 ToString() method 1976–1977 System.IndexOutOfRangeException 2004–2005 constructor 2005–2007 System.Int16.Structure 2008–2010 converting to System.Boolean 623 converting to System.Byte 646 converting to System.Char 669 converting to System.Decimal 707 converting to System.Double 729 converting to System.Int16 754 converting to System.Int32 780 converting to System.Int64 805 converting to System.SByte 832 converting to System.Single 857 converting to System.String 894, 896 converting to System.UInt16 925 converting to System.UInt32 952 converting to System.UInt64 979 Int16.CompareTo() method 2012–2013 Int16.Equals() method 2013–2014 Int16.GetHashCode() method 2015 Int16.GetTypeCode() method 2016 Int16.MaxValue field 2010 Int16.MinValue field 2011 Int16.Parse() method 2016–2025 Int16.ToString() method 2025–2033 System.Int32.Structure 2038–2041 arguments 71 converting to System.Boolean 618 converting to System.Byte 640 converting to System.Char 663 converting to System.Decimal 701 converting to System.Double 724 converting to System.Int16 748 converting to System.Int32 774 converting to System.Int64 800
■
System.IO File
converting to System.SByte 826 converting to System.Single 852 converting to System.String 883, 885 converting to System.UInt16 919 converting to System.UInt32 946 converting to System.UInt64 973 Int32.Compare() method 2043–2044 Int32.Equals() method 2044–2045 Int32.GetHashCode() method 2046 Int32.GetTypeCode() method 2047 Int32.MaxValue field 2041–2042 Int32.MinValue field 2042 Int32.Parse() method 2047–2056 Int32.ToString() method 2056–2064 searching 88 text representations 553, 574 System.Int64.Structure 2069–2071 converting to System.Boolean 619 converting to System.Byte 642 converting to System.Char 665 converting to System.Decimal 702 converting to System.Double 725 converting to System.Int16 750 converting to System.Int32 776 converting to System.Int64 801 converting to System.SByte 828 converting to System.Single 853 converting to System.String 886, 888 converting to System.UInt16 920 converting to System.UInt32 948 converting to System.UInt64 974 Int64.CompareTo() method 2073–2074 Int64.Equals() method 2074–2076 Int64.GetHashCode() method 2076–2077 Int64.GetTypeCode() method 2077 Int64.MaxValue field 2071 Int64.MinValue field 2072 Int64.Parse() method 2077–2086 Int64.ToString() method 2086–2094 text representations 554, 575 System.InvalidCastException 627, 653, 2116–2117 constructor 2117–2119 System.InvalidOperationException 2120–2121 constructor 2121–2124 System.InvalidProgramException 2125 constructor 2125–2127 System.IO File 1633–1635 File.AppendText() method 1635–1637 File.Copy() method 1637–1642
3819
Contents | Index
System.IO.Directory
■
System.IO.FileStream
File.Create() method 1642–1646 File.CreateText() method 1646–1648 File.Delete() method 1648–1650 File.Exists() method 1650–1651 File.GetAttributes() method 1651–1653 File.GetCreationTime() method 1653–1655 File.GetCreationTimeUtc() method 1655–1656 File.GetLastAccessTime() method 1656–1658 File.GetLastAccessTimeUtc() method 1658–1659 File.GetLastWriteTime() method 1659–1661 File.GetLastWriteTimeUtc() method 1662–1663 File.Move() method 1663–1665 File.Open() method 1665–1673 File.OpenRead() method 1673–1675 File.OpenText() method 1675–1677 File.OpenWrite() method 1677–1679 File.SetAttributes() method 1679–1680 File.SetCreationTime() method 1681–1683 File.SetCreationTimeUtc() method 1683–1684 File.SetLastAccessTime() method 1684–1686 File.SetLastAccessTimeUtc() method 1687–1688 File.SetLastWriteTime() method 1688–1690 File.SetLastWriteTimeUtc() method 1690–1692 System.IO.Directory 1340–1342 Directory.CreateDirectory() method 1342–1343 Directory.Delete() method 1344–1347 Directory.Exists() method 1347 Directory.GetCreationTime() method 1349–1351 Directory.GetCreationTimeUtc() method 1351–1352 Directory.GetCurrentDirectory() method 1352 Directory.GetDirectories() method 1353–1358 Directory.GetDirectoryRoot() method 1358–1360 Directory.GetFiles() method 1360–1364 Directory.GetFileSystemEntries() method 1364–1369 Directory.GetLastAccessTime() method 1369–1371 Directory.GetLastAccessTimeUTC() method 1371–1372 Directory.GetLastWriteTime() method 1372–1374 Directory.GetLastWriteTimeUtc() method 1374–1375 Directory.GetLogicalDrives() method 1376 Directory.GetParent() method 1376–1377 Directory.Move() method 1378–1380 Directory.SetCreationTime() method 1380–1382 Directory.SetCreationTimeUtc() method 1382–1384 Directory.SetCurrentDirectory() method 1384–1385 Directory.SetLastAccessTime() method 1386–1388
Directory.SetLastAccessTimeUTC() method 1388–1389 Directory.SetLastWriteTime() method 1389–1391 Directory.SetLastWriteTimeUTC() method 1392–1393 DirectoryNotFoundException() constructor 1395–1397 NotFoundException 1394 System.IO.EndOfStreamException class 1497–1501 System.IO.FileAccess.Enum 1693–1694, 1695 System.IO.FileAttributes 1652 System.IO.FileLoadException 1737–1739 constructor 1739–1743 FileName property 1743–1744 FusionLog property 1744, 1745 GetObjectData() method 1745–1746 ToString() method 1746–1747 System.IO.FileMode.Enum 1748–1749 Append field 1749–1750 Create field 1750 CreateNew field 1750 Open field 1750 OpenOrCreate field 1751 Truncate field 1751 System.IO.FileNotFoundException 1752–1754 constructor 1754–1758 FileName property 1758 FusionLog property 1759 GetObjectData() method 1760 Message property 1759–1760 ToString() method 1760 System.IO.FileShare.Enum 1762–1763 Inheritable field 1764 None field 1764 Read field 1764 ReadWrite field 1764–1765 Write field 1765 System.IO.FileStream 1766–1771 BeginRead() method 1803–1805 BeginWrite() method 1806–1808 CanRead property 1792–1794 CanSeek property 1794–1795 CanWrite property 1795–1797 Close() method 1808–1810 constructor 1771–1792 Dispose() method 1810 EndRead() method 1811–1813 EndWrite() method 1813–1815 Finalize() method 1815–1816
3820
Contents | Index
System.IO.IOException
Flush() method 1816–1817 Handle property 1797–1798 IsAsync property 1798–1799 Length property 1799–1800 Lock() method 1817–1818 Name property 1801 Position property 1801–1803 Read() method 1818–1821 ReadByte() method 1821–1822 Seek() method 1823–1824 SetLength() method 1824–1826 Unlock() method 1826 Write() method 1827–1828 WriteByte() method 1829–1830 System.IO.IOException 2128–2129 constructor 2129–2132 System.IO.MemoryStream 2233–2236 CanRead property 2250–2251 CanSeek property 2251–2253 CanWrite property 2253–2254 Capacity property 2254–2256 Close() method 2260–2261 constructor 2236–2250 Flush() method 2261 GetBuffer() method 2262–2263 Length property 2257–2258 Position property 2258–2260 Read() method 2263–2265 ReadByte() method 2265–2266 Seek() method 2267–2268 SetLength() method 2268–2270 ToArray() method 2271–2272 Write() method 2272–2274 WriteByte() method 2274–2276 WriteTo() method 2276–2277 System.IO.Path 2447–2452 AltDirectorySeparatorChar field 2453–2454 ChangeExtension() method 2457–2458 Combine() method 2458–2460 DirectorySeparatorChar field 2454–2455 GetDirectoryName() method 2460–2461 GetExtension() method 2462–2463 GetFileName() method 2463–2465, 2465–2466 GetFullPath() method 2466–2468 GetPathRoot() method 2468–2470 GetTempFileName() method 2470–2471 GetTempPath() method 2471–2472 HasExtension() method 2472–2473 InvalidPathChars field 2455
■
System.IO.StreamWriter
IsPathRooted() method 2474–2475 PathSeparator field 2456 VolumeSeparatorChar field 2457 System.IO.PathTooLongException 2476–2477 constructor 2477–2480 System.IO.SeekOrigin.Enum 2645–2646 Begin field 2646 Current field 2646 End field 2647 System.IO.Stream 2694–2699 BeginRead() method 2708–2711 BeginWrite() method 2711–2714 CanRead property 2700 CanSeek property 2701 CanWrite property 2703 Close() method 2714–2715 constructor 2699 CreateWaitHandle() method 2715 EndRead() method 2716–2718 EndWrite() method 2718–2720 Flush() method 2720–2722 Length property 2705 Null field 2700 Position property 2706 Read() method 2722–2726 Seek() method 2726–2728 SetLength() method 2728–2730 Write() method 2730–2732 WriteByte() method 2732–2733 System.IO.StreamReader 2735–2737 BaseStream property 2758, 2760 Close() method 2761–2762 constructor 2738–2758 DiscardBufferedData() method 2762–2764 Dispose() method 2764–2766 Null field 2758 Peek() method 2765 Read() method 2766–2770 ReadLine() method 2770–2772 ReadToEnd() method 2772–2773 System.IO.StreamWriter 2774–2776 AutoFlush property 2792 BaseStream property 2794 Close() method 2796–2798 constructor 2776–2792 Dispose() method 2798 Encoding property 2795 Finalize() method 2799 Flush() method 2799–2800
3821
Contents | Index
System.IO.StringReader
■
System.Object
Null field 2792 Write() method 2800–2806 System.IO.StringReader 3042–3043 Close() method 3044–3045 constructor 3043–3044 Dispose() method 3046 Peek() method 3046–3048 Read() method 3048–3051 ReadLine() method 3051–3052 ReadToEnd() method 3052–3053 System.IO.StringWriter 3054–3055 Close() method 3061–3062 constructor 3055–3060 Dispose() method 3062 Encoding property 3060 GetStringBuilder() method 3063 ToString() method 3064 Write() method 3065–3068 System.IO.TextReader 3079–3080 Close() method 3081–3082 constructor 3080–3081 Dispose() method 3082 Null field 3081 Peek() method 3082–3083 Read() method 3083–3085 ReadBlock() method 3085–3086 ReadLine() method 3086 ReadToEnd() method 3087 Synchronized() method 3087–3088 System.IO.TextWriter 3089–3091 Close() method 3094 constructor 3091–3092 CoreNewLine field 3092 Dispose() method 3095 Encoding property 3093 Flush() method 3095 FormatProvider property 3093–3094 NewLine property 3094 Null field 3092–3093 Synchronized() method 3096 Write() method 3097–3111 WriteLine() method 3112–3127 System.MarshalByRefObject 2145–2146 constructor 2146 CreateObjRef() method 2146–2147 GetLifetimeService() method 2147–2148 InitializeLifetimeService() method 2148–2149 System.Math 2150–2152 Abs() method 2153–2163
Acs() method 2163–2164 Asin() method 2165–2166 Atan() method 2166–2167 Atan2() method 2167–2169 BigMul() method 2169–2170 Ceiling() method 2170–2171 Cos() method 2171–2172 Cosh() method 2172–2173 DivRem() method 2174–2176 Exp() method 2175–2177 Floor() method 2176–2180 IEEERemainder() method 2177–2179 Log() method 2179–2181 Log10() method 2182–2184 Max() method 2183–2196 Min() method 2197–2210 PI field 2153 Pow() method 2210–2212 Round() method 2212–2216 Sign() method 2217–2226 Sin() method 2226–2227 Sinh() method 2227–2228 Sqrt() method 2229–2230 Tan() method 2230–2231 Tanh() method 2231–2232 System.NotFiniteNumberException 2313–2314 constructor 2314–2318 GetObjectData() method 2319 OffendingNumber Property 2318 System.NotImplementedException 2320–2321 constructor 2321–2323 System.NotSupportedException 2324–2325 constructor 2325–2328 System.NullReferenceException 2329–2330 constructor 2330–2333 System.Object 2399–2401 8-bit unsigned integers, converting 643, 644 Boolean values, converting 621 constructor 2401–2402 converting to 16-bit signed integer 751 converting to 16-bit unsigned integer 922 converting to 32-bit signed integer 778 converting to 64-bit signed integer 802, 803 converting to 8-bit signed integer 829, 830 converting to System.Decimal number 703, 704 converting to System.String representation 889, 890 double-precision floating point number conversion 726, 727 encoding 1473
3822
Contents | Index
System.ObjectDisposedException
■
Equals() method 142, 2402–2411 Finalize() method 2411–2412 GetHashCode() method 2412–2417 GetType() method 2417–2418 MemberwiseClone() method 2418–2420 ReferenceEquals() method 2421–2422 representations of type and value 1509 returning 600 returning sort order of 1507 single-precision floating point number conversion 854, 855 sort orders 520 ToString() method 2422–2423 type/value representations 430 Unicode characters 667 System.ObjectDisposedException 2424–2425 constructor 2425–2427 GetObjectData() method 2428 Message property 2427–2428 ObjectName property 2428 System.ObsoleteAttribute.Class 2430–2431 constructor 2431–2435 IsError property 2435–2437 Message property 2437–2438 System.OperatingSystem objects 1558 System.OutOfMemoryException 2439–2440 constructor 2440–2442 System.OverflowException 2443–2444 constructors 2444–2446 System.Random 2519–2521 constructor 2521–2523 Next() method 2524–2528 NextBytes() method 2528–2529 NextDouble() method 2529–2530 Sample() method 2531 System.RankException 2532–2533 constructor 2533–2535 System.SByte.Structure 2537–2539 CompareTo() method 2541–2542 converting to System.Boolean 622 converting to System.Byste 645 converting to System.Char 668 converting to System.Decimal 705 converting to System.Double 728 converting to System.Int16 753 converting to System.Int32 779 converting to System.Int64 804 converting to System.SByte 831 converting to System.Single 856
System.Security.Permissions.FileIOPermissionAttribute
converting to System.String 891, 892 converting to System.UInt16 924 converting to System.UInt32 951 converting to System.UInt64 977 Equals() method 2542–2543 GetTypeCode() method 2544–2548 HashCode() method 2543–2544 MaxValue field 2539–2540 MinValue field 2540 Parse() method 2545–2554 ToString() method 2554–2562 System.Security.CodeAccessPermission class 496–499, 501, 503 System.Security.IPermission.Interface 2133–2134 System.Security.IPermission.InterfaceLIPermission Copy() method 2135 Demand() method 2136–2137 Intersect() method 2138–2139 IsSubsetOf() method 2140–2142 Union() method 2142–2144 System.Security.Permissions EnvironmentPermission class 1574–1576 EnvironmentPermissionAccess.Enum class 1594–1595 EnvironmentPermissionAttribute class 1597–1598 System.Security.Permissions.FileIOPermission 1696–1700 FileIOPermission.AddPathList() method 1706–1707 FileIOPermission.Copy() method 1708–1709 FileIOPermission.FomXml() method 1709–1710 FileIOPermission.GetPathList() method 1711–1712 FileIOPermission.Intersection() method 1712–1714 FileIOPermission.IsSubsetOf() method 1714–1716 FileIOPermission.IsUnrestricted() method 1716–1717 FileIOPermission.SetPathList() method 1717–1719 FileIOPermission.ToXml() method 1719–1720 FileIOPermission.Union() method 1721–1722 FileIOPermissions constructor 1700–1705 System.Security.Permissions.FileIOPermissionAccess.Enum 1723–1724 fields 1724, 1724–1725, 1725–1726 System.Security.Permissions.FileIOPermissionAttribute 1727–1728 AllProperty 1730–1731 constructor 1728–1729 CreatePermission() method 1736 PathDiscovery property 1732–1733
3823
Contents | Index
System.Security.Permissions.FileIOPermisson Attribute
Read property 1734–1735 Write property 1735–1736 System.Security.Permissions.FileIOPermissonAttribute Append property 1731–1732 System.Security.Permissions.PermissionState.Enum 2517–2518 System.Security.Permissions.SecurityAction.Enum 2568–2569 Assert field 2569–2571 Demand field 2571–2577 Deny field 2572–2574 InheritanceDemand field 2574–2576 LinkDemand field 2576–2580 PermitOnly field 2577–2579 RequestMinimum field 2579–2581 RequestOptional field 2580–2582 RequestRefuse field 2581 System.Security.Permissions.SecurityAttribute 2583–2584 Action property 2585 constructor 2584 CreatePermission() method 2586 Unrestricted property 2585 System.Security.Permissions.SecurityAttribute class 514–515 System.Security.Permissions.SecurityPermissionAttribute 2628–2630 Assertion property 2631 constructor 2630 ControlAppDomain property 2631 ControlDomainPolicy property 2631–2632 ControlPolicy property 2632 ControlPrincipal property 2633 ControlThread property 2633 CreatePermission() method 2636–2637 Execution property 2633–2634 Flags property 2634 Infrastructure property 2634 RemotingConfiguration property 2635 SerializationFormatter property 2635 SkipVerification property 2635 UnmanagedCode property 2636 System.Security.Permissions.SecurityPermissionFlag.Enum 2638–2639 AllFlags field 2639–2640 Assertion field 2640 BindingRedirects field 2640 ControlAppDomain field 2640
■
System.Security.SecurityElement
ControlDomainPolicy field 2641 ControlEvidence field 2641 ControlPolicy field 2641 ControlPrincipal field 2642 ControlThread field 2642 Execution field 2642 Infrastructure field 2643 NoFlags field 2643 RemotingConfiguration field 2643 SerializationFormatter field 2643 SkipVerification field 2644 UnmanagedCode field 2644 System.Security.Permissions.SecurityPermissions 2611–2613 constructor 2613–2617 Copy() method 2618–2619 Flags property 2617 FromXml() method 2619–2620 Intersect() method 2621–2622 IsSubsetOf() method 2622–2624 IsUnrestricted() method 2624 ToXml() method 2625 Union() method 2626–2627 System.Security.PermissionSet 2481–2486 AddPermission() method 2491–2493 Assert() method 2493–2495 constructor 2486–2489 ContainsNonCodeAccessPermissions() method 2495 ConvertPermissionSet() method 2495 Copy() method 2496–2497 CopyTo() method 2497–2500 Count property 2489–2490 Demand() method 2500–2501 Deny() method 2502–2503 FromXml() method 2504–2506 GetEnumerator() method 2506–2507 IsReadOnly property 2490 IsSubsetOf() method 2507–2509 IsSynchronized property 2490–2491 PermitOnly() method 2509–2511 SyncRoot property 2491 ToString() method 2511–2512 ToXml() method 2512–2514 Union() method 2514–2516 System.Security.SecurityElement 2587–2588 AddAttribute() method 2591 AddChild() method 2592 Attribute() method 2593–2594 Attributes property 2589
3824
Contents | Index
System.Security.SecurityException
Children property 2589 Equal() method 2594 Escape() method 2595 IsValidAttributeName() method 2596 IsValidAttributeTag() method 2597 IsValidAttributeText() method 2597–2599 IsValidAttributeValue() method 2596–2598 SearchForTextOfTag() method 2598–2599 Tag property 2590 Text property 2591 ToString() method 2599–2601 System.Security.SecurityException 2600–2601 constructor 2602–2606 GetObjectData() method 2609–2610 GrantedSet property 2606–2607 PermissionState property 2607–2608 PermissionType property 2608 RefusedSet property 2608–2609 ToString() method 2610 System.Security.SecurityException, forcing 501 System.Security.VerificationException 3704–3705 constructor 3705–3708 System.Single.Structure 2648–2651 CompareTo() method 2658–2659 converting to System.Boolean 617 converting to System.Byte 638 converting to System.Decimal 699 converting to System.Double 722 converting to System.Int16 746 converting to System.Int32 772 converting to System.Int64 798 converting to System.SByte 824 converting to System.String 850, 880, 881 converting to System.UInt16 917 converting to System.UInt32 944 converting to System.UInt64 971 Epsilon field 2651–2652 Equals() method 2660–2661 GetHashCode() method 2661–2662 GetTypeCode() method 2662 IsInfinity() method 2662–2664 IsNaN() method 2664–2665 IsNegativeInfinity() method 2665–2666 IsPositiveInfinity() method 2667–2668 MaxValue field 2652–2653 MinValue field 2653–2654 NaN field 2654–2655 NegativeInfinity field 2656–2657 Parse() method 2668–2678
■
System.String
PositiveInfinity field 2657–2658 text representations 553, 572 ToString() method 2678–2684 System.StackOverflowException 2690–2691 constructor 2691–2693 System.String 2807–2815 8-bit unsigned integers, converting 650 Boolean values, converting 626 Chars property 2827–2828 Clone() method 2829–2830 Compare() method 2830–2843 CompareOrdinal() method 2843–2847 CompareTo() method 2847–2850 Concat() method 2850–2859 constructor 2815–2826 converting 605, 834 converting 16-bit signed integers 758, 895 converting 32-bit unsigned integers 884 converting 64-bit signed integers 808 converting 8-bit signed integers 836 converting 8-bit unsigned integers 869 converting to System.Boolean 624, 868 converting to System.Byte 648, 651 converting to System.Char 671 converting to System.DateTime 686, 688 converting to System.Decimal 708, 710 converting to System.Double 730, 733 converting to System.Int16 755, 758 converting to System.Int32 781, 784 converting to System.Int64 806, 809, 984 converting to System.SByte 837 converting to System.Single 858, 860 converting to System.UInt16 927, 930 converting to System.UInt32 954, 957 converting to System.UInt64 981 Copy() method 2860–2861 CopyTo() method 2861–2863 current instances 477 decimal digits 448 elements 489 Empty field 2826–2827 EndsWith() method 2863–2864 Equals() method 2865–2868 Format() method 2868–2877 GetEnumerator() method 2877–2878 GetHashCode() method 2878–2879 GetTypeCode() method 2879 IndexOf() method 2879–2890 IndexOfAny() method 2890–2895
3825
Contents | Index
System.SystemException
■
System.Text.StringBuilder
Insert() method 2895–2896 instances 899 Intern() method 2896–2898 IsInterned() method 2898–2899 Join() method 2900–2902 LastIndexOf() method 2902–2913 LastIndexOfAny() method 2913–2918 Length property 2828–2829 letters 445 lowercase letters 451 numbers 454 op_Equality() method 2918–2920 op_Inequality() method 2920–2921 PadLeft() method 2921–2924 PadRight() method 2924–2926 punctuation marks 457 Remove() method 2926–2928 Replace() method 2928–2930 Split() method 2930–2933 StartsWith() method 2933–2935 Substring() method 2935–2938 symbols 466 System.DateTime value, converting 1063 ToCharArray() method 2938–2940 ToLower() method 476, 2940–2942 ToString() method 2942–2943 ToUpper() method 2943–2945 Trim() method 2945–2947 TrimEnd() method 2947–2948 TrimStart() method 2948–2949 Unicode characters 672 writing 578 System.SystemException 3075–3076 constructor 3076–3078 System.Text Decoder 1290 Decoder() constructor 1291 Decoder.GetCharCount() method 1291–1292 Decoder.GetChars() method 1293–1294 Delegate() constructor 1298–1300 Delegate.Clone() method 1303–1305 Delegate.Combine() method 1305–1309 Delegate.CombineImpl() method 1309–1310 Delegate.CreateDelegate() method 1311–1319 Delegate.DynamicInvoke() method 1319–1321 Delegate.DynamicInvokeImpl() method 1321–1323 Delegate.Equals() method 1323–1324 Delegate.GetHashCode() method 1325
Delegate.GetInvocationList() method 1326–1327 Delegate.GetMethodImpl() method 1327–1328 Delegate.GetobjectData() method 1328 Delegate.Method property 1301 Delegate.op_Equality() method 1329–1335 Delegate.RemoveImpl() method 1335 Delegate.Target property 1302 System.Text.ASCIIEncoding class 288–289, 1461 System.Text.Decoder 1488 System.Text.Encoder class 1453 Encoder() constructor 1453–1454 Encoder.GetByteCount() method 1454–1455 Encoder.GetBytest() method 1455–1457 returning 1489 System.Text.Encoding class 1458–1463 Encoding() constructor 1463–1464 Encoding.ASCII property 1464 Encoding.BigEndianUnicode property 1464–1465 Encoding.BodyName property 1465 Encoding.CodePage property 1465 Encoding.Convert() method 1471–1472 Encoding.Default property 1466 Encoding.EncodingName property 1466 Encoding.Equal() method 1473 Encoding.GetByteCount() method 1473–1476 Encoding.GetBytes() method 1476–1482 Encoding.GetCharCount() method 1482–1484 Encoding.GetChars() method 1485–1488 Encoding.GetDecoder() method 1488–1489 Encoding.GetEncoder() method 1489 Encoding.GetEncoding() method 1491–1492 Encoding.GetHashCode() method 1492 Encoding.GetMaxByte() method 1493 Encoding.GetMaxCharCount() method 1494 Encoding.GetPreamble() method 1494–1495 Encoding.GetString() method 1495–1496 Encoding.HeaderName property 1466 Encoding.IsBrowserDisplay property 1467 Encoding.IsBrowserSave property 1467 Encoding.IsMailNewsDisplay property 1468 Encoding.IsMailNewsSave property 1468 Encoding.Unicode property 1469 Encoding.UTF7 property 1469 Encoding.UTF8 property 1470 Encoding.WebName property 1470 Encoding.WindowsCodePage property 1470 System.Text.StringBuilder 2955–2959 Append() method 2970–2994 AppendFormat() method 2994–3002
3826
Contents | Index
System.Text.UnicodeEncoding
Capacity property 2965–2967 Chars property 2967–2968 constructor 2959–2965 EnsureCapacity() method 3002–3004 Equals() method 3004–3005 Insert() method 3005–3032 Length property 2968–2970 MaxCapacity property 2970 Remove() method 3032–3033 Replace() method 3034–3039 ToString() method 3039–3041 System.Text.UnicodeEncoding 1461, 3640–3642 CharSize field 3645 constructor 3643–3645 Equals() method 3646–3647 GetByteCount() method 3647–3650 GetBytes() method 3650–3656 GetCharCount() method 3656–3657 GetChars() method 3658–3660 GetDecoder() method 3660–3661 GetHashCode() method 3661–3662 GetMaxByteCount() method 3662–3664 GetMaxCharCount() method 3664–3665 GetPreamble() method 3666 System.Text.UTF8Encoding 1461, 3667–3669 constructor 3669–3672 Equals() method 3672–3673 GetByteCount() method 3674–3677 GetBytes() method 3678–3684 GetCharCount() method 3684–3688 GetDecoder() method 3688–3689 GetEncoder() method 3689–3690 GetHashCode() method 3690–3691 GetMaxByteCount() method 3691–3693 GetMaxCharCount() method 3693–3694 GetPreamble() method 3694–3695 System.Threading.Interlocked 2100–2102 Interlocked.CompareExchange() method 2102–2106 Interlocked.Decrement() method 2106–2110 Interlocked.Exchange() method 2110–2113 Interlocked.Increment() method 2113–2115 System.Threading.Monitor 2278–2282 Monitor.Enter() method 2283–2285 Monitor.Exit() method 2285–2287 Monitor.Pulse() method 2287–2289 Monitor.PulseAll() method 2289–2292 Monitor.TryEnter() method 2292–2299 Monitor.Wait() method 2299–2311
■
System.Threading.ThreadState.Enum
System.Threading.SynchronizationLockException 3069–3070 constructor 3070–3073 System.Threading.Thread 3128–3131 Abort() method 3144–3149 AllocateDataSlot() method 3149 AllocateNamedDataSlot() method 3149–3150 ApartmentState property 3133–3134 constructor 3132–3133 CurrentContext property 3134 CurrentPrincipal property 3135 CurrentThread property 3135–3136 Finalize() method 3150 FreeNamedDataSlot() method 3150–3151 GetData() method 3151–3152 GetDomain() method 3152 GetDomainID() method 3153 GetNamedDataSlot() method 3153–3154 Interrupt() method 3154 IsAlive property 3136–3137 IsBackground property 3138–3139 IsThreadPoolThread property 3139 Join() method 3154–3160 MemoryBarrier() method 3160 Name property 3139–3141 Priority property 3141–3142 ResetAbort() method 3160–3162 Resume() method 3162–3163 SetData() method 3163 Sleep() method 3164–3166 SpinWait() method 3167 Start() method 3167–3168 Suspend() method 3169 ThreadState property 3143–3144 VolatileRead() method 3169–3179 VolatileWrite() method 3180–3191 System.Threading.ThreadAbortException 3192–3193 ExceptionState property 3193–3194 System.Threading.ThreadPriority.Enum 3195–3196 AboveNormal field 3197 BelowNormal field 3197 Highest field 3197 Lowest field 3197 Normal field 3198 System.Threading.ThreadStart.Delegate 3199–3200 System.Threading.ThreadState.Enum 3201–3203 Aborted field 3204 AbortRequest field 3204 Background field 3204
3827
Contents | Index
System.Threading.ThreadStateException
■
System.Type
Running field 3204 Stopped field 3205 StopRequested field 3205 Suspended field 3205 SuspendRequested field 3206 Unstarted field 3206 WaitSleepJoin field 3206 System.Threading.ThreadStateException 3207–3208 constructor 3208–3211 System.Threading.Timeout 3212–3213 Infinite field 3213 System.Threading.Timer 3214–3216 Change() method 3222–3230 constructor 3216–3222 Dispose() method 3230–3233 Finalize() method 3233 System.Threading.TimerCallback.delegate 3234–3235 System.Threading.TimeSpan Negate() method 3286–3287 op_Addition() method 3287–3288 op_Equality() method 3288–3289 op_GreaterThan() method 3289–3290 op_GreaterThanOrEqual() method 3291–3292 op_Inequality() method 3292–3293 op_LessThan() method 3293–3294 op_LessThanOrEqual() method 3294–3295 op_Subtraction() method 3296–3297 op_UnaryNegation() method 3297–3298 op_UnaryPlus() method 3298–3299 Parse() method 3299–3301 Subtract() method 3301–3303 ToString() method 3303–3304 System.Threading.WaitHandle 3739–3741 Close() method 3744–3745 constructor 3741–3742 Dispose() method 3745–3746 Finalize() method 3746 Handle property 3743 InvalidHandle field 3742 WaitAll() method 3747–3752 WaitAny() method 3752–3758 WaitOne() method 3758–3761 WaitTimeout field 3742–3743 System.TimeSpan.Structure 3236–3239 Add() method 3267–3268 Compare() method 3268–3270 CompareTo() method 3270–3271 constructor 3239–3245
Days property 3254–3255 Duration() method 3272 Equals() method 3272–3275 FromDays() method 3275–3276 FromHours() method 3277–3278 FromMilliseconds() method 3278–3280 FromMinutes() method 3280–3281 FromSeconds() method 3282–3283 FromTicks() method 3283–3284 GetHashCode() method 3285–3286 Hours property 3255–3256 MaxValue field 3245–3246 Milliseconds property 3256–3257 Minutes property 3257–3258 MinValue field 3246–3247 Seconds property 3258 subtracting 1075 Ticks property 3259 TicksPerDay field 3248–3249 TicksPerHour field 3249–3250 TicksPerMillisecond field 3250–3251 TicksPerMinute field 3251–3252 TicksPerSecond field 3252–3253 TotalDays property 3260–3262 TotalHours property 3262–3263 TotalMilliseconds property 3263–3264 TotalMinutes property 3264–3265 TotalSeconds property 3266–3267 Zero field 3253–3254 System.Type 3305–3314 Assembly property 3319–3320 AssemblyQualifiedName property 3320–3322 Attributes property 3322–3324 BaseType property 3324–3325 constructor 3314 DeclaringType property 3325–3326 DefaultBinder property 3326–3328 Delimiter field 3314–3315 EmptyTypes field 3315–3316 Equals() method 3374–3376 FilterAttribute field 3316–3317 FilterName field 3317 FilterNameIgnoreCase field 3317–3318 FindInterfaces() method 3376–3377 FindMembers() method 3378–3380 FullName property 3328–3329 GetArrayRank() method 3380–3381 GetAttributeFlagsImpl() method 3381–3382 GetConstructor() method 3382–3397
3828
Contents | Index
System.TypeCode
GetDefaultMembers() method 3397–3398 GetElementType() method 3398–3399 GetEvent() method 3399–3403 GetEvents() method 3403–3406 GetField() method 3406–3410 GetFields() method 3410–3413 GetHashCode() method 3413–3414 GetInterface() method 3414–3417 GetInterfaceMap() method 3417–3418 GetInterfaces() method 3419 GetMember() method 3420–3426 GetMembers() method 3426–3429 GetMethod() method 3429–3445 GetMethodImpl() method 3445–3448 GetMethods() method 3448–3451 GetNestedType() method 3452–3455 GetNestedTypes() method 3456–3459 GetProperties() method 3459–3462 GetProperty() method 3462–3477 GetPropertyImpl() method 3477–3479 GetType() method 3479–3486 GetTypeArray() method 3486–3488 GetTypeCode() method 3488 GetTypeFromCLSID() method 3488–3492 GetTypeFromHandle() method 3492–3494 GetTypeFromProgID() method 3494–3500 GetTypeHandle() method 3500–3501 GUID property 3330 HasElementType property 3330–3331 HasElementTypeImpl() method 3501–3502 InvokeMembers() method 3502–3517 IsAbstract property 3331–3332 IsAnsiClass property 3333 IsArray property 3333–3334 IsArrayImpl() method 3517–3518 IsAssignableFrom() method 3518–3519 IsAutoClass property 3334–3335 IsAutoLayout property 3335–3336 IsByRef property 3336–3337 IsByRefImpl() method 3519–3520 IsClass property 3337–3338 IsCOMObject property 3339 IsCOMObjectImpl() method 3520 IsContextful property 3339 IsContextfulImpl() method 3520–3521 IsEnum property 3340–3341 IsExplicitLayout property 3341–3342 IsImport property 3342–3343 IsInstanceOfType() method 3521–3522
■
System.UInt16.Structure
IsInterface property 3343–3344 IsLayoutSequential property 3344–3346 IsMarshalByRef property 3346–3347 IsMarshalByRefImpl() method 3523 IsNestedAssembly property 3347–3348 IsNestedFamANDAssem property 3349–3350 IsNestedFamily property 3350–3351 IsNestedFamOrAssem property 3352–3353 IsNestedPrivate property 3353–3354 IsNestedPublic property 3355–3356 IsNotPublic property 3356–3357 IsPointer property 3358–3359 IsPointerImpl() method 3523 IsPrimitive property 3359–3360 IsPrimitiveImpl() method 3524 IsPublic property 3360–3361 IsSealed property 3361–3362 IsSerializable property 3363 IsSpecialName property 3363–3364 IsSubclassOf() method 3524–3526 IsUnicodeClass property 3364–3365 IsValueType property 3365–3366 IsValueTypeImpl() method 3526 MemberType property 3366 Missing field 3318–3319 Module property 3366–3367 Namespace property 3368–3369 ReflectedType property 3369–3370 ToString() method 3527 TypeHandle property 3370–3371 TypeInitializer property 3371–3372 UnderlyingSystemType property 3373–3374 System.TypeCode DBNull 607 returning 606 System.Object 601 System.TypeInitializationException 3528–3529 getObjectData property 3530 TypeName property 3529 System.UInt16.Structure 3531–3533 CompareTo() method 3535–3536 converting to System.Boolean 630 converting to System.Byte 657 converting to System.Char 677 converting to System.Decimal 716 converting to System.Double 738 converting to System.Int16 765 converting to System.Int32 790 converting to System.Int64 815
3829
Contents | Index
System.UInt32.Structure
■
Tags
converting to System.SByte 843 converting to System.Single 866 converting to System.String 907, 909 converting to System.UInt16 936 converting to System.UInt32 963 converting to System.UInt64 989 Equals() method 3536–3538 GetHashCode() method 3538–3539 GetTypeCode() method 3539 MaxValue field 3533–3534 MinValue field 3534–3535 Parse() method 3539–3549 ToBoolean() method 3557 ToByte() method 3557 ToChar() method 3557 ToDateTime() method 3558 ToDecimal() method 3558 ToDouble() method 3558 ToString() method 3549–3556 System.UInt32.Structure 3562–3564 CompareTo() method 3566–3567 converting to System.Boolean 628 converting to System.Byte 654 converting to System.Char 674 converting to System.Decimal 713 converting to System.Double 736 converting to System.Int16 761 converting to System.Int32 787 converting to System.Int64 812 converting to System.SByte 840 converting to System.Single 864 converting to System.String 902, 903 converting to System.UInt16 933 converting to System.UInt32 960 converting to System.UInt64 987 Equals() method 3568–3569 GetHashCode() method 3569–3570 GetTypeCode() method 3570 MaxValue field 3564–3565 MinValue field 3565–3566 Parse() method 3570–3580 text representations 561, 586 ToString() method 3580–3587 System.UInt64.Structure 3593–3595 CompareTo() method 3597–3598 converting to System.Boolean 629 converting to System.Byte 655 converting to System.Char 676 converting to System.Decimal 714
converting to System.Double 737 converting to System.Int16 763 converting to System.Int32 789 converting to System.Int64 813 converting to System.SByte 841 converting to System.String 865, 905, 906 converting to System.UInt16 934 converting to System.UInt32 961 converting to System.UInt64 988 Equals() method 3598–3600 GetHashCode() method 3600–3601 GetTypeCode() method 3601 Maxvalue field 3595–3596 Minvalue field 3596–3597 Parse() method 3601–3611 text representations 562, 587 ToString() method 3611–3618 System.UnauthorizedAccessException 3624–3625 constructor 3625–3628 System.ValueType 3698–3700 constructor 3700 Equals() method 3700–3701 GetHashCode() method 3701–3702 ToString() method 3703 System.Version.Class 3709–3710 Build property 3717–3718 Clone() method 3721–3722 CompareTo() method 3723–3724 constructor 3711–3717 Equals() method 3724–3726 GetHashCode() method 3726–3727 Major property 3718–3719 Minor property 3719–3720 op_Equality() method 3727–3728 op_GreaterThan() method 3728–3730 op_GreaterThanOrEqual() method 3730–3731 op_Inequality() method 3731–3733 op_LessThan() method 3733–3734 op_LessThanOrEqual() method 3734–3736 Revision property 3720–3721 ToString() method 3736–3737
T Tags mail agent body tags 1465 mail agent header 1466 SecurityElement property 2590 SecurityElement.IsValidTag() 2597
3830
Contents | Index
Targets
Targets, subsets 1715 Terminators 563 Text See also System.Text ASCIIEncoding() constructor 289–290 creating 1646 namespaces 25 opening 1675 representations writing 564 writing to objects 577 SecurityElement property 2591 SecurityElement.IsValidText() method 2597 System.Text.Encoder class 1453 Encoder() constructor 1453–1454 Encoder.GetByteCount() 1454–1455 Encoder.GetBytes() 1455–1457 System.Text.Encoding class 1458–1463 Encoding() constructor 1463–1464 Encoding.ASCII property 1464 Encoding.BigEndianUnicode property 1464–1465 Encoding.BodyName property 1465 Encoding.CodePage property 1465 Encoding.Convert() method 1471–1472 Encoding.Default property 1466 Encoding.EncodingName property 1466 Encoding.Equal() method 1473 Encoding.GetByteCount() method 1473–1476 Encoding.GetBytes() method 1476–1482 Encoding.GetCharCount() method 1482–1484 Encoding.GetChars() method 1485–1488 Encoding.GetDecoder() method 1488–1489 Encoding.GetEncoder() method 1489 Encoding.GetEncoding() method 1491–1492 Encoding.GetHashCode() method 1492 Encoding.GetMaxByte() method 1493 Encoding.GetMaxCharCount() method 1494 Encoding.GetPreamble() method 1494–1495 Encoding.GetString() method 1495–1496 Encoding.HeaderName property 1466 Encoding.IsBrowserDisplay property 1467 Encoding.IsBrowserSave property 1467 Encoding.IsMailNewsDisplay property 1468 Encoding.IsMailNewsSave property 1468 Encoding.Unicode property 1469 Encoding.UTF7 property 1469 Encoding.UTF8 property 1470 Encoding.WebName property 1470 Encoding.WindowsCodePage property 1470
■
TextWriter
System.Text.UTF8Encoding 3667–3669 constructor 3669–3672 Equals() method 3672–3673 GetByteCount() method 3674–3677 GetBytes() method 3678–3684 GetCharCount() method 3684–3688 GetDecoder() method 3688–3689 GetEncoder() method 3689–3690 GetHashCode() method 3690–3691 GetMaxByteCount() method 3691–3693 GetMaxCharCount() method 3693–3694 GetPreamble() method 3694–3695 UnicodeEncoding 3640–3642 CharSize field 3645 constructor 3643–3645 Equals() method 3646–3647 GetByteCount() method 3647–3650 GetBytes() method 3650–3656 GetCharCount() method 3656–3657 GetChars() method 3658–3660 GetDecoder() method 3660–3661 GetHashCode() method 3661–3662 GetMaxByteCount() method 3662–3664 GetMaxCharCount() method 3664–3665 GetPreamble() method 3666 UTF-8 1635 Text.ASCIIEncoding class 288–289 TextReader 3079–3080 Close() method 3081–3082 constructor 3080–3081 Dispose() method 3082 Null field 3081 Peek() method 3082–3083 Read() method 3083–3085 ReadBlock() method 3085–3086 ReadLine() method 3086 ReadToEnd() method 3087 Synchronized() method 3087–3088 TextWriter 3089–3091 Close() method 3094 constructor 3091–3092 CoreNewLine field 3092 Dispose() method 3095 Encoding property 3093 Flush() method 3095 FormatProvider property 3093–3094 NewLine property 3094 Null Field 3092–3093 Synchronized() method 3096
3831
Contents | Index
Threads
■
Ticks
Write() method 3097–3111 WriteLine() method 3112–3127 Threads namespaces 27–30 System.Threading.Interlocked 2100–2102 Interlocked.CompareExchange() method 2102–2106 Interlocked.Decrement() method 2106–2110 Interlocked.Exchange() method 2110–2113 Interlocked.Increment() method 2113–2115 System.Threading.Monitor 2278–2282 Monitor.Enter() method 2283–2285 Monitor.Exit() method 2285–2287 Monitor.Pulse() method 2287–2289 Monitor.PulseAll() method 2289–2292 Monitor.TryEnter() method 2292–2299 Monitor.Wait() method 2299–2311 System.Threading.SynchonizationLockException constructor 3070–3073 System.Threading.SynchronizationLockException 3069–3070 System.Threading.Thread 3128–3131 Abort() method 3144–3149 AllocateDataSlot() method 3149 AllocateNamedDataSlot() method 3149–3150 ApartmentState property 3133–3134 constructor 3132–3133 CurrentContext property 3134 CurrentPrincipal property 3135 CurrentThread property 3135–3136 Finalize() method 3150 FreeNamedDataSlot() method 3150–3151 GetData() method 3151–3152 GetDomain() method 3152 GetDomainID() method 3153 GetNamedDataSlot() method 3153–3154 Interrupt() method 3154 IsAlive property 3136–3137 IsBackground property 3138–3139 IsThreadPoolThread property 3139 Join() method 3154–3160 MemoryBarrier() method 3160 Name property 3139–3141 Priority property 3141–3142 ResetAbort() method 3160–3162 Resume() method 3162–3163 SetData() method 3163 Sleep() method 3164–3166 SpinWait() method 3167
Start() method 3167–3168 Suspend() method 3169 ThreadState property 3143–3144 VolatileRead() method 3169–3179 VolatileWrite() method 3180–3191 System.Threading.ThreadState.Enum 3201–3203 Aborted field 3204 AbortRequest field 3204 Background field 3204 Running field 3204 Stopped field 3205 StopRequested field 3205 Suspended field 3205 SuspendRequested field 3206 Unstarted field 3206 WaitSleepJoin field 3206 System.Threading.TimeSpan GreaterThan() 3289–3290 GreaterThanOrEqual() 3291–3292 Negate() method 3286–3287 op_Addition() method 3287–3288 op_Equality() 3288–3289 op_Inequality() 3292–3293 op_LessThan() 3293–3294 op_LessThanOrEqual() 3294–3295 op_Substraction() 3296–3297 op_UnaryNegation() 3297–3298 op_UnaryPlus() 3298–3299 Parse() 3299–3301 Subtract() 3301–3303 ToString() 3303–3304 ThreadAbortException 3192–3193 ExceptionState property 3193–3194 ThreadPriority.Enum 3195–3196 AboveNormal field 3197 BelowNormal field 3197 Highest field 3197 Lowest field 3197 Normal field 3198 Timeout 3212–3213 Infinite field 3213 Timer 3214–3216 Change() method 3222–3230 constructor 3216–3222 Dispose() method 3230–3233 Finalize() method 3233 Timercallback.Delegate 3234–3235 Throwing current exceptions 1625 Ticks 995
3832
Contents | Index
Time
Time See also UTC access 1369, 1656 Convert.ToDateTime() method 690 converting 1067, 1082 creating 1653 creation date, configuring 1681 creation time of files or directories 1349 DateTimeStyles AdjustToUniversal field 1155–1156 AllowInnerWhite field 1156 AllowLeadingWhite field 1157 AllowTrailingWhite field 1158 AllowWhiteSpaces field 1158 None field 1160 System.DateTime structure 991–1004 DateTime() constructor 1004–1008 DateTime.Add property 1022–1023 DateTime.AddDays() method 1023–1024 DateTime.AddHours() method 1025 DateTime.AddMilliseconds() method 1026–1028 DateTime.AddMinutes() method 1028–1029 DateTime.AddMonths() method 1029–1031 DateTime.AddSeconds() method 1031–1032 DateTime.AddTicks() method 1032–1033 DateTime.AddYears() method 1034–1035 DateTime.Compare() method 1035–1036 DateTime.CompareTo() method 1037–1038 DateTime.DayOfWeek property 1012 DateTime.DayOfYear property 1013 DateTime.DaysInMonth() method 1039–1040 DateTime.Equals() method 1040–1042 DateTime.FromFileTime() method 1042 DateTime.FromFileTimeUtc() method 1043 DateTime.FromOADate() method 1044 DateTime.GetDateTimeFormats() method 1045–1047 DateTime.GetHashCode() method 1048 DateTime.GetTypeCode() method 1049 DateTime.Hour property 1014 DateTime.IsLeapYear() method 1049–1050 DateTime.MaxValue field 1009 DateTime.Millisecond property 1014–1016 DateTime.Minute property 1015 DateTime.MinValue field 1010–1012 DateTime.Month property 1016–1017 DateTime.Now property 1017 DateTime.op_Addition() method 1050–1051 DateTime.op_Equality() method 1051–1052
■
Time
DateTime.op_GreaterThan() method 1053 DateTime.op_GreaterThanOrEqual() method 1054 DateTime.op_Inequality() method 1055–1056 DateTime.op_LessThan() method 1056–1057 DateTime.op_LessThanOrEqual() method 1057–1058 DateTime.op_Subtraction() method 1059–1061 DateTime.Parse() method 1061–1067 DateTime.ParseExact() method 1067–1074 DateTime.Second property 1018 DateTime.Subtract() method 1074–1076 DateTime.Ticks property 1018 DateTime.TimeOfDay property 1019 DateTime.Today property 1020 DateTime.ToFileTime() method 1076 DateTime.ToFileTimeUtc() method 1077 DateTime.ToLocalTime() method 1077–1078 DateTime.ToLongDateString() method 1078–1079 DateTime.ToLongTimeString() method 1079–1080 DateTime.ToOADate() method 1080–1081 DateTime.ToShortDateString() method 1081–1082 DateTime.ToShortTimeString() method 1082–1083 DateTime.ToString() method 1083–1090 DateTime.ToUniversalTime() method 1090–1091 DateTime.UtcNow property 1021 DateTime.Year property 1021–1022 DateTimeFormatInfo class 1098–1106 DateTimeFormatInfo() constructor 1107 System.TimeSpan.Structure 3236–3239 Add() method 3267–3268 Compare() method 3268–3270 CompareTo() method 3270–3271 constructor 3239–3245 Days property 3254–3255 Duration() method 3272 Equals() method 3272–3275 FromDays() method 3275–3276 FromHours() method 3277–3278 FromMilliseconds() method 3278–3280 FromMinutes() method 3280–3281 FromSeconds() method 3282–3283 FromTicks() method 3283–3284 GetHashCode() method 3285–3286 Hours property 3255–3256 MaxValue field 3245–3246 Milliseconds property 3256–3257 Minutes property 3257–3258 MinValue field 3246–3247 Seconds property 3258
3833
Contents | Index
Timeouts
■
Type
Ticks property 3259 TicksPerDay field 3248–3249 TicksPerHour field 3249–3250 TicksPerMillisecond field 3250–3251 TicksPerMinute field 3251–3252 TicksPerSecond field 3252–3253 TotalDays property 3260–3262 TotalHours property 3262–3263 TotalMilliseconds property 3263–3264 TotalMinutes property 3264–3265 TotalSeconds property 3266–3267 Zero field 3253–3254 UTC 1043, 1655 Timeouts 3212–3213 Infinite field 3213 Timers 3214–3216 constructor 3216–3222 Timer.Change() method 3222–3230 Timer.Dispose() method 3230–3233 Timer.Finalize() method 3233 TimerCallback.Delegate 3234–3235 Timestamps 1043 Trigonometric functions 2150 Troubleshooting applications 33 arguments 38–46 arithmetic operations 61–64 ArrayTypeMismatchException class 283 Console.OpenStandardError() method 535 Console.OpenStandardInput() method 536 Console.OpenStandardOutput() method 538 Console.Read() method 540 Exception.HelpLink property 1619 execution engines 1629 null arguments 54 null methods 47–51 searching 148 streams 1497 System.Exception class 1611 True values 385–386 Two-dimensional arrays 109 Type ArrayTypeMismatchException 287 Byte.GetTypeCode() method 408 current instances 316 determining 388–389 enumeration 1505 System.Byte 403
System.Type 3305–3314 Assembly property 3319–3320 AssemblyQualifiedName property 3320–3322 Attributes property 3322–3324 BaseType property 3324–3325 constructor 3314 DeclaringType property 3325–3326 DefaultBinder property 3326–3328 Delimiter field 3314–3315 EmptyTypes field 3315–3316 Equals() method 3374–3376 FilterAttribute field 3316–3317 FilterName field 3317 FilterNameIgnoreCase field 3317–3318 FindInterfaces() method 3376–3377 FindMembers() method 3378–3380 FullName property 3328–3329 GetArrayRank() method 3380–3381 GetAttributeFlagsImpl() method 3381–3382 GetConstructor() method 3382–3397 GetDefaultMembers() method 3397–3398 GetElementType() method 3398–3399 GetEvent() method 3399–3403 GetEvents() method 3403–3406 GetField() method 3406–3410 GetFields() method 3410–3413 GetHashCode() method 3413–3414 GetInterface() method 3414–3417 GetInterfaceMap() method 3417–3418 GetInterfaces() method 3419 GetMember() method 3420–3426 GetMembers() method 3426–3429 GetMethod() method 3429–3445 GetMethodImpl() method 3445–3448 GetMethods() method 3448–3451 GetNestedType() method 3452–3455 GetNestedTypes() method 3456–3459 GetProperties() method 3459–3462 GetProperty() method 3462–3477 GetPropertyImpl() method 3477–3479 GetType() method 3479–3486 GetTypeArray() method 3486–3488 GetTypeCode() method 3488 GetTypeFromCLSID() method 3488–3492 GetTypeFromHandle() method 3492–3494 GetTypeFromProgID() method 3494–3500 GetTypeHandle() method 3500–3501 GUID property 3330
3834
Contents | Index
types of values
HasElementType property 3330–3331 HasElementTypeImpl() method 3501–3502 InvokeMembers() method 3502–3517 IsAbstract property 3331–3332 IsAnsiClass property 3333 IsArray property 3333–3334 IsArrayImpl() method 3517–3518 IsAssignableFrom() method 3518–3519 IsAutoClass property 3334–3335 IsAutoLayout property 3335–3336 IsByRef property 3336–3337 IsByRefImpl() method 3519–3520 IsClass property 3337–3338 IsCOMObject property 3339 IsCOMObjectImpl() method 3520 IsContextful property 3339 IsContextfulImpl() method 3520–3521 IsEnum property 3340–3341 IsExplicitLayout property 3341–3342 IsImport property 3342–3343 IsInstanceOfType() method 3521–3522 IsInterface property 3343–3344 IsLayoutSequential property 3344–3346 IsMarshalByRef property 3346–3347 IsMarshalByRefImpl() method 3523 IsNestedAssembly property 3347–3348 IsNestedFamANDAssem property 3349–3350 IsNestedFamily property 3350–3351 IsNestedFamOrAssem property 3352–3353 IsNestedPrivate property 3353–3354 IsNestedPublic property 3355–3356 IsNotPublic property 3356–3357 IsPointer property 3358–3359 IsPointerImpl() method 3523 IsPrimitive property 3359–3360 IsPrimitiveImpl() method 3524 IsPublic property 3360–3361 IsSealed property 3361–3362 IsSerializable property 3363 IsSpecialName property 3363–3364 IsSubclassOf() method 3524–3526 IsUnicodeClass property 3364–3365 IsValueType property 3365–3366 IsValueTypeImpl() method 3526 MemberType property 3366 Missing field 3318–3319 Module property 3366–3367 Namespace property 3368–3369
■
Unicode characters
ReflectedType property 3369–3370 ToString() method 3527 TypeHandle property 3370–3371 TypeInitializer property 3371–3372 UnderlyingSystemType property 3373–3374 System.TypeInitializationException 3528–3529 GetObjectData property 3530 TypeName property 3529 Unicode characters 435 types of values, System namespace 3
U UnauthorizedAccessException 3624–3625 constructor 3625–3628 Underlying type 1505 of the specified enumeration type, returning 1517 System.TypeCode, returning 1517 Unicode characters big-endian byte order 1464 control characters 438 little-endian byte order, formatting 1469 separator characters 459 surrogate characters 462 System.Char Structure 423–426 Char.CompareTo() method 428–429 Char.Equals() method 430–431 Char.GetHashCode() method 431–432 Char.GetNumericValue() method 432–435 Char.GetTypeCode() method 435–476 Char.GetUnicodeCategory() method 435–438 Char.IsControl() method 438–441 Char.IsDigit() method 441–444 Char.IsLetter() method 444–447 Char.IsLetterOrDigit() method 447–450 Char.IsLower() method 450–453 Char.IsNumber() method 453–456 Char.IsPunctuation() method 456–459 Char.IsSeparator() method 459–462 Char.IsSurrogate() method 462–464 Char.IsSymbol() method 465–467 Char.IsUpper() method 467–470 Char.IsWhiteSpace() method 470–473 Char.MaxValue field 426–427 Char.MinValue field 427 Char.Parse() method 473–474 Char.ToLower() method 475–476 Char.ToString() method 477–479 Char.ToUpper() method 479–481
3835
Contents | Index
UnicodeCategory.Enum
■
Unsigned integers
to System.String, converting 873 type 435 uppercase letters 468 whitespace characters 470 UnicodeCategory.Enum 3629–3630 ClosePunctuation field 3631 ConnectorPunctuation field 3631 Control field 3631 CurrencySymbol field 3631 DashPunctuation field 3632 DecimalDigitNumber field 3632 EnclosingMark field 3632 FinalQuotePunctuation field 3633 Format field 3633 InitialQuotePunctuation field 3633 LetterNumber field 3633 LineSeparator field 3634 LowercaseLetter field 3634 MathSymbol field 3634 ModifierLetter field 3635 ModifierSymbol field 3635 NonSpacingMark field 3635 OpenPunctuation field 3635 OtherLetter field 3636 OtherNotAssigned field 3636 OtherNumber field 3636 OtherPunctuation field 3637 OtherSymbol field 3637 ParagraphSeparator field 3637 PrivateUse field 3637 SpaceSeparator field 3638 SpacingCombiningMark field 3638 Surrogate field 3638 TitlecaseLetter field 3639 UppercaseLetter field 3639 UnicodeEncoding 3640–3642 CharSize field 3645 constructor 3643–3645 Equals() method 3646–3647 GetByteCount() method 3647–3650 GetBytes() method 3650–3656 GetCharCount() method 3656–3657 GetChars() method 3658–3660 GetDecoder() method 3660–3661 GetHashCode() method 3661–3662 GetMaxByteCount() method 3662–3664 GetMaxCharCount() method 3664–3665 GetPreamble() method 3666 Uniform Resource Locator (URL) 1619
Uniform Resource Name (URN) 1619 Unions current instances 511 permissions 1592, 1721 Universal time, converting 1155 Unrestricted permissions 1589, 1716 Unsigned integers byte structure 400–402 Byte.CompareTo() method 404–405 Byte.Equals() method 405–406 Byte.GetHashCode() method 407 Byte.GetTypeCode() method 408 Byte.MaxValue field 402 Byte.MinValue field 403 Byte.Parse() method 408–413 Byte.ToString() method 415–422 UInt.16.Structure 3531–3533 CompareTo() method 3535–3536 Equals() method 3536–3538 GetHashCode() method 3538–3539 GetTypeCode() method 3539 MaxValue field 3533–3534 MinValue field 3534–3535 Parse() method 3539–3549 ToBoolean() method 3557 ToByte() method 3557 ToChar() method 3557 ToDateTime() method 3558 ToDecimal() method 3558 ToDouble() method 3558 ToString() method 3549–3556 UInt.32.Structure 3562–3564 CompareTo() method 3566–3567 Equals() method 3568–3569 GetHashCode() method 3569–3570 GetTypeCode() method 3570 MaxValue field 3564–3565 MinValue field 3565–3566 Parse() method 3570–3580 ToString() method 3580–3587 UInt.64.Structure 3593–3595 CompareTo() method 3597–3598 Equals() method 3598–3600 GetHashCode() method 3600–3601 GetTypeCode() method 3601 MaxValue field 3595–3596 MinValue field 3596–3597 Parse() method 3601–3611 ToString() method 3611–3618
3836
Contents | Index
Upper bound
Upper bound, Array.GetUpperBound() method 126–127 Uppercase letters, Unicode characters 468, 469, 479 URL (Uniform Resource Locator) 1619 URN (Uniform Resource Name) 1619 Users interactive mode 1562 names 1563 UTC (coordinated universal time) 1043, 1077 converting 1077 creation time of directories 1351 directories, accessing 1371 files 1658 returning creation date and time 1655 UTF-7, encoding 1469 UTF-8 encoded text 1470 appending 1635 writing 1646 UTF8Encoding 3667–3669 constructor 3669–3672 Equals() method 3672–3673 GetByteCount 3674–3677 GetBytes() method 3678–3684 GetCharCount() method 3684–3688 GetDecoder() method 3688–3689 GetEncoder() method 3689–3690 GetHashCode() method 3690–3691 GetMaxByteCount() method 3691–3693 GetMaxCharCount() method 3693–3694 GetPreamble() method 3694–3695 Utility objects, namespaces 5
V Validation 38–46 SecurityElement.IsValidAttributeName() method 2596 Values Array.GetValue() method 128–137 Array.SetValue() method 160–164 arrays 82 binary searches 220 Boolean 616 bytes 405–406 converting 390–392 current instances 316 dates and times 995 determining 388–389 HRESULT 1619
■
Versions
indices 105 integers 609 numeric 432, 434 SecurityElement.IsValidAttributeValue() method 2596 short date 1132 shut down 1556 strings 393–394 subsets 608 System namespace 3 System.DateTime, parsing 1061 System.Security.CodeAccessPermission 501 true 385–386 Unicode characters 426, 427 ValueType 3698–3700 constructor 3700 Equals() method 3700–3701 GetHashCode() method 3701–3702 ToString() method 3703 Variables environments 1574, 1581 System.Threading.Interlocked 2100–2102 Interlocked.CompareExchange() method 2102 Interlocked.Decrement() method 2106 Interlocked.Exchange() method 2110 Interlocked.Increment() method 2113 Vectors 71 VerificationException 3704–3705 constructor 3705–3708 Versions execution engines 1563 identifying 1558 System.Version.Class 3709–3710 Build property 3717–3718 Clone() method 3721–3722 CompareTo() method 3723–3724 constructor 3711–3717 Equals() method 3724–3726 GetHashCode() method 3726–3727 Major property 3718–3719 Minor property 3719–3720 op_Equality() method 3727–3728 op_GreaterThan() method 3728–3730 op_GreaterThanOrEqual() method 3730–3731 op_Inequality() method 3731–3733 op_LessThan() method 3733–3734 op_LessThanOrEqual() method 3734–3736 Revision property 3720–3721 ToString() method 3736–3737
3837
Contents | Index
WaitHandle
■
Zero
W
X
WaitHandle 3739–3741 Close() method 3744–3745 constructor 3741–3742 Dispose() method 3745–3746 Finalize() method 3746 Handle property 3743 InvalidHandle field 3742 WaitAll() method 3747–3752 WaitAny() method 3752–3758 WaitOne() method 3758–3761 WaitTimeout field 3742–3743 White space leading 1157 Unicode characters 470, 472 Windows, encoding 1470 Wrappers fixed size 236 read-only 255–257 returning 275 StreamWriter 2774–2776 AutoFlush property 2792 BaseStream property 2794 Close() method 2796–2798 constructor 2776–2792 Dispose() method 2798 Encoding property 2795 Finalize() method 2799 Flush() method 2799–2800 Null field 2792 Write() method 2800–2806 Write field 1726 Writing arrays 567 files 1677 formatted strings 584 line terminators 563 lines to formatted strings 583 strings. See StringWriter class subarrays 568 text representations 564 to objects 577 UTF-8 encoded text 1646
XML (Extensible Markup Language) CodeAccessPermission.FromXml() method 503 CodeAccessPermission.ToString() method 510 CodeAccessPermission.ToXml() method 511 encoding 1583 permissions 1591 encoding 1709 returning 1719 SecurityElement 2587–2588 Attributes property 2589 Children property 2589 Tag property 2590 Text property 2591 System.Security.SecurityElement AddAttribute() method 2591 AddChild() method 2592 Attribute() method 2593 Equal() method 2594 Escape() method 2595 IsValidAttributeName() method 2596 IsValidAttributeValue() method 2596 IsValidTag() method 2597 IsValidText() method 2597
Y Years See also System.DateTime structure leap year 1049 patterns 1136 retrieving 1021
Z Zero Array.Clear() method 91–92 current instances 222 DivideByZeroException 1399–1402 one-dimensional arrays, enumerating 1518
3838
Contents | Index