Está en la página 1de 416

enum (Referencia de C#)

Visual Studio 2008

Actualizacin: noviembre 2007 La palabra clave enum se utiliza para declarar una enumeracin, un tipo distinto que consiste en un conjunto de constantes con nombre denominado lista de enumeradores. Normalmente suele ser recomendable definir una enumeracin directamente dentro de un espacio de nombres para que todas las clases de dicho espacio puedan tener acceso a sta con la misma facilidad. Sin embargo, una enumeracin tambin puede anidarse dentro de una clase o estructura. De forma predeterminada, el primer enumerador tiene el valor 0 y el valor de cada enumerador sucesivo se incrementa en 1. Por ejemplo:
enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

En esta enumeracin, Sat es 0, Sun es 1, Mon es 2 y as sucesivamente. Los enumeradores pueden tener inicializadores que reemplazan a los valores predeterminados. Por ejemplo:
enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

En esta enumeracin, se obliga a que la secuencia de elementos empiece en 1 en vez de en 0. Sin embargo, se recomienda que una enumeracin contenga una constante con un valor de 0. Para obtener ms informacin, vea Tipos de enumeracin (Gua de programacin de C#). Cada tipo de enumeracin tiene un tipo subyacente, que puede ser cualquier tipo integral excepto char. El tipo predeterminado subyacente de los elementos de la enumeracin es int. Para declarar una enumeracin de otro tipo integral, como byte, use un carcter de dos puntos despus del identificador y escriba a continuacin el tipo:
enum Days : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

Los tipos admitidos para una enumeracin son byte, sbyte, short, ushort, int, uint, long o ulong. A una variable de tipo Days se le puede asignar cualquier valor en el intervalo del tipo subyacente; los valores no se limitan a las constantes con nombre. El valor predeterminado de un elemento enum E es el valor producido por la expresin (E)0.

Nota:

Un enumerador no puede contener espacio en blanco en su nombre. El tipo subyacente especifica el almacenamiento asignado para cada enumerador. No obstante, se necesita una conversin explcita para convertir un tipo enum a un tipo integral. Por ejemplo, la siguiente instruccin asigna el enumerador Sun a una variable de tipo int utilizando una conversin de tipos para convertir de enum a int:
int x = (int)Days.Sun;

Cuando se aplica System.FlagsAttribute a una enumeracin que contiene algunos elementos combinados con una operacin OR bit a bit, se observar que el atributo afecta al comportamiento de enum cuando se utiliza con algunas herramientas. Se pueden observar estos cambios al utilizar herramientas tales como los mtodos de la clase Console, el Evaluador de expresiones, etc. (Vea el ejemplo 3).
Programacin slida

Como ocurre con cualquier constante, todas las referencias a los valores individuales de una enumeracin se convierten en literales numricos en tiempo de compilacin. Esto puede crear posibles problemas de versiones como se describe en Constantes (Gua de programacin de C#). Asignar valores adicionales a nuevas versiones de enumeraciones o cambiar los valores de los miembros de enumeracin en una nueva versin puede producir problemas para el cdigo fuente dependiente. Los valores enum se utilizan a menudo en instrucciones switch. Si se han agregado elementos adicionales al tipo enum, la comprobacin de los valores predeterminados puede devolver true de forma inesperada. Si otros desarrolladores van a utilizar su cdigo, debera proporcionar instrucciones sobre cmo debera reaccionar el cdigo de ellos al agregar nuevos elementos a cualquier tipo enum.
Ejemplo

En este ejemplo, se declara la enumeracin Days. Dos enumeradores se convierten explcitamente en un nmero entero y se asignan a variables de nmero entero.
C#
public class EnumTest {

enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; static void Main() { int x = (int)Days.Sun; int y = (int)Days.Fri; Console.WriteLine("Sun = {0}", x); Console.WriteLine("Fri = {0}", y); } } /* Output: Sun = 0 Fri = 5 */

En este ejemplo, la opcin de tipo base se utiliza para declarar un enum cuyos miembros son del tipo long. Observe que a pesar de que el tipo subyacente de la enumeracin es long, los miembros de la enumeracin todava deben convertirse explcitamente al tipo long mediante una conversin de tipos.
C#
public class EnumTest2 { enum Range : long { Max = 2147483648L, Min = 255L }; static void Main() { long x = (long)Range.Max; long y = (long)Range.Min; Console.WriteLine("Max = {0}", x); Console.WriteLine("Min = {0}", y); } } /* Output: Max = 2147483648 Min = 255 */

El ejemplo de cdigo siguiente ilustra el uso y efecto del atributo System.FlagsAttribute en una declaracin enum.
C#
[Flags] public enum CarOptions { SunRoof = 0x01, Spoiler = 0x02,

FogLights = 0x04, TintedWindows = 0x08, } class FlagTest { static void Main() { CarOptions options = CarOptions.SunRoof | CarOptions.FogLights; Console.WriteLine(options); Console.WriteLine((int)options); } } /* Output: SunRoof, FogLights 5 */

Comentarios

Observe que si quita FlagsAttribute, el ejemplo generar lo siguiente: 5 5

Mtodos (Gua de programacin de C#)


Visual Studio 2008

Actualizacin: noviembre 2007 Un mtodo es un bloque de cdigo que contiene una serie de instrucciones. Los programas hacen que las instrucciones se ejecuten mediante una llamada al mtodo y la especificacin de los argumentos de mtodo necesarios. En C#, cada instruccin se ejecuta en el contexto de un mtodo. El mtodo Main es el punto de entrada de cada aplicacin C# al que llama Common Language Runtime (CLR) cuando se inicia el programa.
Nota:

En este tema se analizan los mtodos con nombre. Para obtener ms informacin sobre las funciones annimas, vea Funciones annimas (Gua de programacin de C#).
Firmas de mtodo

Los mtodos se declaran en una clase o estructura mediante la especificacin del nivel de acceso como public o private, modificadores opcionales como abstract o sealed, el valor devuelto, el nombre del mtodo y cualquier parmetro de mtodo. Todos esos elementos constituyen la firma del mtodo.
Nota:

Un tipo de valor devuelto desde un mtodo no forma parte de su firma a efectos de la sobrecarga de mtodos. Sin embargo, s forma parte de la firma del mtodo a la hora de determinar la compatibilidad entre un delegado y el mtodo al que apunta. Los parmetros del mtodo se encierran entre parntesis y se separan por comas. Los parntesis vacos indican que el mtodo no requiere ningn parmetro. Esta clase contiene tres mtodos:
C#
abstract class Motorcycle { // Anyone can call this. public void StartEngine() {/* Method statements here */ } // Only derived classes can call this. protected void AddGas(int gallons) { /* Method statements here */ } // Derived classes can override the base class implementation.

public virtual int Drive(int miles, int speed) { /* Method statements here */ return 1; } // Derived classes must implement this. public abstract double GetTopSpeed(); }

Acceso al mtodo

Llamar a un mtodo de un objeto es como obtener acceso a un campo. Despus del nombre de objeto, agregue un punto, el nombre del mtodo y parntesis. Los argumentos se colocan entre parntesis y separados por comas. Por tanto, se puede llamar a los mtodos de la clase Motorcycle como en el ejemplo siguiente:
C#
class TestMotorcycle : Motorcycle { public override double GetTopSpeed() { return 108.4; } static void Main() { TestMotorcycle moto = new TestMotorcycle(); moto.StartEngine(); moto.AddGas(15); moto.Drive(5, 20); double speed = moto.GetTopSpeed(); Console.WriteLine("My top speed is {0}", speed); } }

Parmetros y argumentos de mtodo

La definicin de mtodo especifica los nombres y tipos de cualquier parmetro que se requiera. Cuando el cdigo de llamada llama al mtodo, proporciona valores concretos denominados argumentos a cada parmetro. Los argumentos deben ser compatibles con el tipo de parmetro pero el nombre del argumento (si existe) que se utiliza en el cdigo de llamada no tiene que ser igual que el nombre de parmetro definido en el mtodo. Por ejemplo:

C#
public void Caller() { int numA = 4; // Call with an int variable. int productA = Square(numA); int numB = 32; // Call with another int variable. int productB = Square(numB); // Call with an integer literal. int productC = Square(12); // Call with an expression that evaulates to int. productC = Square(productA * 3); } int Square(int i) { // Store input argument in a local variable. int input = i; return input * input; }

Pasar por referencia y pasar por valor

De forma predeterminada, cuando un tipo de valor se pasa a un mtodo, se pasa una copia en lugar del propio objeto. Por tanto, los cambios en el argumento no tienen ningn efecto en la copia original del mtodo de llamada. Puede pasar un tipo de valor por referencia mediante la palabra clave ref. Para obtener ms informacin, vea Pasar parmetros de tipo de valor (Gua de programacin de C#). Para obtener una lista de los tipos de valor integrados, vea Tabla de tipos de valores (Referencia de C#). Los tipos de referencia se pasan por referencia. Cuando un objeto de un tipo de referencia se pasa a un mtodo, la referencia seala al objeto original, no a una copia. Los cambios realizados a travs de esta referencia se reflejarn por consiguiente en el mtodo de llamada. Un tipo de referencia se crea utilizando la palabra clave class como en el ejemplo siguiente:
C#
public class SampleRefType { public int value; }

Ahora, si un objeto basado en este tipo se pasa a un mtodo, se pasar por referencia. Por ejemplo:
C#
public static void TestRefType() { SampleRefType rt = new SampleRefType(); rt.value = 44; ModifyObject(rt); Console.WriteLine(rt.value); } static void ModifyObject(SampleRefType obj) { obj.value = 33; }

Este ejemplo hace esencialmente lo mismo que el ejemplo anterior. Pero, como se utiliza un tipo de referencia, la modificacin realizada por ModifyObject se efecta en el objeto creado en el mtodo TestRefType. Por consiguiente, el mtodo TestRefType mostrar el valor 33. Para obtener ms informacin, vea Pasar parmetros Reference-Type (Gua de programacin de C#) y Tipos de referencia (Referencia de C#).
Valores devueltos

Los mtodos pueden devolver un valor al llamador. Si el tipo de valor devuelto (el que aparece antes del nombre del mtodo) no es void, el mtodo puede devolver el valor mediante la palabra clave return. Una instruccin con la palabra clave return seguida de un valor que se corresponda con el tipo de valor devuelto devolver ese valor al llamador del mtodo. La palabra clave return tambin detiene la ejecucin del mtodo. Si el tipo de valor devuelto es void, una instruccin return sin ningn valor sigue siendo til para detener la ejecucin del mtodo. Sin la palabra clave return, el mtodo detendr la ejecucin cuando llegue al fin del bloque de cdigo. Es necesario que los mtodos con un tipo de valor devuelto no nulo utilicen la palabra clave return para devolver un valor. Por ejemplo, estos dos mtodos utilizan la palabra clave return para devolver enteros:
C#
class SimpleMath { public int AddTwoNumbers(int number1, int number2) { return number1 + number2; }

public int SquareANumber(int number) { return number * number; } }

Para emplear un valor devuelto desde un mtodo, el mtodo que realiza la llamada puede utilizar la propia llamada al otro mtodo en cualquier parte donde pueda aparecer un valor del mismo tipo. El valor devuelto tambin se puede asignar a una variable. Por ejemplo, los dos ejemplos de cdigo siguientes logran el mismo objetivo:
C#
int result = obj.AddTwoNumbers(1, 2); obj.SquareANumber(result);

C#
obj.SquareANumber(obj.AddTwoNumbers(1, 2));

El uso de una variable local, en este caso result, para almacenar un valor es opcional. Puede ayudar a la legibilidad del cdigo o puede ser necesaria si necesita almacenar el valor original del argumento para todo el mbito del mtodo. Para obtener ms informacin, vea return (Referencia de C#).

Estructuras (Gua de programacin de C#)


Visual Studio 2008

Actualizacin: noviembre 2007 Las estructuras se definen mediante la palabra clave struct, por ejemplo:
C#
public struct PostalAddress { // Fields, properties, methods and events go here... }

Casi todas las estructuras comparten la misma sintaxis que las clases, aunque estn ms limitadas que stas:

Dentro de una declaracin de estructura, los campos no se pueden inicializar a menos que se declaren como constantes o estticos. Una estructura no puede declarar un constructor predeterminado (es decir, un constructor sin parmetros) ni un destructor. Las estructuras no pueden heredar de clases u otras estructuras. Las estructuras se copian en la asignacin. Cuando se asigna una estructura a una nueva variable, se copian todos los datos, y cualquier modificacin que se realice en la nueva copia no afecta a los datos de la copia original. Las estructuras son tipos de valor y las clases son tipos de referencia. A diferencia de las clases, se pueden crear instancias de las estructuras sin utilizar un operador new. Las estructuras pueden declarar constructores que tienen parmetros. Una estructura no puede heredar de otra estructura o clase, ni puede ser la base de una clase. Todas las estructuras heredan directamente de System.ValueType, que hereda de System.Object. Una estructura puede implementar interfaces. Una estructura se puede utilizar como tipo que acepta valores null y se le puede asignar un valor null.

Utilizar estructuras (Gua de programacin de C#)


Visual Studio 2008

Actualizacin: Julio de 2008 El tipo struct es adecuado para representar objetos de poca complejidad, como Point, Rectangle y Color. Aunque resulta igual de adecuado representar un punto como una clase con propiedades autoimplementadas, una estructura puede resultar ms eficaz en algunos escenarios. Por ejemplo, si declara una matriz de 1000 objetos Point, asignar memoria adicional para hacer referencia a cada objeto; en este caso, una estructura sera menos costosa. Dado que .NET Framework contiene un objeto llamado Point, la estructura de este ejemplo se denomina "CoOrds".
C#
public struct CoOrds { public int x, y; public CoOrds(int p1, int p2) { x = p1; y = p2; } }

Es un error definir un constructor predeterminado (sin parmetros) para una estructura. Tambin es un error inicializar un campo de instancia en el cuerpo de una estructura. Solo puede inicializar los miembros de una estructura utilizando un constructor con parmetros o mediante el acceso de forma individual a los miembros una vez declarada la estructura. Los miembros privados o inaccesibles de cualquier modo solo se pueden inicializar en un constructor. Cuando se crea un objeto struct mediante el operador new, se crea y se llama al constructor apropiado. A diferencia de las clases, es posible crear instancias de las estructuras sin utilizar el operador new. En este caso, no hay ninguna llamada de constructor, lo que hace que la asignacin sea ms eficaz. Sin embargo, los campos permanecern sin asignar y el objeto no se podr utilizar hasta haber inicializado todos los campos. Cuando una estructura contiene un tipo de referencia como miembro, el constructor predeterminado del miembro se debe invocar explcitamente, de lo contrario el miembro seguir sin asignar y no se podr utilizar la estructura. (Esto produce el error del compilador CS0171.)

A diferencia de las clases, para las estructuras no existe herencia. Una estructura no puede heredar de otra estructura o clase, ni puede ser la base de una clase. Sin embargo, las estructuras heredan de la clase base Object. Una estructura puede implementar interfaces del mismo modo que las clases. A diferencia de C++, no se puede declarar una clase mediante la palabra clave struct. En C#, las clases y las estructuras son semnticamente diferentes. Una estructura es un tipo de valor, mientras que una clase es un tipo de referencia. Para obtener ms informacin, vea Tipos de valores (Referencia de C#). A menos que se necesite semntica de tipo de referencia, el sistema puede controlar ms eficazmente las clases pequeas si se definen como estructuras.
Ejemplo 1

Description

Este ejemplo muestra la inicializacin de tipo struct mediante constructores predeterminados y constructores con parmetros.
Code C#
public struct CoOrds { public int x, y; public CoOrds(int p1, int p2) { x = p1; y = p2; } }

C#
// Declare and initialize struct objects. class TestCoOrds { static void Main() { // Initialize: CoOrds coords1 = new CoOrds(); CoOrds coords2 = new CoOrds(10, 10); // Display results: Console.Write("CoOrds 1: "); Console.WriteLine("x = {0}, y = {1}", coords1.x, coords1.y);

Console.Write("CoOrds 2: "); Console.WriteLine("x = {0}, y = {1}", coords2.x, coords2.y); // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } /* Output: CoOrds 1: x = 0, y = 0 CoOrds 2: x = 10, y = 10 */

Ejemplo 2

Description

Este ejemplo muestra una caracterstica exclusiva de las estructuras. Crea un objeto CoOrds sin utilizar el operador new. Si se reemplaza la palabra struct por la palabra class, el programa no se compilar.
Code C#
public struct CoOrds { public int x, y; public CoOrds(int p1, int p2) { x = p1; y = p2; } }

C#
// Declare a struct object without "new." class TestCoOrdsNoNew { static void Main() { // Declare an object: CoOrds coords1; // Initialize: coords1.x = 10; coords1.y = 20; // Display results:

Console.Write("CoOrds 1: "); Console.WriteLine("x = {0}, y = {1}", coords1.x, coords1.y); // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } // Output: CoOrds 1: x = 10, y = 20

Excepciones
.NET Framework 4 Este tema es aplicable a Windows Workflow Foundation 4.

Los flujos de trabajo pueden usar la actividad TryCatch para controlar excepciones que se producen durante la ejecucin de un flujo de trabajo. Se pueden controlar estas excepciones o se pueden volver a producir usando la actividad Rethrow. Las actividades de la seccin Finally se ejecutan cuando la seccin Try o la seccin Catches se hayan completado. Los flujos de trabajo hospedados por una instancia WorkflowApplication tambin pueden usar el controlador de eventos OnUnhandledException para controlar excepciones no controladas por una actividad TryCatch.

Causas de excepciones
En un flujo de trabajo, las excepciones se pueden generar de las maneras siguientes:

Un tiempo de espera de transacciones en TransactionScope. Una excepcin explcita iniciada por el flujo de trabajo mediante la actividad Throw. Una excepcin .NET Framework 4 iniciada desde una actividad. Una excepcin iniciada desde el cdigo externo, como bibliotecas, componentes o servicios que se usan en el flujo de trabajo.

Controlar las excepciones


Si la actividad inicia una excepcin y no est controlada, el comportamiento predeterminado es finalizar la instancia de flujo de trabajo. Si un controlador OnUnhandledException personalizado est presente, puede invalidar este comportamiento predeterminado. Este controlador da al autor de host de flujo de trabajo la oportunidad de proporcionar el control adecuado, como el registro personalizado o la anulacin, cancelacin o finalizacin del flujo de trabajo. En el ejemplo siguiente se invoca un flujo de trabajo que produce una excepcin. El flujo de trabajo no controla la excepcin y se invoca el controlador de la propiedad OnUnhandledException. El objeto WorkflowApplicationUnhandledExceptionEventArgs se inspecciona para proporcionar informacin acerca de la excepcin y se termina el flujo de trabajo.
C#
Activity wf = new Sequence { Activities = {

new WriteLine { Text = "Starting the workflow." }, new Throw { Exception = new InArgument<Exception>((env) => new ApplicationException("Something unexpected happened.")) }, new WriteLine { Text = "Ending the workflow." } } }; WorkflowApplication wfApp = new WorkflowApplication(wf); wfApp.OnUnhandledException = delegate(WorkflowApplicationUnhandledExceptionEventArgs e) { // Display the unhandled exception. Console.WriteLine("OnUnhandledException in Workflow {0}\n{1}", e.InstanceId, e.UnhandledException.Message); Console.WriteLine("ExceptionSource: {0} - {1}", e.ExceptionSource.DisplayName, e.ExceptionSourceInstanceId); // Instruct the runtime to terminate the workflow. return UnhandledExceptionAction.Terminate; // Other choices are UnhandledExceptionAction.Abort and // UnhandledExceptionAction.Cancel }; wfApp.Run();

Administrar excepciones con la actividad TryCatch

La administracin de excepciones dentro de un flujo de trabajo se realiza mediante la actividad TryCatch. La actividad TryCatch tiene una coleccin de Catches de las actividades de Catch que se asocian con un tipo Exception concreto. Si la excepcin producida por una actividad incluida en la seccin Try de una actividad TryCatch coincide con la excepcin de una actividad Catch en la coleccin de Catches, se administrar la excepcin. Si se vuelve a producir explcitamente la excepcin o se produce una nueva, esta excepcin se pasa a la actividad principal. Se ejecutarn las actividades en la seccin Finally cuando la seccin Try o la seccin Catches se hayan completado. El siguiente ejemplo de cdigo muestra una actividad TryCatch que administra un objeto ApplicationException que se produce en la seccin Try mediante una actividad Throw. El mensaje de la excepcin se escribe en la consola mediante la actividad Catch y, a continuacin, se escribe un mensaje en la consola de la seccin Finally.

C#
DelegateInArgument<ApplicationException> ex = new DelegateInArgument<ApplicationException>() { Name = "ex" }; Activity wf = new TryCatch { Try = new Throw() { Exception = new InArgument<Exception>((env) =>new ApplicationException("An ApplicationException was thrown.")) }, Catches = { new Catch<ApplicationException> { Action = new ActivityAction<ApplicationException> { Argument = ex, Handler = new WriteLine() { Text = new InArgument<string>((env) => ex.Get(env).Message) } } } }, Finally = new WriteLine() { Text = "Executing in Finally." } };

Control de excepciones contra compensacin

La diferencia entre el control de excepciones y la compensacin es que el primero se produce durante la ejecucin de una actividad. La compensacin, sin embargo, se produce despus de que una actividad se haya completado correctamente. El control de excepciones proporciona una oportunidad para limpiar despus de que la actividad produzca la excepcin, mientras la compensacin proporciona un mecanismo por el que se puede deshacer el trabajo terminado correctamente de una actividad completada previamente. Para obtener ms informacin, vea Compensation Programming Model.

.NET Class Library


The .NET Framework class library is a library of classes, interfaces, and value types that are included in the Microsoft .NET Framework SDK. This library provides access to system functionality and is designed to be the foundation on which .NET Framework applications, components, and controls are built.

Namespaces
The .NET Framework class library provides the following namespaces: Microsoft.CSharp Contains classes that support compilation and code generation using the C# language. Microsoft.JScript Contains classes that support compilation and code generation using the JScript language. Microsoft.VisualBasic Contains classes that support compilation and code generation using the Visual Basic .NET language. Microsoft.Vsa Contains interfaces that allow you to integrate script for the .NET Framework script engines into applications, and to compile and execute code at run time. Microsoft.Win32 Provides two types of classes: those that handle events raised by the operating system and those that manipulate the system registry. System Contains fundamental classes and base classes that define commonly used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. Other classes provide services supporting data type conversion, method parameter manipulation, mathematics, remote and local program invocation, application environment management, and supervision of managed and unmanaged applications. System.CodeDom Contains classes that can be used to represent the elements and structure of a source code document. These elements can be used to model the structure of a source code document that can be output as source code in a supported language using the functionality provided by the System.CodeDom.Compiler namespace. System.CodeDom.Compiler Contains types for managing the generation and compilation of source code in supported programming languages. Code generators can each produce source code in a particular programming language based on the structure of Code Document

Object Model (CodeDOM) source code models consisting of elements provided by the System.CodeDom namespace. System.Collections Contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hashtables and dictionaries. System.Collections.Specialized Contains specialized and strongly typed collections; for example, a linked list dictionary, a bit vector, and collections that contain only strings. System.ComponentModel Provides classes that are used to implement the run-time and design-time behavior of components and controls. This namespace includes the base classes and interfaces for implementing attributes and type converters, binding to data sources, and licensing components. System.ComponentModel.Design Contains classes that developers can use to build custom design-time behavior for components and user interfaces for configuring components at design time. The design time environment provides systems that enable developers to arrange components and configure their properties. System.ComponentModel.Design.Serialization Provides types that support customization and control of serialization at design time. System.Configuration Provides classes and interfaces that allow you to programmatically access .NET Framework configuration settings and handle errors in configuration files (.config files). System.Configuration.Assemblies Contains classes that are used to configure an assembly. System.Configuration.Install Provides classes that allow you to write custom installers for your own components. The Installer class is the base class for all custom installers in the .NET Framework. System.Data Consists mostly of the classes that constitute the ADO.NET architecture. The ADO.NET architecture enables you to build components that efficiently manage data from multiple data sources. In a disconnected scenario (such as the Internet), ADO.NET provides the tools to request, update, and reconcile data in multiple tier systems. The ADO.NET architecture is also implemented in client applications, such as Windows Forms, or HTML pages created by ASP.NET. System.Data.Common Contains classes shared by the .NET Framework data providers. A .NET Framework data provider describes a collection of classes used to access a data source, such as a database, in the managed space. System.Data.Odbc Encapsulates the .NET Framework Data Provider for ODBC. A .NET Framework data provider describes a collection of classes used to access a data source, such as a database, in the managed space. Using the OdbcDataAdapter class, you can fill a memory-resident DataSet, which you can use to query and update the data source.

For additional information about how to use this namespace, see the OdbcDataReader, the OdbcCommand, and the OdbcConnection classes. Note: This namespace is supported only in version 1.1 of the .NET Framework. System.Data.OleDb Encapsulates the .NET Framework Data Provider for OLE DB. The .NET Framework Data Provider for OLE DB describes a collection of classes used to access an OLE DB data source in the managed space. System.Data.OracleClient Encapsulates the .NET Framework Data Provider for Oracle. The .NET Framework Data Provider for Oracle describes a collection of classes used to access an Oracle data source in the managed space. Note: This namespace is supported only in version 1.1 of the .NET Framework. System.Data.SqlClient Encapsulates the .NET Framework Data Provider for SQL Server. The .NET Framework Data Provider for SQL Server describes a collection of classes used to access a SQL Server database in the managed space. System.Data.SqlServerCE Describes a collection of classes that can be used to access a database in SQL Server CE from Windows CE-based devices in the managed environment. With this namespace you can create SQL Server CE databases on a device and also establish connections to SQL Server databases that are on a device or on a remote server. Note: This namespace is supported only in version 1.1 of the .NET Framework. System.Data.SqlTypes Provides classes for native data types within SQL Server. These classes provide a safer, faster alternative to other data types. Using the classes in this namespace helps prevent type conversion errors caused in situations where loss of precision could occur. Because other data types are converted to and from SqlTypes behind the scenes, explicitly creating and using objects within this namespace results in faster code as well. System.Diagnostics Provides classes that allow you to interact with system processes, event logs, and performance counters. This namespace also provides classes that allow you to debug your application and to trace the execution of your code. For more information, see the Trace and Debug classes. System.Diagnostics.SymbolStore Provides classes that allow you to read and write debug symbol information, such as source line to Microsoft intermediate language (MSIL) maps. Compilers targeting the .NET Framework can store the debug symbol information into programmer's database (PDB) files. Debuggers and code profiler tools can read the debug symbol information at run time. System.DirectoryServices Provides easy access to Active Directory from managed code. The namespace contains two component classes, DirectoryEntry and DirectorySearcher, which use

the Active Directory Services Interfaces (ADSI) technology. ADSI is the set of interfaces that Microsoft provides as a flexible tool for working with a variety of network providers. ADSI gives the administrator the ability to locate and manage resources on a network with relative ease, regardless of the network's size. System.Drawing Provides access to GDI+ basic graphics functionality. More advanced functionality is provided in the System.Drawing.Drawing2D, System.Drawing.Imaging, and System.Drawing.Text namespaces. System.Drawing.Design Contains classes that extend design-time user interface (UI) logic and drawing. You can further extend this design-time functionality to create custom toolbox items, type-specific value editors that can edit and graphically represent values of their supported types, or type converters that can convert values between certain types. This namespace provides the basic frameworks for developing extensions to the design-time UI. System.Drawing.Drawing2D Provides advanced 2-dimensional and vector graphics functionality. This namespace includes the gradient brushes, the Matrix class (used to define geometric transforms), and the GraphicsPath class. System.Drawing.Imaging Provides advanced GDI+ imaging functionality. Basic graphics functionality is provided by the System.Drawing namespace. System.Drawing.Printing Provides print-related services. Typically, you create a new instance of the PrintDocument class, set the properties that describe what to print, and call the Print method to actually print the document. System.Drawing.Text Provides advanced GDI+ typography functionality. Basic graphics functionality is provided by the System.Drawing namespace. The classes in this namespace allow users to create and use collections of fonts. System.EnterpriseServices Provides an important infrastructure for enterprise applications. COM+ provides a services architecture for component programming models deployed in an enterprise environment. This namespace provides .NET Framework objects with access to COM+ services, making the .NET Framework objects more practical for enterprise applications. System.EnterpriseServices.CompensatingResourceManager Provides classes that allow you to use a Compensating Resource Manager (CRM) in managed code. A CRM is a service provided by COM+ that enables you to include non-transactional objects in Microsoft Distributed Transaction Coordinator (DTC) transactions. Although CRMs do not provide the capabilities of a full resource manager, they do provide transactional atomicity (all-or-nothing behavior) and durability through the recovery log. System.EnterpriseServices.Internal Provides infrastructure support for COM+ services. The classes and interfaces in this namespace are specifically intended to support calls into System.EnterpriseServices from the unmanaged COM+ classes.

System.Globalization Contains classes that define culture-related information, including the language, the country/region, the calendars in use, the format patterns for dates, currency, and numbers, and the sort order for strings. These classes are useful for writing globalized (internationalized) applications. System.IO Contains types that allow synchronous and asynchronous reading and writing on data streams and files. System.IO.IsolatedStorage Contains types that allow the creation and use of isolated stores. With these stores, you can read and write data that less trusted code cannot access and prevent the exposure of sensitive information that can be saved elsewhere on the file system. Data is stored in compartments that are isolated by the current user and by the assembly in which the code exists. System.Management Provides access to a rich set of management information and management events about the system, devices, and applications instrumented to the Windows Management Instrumentation (WMI) infrastructure. System.Management.Instrumentation Provides the classes necessary for instrumenting applications for management and exposing their management information and events through WMI to potential consumers. Consumers such as Microsoft Application Center or Microsoft Operations Manager can then manage your application easily, and monitoring and configuring of your application is available for administrator scripts or other applications, both managed as well as unmanaged. System.Messaging Provides classes that allow you to connect to, monitor, and administer message queues on the network and send, receive, or peek messages. System.Net Provides a simple programming interface for many of the protocols used on networks today. The WebRequest and WebResponse classes form the basis of what are called pluggable protocols, an implementation of network services that enables you to develop applications that use Internet resources without worrying about the specific details of the individual protocols. System.Net.Sockets Provides a managed implementation of the Windows Sockets (Winsock) interface for developers who need to tightly control access to the network. System.Reflection Contains classes and interfaces that provide a managed view of loaded types, methods, and fields, with the ability to dynamically create and invoke types. System.Reflection.Emit Contains classes that allow a compiler or tool to emit metadata and Microsoft intermediate language (MSIL) and optionally generate a PE file on disk. The primary clients of these classes are script engines and compilers. System.Resources Provides classes and interfaces that allow developers to create, store, and manage various culture-specific resources used in an application.

System.Runtime.CompilerServices Provides functionality for compiler writers using managed code to specify attributes in metadata that affect the run-time behavior of the common language runtime. The classes in this namespace are for compiler writers use only. System.Runtime.InteropServices Provides a wide variety of members that support COM interop and platform invoke services. If you are unfamiliar with these services, see Interoperating with Unmanaged Code . System.Runtime.InteropServices.CustomMarshalers Supports the .NET infrastructure and is not intended to be used directly from your code. System.Runtime.InteropServices.Expando Contains the IExpando interface which allows modification of an object by adding or removing its members. System.Runtime.Remoting Provides classes and interfaces that allow developers to create and configure distributed applications. System.Runtime.Remoting.Activation Provides classes and objects that support server and client activation of remote objects. System.Runtime.Remoting.Channels Contains classes that support and handle channels and channel sinks, which are used as the transport medium when a client calls a method on a remote object. System.Runtime.Remoting.Channels.Http Contains channels that use the HTTP protocol to transport messages and objects to and from remote locations. By default, the HTTP channels encode objects and method calls in SOAP format for transmission, but other encoding and decoding formatter sinks can be specified in the configuration properties of a channel. System.Runtime.Remoting.Channels.Tcp Contains channels that use the TCP protocol to transport messages and objects to and from remote locations. By default, the TCP channels encode objects and method calls in binary format for transmission, but other encoding and decoding formatter sinks can be specified in the configuration properties of a channel. System.Runtime.Remoting.Contexts Contains objects that define the contexts all objects reside within. A context is an ordered sequence of properties that defines an environment for the objects within it. Contexts are created during the activation process for objects that are configured to require certain automatic services such synchronization, transactions, just-in-time (JIT) activation, security, and so on. Multiple objects can live inside a context. System.Runtime.Remoting.Lifetime Contains classes that manage the lifetime of remote objects. Traditionally, distributed garbage collection uses reference counts and pinging for control over the lifetime of objects. This works well when there are a few clients per service, but doesn't scale well when there are thousands of clients per service. The remoting lifetime service associates a lease with each service, and deletes a service when its lease time expires. The lifetime service can take on the function of a traditional

distributed garbage collector, and it also adjusts well when the numbers of clients per server increases. System.Runtime.Remoting.Messaging Contains classes used to create and remote messages. The remoting infrastructure uses messages to communicate with remote objects. Messages are used to transmit remote method calls, to activate remote objects, and to communicate information. A message object carries a set of named properties, including action identifiers, envoy information, and parameters. System.Runtime.Remoting.Metadata Contains classes and attributes that can be used to customize generation and processing of SOAP for objects and fields. The classes of this namespace can be used to indicate the SOAPAction, type output, XML element name, and the method XML namespace URI. System.Runtime.Remoting.Metadata.W3cXsd2001 Contains the XML Schema Definition (XSD) defined by the World Wide Web Consortium (W3C) in 2001. The XML Schema Part2: Data types specification from W3C identifies format and behavior of various data types. This namespace contains wrapper classes for the data types that conform to the W3C specification. All date and time types conform to the ISO standards specification. System.Runtime.Remoting.MetadataServices Contains the classes used by the Soapsuds.exe command line tool and the user code to convert metadata to and from XML schema for the remoting infrastructure. System.Runtime.Remoting.Proxies Contains classes that control and provide functionality for proxies. A proxy is a local object that is an image of a remote object. Proxies enable clients to access objects across remoting boundaries. System.Runtime.Remoting.Services Contains service classes that provide functionality to the .NET Framework. System.Runtime.Serialization Contains classes that can be used for serializing and deserializing objects. Serialization is the process of converting an object or a graph of objects into a linear sequence of bytes for either storage or transmission to another location. Deserialization is the process of taking in stored information and recreating objects from it. System.Runtime.Serialization.Formatters Provides common enumerations, interfaces, and classes that are used by serialization formatters. System.Runtime.Serialization.Formatters.Binary Contains the BinaryFormatter class, which can be used to serialize and deserialize objects in binary format. System.Runtime.Serialization.Formatters.Soap Contains the SoapFormatter class, which can be used to serialize and deserialize objects in the SOAP format. System.Security Provides the underlying structure of the .NET Framework security system, including base classes for permissions. System.Security.Cryptography

Provides cryptographic services, including secure encoding and decoding of data, as well as many other operations, such as hashing, random number generation, and message authentication. System.Security.Cryptography.X509Certificates Contains the common language runtime implementation of the Authenticode X.509 v.3 certificate. This certificate is signed with a private key that uniquely and positively identifies the holder of the certificate. System.Security.Cryptography.Xml Contains classes to support the creation and validation of XML digital signatures. The classes in this namespace implement the World Wide Web Consortium Recommendation, "XML-Signature Syntax and Processing", described at http://www.w3.org/TR/xmldsig-core/. System.Security.Permissions Defines classes that control access to operations and resources based on policy. System.Security.Policy Contains code groups, membership conditions, and evidence. These three types of classes are used to create the rules applied by the .NET Framework security policy system. Evidence classes are the input to security policy and membership conditions are the switches; together these create policy statements and determine the granted permission set. Policy levels and code groups are the structure of the policy hierarchy. Code groups are the encapsulation of a rule and are arranged hierarchically in a policy level. System.Security.Principal Defines a principal object that represents the security context under which code is running. System.ServiceProcess Provides classes that allow you to implement, install, and control Windows service applications. Services are long-running executables that run without a user interface. Implementing a service involves inheriting from the ServiceBase class and defining specific behavior to process when start, stop, pause, and continue commands are passed in, as well as custom behavior and actions to take when the system shuts down. System.Text Contains classes representing ASCII, Unicode, UTF-7, and UTF-8 character encodings; abstract base classes for converting blocks of characters to and from blocks of bytes; and a helper class that manipulates and formats String objects without creating intermediate instances of String. System.Text.RegularExpressions Contains classes that provide access to the .NET Framework regular expression engine. The namespace provides regular expression functionality that can be used from any platform or language that runs within the Microsoft .NET Framework. System.Threading Provides classes and interfaces that enable multithreaded programming. In addition to classes for synchronizing thread activities and access to data (Mutex, Monitor, Interlocked, AutoResetEvent, and so on), this namespace includes a ThreadPool class that allows you to use a pool of system-supplied threads, and a Timer class that executes callback methods on thread pool threads.

System.Timers Provides the Timer component, which allows you to raise an event on a specified interval. System.Web Supplies classes and interfaces that enable browser-server communication. This namespace includes the HTTPRequest class that provides extensive information about the current HTTP request, the HTTPResponse class that manages HTTP output to the client, and the HTTPServerUtility object that provides access to server-side utilities and processes. System.Web also includes classes for cookie manipulation, file transfer, exception information, and output cache control. System.Web.Caching Provides classes for caching frequently used data on the server. This includes the Cache class, a dictionary that allows you to store arbitrary data objects, such as hash tables and data sets. It also provides expiration functionality for those objects, and methods that allow you to add and removed the objects. You can also add the objects with a dependency upon other files or cache entries, and perform a callback to notify your application when an object is removed from the Cache. System.Web.Configuration Contains classes that are used to set up ASP.NET configuration. System.Web.Hosting Provides the functionality for hosting ASP.NET applications from managed applications outside of Microsoft Internet Information Services (IIS). System.Web.Mail Contains classes that enable you to construct and send messages using the CDOSYS Message component. The mail message is delivered through either the SMTP mail service built into Microsoft Windows 2000 or through an arbitrary SMTP server. The classes in this namespace can be used either from ASP.NET or from any managed application. System.Web.Mobile Contains the core capabilities, including authentication and error-handling, required for building ASP.NET mobile Web applications. System.Web.Security Contains classes that are used to implement ASP.NET security in Web server applications. System.Web.Services Consists of the classes that enable you to create XML Web services using ASP.NET and XML Web service clients. XML Web services are applications that provide the ability to exchange messages in a loosely coupled environment using standard protocols such as HTTP, XML, XSD, SOAP, and WSDL. XML Web services enable the building of modular applications within and across companies in heterogeneous environments making them interoperable with a broad variety of implementations, platforms and devices. The SOAP-based XML messages of these applications can have well-defined (structured and typed), or loosely defined parts (using arbitrary XML). The ability of the messages to evolve over time without breaking the protocol is fundamental to the flexibility and robustness of XML Web services as a building block for the future of the Web. System.Web.Services.Configuration

Consists of the classes that configure how XML Web services created using ASP.NET run. System.Web.Services.Description Consists of the classes that enable you to publicly describe an XML Web service by using the Web Services Description Language (WSDL). Each class in this namespace corresponds to a specific element in the WSDL specification, and the class hierarchy corresponds to the XML structure of a valid WSDL document. System.Web.Services.Discovery Consists of the classes that allows XML Web service clients to locate the available XML Web services on a Web server through a process called XML Web services Discovery. System.Web.Services.Protocols Consists of the classes that define the protocols used to transmit data across the wire during the communication between XML Web service clients and XML Web services created using ASP.NET. System.Web.SessionState Supplies classes and interfaces that enable storage of data specific to a single client within a Web application on the server. The session state data is used to give the client the appearance of a persistent connection with the application. State information can be stored within local process memory or, for Web farm configurations, out-of-process using either the ASP.NET State Service or a SQL Server database. System.Web.UI Provides classes and interfaces that allow you to create controls and pages that will appear in your Web applications as user interface on a Web page. This namespace includes the Control class, which provides all controls, whether HTML, Web, or User controls, with a common set of functionality. It also includes the Page control, which is generated automatically whenever a request is made for a page in your Web application. Also provided are classes which provide the Web Forms Server Controls data binding functionality, the ability to save the view state of a given control or page, as well as parsing functionality for both programmable and literal controls. System.Web.UI.Design Contains classes that can be used to extend design-time support for Web Forms. System.Web.UI.Design.WebControls Contains classes that can be used to extend design-time support for Web server controls. System.Web.UI.HtmlControls Consists of a collection of classes that allow you to create HTML server controls on a Web Forms page. HTML server controls run on the server and map directly to standard HTML tags supported by most browsers. This allows you to programmatically control the HTML elements on a Web Forms page. System.Web.UI.MobileControls Contains a set of ASP.NET server controls that can intelligently render your application for different mobile devices. System.Web.UI.MobileControls.Adapters

Contains the core device adapter classes used by the ASP.NET mobile controls for device customization and extended device support. System.Web.UI.WebControls Contains classes that allow you to create Web server controls on a Web page. Web server controls run on the server and include form controls such as buttons and text boxes. They also include special purpose controls such as a calendar. Because Web server controls run on the server, you can programmatically control these elements. Web server controls are more abstract than HTML server controls. Their object model does not necessarily reflect HTML syntax. System.Windows.Forms Contains classes for creating Windows-based applications that take full advantage of the rich user interface features available in the Microsoft Windows operating system. System.Windows.Forms.Design Contains classes that support design-time configuration and behavior for Windows Forms components. These classes consist of: Designer classes that provide support for Windows Forms components, a set of design time services, UITypeEditor classes for configuring certain types of properties, and classes for importing ActiveX controls. System.Xml Provides standards-based support for processing XML. System.Xml.Schema Contains the XML classes that provide standards-based support for XML Schemas definition language (XSD) schemas. System.Xml.Serialization Contains classes that are used to serialize objects into XML format documents or streams. System.Xml.XPath Contains the XPath parser and evaluation engine. It supports the W3C XML Path Language (XPath) Version 1.0 Recommendation (www.w3.org/TR/xpath). System.Xml.Xsl Provides support for Extensible Stylesheet Transformation (XSLT) transforms. It supports the W3C XSL Transformations (XSLT) Version 1.0 Recommendation (www.w3.org/TR/xslt).

Usage
The class library reference documentation can be filtered by language, so that you can view syntax, descriptions, and examples for one language (either Visual Basic, C#, the Managed Extensions for C++, or JScript) or all four languages at once. To filter by language, click the filtering icon at the top of any reference page and select a language or choose Show All.

Exceptions

All instance methods in the class library throw an instance of NullReferenceException when an attempt is made to call the method and the underlying object holds a null reference. Because this exception can occur with any instance method, it is not explicitly listed in the reference documentation for each instance method. The class library documentation lists the other exceptions that each member throws along with a description of the condition under which it is thrown.

Thread Safety
All public static members (methods, properties, fields, and events) within the .NET Framework support concurrent access within a multithreaded environment. Therefore, any .NET Framework static member can be simultaneously invoked from two threads without encountering race conditions, deadlocks, or crashes. For all classes and structures in the .NET Framework, check the Thread Safety section in the API reference documentation to determine whether it is thread safe. If you want to use a class that is not thread-safe in a multithreaded environment, you must wrap an instance of the class with code that supplies the necessary synchronization constructs.

DESCRIPCION DE LOS NAMESPACES CON SUS CLASES NET FRAMEWORK 4

Microsoft.CSharp Namespace
.NET Framework 4

The Microsoft.CSharp namespace contains classes that support compilation and code generation using the C# language. Classes Description Provides access to instances of the C# code generator and code CSharpCodeProvider compiler. Class

________________________________________________________________________________

CSharpCodeProvider Class
.NET Framework 4

Provides access to instances of the C# code generator and code compiler.


Inheritance Hierarchy

System.Object System.MarshalByRefObject System.ComponentModel.Component System.CodeDom.Compiler.CodeDomProvider Microsoft.CSharp.CSharpCodeProvider Namespace: Microsoft.CSharp Assembly: System (in System.dll) Syntax

C#
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")] [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] public class CSharpCodeProvider : CodeDomProvider

The CSharpCodeProvider type exposes the following members.


Constructors

Show:

Inherited

Protected Description Initializes a new instance of the CSharpCodeProvider class. Initializes a new instance of the CSharpCodeProvider class by using the specified provider options.

Name CSharpCodeProvider() CSharpCodeProvider(IDictionary<String, String>) Top Properties

Show:

Inherited Name

Protected Description

CanRaiseEvents

Gets a value indicating whether the component can raise an event. (Inherited from Component.) Gets the IContainer that contains the Component. (Inherited from Component.) Gets a value that indicates whether the Component is currently in design mode. (Inherited from Component.) Gets the list of event handlers that are attached to this Component. (Inherited from Component.) Gets the file name extension to use when creating source code files. (Overrides CodeDomProvider.FileExtension.)

Container

DesignMode

Events

FileExtension

LanguageOptions Gets a language features identifier. (Inherited from CodeDomProvider.) Site Top Methods Gets or sets the ISite of the Component. (Inherited from Component.)

Show:

Inherited Name

Protected Description Compiles an assembly based on the System.CodeDom trees contained in the specified array of CodeCompileUnit objects, using the specified compiler settings. (Inherited from CodeDomProvider.) Compiles an assembly from the source code contained in the specified files, using the specified compiler settings. (Inherited from CodeDomProvider.)

CompileAssemblyFromDom

CompileAssemblyFromFile

Compiles an assembly from the specified array of strings CompileAssemblyFromSource containing source code, using the specified compiler settings. (Inherited from CodeDomProvider.) CreateCompiler Obsolete. Gets an instance of the C# code compiler. (Overrides CodeDomProvider.CreateCompiler().) Creates an escaped identifier for the specified value. (Inherited from CodeDomProvider.) Obsolete. Gets an instance of the C# code generator. (Overrides CodeDomProvider.CreateGenerator().) When overridden in a derived class, creates a new code generator using the specified file name for output. (Inherited from CodeDomProvider.) When overridden in a derived class, creates a new code generator using the specified TextWriter for output. (Inherited from CodeDomProvider.) Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.) Obsolete. When overridden in a derived class, creates a new

CreateEscapedIdentifier

CreateGenerator()

CreateGenerator(String)

CreateGenerator(TextWriter)

CreateObjRef

CreateParser

code parser. (Inherited from CodeDomProvider.) CreateValidIdentifier Creates a valid identifier for the specified value. (Inherited from CodeDomProvider.) Releases all resources used by the Component. (Inherited from Component.) Releases the unmanaged resources used by the Component and optionally releases the managed resources. (Inherited from Component.) Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Releases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.)

Dispose()

Dispose(Boolean)

Equals(Object)

Finalize

Generates code for the specified Code Document Object Model GenerateCodeFromCompileUn (CodeDOM) compilation unit and sends it to the specified text writer, using the specified options. (Inherited from it CodeDomProvider.) Generates code for the specified Code Document Object Model GenerateCodeFromExpression (CodeDOM) expression and sends it to the specified text writer, using the specified options. (Inherited from CodeDomProvider.) Generates code for the specified class member using the specified text writer and code generator options. (Overrides CodeDomProvider.GenerateCodeFromMember(CodeTypeMemb er, TextWriter, CodeGeneratorOptions).)

GenerateCodeFromMember

Generates code for the specified Code Document Object Model GenerateCodeFromNamespac (CodeDOM) namespace and sends it to the specified text writer, e using the specified options. (Inherited from CodeDomProvider.) Generates code for the specified Code Document Object Model GenerateCodeFromStatement (CodeDOM) statement and sends it to the specified text writer, using the specified options. (Inherited from CodeDomProvider.) GenerateCodeFromType Generates code for the specified Code Document Object Model (CodeDOM) type declaration and sends it to the specified text

writer, using the specified options. (Inherited from CodeDomProvider.) GetConverter Gets a TypeConverter for the specified type of object. (Overrides CodeDomProvider.GetConverter(Type).) Serves as a hash function for a particular type. (Inherited from Object.) Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.) Returns an object that represents a service provided by the Component or by its Container. (Inherited from Component.) Gets the Type of the current instance. (Inherited from Object.) Gets the type indicated by the specified CodeTypeReference. (Inherited from CodeDomProvider.) Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.) Returns a value that indicates whether the specified value is a valid identifier for the current language. (Inherited from CodeDomProvider.) Creates a shallow copy of the current Object. (Inherited from Object.) Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.) Compiles the code read from the specified text stream into a CodeCompileUnit. (Inherited from CodeDomProvider.) Returns a value indicating whether the specified code generation support is provided. (Inherited from CodeDomProvider.) Returns a String containing the name of the Component, if any. This method should not be overridden. (Inherited from Component.)

GetHashCode

GetLifetimeService

GetService GetType GetTypeOutput

InitializeLifetimeService

IsValidIdentifier

MemberwiseClone()

MemberwiseClone(Boolean)

Parse

Supports

ToString

Top Events

Show: Name Disposed Top Remarks

Inherited

Protected Description

Occurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)

This class provides methods that can be used to retrieve instances of the C# ICodeGenerator and ICodeCompiler implementations.
Note

This class contains a link demand and an inheritance demand at the class level that applies to all members. A SecurityException is thrown when either the immediate caller or the derived class does not have full-trust permission. For details about security demands, see Link Demands and Inheritance Demands.
Examples

The following example uses either the C# or Visual Basic code provider to compile a source file. The example checks the input file extension and uses the corresponding CSharpCodeProvider or VBCodeProvider for compilation. The input file is compiled into an executable file, and any compilation errors are displayed to the console.
C#
public static bool CompileExecutable(String sourceName) { FileInfo sourceFile = new FileInfo(sourceName); CodeDomProvider provider = null; bool compileOk = false; // Select the code provider based on the input file extension.

if (sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) == ".CS") { provider = CodeDomProvider.CreateProvider("CSharp"); } else if (sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) == ".VB") { provider = CodeDomProvider.CreateProvider("VisualBasic"); } else { Console.WriteLine("Source file must have a .cs or .vb extension"); } if (provider != null) { // Format the executable file name. // Build the output assembly path using the current directory // and <source>_cs.exe or <source>_vb.exe. String exeName = String.Format(@"{0}\{1}.exe", System.Environment.CurrentDirectory, sourceFile.Name.Replace(".", "_")); CompilerParameters cp = new CompilerParameters(); // Generate an executable instead of // a class library. cp.GenerateExecutable = true; // Specify the assembly file name to generate. cp.OutputAssembly = exeName; // Save the assembly as a physical file. cp.GenerateInMemory = false; // Set whether to treat all warnings as errors. cp.TreatWarningsAsErrors = false; // Invoke compilation of the source file. CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceName); if(cr.Errors.Count > 0) { // Display compilation errors. Console.WriteLine("Errors building {0} into {1}", sourceName, cr.PathToAssembly); foreach(CompilerError ce in cr.Errors) { Console.WriteLine(" {0}", ce.ToString()); Console.WriteLine(); } }

else { // Display a successful compilation message. Console.WriteLine("Source {0} built into {1} successfully.", sourceName, cr.PathToAssembly); } // Return the results of the compilation. if (cr.Errors.Count > 0) { compileOk = false; } else { compileOk = true; } } return compileOk; }

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

********************************************************************************

Microsoft.Win32 Namespace
.NET Framework 4 The Microsoft.Win32 namespace provides two types of classes: those that handle events raised by the operating system and those that manipulate the system registry. Classes Class CommonDialog Description An abstract base class for displaying common Win32 dialogs.

An abstract base class that encapsulates functionality FileDialog that is common to file dialogs, including OpenFileDialog and SaveFileDialog. FileDialogCustomPlace Represents an entry in a FileDialog custom place list. Defines the known folders for custom places in file FileDialogCustomPlaces dialog boxes. Defines a credential policy to be used for resource IntranetZoneCredentialPolicy requests that are made using WebRequest and its derived classes. Represents a common dialog box that allows a user to OpenFileDialog specify a filename for one or more files to open. PowerModeChangedEventArgs Provides data for the PowerModeChanged event. Provides RegistryKey objects that represent the root Registry keys in the Windows registry, and static methods to access key/value pairs. Represents a key-level node in the Windows registry. RegistryKey This class is a registry encapsulation. Represents a common dialog that allows the user to specify a filename to save a file as. SaveFileDialog SaveFileDialog cannot be used by an application that is executing under partial trust. SessionEndedEventArgs Provides data for the SessionEnded event. SessionEndingEventArgs Provides data for the SessionEnding event. SessionSwitchEventArgs Provides data for the SessionSwitch event. Provides access to system event notifications. This SystemEvents class cannot be inherited. TimerElapsedEventArgs Provides data for the TimerElapsed event. UserPreferenceChangedEventArgs Provides data for the UserPreferenceChanged event. UserPreferenceChangingEventArgs Provides data for the UserPreferenceChanging event.

DESCRIPCION DE LAS CLASES DEL ESPACIO DE NOMBRES Microsoft.Win32

CommonDialog Class
.NET Framework 4 An abstract base class for displaying common Win32 dialogs. Inheritance Hierarchy

System.Object Microsoft.Win32.CommonDialog Microsoft.Win32.FileDialog Namespace: Microsoft.Win32 Assembly: PresentationFramework (in PresentationFramework.dll) Syntax

C#
[UIPermissionAttribute(SecurityAction.InheritanceDemand, Window = UIPermissionWindow.AllWindows)] public abstract class CommonDialog

The CommonDialog type exposes the following members.


Constructors

Show:

Inherited

Protected Description

Name CommonDialog Properties

Provides initialization for base class values when called by the constructor of a derived class.

Show: Name Tag

Inherited

Protected Description

Gets or sets an object associated with the dialog. This provides the ability to attach an arbitrary object to the dialog.

Methods

Show:

Inherited

Protected

Name CheckPermissionsToShowDialog

Description Determines whether sufficient permissions for displaying a dialog exist. Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.) Defines the common dialog box hook procedure that is overridden to add specific functionality to a common dialog box. Creates a shallow copy of the current Object. (Inherited from Object.) When overridden in a derived class, resets the properties of a common dialog to their default values. When overridden in a derived class, is called to display a particular type of Win32 common dialog. Displays a common dialog. Displays a common dialog. Returns a string that represents the current object. (Inherited from Object.)

Equals(Object)

Finalize

GetHashCode GetType HookProc

MemberwiseClone

Reset

RunDialog ShowDialog() ShowDialog(Window) ToString Version Information

.NET Framework
Supported in: 4, 3.5, 3.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements. Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

FileDialog Class
.NET Framework 4

An abstract base class that encapsulates functionality that is common to file dialogs, including OpenFileDialog and SaveFileDialog.
Inheritance Hierarchy

System.Object Microsoft.Win32.CommonDialog Microsoft.Win32.FileDialog Microsoft.Win32.OpenFileDialog Microsoft.Win32.SaveFileDialog Namespace: Microsoft.Win32 Assembly: PresentationFramework (in PresentationFramework.dll) Syntax

C#
public abstract class FileDialog : CommonDialog

The FileDialog type exposes the following members.


Constructors

Show: Name

Inherited

Protected Description

FileDialog Initializes a new instance of the FileDialog class. Properties

Show:

Inherited Name

Protected Description

AddExtension

Gets or sets a value indicating whether a file dialog automatically adds an extension to a file name if the user omits an extension. Gets or sets a value indicating whether a file dialog displays a warning if the user specifies a file name that does not exist. Gets or sets a value that specifies whether warnings are displayed if the user types invalid paths and file names. Gets or sets the list of custom places for file dialog boxes. Gets or sets a value that specifies the default extension string to use to filter the list of files that are displayed. Gets or sets a value indicating whether a file dialog returns either the location of the file referenced by a shortcut or the location of the shortcut file (.lnk). Gets or sets a string containing the full path of the file selected in a file dialog.

CheckFileExists

CheckPathExists CustomPlaces DefaultExt

DereferenceLinks FileName

FileNames Filter FilterIndex InitialDirectory Options

Gets an array that contains one file name for each selected file. Gets or sets the filter string that determines what types of files are displayed from either the OpenFileDialog or SaveFileDialog. Gets or sets the index of the filter currently selected in a file dialog. Gets or sets the initial directory that is displayed by a file dialog. Gets the Win32 common file dialog flags that are used by file dialogs for initialization.

RestoreDirectory This property is not implemented. SafeFileName SafeFileNames Tag Title ValidateNames Methods Gets a string that only contains the file name for the selected file. Gets an array that contains one safe file name for each selected file. Gets or sets an object associated with the dialog. This provides the ability to attach an arbitrary object to the dialog. (Inherited from CommonDialog.) Gets or sets the text that appears in the title bar of a file dialog. Gets or sets a value indicating whether the dialog accepts only valid Win32 file names.

Show:

Inherited Name

Protected Description Determines whether sufficient permissions for displaying a dialog exist. (Inherited from CommonDialog.) Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)

CheckPermissionsToShowDialog

Equals(Object)

Finalize

GetHashCode GetType

Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.) Defines the common file dialog hook procedure that is overridden to add common functionality to a file dialog. (Overrides CommonDialog.HookProc(IntPtr, Int32, IntPtr, IntPtr).) Creates a shallow copy of the current Object. (Inherited from Object.) Raises the FileOk event. Sets all properties of a file dialog back to their initial values. (Overrides CommonDialog.Reset().) RunDialog is called to display a file dialog in a derived class, such as OpenFileDialog and SaveFileDialog. (Overrides CommonDialog.RunDialog(IntPtr).) Displays a common dialog. (Inherited from CommonDialog.) Displays a common dialog. (Inherited from CommonDialog.) Returns a string that represents a file dialog. (Overrides Object.ToString().)

HookProc

MemberwiseClone OnFileOk Reset

RunDialog

ShowDialog() ShowDialog(Window) ToString Events

Show: Name FileOk

Inherited

Protected Description

Occurs when the user selects a file name by either clicking the Open button of the OpenFileDialog or the Save button of the SaveFileDialog.

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements. Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

FileDialogCustomPlace Class
.NET Framework 4

Represents an entry in a FileDialog custom place list.


Inheritance Hierarchy

System.Object Microsoft.Win32.FileDialogCustomPlace Namespace: Microsoft.Win32 Assembly: PresentationFramework (in PresentationFramework.dll) Syntax

C#
public sealed class FileDialogCustomPlace

The FileDialogCustomPlace type exposes the following members.


Constructors

Show:

Inherited Name

Protected Description Initializes a new instance of the FileDialogCustomPlace class with the specified known folder GUID. Initializes a new instance of the FileDialogCustomPlace class with the specified path.

FileDialogCustomPlace(Guid)

FileDialogCustomPlace(String) Properties

Show: Name

Inherited

Protected Description

KnownFolder Gets the GUID of the known folder for the custom place. Path Methods Gets the file path for the custom place.

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.)

Equals(Object)

Finalize

Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.)

GetHashCode GetType

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Remarks Returns a string that represents the current object. (Inherited from Object.)

Starting in Windows Vista, open and save file dialog boxes have a Favorite Links panel on the left side of the dialog box that allows the user to quickly navigate to a different location. These links are called custom places. This class allows you to modify the list that appears when your application uses a file dialog box. For the list of known folders for custom places, see FileDialogCustomPlaces.
Version Information

.NET Framework
Supported in: 4

.NET Framework Client Profile


Supported in: 4 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements. Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

FileDialogCustomPlaces Class
.NET Framework 4

Defines the known folders for custom places in file dialog boxes.
Inheritance Hierarchy

System.Object Microsoft.Win32.FileDialogCustomPlaces Namespace: Microsoft.Win32 Assembly: PresentationFramework (in PresentationFramework.dll) Syntax

C#
public static class FileDialogCustomPlaces

The FileDialogCustomPlaces type exposes the following members.


Properties

Name Contacts Cookies Desktop

Description Gets the Contacts folder for the current user. Gets the Internet cookies folder for the current user. Gets the folder for storing files on the desktop for the current user.

Documents Favorites LocalApplicationData Music Pictures ProgramFiles ProgramFilesCommon Programs RoamingApplicationData

Gets the Documents folder for the current user. Gets the Favorites folder for the current user. Gets the folder for application-specific data that is used by the current, non-roaming user. Gets the Music folder for the current user. Gets the Pictures folder for the current user. Gets the Program Files folder. Gets the folder for components that are shared across applications. Gets the folder that contains the program groups for the current user. Gets the folder for application-specific data for the current roaming user. Gets the folder that contains the Send To menu items for the current user. Gets the folder that contains the Start menu items for the current user. Gets the folder that corresponds to the Startup program group for the current user. Gets the System folder. Gets the folder for document templates for the current user.

SendTo StartMenu Startup System Templates Remarks

Custom places are available starting in Windows Vista.


Version Information

.NET Framework
Supported in: 4

.NET Framework Client Profile


Supported in: 4 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements. Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

IntranetZoneCredentialPolicy Class
.NET Framework 4

Defines a credential policy to be used for resource requests that are made using WebRequest and its derived classes.
Inheritance Hierarchy

System.Object Microsoft.Win32.IntranetZoneCredentialPolicy Namespace: Microsoft.Win32 Assembly: System (in System.dll) Syntax

C#

public class IntranetZoneCredentialPolicy : ICredentialPolicy

The IntranetZoneCredentialPolicy type exposes the following members.


Constructors

Show:

Inherited Name

Protected Description

IntranetZoneCredentialPolicy Initializes a new instance of the IntranetZoneCredentialPolicy class. Top Methods

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.) Creates a shallow copy of the current Object. (Inherited from Object.) Returns a Boolean that indicates whether the client's credentials are sent with a request for a resource that was made using WebRequest. Returns a string that represents the current object. (Inherited from Object.)

Equals(Object)

Finalize

GetHashCode GetType MemberwiseClone ShouldSendCredential

ToString Remarks

This policy allows credentials to be sent only if the requested resource is in the same domain as the client that is making the request. For many applications this is the optimal policy because it prevents network credentials from being sent with requests for resources that are not on the intranet.
Note

ICredentialPolicy policies are invoked only if the WebRequest or the WebProxy that is associated with the request has credentials that are not null. Setting this policy has no effect on requests that do not specify credentials. Use the AuthenticationManager.CredentialPolicy property to set the IntranetZoneCredentialPolicy policy. The IAuthenticationModule that handles authentication for the request will invoke the ShouldSendCredential method before performing the authentication. If the requested resource is in a different domain than the client, the ShouldSendCredential method returns false, and authentication is not performed. This policy affects all instances of WebRequest with non-null credentials in the current application domain. The policy cannot be overridden on individual requests.
Examples

The following code example demonstrates creating an instance of IntranetZoneCredentialPolicy and using it to set the credential policy for the application domain.
C#
public static void UseIntranetCredentialPolicy() { IntranetZoneCredentialPolicy policy = new IntranetZoneCredentialPolicy(); AuthenticationManager.CredentialPolicy = policy; }

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements. Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

OpenFileDialog Class
.NET Framework 4

Represents a common dialog box that allows a user to specify a filename for one or more files to open.
Inheritance Hierarchy

System.Object Microsoft.Win32.CommonDialog Microsoft.Win32.FileDialog Microsoft.Win32.OpenFileDialog Namespace: Microsoft.Win32 Assembly: PresentationFramework (in PresentationFramework.dll) XMLNS for XAML: Not mapped to an xmlns. Syntax

C#
public sealed class OpenFileDialog : FileDialog

XAML Copy
You cannot declare this managed class in XAML.

The OpenFileDialog type exposes the following members.


Constructors

Show:

Inherited

Protected Description

Name

OpenFileDialog Initializes a new instance of the OpenFileDialog class. Properties

Show:

Inherited Name

Protected Description

AddExtension

Gets or sets a value indicating whether a file dialog automatically adds an extension to a file name if the user omits an extension. (Inherited from FileDialog.) Gets or sets a value indicating whether a file dialog displays a warning if the user specifies a file name that does not exist. (Inherited from FileDialog.) Gets or sets a value that specifies whether warnings are displayed if the user types invalid paths and file names. (Inherited from FileDialog.) Gets or sets the list of custom places for file dialog boxes. (Inherited from FileDialog.) Gets or sets a value that specifies the default extension string to use to filter the list of files that are displayed. (Inherited from FileDialog.)

CheckFileExists

CheckPathExists

CustomPlaces

DefaultExt

Gets or sets a value indicating whether a file dialog returns either the location DereferenceLinks of the file referenced by a shortcut or the location of the shortcut file (.lnk). (Inherited from FileDialog.) FileName Gets or sets a string containing the full path of the file selected in a file dialog. (Inherited from FileDialog.) Gets an array that contains one file name for each selected file. (Inherited from FileDialog.) Gets or sets the filter string that determines what types of files are displayed from either the OpenFileDialog or SaveFileDialog. (Inherited from FileDialog.) Gets or sets the index of the filter currently selected in a file dialog. (Inherited from FileDialog.) Gets or sets the initial directory that is displayed by a file dialog. (Inherited from FileDialog.) Gets or sets an option indicating whether OpenFileDialog allows users to select multiple files. Gets the Win32 common file dialog flags that are used by file dialogs for initialization. (Inherited from FileDialog.) Gets or sets a value indicating whether the read-only check box displayed by OpenFileDialog is selected.

FileNames

Filter

FilterIndex

InitialDirectory

Multiselect

Options

ReadOnlyChecked

RestoreDirectory This property is not implemented. (Inherited from FileDialog.) SafeFileName Gets a string that only contains the file name for the selected file. (Inherited from FileDialog.) Gets an array that contains one safe file name for each selected file. (Inherited from FileDialog.) Gets or sets a value indicating whether OpenFileDialog contains a read-only check box. Gets or sets an object associated with the dialog. This provides the ability to attach an arbitrary object to the dialog. (Inherited from CommonDialog.) Gets or sets the text that appears in the title bar of a file dialog. (Inherited

SafeFileNames

ShowReadOnly

Tag Title

from FileDialog.) ValidateNames Methods Gets or sets a value indicating whether the dialog accepts only valid Win32 file names. (Inherited from FileDialog.)

Show:

Inherited Name

Protected Description Determines whether sufficient permissions for displaying a dialog exist. (Inherited from CommonDialog.) Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.) Defines the common file dialog hook procedure that is overridden to add common functionality to a file dialog. (Inherited from FileDialog.) Creates a shallow copy of the current Object. (Inherited from Object.) Raises the FileOk event. (Inherited from FileDialog.) Opens a read-only stream for the file that is selected by the user using OpenFileDialog. Creates an array that contains one read-only stream for each file selected by the user using OpenFileDialog.

CheckPermissionsToShowDialog

Equals(Object)

Finalize

GetHashCode GetType

HookProc

MemberwiseClone OnFileOk OpenFile

OpenFiles

Reset

Resets all OpenFileDialog properties to their default values. (Overrides FileDialog.Reset().) RunDialog is called to display a file dialog in a derived class, such as OpenFileDialog and SaveFileDialog. (Inherited from FileDialog.) Displays a common dialog. (Inherited from CommonDialog.) Displays a common dialog. (Inherited from CommonDialog.) Returns a string that represents a file dialog. (Inherited from FileDialog.)

RunDialog

ShowDialog() ShowDialog(Window) ToString Events

Show: Name FileOk

Inherited

Protected Description

Occurs when the user selects a file name by either clicking the Open button of the OpenFileDialog or the Save button of the SaveFileDialog. (Inherited from FileDialog.)

Remarks

The following figure shows an OpenFileDialog for Windows Vista.

Starting in Windows Vista, open and save file dialog boxes have a Favorite Links panel on the left side of the dialog box that allows the user to quickly navigate to a different location. These links are called custom places. Use the CustomPlaces property to set this list of links.
Examples

The following example shows how to create an OpenFileDialog that contains a default file name and extension type.
C#
// Configure open file dialog box Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.FileName = "Document"; // Default file name dlg.DefaultExt = ".txt"; // Default file extension dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension // Show open file dialog box Nullable<bool> result = dlg.ShowDialog(); // Process open file dialog box results if (result == true) { // Open document

string filename = dlg.FileName; }

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements. Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

PowerModeChangedEventArgs Class
.NET Framework 4

Provides data for the PowerModeChanged event.


Inheritance Hierarchy

System.Object System.EventArgs Microsoft.Win32.PowerModeChangedEventArgs Namespace: Microsoft.Win32 Assembly: System (in System.dll) Syntax

C#
[HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)] [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")] [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] public class PowerModeChangedEventArgs : EventArgs

The PowerModeChangedEventArgs type exposes the following members.


Constructors

Show:

Inherited Name

Protected Description Initializes a new instance of the PowerModeChangedEventArgs class using the specified power mode event type.

PowerModeChangedEventArgs Properties

Show: Name

Inherited

Protected Description

Mode Gets an identifier that indicates the type of the power mode event that has occurred. Methods

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.)

Equals(Object)

Finalize

GetHashCode GetType

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Remarks Returns a string that represents the current object. (Inherited from Object.)

A PowerModeChanged event is raised when the user suspends or resumes the operating system, or when a system power status notification occurs. A system power status notification can occur when a weak or charging power source is detected, or when a transition from AC or battery power source occurs. The Mode property of a PowerModeChangedEventArgs indicates the type of power mode event that has occurred.
Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.
Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements. Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Registry Class
.NET Framework 4

Provides RegistryKey objects that represent the root keys in the Windows registry, and static methods to access key/value pairs.
Inheritance Hierarchy

System.Object Microsoft.Win32.Registry Namespace: Microsoft.Win32 Assembly: mscorlib (in mscorlib.dll) Syntax

C#

[ComVisibleAttribute(true)] public static class Registry

The Registry type exposes the following members.


Methods

Name

Description Retrieves the value associated with the specified name, in the specified registry key. If the name is not found in the specified key, returns a default value that you provide, or null if the specified key does not exist. Sets the specified name/value pair on the specified registry key. If the specified key does not exist, it is created.

GetValue

SetValue(String, String, Object)

Sets the name/value pair on the specified registry key, using the SetValue(String, String, specified registry data type. If the specified key does not exist, it is Object, RegistryValueKind) created. Fields

Name

Description Defines the types (or classes) of documents and the properties associated with those types. This field reads the Windows registry base key HKEY_CLASSES_ROOT. Contains configuration information pertaining to the hardware that is not specific to the user. This field reads the Windows registry base key HKEY_CURRENT_CONFIG. Contains information about the current user preferences. This field reads the Windows registry base key HKEY_CURRENT_USER Obsolete. Contains dynamic registry data. This field reads the Windows registry base key HKEY_DYN_DATA. Contains the configuration data for the local machine. This field reads the

ClassesRoot

CurrentConfig

CurrentUser

DynData LocalMachine

Windows registry base key HKEY_LOCAL_MACHINE. PerformanceData Contains performance information for software components. This field reads the Windows registry base key HKEY_PERFORMANCE_DATA. Contains information about the default user configuration. This field reads the Windows registry base key HKEY_USERS.

Users Remarks

This class provides the set of standard root keys found in the registry on machines running Windows. The registry is a storage facility for information about applications, users, and default system settings. For example, applications can use the registry for storing information that needs to be preserved after the application is closed, and access that same information when the application is reloaded. For instance, you can store color preferences, screen locations, or the size of the window. You can control this data for each user by storing the information in a different location in the registry. The base, or root RegistryKey instances that are exposed by the Registry class delineate the basic storage mechanism for subkeys and values in the registry. All keys are read-only because the registry depends on their existence. The keys exposed by Registry are:
CurrentUser

Stores information about user preferences.


LocalMachine

Stores configuration information for the local machine.


ClassesRoot

Stores information about types (and classes) and their properties.


Users

Stores information about the default user configuration.


PerformanceData

Stores performance information for software components.


CurrentConfig

Stores non-user-specific hardware information.


DynData

Stores dynamic data. Once you have identified the root key under which you want to store/retrieve information from the registry, you can use the RegistryKey class to add or remove subkeys, and manipulate the values for a given key. Hardware devices can place information in the registry automatically using the Plug and Play interface. Software for installing device drivers can place information in the registry by writing to standard APIs.
Static Methods for Getting and Setting Values

In the .NET Framework version 2.0, the Registry class also contains static GetValue and SetValue methods for setting and retrieving values from registry keys. These methods open and close registry keys each time they are used, so they do not perform as well as analogous methods in the RegistryKey class, when you access a large number of values. The RegistryKey class also provides methods that allow you to set Windows access control security for registry keys, to test the data type of a value before retrieving it, and to delete keys.
Examples

This section contains two code examples. The first example demonstrates root keys, and the second example demonstrates the static GetValue and SetValue methods. Example 1 The following code example demonstrates how to retrieve the subkeys of the HKEY_USERS key, and print their names to the screen. Use the OpenSubKey method to create an instance of the particular subkey of interest. You can then use other operations in RegistryKey to manipulate that key.
C#
using System; using Microsoft.Win32; class Reg { public static void Main() { // Create a RegistryKey, which will access the HKEY_USERS

// key in the registry of this machine. RegistryKey rk = Registry.Users; // Print out the keys. PrintKeys(rk); } static void PrintKeys(RegistryKey rkey) { // Retrieve all the subkeys for the specified key. String [] names = rkey.GetSubKeyNames(); int icount = 0; Console.WriteLine("Subkeys of " + rkey.Name); Console.WriteLine("----------------------------------------------"); // Print the contents of the array to the console. foreach (String s in names) { Console.WriteLine(s); // The following code puts a limit on the number // of keys displayed. Comment it out to print the // complete list. icount++; if (icount >= 10) break; } } }

Example 2 The following code example stores values of several data types in an example key, creating the key as it does so, and then retrieves and displays the values. The example demonstrates storing and retrieving the default (nameless) name/value pair, and the use of defaultValue when a name/value pair does not exist.
C#
using System; using Microsoft.Win32; public class Example { public static void Main() { // The name of the key must include a valid root. const string userRoot = "HKEY_CURRENT_USER"; const string subkey = "RegistrySetValueExample"; const string keyName = userRoot + "\\" + subkey;

// An int value can be stored without specifying the // registry data type, but long values will be stored // as strings unless you specify the type. Note that // the int is stored in the default name/value // pair. Registry.SetValue(keyName, "", 5280); Registry.SetValue(keyName, "TestLong", 12345678901234, RegistryValueKind.QWord); // Strings with expandable environment variables are // stored as ordinary strings unless you specify the // data type. Registry.SetValue(keyName, "TestExpand", "My path: %path%"); Registry.SetValue(keyName, "TestExpand2", "My path: %path%", RegistryValueKind.ExpandString); // Arrays of strings are stored automatically as // MultiString. Similarly, arrays of Byte are stored // automatically as Binary. string[] strings = {"One", "Two", "Three"}; Registry.SetValue(keyName, "TestArray", strings); // Your default value is returned if the name/value pair // does not exist. string noSuch = (string) Registry.GetValue(keyName, "NoSuchName", "Return this default if NoSuchName does not exist."); Console.WriteLine("\r\nNoSuchName: {0}", noSuch); // Retrieve the int and long values, specifying // numeric default values in case the name/value pairs // do not exist. The int value is retrieved from the // default (nameless) name/value pair for the key. int tInteger = (int) Registry.GetValue(keyName, "", -1); Console.WriteLine("(Default): {0}", tInteger); long tLong = (long) Registry.GetValue(keyName, "TestLong", long.MinValue); Console.WriteLine("TestLong: {0}", tLong); // When retrieving a MultiString value, you can specify // an array for the default return value. string[] tArray = (string[]) Registry.GetValue(keyName, "TestArray", new string[] {"Default if TestArray does not exist."}); for(int i=0; i<tArray.Length; i++) { Console.WriteLine("TestArray({0}): {1}", i, tArray[i]); } // A string with embedded environment variables is not // expanded if it was stored as an ordinary string. string tExpand = (string) Registry.GetValue(keyName, "TestExpand", "Default if TestExpand does not exist."); Console.WriteLine("TestExpand: {0}", tExpand); // A string stored as ExpandString is expanded.

string tExpand2 = (string) Registry.GetValue(keyName, "TestExpand2", "Default if TestExpand2 does not exist."); Console.WriteLine("TestExpand2: {0}...", tExpand2.Substring(0, 40)); Console.WriteLine("\r\nUse the registry editor to examine the key."); Console.WriteLine("Press the Enter key to delete the key."); Console.ReadLine(); Registry.CurrentUser.DeleteSubKey(subkey); } } // // This code example produces output similar to the following: // //NoSuchName: Return this default if NoSuchName does not exist. //(Default): 5280 //TestLong: 12345678901234 //TestArray(0): One //TestArray(1): Two //TestArray(2): Three //TestExpand: My path: %path% //TestExpand2: My path: D:\Program Files\Microsoft.NET\... // //Use the registry editor to examine the key. //Press the Enter key to delete the key.

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

RegistryKey Class
.NET Framework 4

Represents a key-level node in the Windows registry. This class is a registry encapsulation.
Inheritance Hierarchy

System.Object System.MarshalByRefObject Microsoft.Win32.RegistryKey Namespace: Microsoft.Win32 Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[ComVisibleAttribute(true)] public sealed class RegistryKey : MarshalByRefObject, IDisposable

The RegistryKey type exposes the following members.


Properties

Show:

Inherited

Protected

Name Handle Name

Description Gets a SafeRegistryHandle object that represents the registry key that the current RegistryKey object encapsulates. Retrieves the name of the key.

SubKeyCount Retrieves the count of subkeys of the current key. ValueCount Retrieves the count of values in the key. View Methods Gets the view that was used to create the registry key.

Show:

Inherited

Protected Name Description Closes the key and flushes it to disk if its contents have been modified. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.) Creates a new subkey or opens an existing subkey for write access. Creates a new subkey or opens an existing subkey for write access, using the specified permission check option. Creates a subkey or opens a subkey for write access, using the specified permission check and registry options. Creates a new subkey or opens an existing subkey for write access, using the specified permission check option and registry security.

Close

CreateObjRef

CreateSubKey(String)

CreateSubKey(String, RegistryKeyPermissionCheck)

CreateSubKey(String, RegistryKeyPermissionCheck, RegistryOptions)

CreateSubKey(String, RegistryKeyPermissionCheck, RegistrySecurity)

CreateSubKey(String, RegistryKeyPermissionCheck, RegistryOptions, RegistrySecurity) DeleteSubKey(String)

Creates a subkey or opens a subkey for write access, using the specified permission check option, registry option, and registry security. Deletes the specified subkey. Deletes the specified subkey, and specifies whether an exception is raised if the subkey is not found. Deletes a subkey and any child subkeys recursively. Deletes the specified subkey and any child subkeys recursively, and specifies whether an exception is raised if the subkey is not found. Deletes the specified value from this key. Deletes the specified value from this key, and specifies whether an exception is raised if the value is not found. Releases all resources used by the current instance of the RegistryKey class. Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Writes all the attributes of the specified open registry key into the registry. Creates a registry key from a specified handle. Creates a registry key from a specified handle and registry view setting.

DeleteSubKey(String, Boolean)

DeleteSubKeyTree(String)

DeleteSubKeyTree(String, Boolean)

DeleteValue(String)

DeleteValue(String, Boolean)

Dispose

Equals(Object)

Finalize

Flush FromHandle(SafeRegistryHandle) FromHandle(SafeRegistryHandle, RegistryView)

GetAccessControl()

Returns the access control security for the current registry key. Returns the specified sections of the access control security for the current registry key. Serves as a hash function for a particular type. (Inherited from Object.) Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.) Retrieves an array of strings that contains all the subkey names. Gets the Type of the current instance. (Inherited from Object.) Retrieves the value associated with the specified name. Returns null if the name/value pair does not exist in the registry. Retrieves the value associated with the specified name. If the name is not found, returns the default value that you provide. Retrieves the value associated with the specified name and retrieval options. If the name is not found, returns the default value that you provide. Retrieves the registry data type of the value associated with the specified name. Retrieves an array of strings that contains all the value names associated with this key. Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.) Creates a shallow copy of the current Object.

GetAccessControl(AccessControlSections)

GetHashCode

GetLifetimeService

GetSubKeyNames

GetType

GetValue(String)

GetValue(String, Object)

GetValue(String, Object, RegistryValueOptions)

GetValueKind

GetValueNames

InitializeLifetimeService

MemberwiseClone()

(Inherited from Object.) Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.) Opens a new RegistryKey that represents the requested key on the local machine with the specified view. Opens a new RegistryKey that represents the requested key on a remote machine. Opens a new registry key that represents the requested key on a remote machine with the specified view. Retrieves a subkey as read-only. Retrieves the specified subkey for read or read/write access. Retrieves a specified subkey, and specifies whether write access is to be applied to the key. Retrieves the specified subkey for read or read/write access, requesting the specified access rights. Applies Windows access control security to an existing registry key. Sets the specified name/value pair. Sets the value of a name/value pair in the registry key, using the specified registry data type. Retrieves a string representation of this key. (Overrides Object.ToString().)

MemberwiseClone(Boolean)

OpenBaseKey

OpenRemoteBaseKey(RegistryHive, String)

OpenRemoteBaseKey(RegistryHive, String, RegistryView) OpenSubKey(String) OpenSubKey(String, RegistryKeyPermissionCheck)

OpenSubKey(String, Boolean)

OpenSubKey(String, RegistryKeyPermissionCheck, RegistryRights)

SetAccessControl SetValue(String, Object)

SetValue(String, Object, RegistryValueKind)

ToString Remarks

To get an instance of RegistryKey, use one of the static members of the Registry class. The registry acts as a central repository of information for the operating system and the applications on a computer. The registry is organized in a hierarchical format, based on a logical ordering of the elements stored within it (please see Registry for the base-level items in this hierarchy). When storing information in the registry, select the appropriate location based on the type of information being stored. Be sure to avoid destroying information created by other applications, because this can cause those applications to exhibit unexpected behavior, and can also have an adverse effect upon your own application. Registry keys are the base unit of organization in the registry, and can be compared to folders in Windows Explorer. A particular key can have subkeys, just as a folder can have subfolders. Each key can be deleted, as long as the user has the appropriate permissions to do so, and the key is not a base key or at the level directly under the base keys. Each key can also have multiple values associated with it (a value can be compared to a file), which are used to store the information for example, information about an application installed on the computer. Each value holds one particular piece of information, which can be retrieved or updated when required. For instance, you can create a RegistryKey for your company, under the key HKEY_LOCAL_MACHINE\Software, and then a subkey for each application that your company creates. Each subkey holds the information specific to that application, such as color settings, screen location and size, or recognized file extensions. Note that information stored in the registry is available to other applications and users, and therefore should not be used to store security data or critical application information.
Caution

Do not expose RegistryKey objects in such a way that a malicious program could create thousands of meaningless subkeys or key/value pairs. For example, do not allow callers to enter arbitrary keys or values. Starting in the .NET Framework version 4, the length of a registry key is no longer limited to 255 characters.
Examples

The following code example shows how to create a subkey under HKEY_CURRENT_USER, manipulate its contents, and then delete the subkey.
C#

using System; using System.Security.Permissions; using Microsoft.Win32; class RegKey { static void Main() { // Create a subkey named Test9999 under HKEY_CURRENT_USER. RegistryKey test9999 = Registry.CurrentUser.CreateSubKey("Test9999"); // Create two subkeys under HKEY_CURRENT_USER\Test9999. The // keys are disposed when execution exits the using statement. using(RegistryKey testName = test9999.CreateSubKey("TestName"), testSettings = test9999.CreateSubKey("TestSettings")) { // Create data for the TestSettings subkey. testSettings.SetValue("Language", "French"); testSettings.SetValue("Level", "Intermediate"); testSettings.SetValue("ID", 123); } // Print the information from the Test9999 subkey. Console.WriteLine("There are {0} subkeys under {1}.", test9999.SubKeyCount.ToString(), test9999.Name); foreach(string subKeyName in test9999.GetSubKeyNames()) { using(RegistryKey tempKey = test9999.OpenSubKey(subKeyName)) { Console.WriteLine("\nThere are {0} values for {1}.", tempKey.ValueCount.ToString(), tempKey.Name); foreach(string valueName in tempKey.GetValueNames()) { Console.WriteLine("{0,-8}: {1}", valueName, tempKey.GetValue(valueName).ToString()); } } } using(RegistryKey testSettings = test9999.OpenSubKey("TestSettings", true)) { // Delete the ID value. testSettings.DeleteValue("id"); // Verify the deletion. Console.WriteLine((string)testSettings.GetValue( "id", "ID not found.")); } // Delete or close the new subkey. Console.Write("\nDelete newly created registry key? (Y/N) "); if(Char.ToUpper(Convert.ToChar(Console.Read())) == 'Y') { Registry.CurrentUser.DeleteSubKeyTree("Test9999");

Console.WriteLine("\nRegistry key {0} deleted.", test9999.Name); } else { Console.WriteLine("\nRegistry key {0} closed.", test9999.ToString()); test9999.Close(); } } }

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements. Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

SaveFileDialog Class
.NET Framework 4

Represents a common dialog that allows the user to specify a filename to save a file as. SaveFileDialog cannot be used by an application that is executing under partial trust.
Inheritance Hierarchy

System.Object Microsoft.Win32.CommonDialog Microsoft.Win32.FileDialog Microsoft.Win32.SaveFileDialog Namespace: Microsoft.Win32 Assembly: PresentationFramework (in PresentationFramework.dll) XMLNS for XAML: Not mapped to an xmlns. Syntax

C#
public sealed class SaveFileDialog : FileDialog

XAML Copy
You cannot declare this managed class in XAML.

The SaveFileDialog type exposes the following members.


Constructors

Show:

Inherited

Protected Description

Name

SaveFileDialog Initializes a new instance of the SaveFileDialog class. Properties

Show:

Inherited

Protected

Name

Description Gets or sets a value indicating whether a file dialog automatically adds an extension to a file name if the user omits an extension. (Inherited from FileDialog.) Gets or sets a value indicating whether a file dialog displays a warning if the user specifies a file name that does not exist. (Inherited from FileDialog.) Gets or sets a value that specifies whether warnings are displayed if the user types invalid paths and file names. (Inherited from FileDialog.) Gets or sets a value indicating whether SaveFileDialog prompts the user for permission to create a file if the user specifies a file that does not exist. Gets or sets the list of custom places for file dialog boxes. (Inherited from FileDialog.) Gets or sets a value that specifies the default extension string to use to filter the list of files that are displayed. (Inherited from FileDialog.)

AddExtension

CheckFileExists

CheckPathExists

CreatePrompt

CustomPlaces

DefaultExt

Gets or sets a value indicating whether a file dialog returns either the location DereferenceLinks of the file referenced by a shortcut or the location of the shortcut file (.lnk). (Inherited from FileDialog.) FileName Gets or sets a string containing the full path of the file selected in a file dialog. (Inherited from FileDialog.) Gets an array that contains one file name for each selected file. (Inherited from FileDialog.) Gets or sets the filter string that determines what types of files are displayed from either the OpenFileDialog or SaveFileDialog. (Inherited from FileDialog.) Gets or sets the index of the filter currently selected in a file dialog. (Inherited from FileDialog.) Gets or sets the initial directory that is displayed by a file dialog. (Inherited from FileDialog.) Gets the Win32 common file dialog flags that are used by file dialogs for initialization. (Inherited from FileDialog.)

FileNames

Filter

FilterIndex

InitialDirectory

Options

OverwritePrompt

Gets or sets a value indicating whether SaveFileDialog displays a warning if the user specifies the name of a file that already exists.

RestoreDirectory This property is not implemented. (Inherited from FileDialog.) SafeFileName Gets a string that only contains the file name for the selected file. (Inherited from FileDialog.) Gets an array that contains one safe file name for each selected file. (Inherited from FileDialog.) Gets or sets an object associated with the dialog. This provides the ability to attach an arbitrary object to the dialog. (Inherited from CommonDialog.) Gets or sets the text that appears in the title bar of a file dialog. (Inherited from FileDialog.) Gets or sets a value indicating whether the dialog accepts only valid Win32 file names. (Inherited from FileDialog.)

SafeFileNames

Tag

Title

ValidateNames Methods

Show:

Inherited Name

Protected Description Determines whether sufficient permissions for displaying a dialog exist. (Inherited from CommonDialog.) Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.)

CheckPermissionsToShowDialog

Equals(Object)

Finalize

GetHashCode GetType

HookProc

Defines the common file dialog hook procedure that is overridden to add common functionality to a file dialog. (Inherited from FileDialog.) Creates a shallow copy of the current Object. (Inherited from Object.) Raises the FileOk event. (Inherited from FileDialog.) Creates a read-write file stream for the filename selected by the user using SaveFileDialog. Resets all SaveFileDialog properties to their default values. (Overrides FileDialog.Reset().) RunDialog is called to display a file dialog in a derived class, such as OpenFileDialog and SaveFileDialog. (Inherited from FileDialog.) Displays a common dialog. (Inherited from CommonDialog.) Displays a common dialog. (Inherited from CommonDialog.) Returns a string that represents a file dialog. (Inherited from FileDialog.)

MemberwiseClone OnFileOk OpenFile

Reset

RunDialog

ShowDialog() ShowDialog(Window) ToString Events

Show: Name FileOk

Inherited

Protected Description

Occurs when the user selects a file name by either clicking the Open button of the OpenFileDialog or the Save button of the SaveFileDialog. (Inherited from FileDialog.)

Remarks

The following figure shows a SaveFileDialog for Windows Vista.

Starting in Windows Vista, open and save file dialog boxes have a Favorite Links panel on the left side of the dialog box that allows the user to quickly navigate to a different location. These links are called custom places. Use the CustomPlaces property to set this list of links.
Examples

The following example demonstrates how to create a SaveFileDialog and process the result.
C#
// Configure save file dialog box Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.FileName = "Document"; // Default file name dlg.DefaultExt = ".text"; // Default file extension dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension // Show save file dialog box Nullable<bool> result = dlg.ShowDialog(); // Process save file dialog box results if (result == true) { // Save document string filename = dlg.FileName; }

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements. Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

SessionEndedEventArgs Class
.NET Framework 4

Provides data for the SessionEnded event.


Inheritance Hierarchy

System.Object System.EventArgs Microsoft.Win32.SessionEndedEventArgs Namespace: Microsoft.Win32 Assembly: System (in System.dll) Syntax

C#
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")] [HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)] [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] public class SessionEndedEventArgs : EventArgs

The SessionEndedEventArgs type exposes the following members.


Constructors

Show:

Inherited Name

Protected Description

SessionEndedEventArgs Initializes a new instance of the SessionEndedEventArgs class. Properties

Show: Name

Inherited

Protected Description

Reason Gets an identifier that indicates how the session ended. Methods

Show:

Inherited

Protected

Name Equals(Object)

Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.)

Finalize

GetHashCode GetType

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Remarks Returns a string that represents the current object. (Inherited from Object.)

A SessionEnded event is raised when the user logs off or shuts down the system.
Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.
Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements. Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

SessionEndingEventArgs Class
.NET Framework 4

Provides data for the SessionEnding event.


Inheritance Hierarchy

System.Object System.EventArgs Microsoft.Win32.SessionEndingEventArgs Namespace: Microsoft.Win32 Assembly: System (in System.dll) Syntax

C#
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")] [HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)] public class SessionEndingEventArgs : EventArgs

The SessionEndingEventArgs type exposes the following members.

Constructors

Show:

Inherited Name

Protected Description

Initializes a new instance of the SessionEndingEventArgs class using the SessionEndingEventArgs specified value indicating the type of session close event that is occurring. Properties

Show: Name

Inherited

Protected Description

Cancel Gets or sets a value indicating whether to cancel the user request to end the session. Reason Gets the reason the session is ending. Methods

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.)

Equals(Object)

Finalize

GetHashCode GetType

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)

ToString Remarks

Returns a string that represents the current object. (Inherited from Object.)

A SessionEnding event is raised when the user is trying to log off or shut the system down. This SessionEnding event can sometimes be canceled. Setting the Cancel property of a SessionEndingEventArgs to false will request that the session continue instead of ending. Making such a request provides no guarantee that the session will not end.
Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.
Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements. Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

SessionSwitchEventArgs Class
.NET Framework 4

Provides data for the SessionSwitch event.


Inheritance Hierarchy

System.Object System.EventArgs Microsoft.Win32.SessionSwitchEventArgs Namespace: Microsoft.Win32 Assembly: System (in System.dll) Syntax

C#
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")] [HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)] [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] public class SessionSwitchEventArgs : EventArgs

The SessionSwitchEventArgs type exposes the following members.


Constructors

Show:

Inherited Name

Protected Description

SessionSwitchEventArgs Initializes a new instance of the SessionSwitchEventArgs class using the

specified session change event type identifer. Properties

Show: Name

Inherited

Protected Description

Reason Gets an identifier that indicates the type of session change event. Methods

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.)

Equals(Object)

Finalize

GetHashCode GetType

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Remarks Returns a string that represents the current object. (Inherited from Object.)

A SessionSwitch event is raised when the current user changes.


Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect

desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.
Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements. Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

SystemEvents Class
.NET Framework 4

Provides access to system event notifications. This class cannot be inherited.


Inheritance Hierarchy

System.Object Microsoft.Win32.SystemEvents Namespace: Microsoft.Win32 Assembly: System (in System.dll) Syntax

C#
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")] [HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)] public sealed class SystemEvents

The SystemEvents type exposes the following members.


Methods

Show:

Inherited Name

Protected Description Creates a new window timer associated with the system events window. Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.) Invokes the specified delegate using the thread that listens for system events. Terminates the timer specified by the given id. Creates a shallow copy of the current Object. (Inherited from Object.)

CreateTimer Equals(Object)

Finalize

GetHashCode GetType InvokeOnEventsThread KillTimer MemberwiseClone

ToString Events

Returns a string that represents the current object. (Inherited from Object.)

Show:

Inherited Name

Protected Description

DisplaySettingsChanged Occurs when the user changes the display settings. DisplaySettingsChanging Occurs when the display settings are changing. EventsThreadShutdown Occurs before the thread that listens for system events is terminated. InstalledFontsChanged LowMemory PaletteChanged PowerModeChanged SessionEnded SessionEnding SessionSwitch TimeChanged TimerElapsed Occurs when the user adds fonts to or removes fonts from the system. Obsolete. Occurs when the system is running out of available RAM. Occurs when the user switches to an application that uses a different palette. Occurs when the user suspends or resumes the system. Occurs when the user is logging off or shutting down the system. Occurs when the user is trying to log off or shut down the system. Occurs when the currently logged-in user has changed. Occurs when the user changes the time on the system clock. Occurs when a windows timer interval has expired.

UserPreferenceChanged Occurs when a user preference has changed. UserPreferenceChanging Occurs when a user preference is changing. Remarks

The SystemEvents class provides the ability to respond to specific types of system events.

When a system event is raised, any delegates attached to the event are called using the thread that monitors for system events. Therefore, you should make any calls from your event handlers thread-safe. If you need to call a system event that is not exposed as a member of this class, you can use the InvokeOnEventsThread method.
Caution

Do not perform time-consuming processing on the thread that raises a system event handler because it might prevent other applications from functioning.
Note

Some system events might not be raised on Windows Vista. Be sure to verify that your application works as expected on Windows Vista.
Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.
Examples

This section contains two examples. The first example shows how to use system events in an ordinary application, and the second example shows how to use system events in a Windows service. Example 1 The following code example registers interest in some system events and then waits for any of those events to occur. The output shown occurs if the user changes the display resolution.
C#
using System; using Microsoft.Win32; public sealed class App { static void Main() { // Set the SystemEvents class to receive event notification when a user // preference changes, the palette changes, or when display settings change. SystemEvents.UserPreferenceChanging += new

UserPreferenceChangingEventHandler(SystemEvents_UserPreferenceChanging); SystemEvents.PaletteChanged += new EventHandler(SystemEvents_PaletteChanged); SystemEvents.DisplaySettingsChanged += new EventHandler(SystemEvents_DisplaySettingsChanged); // For demonstration purposes, this application sits idle waiting for events. Console.WriteLine("This application is waiting for system events."); Console.WriteLine("Press <Enter> to terminate this application."); Console.ReadLine(); } // This method is called when a user preference changes. static void SystemEvents_UserPreferenceChanging(object sender, UserPreferenceChangingEventArgs e) { Console.WriteLine("The user preference is changing. Category={0}", e.Category); } // This method is called when the palette changes. static void SystemEvents_PaletteChanged(object sender, EventArgs e) { Console.WriteLine("The palette changed."); } // This method is called when the display settings change. static void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e) { Console.WriteLine("The display settings changed."); } } // This code produces the following output. // // This app is waiting for system events. // Press <Enter> to terminate this application. // Display Settings changed. // User preference is changing. Category=General

Example 2 The following code example demonstrates a very simple Windows service that handles the TimeChanged and UserPreferenceChanged events. The example includes a service named SimpleService, a form named HiddenForm, and an installer. The form provides the message loop that is required by system events.

Note

Services do not have message loops, unless they are allowed to interact with the desktop. If the message loop is not provided by a hidden form, as in this example, the service must be run under the local system account, and manual intervention is required to enable interaction with the desktop. That is, the administrator must manually check the Allow service to interact with desktop check box on the Log On tab of the service properties dialog box. In that case, a message loop is automatically provided. This option is available only when the service is run under the local system account. Interaction with the desktop cannot be enabled programmatically. The service in this example starts a thread that runs an instance of HiddenForm. The events are hooked up and handled in the form. The events must be hooked up in the load event of the form, to make sure that the form is completely loaded first; otherwise the events will not be raised.
Note

The example provides all the necessary code, including the form initialization code typically generated by Visual Studio designers. If you are developing your service in Visual Studio, you can omit the second partial class and use the Properties window to set the height and width of the hidden form to zero, the border style to FormBorderStyle.None, and the window state to FormWindowState.Minimized. To run the example: 1. Compile the code from the command line. The name that you use for the source file is not important. 2. Install the service from the command line using the Installutil.exe (Installer Tool) utility. For example, InstallUtil example.exe if the source file name is example.cs or example.vb. You must be an administrator to install the service. 3. Use the Services console to start the service. 4. Change the system time, or change user preferences, such as mouse properties. 5. View the messages in the Application category of Event Viewer. 6. Use the Services console to stop the service. 7. Uninstall the service from the command line by using the /u option. For example, InstallUtil /u example.exe.
C#
using using using using using using using System; System.ServiceProcess; System.Threading; System.Windows.Forms; System.Diagnostics; Microsoft.Win32; System.ComponentModel;

using System.Configuration.Install; namespace SimpleServiceCs { public class SimpleService : ServiceBase { static void Main(string[] args) { ServiceBase.Run(new SimpleService()); } protected override void OnStart(string[] args) { EventLog.WriteEntry("SimpleService", "Starting SimpleService"); new Thread(RunMessagePump).Start(); } void RunMessagePump() { EventLog.WriteEntry("SimpleService.MessagePump", "Starting SimpleService Message Pump"); Application.Run(new HiddenForm()); } protected override void OnStop() { Application.Exit(); } } public partial class HiddenForm : Form { public HiddenForm() { InitializeComponent(); } private void HiddenForm_Load(object sender, EventArgs e) { SystemEvents.TimeChanged += new EventHandler(SystemEvents_TimeChanged); SystemEvents.UserPreferenceChanged += new UserPreferenceChangedEventHandler(SystemEvents_UPCChanged); } private void HiddenForm_FormClosing(object sender, FormClosingEventArgs e) { SystemEvents.TimeChanged -= new EventHandler(SystemEvents_TimeChanged); SystemEvents.UserPreferenceChanged -= new UserPreferenceChangedEventHandler(SystemEvents_UPCChanged); } private void SystemEvents_TimeChanged(object sender, EventArgs e) {

EventLog.WriteEntry("SimpleService.TimeChanged", "Time changed; it is now " + DateTime.Now.ToLongTimeString()); } private void SystemEvents_UPCChanged(object sender, UserPreferenceChangedEventArgs e) { EventLog.WriteEntry("SimpleService.UserPreferenceChanged", e.Category.ToString()); } } partial class HiddenForm { private System.ComponentModel.IContainer components = null; protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } private void InitializeComponent() { this.SuspendLayout(); this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(0, 0); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Name = "HiddenForm"; this.Text = "HiddenForm"; this.WindowState = System.Windows.Forms.FormWindowState.Minimized; this.Load += new System.EventHandler(this.HiddenForm_Load); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.HiddenForm_FormClosing) ; this.ResumeLayout(false); } } [RunInstaller(true)] public class SimpleInstaller : Installer { private ServiceInstaller serviceInstaller; private ServiceProcessInstaller processInstaller; public SimpleInstaller() { processInstaller = new ServiceProcessInstaller(); serviceInstaller = new ServiceInstaller();

// Service will run under system account processInstaller.Account = ServiceAccount.LocalSystem; // Service will have Start Type of Manual serviceInstaller.StartType = ServiceStartMode.Automatic; serviceInstaller.ServiceName = "Simple Service"; Installers.Add(serviceInstaller); Installers.Add(processInstaller); } } }

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 .NET Framework Security

NamedPermissionSet

for full access to system resources. Demand values: LinkDemand. Associated state: FullTrust
Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements. Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

TimerElapsedEventArgs Class
.NET Framework 4

Provides data for the TimerElapsed event.


Inheritance Hierarchy

System.Object System.EventArgs Microsoft.Win32.TimerElapsedEventArgs Namespace: Microsoft.Win32 Assembly: System (in System.dll) Syntax

C#
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")] [HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)] public class TimerElapsedEventArgs : EventArgs

The TimerElapsedEventArgs type exposes the following members.


Constructors

Show:

Inherited Name

Protected Description

TimerElapsedEventArgs Initializes a new instance of the TimerElapsedEventArgs class. Properties

Show: Name

Inherited

Protected Description

TimerId Gets the ID number for the timer. Methods

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.)

Equals(Object)

Finalize

GetHashCode GetType

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Remarks Returns a string that represents the current object. (Inherited from Object.)

A TimerElapsed event is raised when a windows timer interval has expired.


Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect

desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.
Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements. Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

UserPreferenceChangedEventArgs Class
.NET Framework 4

Provides data for the UserPreferenceChanged event.


Inheritance Hierarchy

System.Object System.EventArgs Microsoft.Win32.UserPreferenceChangedEventArgs Namespace: Microsoft.Win32 Assembly: System (in System.dll) Syntax

C#
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")] [HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)] [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] public class UserPreferenceChangedEventArgs : EventArgs

The UserPreferenceChangedEventArgs type exposes the following members.


Constructors

Show:

Inherited Name

Protected Description

Initializes a new instance of the UserPreferenceChangedEventArgs UserPreferenceChangedEventArgs class using the specified user preference category identifier. Properties

Show: Name

Inherited

Protected Description

Category Gets the category of user preferences that has changed. Methods

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.)

Equals(Object)

Finalize

GetHashCode GetType

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Remarks Returns a string that represents the current object. (Inherited from Object.)

A UserPreferenceChanged event occurs when a user preference has changed.


Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.
Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements. Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

UserPreferenceChangingEventArgs Class
.NET Framework 4

Provides data for the UserPreferenceChanging event.


Inheritance Hierarchy

System.Object System.EventArgs Microsoft.Win32.UserPreferenceChangingEventArgs Namespace: Microsoft.Win32 Assembly: System (in System.dll) Syntax

C#
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")] [HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)] public class UserPreferenceChangingEventArgs : EventArgs

The UserPreferenceChangingEventArgs type exposes the following members.


Constructors

Show:

Inherited Name

Protected Description

Initializes a new instance of the UserPreferenceChangingEventArgs UserPreferenceChangingEventArgs class using the specified user preference category identifier. Properties

Show: Name

Inherited

Protected Description

Category Gets the category of user preferences that is changing. Methods

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.)

Equals(Object)

Finalize

GetHashCode GetType

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)

ToString Remarks

Returns a string that represents the current object. (Inherited from Object.)

A UserPreferenceChanging event occurs when a change to a user preference is about to be applied.


Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.
Examples

The following code example demonstrates how to use the UserPreferenceChangingEventArgs type to monitor the UserPreferenceChanging event. This code example is part of a larger example provided for the SystemEvents class.
C#
using System; using Microsoft.Win32; public sealed class App { static void Main() { // Set the SystemEvents class to receive event notification when a user // preference changes, the palette changes, or when display settings change. SystemEvents.UserPreferenceChanging += new UserPreferenceChangingEventHandler(SystemEvents_UserPreferenceChanging); SystemEvents.PaletteChanged += new EventHandler(SystemEvents_PaletteChanged); SystemEvents.DisplaySettingsChanged += new EventHandler(SystemEvents_DisplaySettingsChanged); // For demonstration purposes, this application sits idle waiting for events. Console.WriteLine("This application is waiting for system events."); Console.WriteLine("Press <Enter> to terminate this application.");

Console.ReadLine(); } // This method is called when a user preference changes. static void SystemEvents_UserPreferenceChanging(object sender, UserPreferenceChangingEventArgs e) { Console.WriteLine("The user preference is changing. Category={0}", e.Category); } // This method is called when the palette changes. static void SystemEvents_PaletteChanged(object sender, EventArgs e) { Console.WriteLine("The palette changed."); } // This method is called when the display settings change. static void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e) { Console.WriteLine("The display settings changed."); } } // This code produces the following output. // // This app is waiting for system events. // Press <Enter> to terminate this application. // Display Settings changed. // User preference is changing. Category=General

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements. Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Delegates Description Represents the method that will handle the PowerModeChangedEventHandler PowerModeChanged event. Represents the method that will handle the SessionEndedEventHandler SessionEnded event. Represents the method that will handle the SessionEndingEventHandler SessionEnding event from the operating system. Represents the method that will handle the SessionSwitchEventHandler SessionSwitch event. Represents the method that will handle the TimerElapsedEventHandler TimerElapsed event. Represents the method that will handle the UserPreferenceChangedEventHandler UserPreferenceChanged event. Represents the method that will handle the UserPreferenceChangingEventHandler UserPreferenceChanging event. Delegate

DESCRIPCION DE LOS DELEGADOS DELEGATES DEL ESPACIO DE NOMBRES Microsoft.Win32

PowerModeChangedEventHandler Delegate
.NET Framework 4

Represents the method that will handle the PowerModeChanged event.


Namespace: Microsoft.Win32 Assembly: System (in System.dll)

Syntax

C#
[HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)] public delegate void PowerModeChangedEventHandler( Object sender, PowerModeChangedEventArgs e )

Parameters
sender Type: System.Object The source of the event. When this event is raised by the SystemEvents class, this object is always null. e Type: Microsoft.Win32.PowerModeChangedEventArgs A PowerModeChangedEventArgs that contains the event data. Remarks

When you create a PowerModeChangedEventHandler delegate, you identify the method that will handle the event. To associate the event with your event-handling method, add an instance of the delegate to the event. The event-handling method is called whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see Events and Delegates.
Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.
Version Information

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

SessionEndedEventHandler Delegate
.NET Framework 4

Represents the method that will handle the SessionEnded event.


Namespace: Microsoft.Win32 Assembly: System (in System.dll) Syntax

C#
[HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)] public delegate void SessionEndedEventHandler( Object sender, SessionEndedEventArgs e )

Parameters
sender

Type: System.Object The source of the event. When this event is raised by the SystemEvents class, this object is always null. e Type: Microsoft.Win32.SessionEndedEventArgs A SessionEndedEventArgs that contains the event data. Remarks

When you create a SessionEndedEventHandler delegate, you identify the method that will handle the event. To associate the event with your event-handling method, add an instance of the delegate to the event. The event-handling method is called whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see Events and Delegates.
Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.
Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

SessionEndingEventHandler Delegate
.NET Framework 4

Represents the method that will handle the SessionEnding event from the operating system.
Namespace: Microsoft.Win32 Assembly: System (in System.dll) Syntax

C#
[HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)] public delegate void SessionEndingEventHandler( Object sender, SessionEndingEventArgs e )

Parameters
sender Type: System.Object The source of the event. When this event is raised by the SystemEvents class, this object is always null. e Type: Microsoft.Win32.SessionEndingEventArgs A SessionEndingEventArgs that contains the event data. Remarks

When you create a SessionEndingEventHandler delegate, you identify the method that will handle the event. To associate the event with your event-handling method, add an instance of the delegate to the event. The event-handling method is called whenever the event

occurs, unless you remove the delegate. For more information about event-handler delegates, see Events and Delegates.
Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.
Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

SessionSwitchEventHandler Delegate
.NET Framework 4

Represents the method that will handle the SessionSwitch event.


Namespace: Microsoft.Win32 Assembly: System (in System.dll) Syntax

C#
[HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)] public delegate void SessionSwitchEventHandler( Object sender, SessionSwitchEventArgs e )

Parameters
sender Type: System.Object The source of the event. e Type: Microsoft.Win32.SessionSwitchEventArgs A SessionSwitchEventArgs indicating the type of the session change event. Remarks

When you create a SessionSwitchEventHandler delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about event handler delegates, see Events and Delegates.
Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.
Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

TimerElapsedEventHandler Delegate
.NET Framework 4

Represents the method that will handle the TimerElapsed event.


Namespace: Microsoft.Win32 Assembly: System (in System.dll) Syntax

C#
[HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)] public delegate void TimerElapsedEventHandler( Object sender, TimerElapsedEventArgs e )

Parameters
sender Type: System.Object The source of the event. When this event is raised by the SystemEvents class, this object is always null.

e Type: Microsoft.Win32.TimerElapsedEventArgs A TimerElapsedEventArgs that contains the event data. Remarks

When you create a TimerElapsedEventHandler delegate, you identify the method that will handle the event. To associate the event with your event-handling method, add an instance of the delegate to the event. The event-handling method is called whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see Events and Delegates.
Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.
Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

UserPreferenceChangedEventHandler Delegate
.NET Framework 4

Represents the method that will handle the UserPreferenceChanged event.


Namespace: Microsoft.Win32 Assembly: System (in System.dll) Syntax

C#
[HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)] public delegate void UserPreferenceChangedEventHandler( Object sender, UserPreferenceChangedEventArgs e )

Parameters
sender Type: System.Object The source of the event. When this event is raised by the SystemEvents class, this object is always null. e Type: Microsoft.Win32.UserPreferenceChangedEventArgs A UserPreferenceChangedEventArgs that contains the event data. Remarks

When you create a UserPreferenceChangedEventHandler delegate, you identify the method that will handle the event. To associate the event with your event-handling method, add an instance of the delegate to the event. The event-handling method is called whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see Events and Delegates.

Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.
Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

UserPreferenceChangingEventHandler Delegate
.NET Framework 4

Represents the method that will handle the UserPreferenceChanging event.


Namespace: Microsoft.Win32 Assembly: System (in System.dll) Syntax

C#
[HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)] public delegate void UserPreferenceChangingEventHandler( Object sender, UserPreferenceChangingEventArgs e )

Parameters
sender Type: System.Object The source of the event. When this event is raised by the SystemEvents class, this object is always null. e Type: Microsoft.Win32.UserPreferenceChangingEventArgs A UserPreferenceChangedEventArgs that contains the event data. Remarks

When you create a UserPreferenceChangingEventHandler delegate, you identify the method that will handle the event. To associate the event with your event-handling method, add an instance of the delegate to the event. The event-handling method is called whenever the event occurs, unless you remove the delegate. For more information about eventhandler delegates, see Events and Delegates.
Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: MayLeakOnAbort. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.
Examples

The following code example demonstrates how to use the UserPreferenceChangingEventHandler type to monitor the UserPreferenceChanging event. This code example is part of a larger example provided for the SystemEvents class.

C#
using System; using Microsoft.Win32; public sealed class App { static void Main() { // Set the SystemEvents class to receive event notification when a user // preference changes, the palette changes, or when display settings change. SystemEvents.UserPreferenceChanging += new UserPreferenceChangingEventHandler(SystemEvents_UserPreferenceChanging); SystemEvents.PaletteChanged += new EventHandler(SystemEvents_PaletteChanged); SystemEvents.DisplaySettingsChanged += new EventHandler(SystemEvents_DisplaySettingsChanged); // For demonstration purposes, this application sits idle waiting for events. Console.WriteLine("This application is waiting for system events."); Console.WriteLine("Press <Enter> to terminate this application."); Console.ReadLine(); } // This method is called when a user preference changes. static void SystemEvents_UserPreferenceChanging(object sender, UserPreferenceChangingEventArgs e) { Console.WriteLine("The user preference is changing. Category={0}", e.Category); } // This method is called when the palette changes. static void SystemEvents_PaletteChanged(object sender, EventArgs e) { Console.WriteLine("The palette changed."); } // This method is called when the display settings change. static void SystemEvents_DisplaySettingsChanged(object sender, EventArgs e) { Console.WriteLine("The display settings changed."); } } // This code produces the following output. // // This app is waiting for system events. // Press <Enter> to terminate this application. // Display Settings changed.

//

User preference is changing. Category=General

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Enumerations Description Defines identifiers for power mode events reported by the PowerModes operating system. Represents the possible values for a top-level node on a RegistryHive foreign machine. Specifies whether security checks are performed when RegistryKeyPermissionCheck opening registry keys and accessing their name/value pairs. RegistryOptions Specifies options to use when creating a registry key. Specifies the data types to use when storing values in the RegistryValueKind registry, or identifies the data type of a value in the registry. Specifies optional behavior when retrieving name/value RegistryValueOptions pairs from a registry key. Specifies which registry view to target on a 64-bit RegistryView operating system. Defines identifiers that represent how the current logon SessionEndReasons session is ending. Enumeration

SessionSwitchReason UserPreferenceCategory

Defines identifiers used to represent the type of a session switch event. Defines identifiers that represent categories of user preferences.

DESCRIPCION DE LOS ENUMERADOS ENUMERATIONS DEL ESPACIO DE NOMBRES Microsoft.Win32

PowerModes Enumeration
.NET Framework 4

Defines identifiers for power mode events reported by the operating system.
Namespace: Microsoft.Win32 Assembly: System (in System.dll) Syntax

C#
public enum PowerModes

Members

Member name Resume

Description The operating system is about to resume from a suspended state.

A power mode status notification event has been raised by the operating system. StatusChange This might indicate a weak or charging battery, a transition between AC power and battery, or another change in the status of the system power supply. Suspend Remarks The operating system is about to be suspended.

This enumeration defines identifiers that represent types of power mode changes or events. The values of this enumeration are used by a PowerModeChangedEventArgs to indicate the type of a PowerModeChanged event.
Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

RegistryHive Enumeration
.NET Framework 4

Represents the possible values for a top-level node on a foreign machine.


Namespace: Microsoft.Win32 Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[SerializableAttribute] [ComVisibleAttribute(true)] public enum RegistryHive

Members

Member name

Description Represents the HKEY_CLASSES_ROOT base key on another computer. This value can be passed to the OpenRemoteBaseKey method, to open this node remotely.

ClassesRoot

CurrentUser

Represents the HKEY_CURRENT_USER base key on another computer. This value can be passed to the OpenRemoteBaseKey method, to open this node remotely. Represents the HKEY_LOCAL_MACHINE base key on another computer. This value can be passed to the OpenRemoteBaseKey method, to open this node remotely. Represents the HKEY_USERS base key on another computer. This value can be passed to the OpenRemoteBaseKey method, to open this node remotely.

LocalMachine

Users

Represents the HKEY_PERFORMANCE_DATA base key on another computer. PerformanceData This value can be passed to the OpenRemoteBaseKey method, to open this node remotely. Represents the HKEY_CURRENT_CONFIG base key on another computer. This value can be passed to the OpenRemoteBaseKey method, to open this node remotely. Represents the HKEY_DYN_DATA base key on another computer. This value can be passed to the OpenRemoteBaseKey method, to open this node remotely.

CurrentConfig

DynData Remarks

RegistryHive values are used by the OpenRemoteBaseKey method to represent the toplevel node of a requested key on a foreign (remote) machine. The node that can be opened with the OpenRemoteBaseKey method must be one of these top-level RegistryKeys. Further access to the subkeys of the identified node is available using using methods in RegistryKey, so long as the the user has appropriate permission.
Examples

The following code example shows how to open a registry key on a remote computer and enumerate the values of the key. The remote computer must be running the remote registry service. Specify the name of the remote computer as a command-line argument when invoking the program.
C#
using System; using System.IO; using System.Security.Permissions;

using Microsoft.Win32; class RemoteKey { static void Main(string[] args) { RegistryKey environmentKey; string remoteName; // Check that an argument was specified when the // program was invoked. if(args.Length == 0) { Console.WriteLine("Error: The name of the remote " + "computer must be specified when the program is " + "invoked."); return; } else { remoteName = args[0]; } try { // Open HKEY_CURRENT_USER\Environment // on a remote computer. environmentKey = RegistryKey.OpenRemoteBaseKey( RegistryHive.CurrentUser, remoteName).OpenSubKey( "Environment"); } catch(IOException e) { Console.WriteLine("{0}: {1}", e.GetType().Name, e.Message); return; } // Print the values. Console.WriteLine("\nThere are {0} values for {1}.", environmentKey.ValueCount.ToString(), environmentKey.Name); foreach(string valueName in environmentKey.GetValueNames()) { Console.WriteLine("{0,-20}: {1}", valueName, environmentKey.GetValue(valueName).ToString()); } // Close the registry key. environmentKey.Close(); } }

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

RegistryKeyPermissionCheck Enumeration
.NET Framework 4

Specifies whether security checks are performed when opening registry keys and accessing their name/value pairs.
Namespace: Microsoft.Win32 Assembly: mscorlib (in mscorlib.dll) Syntax

C#
public enum RegistryKeyPermissionCheck

Members

Member name

Description The registry key inherits the mode of its parent. Security checks are performed when trying to access subkeys or values, unless the parent was opened with ReadSubTree or ReadWriteSubTree mode. Security checks are not performed when accessing subkeys or values. A security check is performed when trying to open the current key, unless the parent was opened with ReadSubTree or ReadWriteSubTree.

Default

ReadSubTree

Security checks are not performed when accessing subkeys or values. A ReadWriteSubTree security check is performed when trying to open the current key, unless the parent was opened with ReadWriteSubTree. Remarks

When an application saves or retrieves a large number of registry settings from a set of subkeys, numerous redundant security checks are performed. This enumeration specifies when security checks on a key are to be omitted. The following table shows when security checks are performed, based on the way the parent key and the current key are opened. Parent key opened with Current key opened with Result

A security check is performed when accessing any value in the current key, or when attempting Default Default to access a subkey. This is the behavior in the .NET Framework versions 1.0 and 1.1. A security check is performed when trying to Default ReadSubTree open the current key. A security check is performed when trying to Default ReadWriteSubTree open the current key. Default or No security checks are performed when opening ReadSubTree ReadSubTree the current key or its values. A security check is performed when trying to ReadSubTree ReadWriteSubTree open the current key. No security checks are performed when opening ReadWriteSubTree Any the current key or its values.
Examples

The following code example creates a subkey containing 100 key/value pairs and closes it. The example opens the subkey with Default and records the time it takes to read all the values. Then the example opens the subkey with ReadSubTree and records the time it takes to read all the values. Finally, the example computes and displays the percentage improvement.
C#
using System; using Microsoft.Win32;

using System.Diagnostics; public class Example { public static void Main() { const int LIMIT = 100; RegistryKey cu = Registry.CurrentUser; const string testKey = "RegistryKeyPermissionCheckExample"; Console.WriteLine("Generating {0} key/value pairs.", LIMIT); RegistryKey rk = cu.CreateSubKey(testKey); for (int i = 0; i < LIMIT; i++) { rk.SetValue("Key" + i, i); } rk.Close(); Stopwatch s = new Stopwatch(); // On the default setting, security is checked every time // a key/value pair is read. rk = cu.OpenSubKey(testKey, RegistryKeyPermissionCheck.Default); s.Start(); for (int i = 0; i < LIMIT; i++) { rk.GetValue("Key" + i, i); } s.Stop(); rk.Close(); long delta1 = s.ElapsedTicks; s.Reset(); // When the key is opened with ReadSubTree, security is // not checked when the values are read. rk = cu.OpenSubKey(testKey, RegistryKeyPermissionCheck.ReadSubTree); s.Start(); for (int i = 0; i < LIMIT; i++) { rk.GetValue("Key" + i, i); } s.Stop(); rk.Close(); long delta2 = s.ElapsedTicks; double faster = (double) (delta1 - delta2) / (double) delta1; Console.WriteLine("ReadSubTree is {0}% faster for {1} values.", (faster * 100).ToString("0.0"), LIMIT); cu.DeleteSubKey(testKey); } }

/* This code example produces output similar to the following: Generating 100 key/value pairs. ReadSubTree is 23.4% faster for 100 values. */

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

RegistryOptions Enumeration
.NET Framework 4

Specifies options to use when creating a registry key. This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.
Namespace: Microsoft.Win32 Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[FlagsAttribute] public enum RegistryOptions

Members

Member

Description

name None Volatile Remarks A non-volatile key. This is the default. A volatile key. The information is stored in memory and is not preserved when the corresponding registry hive is unloaded.

You can create a registry key that is available only in memory and that will not be persisted when the computer is restarted. This is known as a volatile key. You can specify that you want to create a volatile or non-volatile key by using the RegistryKey.CreateSubKey method overloads that take an options parameter.
Version Information

.NET Framework
Supported in: 4

.NET Framework Client Profile


Supported in: 4

RegistryValueKind Enumeration
.NET Framework 4

Specifies the data types to use when storing values in the registry, or identifies the data type of a value in the registry.
Namespace: Microsoft.Win32 Assembly: mscorlib (in mscorlib.dll) Syntax

C#

[ComVisibleAttribute(true)] public enum RegistryValueKind

Members

Member name String

Description A null-terminated string. This value is equivalent to the Win32 API registry data type REG_SZ.

A null-terminated string that contains unexpanded references to environment ExpandString variables, such as %PATH%, that are expanded when the value is retrieved. This value is equivalent to the Win32 API registry data type REG_EXPAND_SZ. Binary Binary data in any form. This value is equivalent to the Win32 API registry data type REG_BINARY. A 32-bit binary number. This value is equivalent to the Win32 API registry data type REG_DWORD. An array of null-terminated strings, terminated by two null characters. This value is equivalent to the Win32 API registry data type REG_MULTI_SZ. A 64-bit binary number. This value is equivalent to the Win32 API registry data type REG_QWORD. An unsupported registry data type. For example, the Microsoft Win32 API registry data type REG_RESOURCE_LIST is unsupported. Use this value to specify that the SetValue method should determine the appropriate registry data type when storing a name/value pair. No data type.

DWord

MultiString

QWord

Unknown

None Remarks

The RegistryValueKind enumeration defines the set of supported registry data types and the value that is used for unsupported types (Unknown). Starting in the .NET Framework version 4, you can specify not to use a data type with the None value.

Use the RegistryKey.GetValueKind method to determine the data type of a registry key value before retrieving the value. When you set a registry key value, use the SetValue method to specify the registry data type explicitly.
Examples

The following code example creates a registry key and sets several values for that key, using RegistryValueKind to specify the registry data types. The example then uses RegistryKey.GetValueKind to check the registry data types, in order to retrieve the values and display them.
C#
using System; using Microsoft.Win32; public class Example { public static void Main() { // Delete and recreate the test key. Registry.CurrentUser.DeleteSubKey("RegistryValueKindExample", false); RegistryKey rk = Registry.CurrentUser.CreateSubKey("RegistryValueKindExample"); // Create name/value pairs. // This overload supports QWord (long) values. rk.SetValue("QuadWordValue", 42, RegistryValueKind.QWord); // The following SetValue calls have the same effect as using the // SetValue overload that does not specify RegistryValueKind. // rk.SetValue("DWordValue", 42, RegistryValueKind.DWord); rk.SetValue("MultipleStringValue", new string[] {"One", "Two", "Three"}, RegistryValueKind.MultiString); rk.SetValue("BinaryValue", new byte[] {10, 43, 44, 45, 14, 255}, RegistryValueKind.Binary); rk.SetValue("StringValue", "The path is %PATH%", RegistryValueKind.String); // This overload supports setting expandable string values. Compare // the output from this value with the previous string value. rk.SetValue("ExpandedStringValue", "The path is %PATH%", RegistryValueKind.ExpandString); // Display all name/value pairs stored in the test key, with each // registry data type in parentheses. //

string[] valueNames = rk.GetValueNames(); foreach (string s in valueNames) { RegistryValueKind rvk = rk.GetValueKind(s); switch (rvk) { case RegistryValueKind.MultiString : string[] values = (string[]) rk.GetValue(s); Console.Write("\r\n {0} ({1}) =", s, rvk); for (int i = 0; i < values.Length; i++) { if (i != 0) Console.Write(","); Console.Write(" \"{0}\"", values[i]); } Console.WriteLine(); break; case RegistryValueKind.Binary : byte[] bytes = (byte[]) rk.GetValue(s); Console.Write("\r\n {0} ({1}) =", s, rvk); for (int i = 0; i < bytes.Length; i++) { // Display each byte as two hexadecimal digits. Console.Write(" {0:X2}", bytes[i]); } Console.WriteLine(); break; default : Console.WriteLine("\r\n {0} ({1}) = {2}", s, rvk, rk.GetValue(s)); break; } } } } /* This code example produces the following output: QuadWordValue (QWord) = 42 DWordValue (DWord) = 42 MultipleStringValue (MultiString) =, "One", "Two", "Three" BinaryValue (Binary) = 0A 2B 2C 2D 0E FF StringValue (String) = The path is %PATH% ExpandedStringValue (ExpandString) = The path is C:\Program Files\Microsoft.NET\SDK\v2.0\Bin; [***The remainder of this output is omitted.***] */

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

RegistryValueOptions Enumeration
.NET Framework 4

Specifies optional behavior when retrieving name/value pairs from a registry key. This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values.
Namespace: Microsoft.Win32 Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[FlagsAttribute] public enum RegistryValueOptions

Members

Member name None DoNotExpandEnvironmentNames Remarks

Description No optional behavior is specified. A value of type RegistryValueKind.ExpandString is retrieved without expanding its embedded environment variables.

Use the DoNotExpandEnvironmentNames flag with the RegistryKey.GetValue(String, Object, RegistryValueOptions) method overload.
Examples

The following code sample creates a test key, adds a value with an embedded environment variable, and retrieves the value in both expanded and unexpanded forms.
C#
using System; using Microsoft.Win32; using Microsoft.VisualBasic; public class Example { public static void Main() { // Delete and recreate the test key. Registry.CurrentUser.DeleteSubKey("RegistryValueOptionsExample", false); RegistryKey rk = Registry.CurrentUser.CreateSubKey("RegistryValueOptionsExample"); // Add a value that contains an environment variable. rk.SetValue("ExpandValue", "The path is %PATH%", RegistryValueKind.ExpandString); // Retrieve the value, first without expanding the environment // variable and then expanding it. Console.WriteLine("Unexpanded: \"{0}\"", rk.GetValue("ExpandValue", "No Value", RegistryValueOptions.DoNotExpandEnvironmentNames)); Console.WriteLine("Expanded: \"{0}\"", rk.GetValue("ExpandValue")); } //Main } //Example

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

RegistryView Enumeration
.NET Framework 4

Specifies which registry view to target on a 64-bit operating system.


Namespace: Microsoft.Win32 Assembly: mscorlib (in mscorlib.dll) Syntax

C#
public enum RegistryView

Members

Member name Default Registry64 Registry32 Remarks

Description The default view. The 64-bit view. The 32-bit view.

On the 64-bit version of Windows, portions of the registry are stored separately for 32-bit and 64-bit applications. There is a 32-bit view for 32-bit applications and a 64-bit view for 64-bit applications. You can specify a registry view when you use the OpenBaseKey and OpenRemoteBaseKey(RegistryHive, String, RegistryView) methods, and the FromHandle property on a RegistryKey object. If you request a 64-bit view on a 32-bit operating system, the returned keys will be in the 32-bit view.

Version Information

.NET Framework
Supported in: 4

.NET Framework Client Profile


Supported in: 4

SessionEndReasons Enumeration
.NET Framework 4

Defines identifiers that represent how the current logon session is ending.
Namespace: Microsoft.Win32 Assembly: System (in System.dll) Syntax

C#
public enum SessionEndReasons

Members

Member name Logoff

Description The user is logging off and ending the current user session. The operating system continues to run.

SystemShutdown The operating system is shutting down. Version Information

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

SessionSwitchReason Enumeration
.NET Framework 4

Defines identifiers used to represent the type of a session switch event.


Namespace: Microsoft.Win32 Assembly: System (in System.dll) Syntax

C#
public enum SessionSwitchReason

Members

Member name ConsoleConnect ConsoleDisconnect RemoteConnect RemoteDisconnect SessionLogon SessionLogoff SessionLock

Description A session has been connected from the console. A session has been disconnected from the console. A session has been connected from a remote connection. A session has been disconnected from a remote connection. A user has logged on to a session. A user has logged off from a session. A session has been locked.

SessionUnlock

A session has been unlocked.

SessionRemoteControl A session has changed its status to or from remote controlled mode. Remarks

The SessionSwitchEventArgs class uses the SessionSwitchReason class to represent the type of a session switch event.
Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

UserPreferenceCategory Enumeration
.NET Framework 4

Defines identifiers that represent categories of user preferences.


Namespace: Microsoft.Win32 Assembly: System (in System.dll) Syntax

C#
public enum UserPreferenceCategory

Members

Member name Accessibility

Description Indicates user preferences associated with accessibility features of the system for users with disabilities. Indicates user preferences associated with system colors. This category includes such as the default color of windows or menus. Indicates user preferences associated with the system desktop. This category includes the background image or background image layout of the desktop. Indicates user preferences that are not associated with any other category. Indicates user preferences for icon settings, including icon height and spacing. Indicates user preferences for keyboard settings, such as the key down repeat rate and delay. Indicates user preferences for menu settings, such as menu delays and text alignment. Indicates user preferences for mouse settings, such as double-click time and mouse sensitivity. Indicates user preferences for policy settings, such as user rights and access levels. Indicates the user preferences for system power settings. This category includes power feature settings, such as the idle time before the system automatically enters low power mode.

Color

Desktop General Icon Keyboard

Menu

Mouse Policy

Power

Screensaver Indicates user preferences associated with the screensaver. Window Indicates user preferences associated with the dimensions and characteristics of windows on the system. Indicates changes in user preferences for regional settings, such as the character encoding and culture strings. Indicates user preferences associated with visual styles, such as enabling or disabling visual styles and switching from one visual style to another.

Locale

VisualStyle Remarks

UserPreferenceCategory provides identifiers that can represent a category of user preferences. Some of the user preferences in these categories can be changed using the Windows Control Panel, the Computer Management console, or programatically using an appropriate API.
Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

System Namespace
.NET Framework 4 The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. Other classes provide services supporting data type conversion, method parameter manipulation, mathematics, remote and local program invocation, application environment management, and supervision of managed and unmanaged applications. Classes Class AccessViolationException ActivationContext Activator AggregateException AppDomain AppDomainManager AppDomainSetup AppDomainUnloadedException ApplicationException ApplicationId Description The exception that is thrown when there is an attempt to read or write protected memory. Identifies the activation context for the current application. This class cannot be inherited. Contains methods to create types of objects locally or remotely, or obtain references to existing remote objects. This class cannot be inherited. Represents one or more errors that occur during application execution. Represents an application domain, which is an isolated environment where applications execute. This class cannot be inherited. Provides a managed equivalent of an unmanaged host. Represents assembly binding information that can be added to an instance of AppDomain. The exception that is thrown when an attempt is made to access an unloaded application domain. The exception that is thrown when a non-fatal application error occurs. Contains information used to uniquely identify a manifest-based application. This class cannot be inherited. Provides the ability to uniquely identify a manifestactivated application. This class cannot be inherited. The exception that is thrown when one of the arguments provided to a method is not valid.

ApplicationIdentity ArgumentException

The exception that is thrown when a null reference ArgumentNullException (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument. The exception that is thrown when the value of an ArgumentOutOfRangeException argument is outside the allowable range of values as defined by the invoked method. The exception that is thrown for errors in an ArithmeticException arithmetic, casting, or conversion operation. Provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the Array base class for all arrays in the common language runtime. The exception that is thrown when an attempt is ArrayTypeMismatchException made to store an element of the wrong type within an array. AssemblyLoadEventArgs Provides data for the AssemblyLoad event. Attribute Represents the base class for custom attributes. Specifies the usage of another attribute class. This AttributeUsageAttribute class cannot be inherited. The exception that is thrown when the file image of BadImageFormatException a dynamic link library (DLL) or an executable program is invalid. Converts base data types to an array of bytes, and BitConverter an array of bytes to base data types. Buffer Manipulates arrays of primitive types. The exception that is thrown when an attempt to CannotUnloadAppDomainException unload an application domain fails. Supports iterating over a String object and reading CharEnumerator its individual characters. This class cannot be inherited. Indicates whether a program element is compliant CLSCompliantAttribute with the Common Language Specification (CLS). This class cannot be inherited. Represents the standard input, output, and error Console streams for console applications. This class cannot be inherited. Provides data for the Console.CancelKeyPress ConsoleCancelEventArgs event. This class cannot be inherited. ContextBoundObject Defines the base class for all context-bound classes. The exception that is thrown when an attempt to ContextMarshalException marshal an object across a context boundary fails. ContextStaticAttribute Indicates that the value of a static field is unique for

Convert DataMisalignedException

DBNull Delegate

DivideByZeroException DllNotFoundException DuplicateWaitObjectException

EntryPointNotFoundException Enum Environment EventArgs Exception

ExecutionEngineException

FieldAccessException FileStyleUriParser FlagsAttribute FormatException

a particular context. Converts a base data type to another base data type. The exception that is thrown when a unit of data is read from or written to an address that is not a multiple of the data size. This class cannot be inherited. Represents a nonexistent value. This class cannot be inherited. Represents a delegate, which is a data structure that refers to a static method or to a class instance and an instance method of that class. The exception that is thrown when there is an attempt to divide an integral or decimal value by zero. The exception that is thrown when a DLL specified in a DLL import cannot be found. The exception that is thrown when an object appears more than once in an array of synchronization objects. The exception that is thrown when an attempt to load a class fails due to the absence of an entry method. Provides the base class for enumerations. Provides information about, and means to manipulate, the current environment and platform. This class cannot be inherited. EventArgs is the base class for classes containing event data. Represents errors that occur during application execution. Obsolete. The exception that is thrown when there is an internal error in the execution engine of the common language runtime. This class cannot be inherited. The exception that is thrown when there is an invalid attempt to access a private or protected field inside a class. A customizable parser based on the File scheme. Indicates that an enumeration can be treated as a bit field; that is, a set of flags. The exception that is thrown when the format of an argument does not meet the parameter specifications of the invoked method.

A customizable parser based on the File Transfer Protocol (FTP) scheme. Controls the system garbage collector, a service that GC automatically reclaims unused memory. GenericUriParser A customizable parser for a hierarchical URI. A customizable parser based on the Gopher GopherStyleUriParser scheme. HttpStyleUriParser A customizable parser based on the HTTP scheme. The exception that is thrown when an attempt is made to access an element of an array with an index IndexOutOfRangeException that is outside the bounds of the array. This class cannot be inherited. The exception that is thrown when there is InsufficientExecutionStackException insufficient execution stack available to allow most methods to execute. The exception that is thrown when a check for InsufficientMemoryException sufficient available memory fails. This class cannot be inherited. The exception that is thrown for invalid casting or InvalidCastException explicit conversion. The exception that is thrown when a method call is InvalidOperationException invalid for the object's current state. The exception that is thrown when a program contains invalid Microsoft intermediate language InvalidProgramException (MSIL) or metadata. Generally this indicates a bug in the compiler that generated the program. The exception that is thrown when time zone InvalidTimeZoneException information is invalid. Lazy<T> Provides support for lazy initialization. Provides a lazy indirect reference to an object and Lazy<T, TMetadata> its associated metadata for use by the Managed Extensibility Framework. A customizable parser based on the Lightweight LdapStyleUriParser Directory Access Protocol (LDAP) scheme. Used to set the default loader optimization policy LoaderOptimizationAttribute for the main method of an executable application. Encapsulates a memory slot to store local data. This LocalDataStoreSlot class cannot be inherited. Enables access to objects across application domain MarshalByRefObject boundaries in applications that support remoting. Provides constants and static methods for Math trigonometric, logarithmic, and other common FtpStyleUriParser

MemberAccessException

MethodAccessException

MissingFieldException

MissingMemberException

MissingMethodException MTAThreadAttribute MulticastDelegate

MulticastNotSupportedException

NetPipeStyleUriParser NetTcpStyleUriParser NewsStyleUriParser NonSerializedAttribute NotFiniteNumberException NotImplementedException

NotSupportedException

mathematical functions. The exception that is thrown when an attempt to access a class member fails. The exception that is thrown when there is an invalid attempt to access a method, such as accessing a private method from partially trusted code. The exception that is thrown when there is an attempt to dynamically access a field that does not exist. The exception that is thrown when there is an attempt to dynamically access a class member that does not exist. The exception that is thrown when there is an attempt to dynamically access a method that does not exist. Indicates that the COM threading model for an application is multithreaded apartment (MTA). Represents a multicast delegate; that is, a delegate that can have more than one element in its invocation list. The exception that is thrown when there is an attempt to combine two delegates based on the Delegate type instead of the MulticastDelegate type. This class cannot be inherited. A parser based on the NetPipe scheme for the "Indigo" system. A parser based on the NetTcp scheme for the "Indigo" system. A customizable parser based on the news scheme using the Network News Transfer Protocol (NNTP). Indicates that a field of a serializable class should not be serialized. This class cannot be inherited. The exception that is thrown when a floating-point value is positive infinity, negative infinity, or Nota-Number (NaN). The exception that is thrown when a requested method or operation is not implemented. The exception that is thrown when an invoked method is not supported, or when there is an attempt to read, seek, or write to a stream that does not support the invoked functionality.

Nullable NullReferenceException

Object

ObjectDisposedException ObsoleteAttribute OperatingSystem

OperationCanceledException

OutOfMemoryException

OverflowException

ParamArrayAttribute PlatformNotSupportedException

Random

RankException

ResolveEventArgs

SerializableAttribute StackOverflowException

Supports a value type that can be assigned null like a reference type. This class cannot be inherited. The exception that is thrown when there is an attempt to dereference a null object reference. Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy. The exception that is thrown when an operation is performed on a disposed object. Marks the program elements that are no longer in use. This class cannot be inherited. Represents information about an operating system, such as the version and platform identifier. This class cannot be inherited. The exception that is thrown in a thread upon cancellation of an operation that the thread was executing. The exception that is thrown when there is not enough memory to continue the execution of a program. The exception that is thrown when an arithmetic, casting, or conversion operation in a checked context results in an overflow. Indicates that a method will allow a variable number of arguments in its invocation. This class cannot be inherited. The exception that is thrown when a feature does not run on a particular platform. Represents a pseudo-random number generator, a device that produces a sequence of numbers that meet certain statistical requirements for randomness. The exception that is thrown when an array with the wrong number of dimensions is passed to a method. Provides data for loader resolution events, such as the TypeResolve, ResourceResolve, ReflectionOnlyAssemblyResolve, and AssemblyResolve events. Indicates that a class can be serialized. This class cannot be inherited. The exception that is thrown when the execution

STAThreadAttribute String StringComparer SystemException ThreadStaticAttribute TimeoutException TimeZone TimeZoneInfo TimeZoneInfo.AdjustmentRule TimeZoneNotFoundException Tuple Tuple<T1> Tuple<T1, T2> Tuple<T1, T2, T3> Tuple<T1, T2, T3, T4> Tuple<T1, T2, T3, T4, T5> Tuple<T1, T2, T3, T4, T5, T6> Tuple<T1, T2, T3, T4, T5, T6, T7> Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> Type

stack overflows because it contains too many nested method calls. This class cannot be inherited. Indicates that the COM threading model for an application is single-threaded apartment (STA). Represents text as a series of Unicode characters. Represents a string comparison operation that uses specific case and culture-based or ordinal comparison rules. Defines the base class for predefined exceptions in the System namespace. Indicates that the value of a static field is unique for each thread. The exception that is thrown when the time allotted for a process or operation has expired. Represents a time zone. Represents any time zone in the world. Provides information about a time zone adjustment, such as the transition to and from daylight saving time. The exception that is thrown when a time zone cannot be found. Provides static methods for creating tuple objects. Represents a 1-tuple, or singleton. Represents a 2-tuple, or pair. Represents a 3-tuple, or triple. Represents a 4-tuple, or quadruple. Represents a 5-tuple, or quintuple. Represents a 6-tuple, or sextuple. Represents a 7-tuple, or septuple. Represents an n-tuple, where n is 8 or greater. Represents type declarations: class types, interface types, array types, value types, enumeration types, type parameters, generic type definitions, and open or closed constructed generic types. The exception that is thrown when a method attempts to use a type that it does not have access to. The exception that is thrown as a wrapper around the exception thrown by the class initializer. This class cannot be inherited.

TypeAccessException

TypeInitializationException

TypeLoadException TypeUnloadedException UnauthorizedAccessException

UnhandledExceptionEventArgs

Uri

UriBuilder UriFormatException UriParser UriTemplate UriTemplateEquivalenceComparer UriTemplateMatch UriTemplateMatchException UriTemplateTable UriTypeConverter ValueType Version

WeakReference

The exception that is thrown when type-loading failures occur. The exception that is thrown when there is an attempt to access an unloaded class. The exception that is thrown when the operating system denies access because of an I/O error or a specific type of security error. Provides data for the event that is raised when there is an exception that is not handled in any application domain. Provides an object representation of a uniform resource identifier (URI) and easy access to the parts of the URI. Provides a custom constructor for uniform resource identifiers (URIs) and modifies URIs for the Uri class. The exception that is thrown when an invalid Uniform Resource Identifier (URI) is detected. Parses a new URI scheme. This is an abstract class. A class that represents a Uniform Resource Identifier (URI) template. A class used to compare UriTemplate instances for structural (instead of reference) equivalence. A class that represents the results of a match operation on a UriTemplate instance. Represents an error when matching a Uri to a UriTemplateTable. A class that represents an associative set of UriTemplate objects. Converts a String type to a Uri type, and vice versa. Provides the base class for value types. Represents the version number of an assembly, operating system, or the common language runtime. This class cannot be inherited. Represents a weak reference, which references an object while still allowing that object to be reclaimed by garbage collection.

DESCRIPCION DE LAS CLASES DEL ESPACIO DE NOMBRES System Namespace

AccessViolationException Class
.NET Framework 4

The exception that is thrown when there is an attempt to read or write protected memory.
Inheritance Hierarchy

System.Object System.Exception System.SystemException System.AccessViolationException Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[SerializableAttribute] [ComVisibleAttribute(true)] public class AccessViolationException : SystemException

The AccessViolationException type exposes the following members.


Constructors

Show:

Inherited

Protected Name Description Initializes a new instance of the AccessViolationException class with a systemsupplied message that describes the error. Initializes a new instance of the AccessViolationException class with a specified message that describes the error.

AccessViolationException()

AccessViolationException(String)

AccessViolationException(SerializationInfo, StreamingContext)

Initializes a new instance of the AccessViolationException class with serialized data. Initializes a new instance of the AccessViolationException class with a specified error message and a reference to the inner exception that is the cause of this exception.

AccessViolationException(String, Exception)

Properties

Show:

Inherited

Protected Description

Name Data

Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.) Gets or sets a link to the help file associated with this exception. (Inherited from Exception.) Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.) Gets the Exception instance that caused the current exception. (Inherited from Exception.) Gets a message that describes the current exception. (Inherited from Exception.) Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.) Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.) Gets the method that throws the current exception. (Inherited from Exception.)

HelpLink

HResult

InnerException Message Source

StackTrace TargetSite Methods

Show:

Inherited

Protected

Name Equals(Object)

Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.) Serves as a hash function for a particular type. (Inherited from Object.) When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.) Gets the runtime type of the current instance. (Inherited from Exception.)

Finalize

GetBaseException GetHashCode GetObjectData GetType

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Events Creates and returns a string representation of the current exception. (Inherited from Exception.)

Show:

Inherited Name

Protected Description

Occurs when an exception is serialized to create an exception state object SerializeObjectState that contains serialized data about the exception. (Inherited from Exception.) Remarks

An access violation occurs in unmanaged or unsafe code when the code attempts to read or write to memory that has not been allocated, or to which it does not have access. This usually occurs because a pointer has a bad value. Not all reads or writes through bad pointers lead to access violations, so an access violation usually indicates that several reads or writes have occurred through bad pointers, and that memory might be corrupted. Thus,

access violations almost always indicate serious programming errors. In the .NET Framework version 2.0, an AccessViolationException clearly identifies these serious errors. In programs consisting entirely of verifiable managed code, all references are either valid or null, and access violations are impossible. An AccessViolationException occurs only when verifiable managed code interacts with unmanaged code or with unsafe managed code.
Version Information

This exception is new in the .NET Framework version 2.0. In earlier versions of the .NET Framework, an access violation in unmanaged code or unsafe managed code is represented by a NullReferenceException in managed code. A NullReferenceException is also thrown when a null reference is dereferenced in verifiable managed code, an occurrence that does not involve data corruption, and there is no way to distinguish between the two situations in versions 1.0 or 1.1. Administrators can allow selected applications to revert to the behavior of the .NET Framework version 1.1. Place the following line in the <runtime> Element section of the configuration file for the application:
Copy
<legacyNullReferenceExceptionPolicy enabled = "1"/>

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

ActivationContext Class
.NET Framework 4

Identifies the activation context for the current application. This class cannot be inherited.
Inheritance Hierarchy

System.Object System.ActivationContext Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[SerializableAttribute] [ComVisibleAttribute(false)] public sealed class ActivationContext : IDisposable, ISerializable

The ActivationContext type exposes the following members.


Properties

Show:

Inherited Name

Protected Description

ApplicationManifestBytes Gets the ClickOnce application manifest for the current application. DeploymentManifestBytes Gets the ClickOnce deployment manifest for the current application. Form Identity Methods Gets the form, or store context, for the current application. Gets the application identity for the current application.

Show:

Inherited

Protected Name Description

Initializes a new instance of the CreatePartialActivationContext(ApplicationIdentity) ActivationContext class using the specified application identity.

Initializes a new instance of the CreatePartialActivationContext(ApplicationIdentity, ActivationContext class using the specified application identity and array of manifest String[]) paths. Dispose Releases all resources used by the ActivationContext. Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.) Creates a shallow copy of the current Object. (Inherited from Object.) Returns a string that represents the current object. (Inherited from Object.)

Equals(Object)

Finalize

GetHashCode

GetType

MemberwiseClone

ToString Explicit Interface Implementations

Show:

Inherited Name

Protected Description Infrastructure. Populates a SerializationInfo with the data needed to serialize the target object.

ISerializable.GetObjectData Remarks

The ActivationContext class contains an ApplicationIdentity and provides internal-only access to the application manifest. The activation context is used during manifest-based activation to set up the domain policy and provide an application-based security model. For more information, see the ApplicationSecurityManager class.
Examples

The following code example demonstrates the use of an ActivationContext object to obtain the ApplicationIdentity for a manifest-based application. For correct results, execute this code example as a manifest-based application.
C#
using using using using using using using System; System.Collections; System.Text; System.Security.Policy; System.Reflection; System.Security; System.Security.Permissions;

namespace ActivationContextSample { public class Program : MarshalByRefObject { [SecurityPermission(SecurityAction.LinkDemand, ControlDomainPolicy=true)] public static void Main(string[] args) { ActivationContext ac = AppDomain.CurrentDomain.ActivationContext; ApplicationIdentity ai = ac.Identity; Console.WriteLine("Full name = " + ai.FullName); Console.WriteLine("Code base = " + ai.CodeBase); Console.Read(); } [SecurityPermission(SecurityAction.LinkDemand, ControlDomainPolicy=true)] public void Run() { Main(new string[] { }); Console.ReadLine(); } } }

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

Activator Class
.NET Framework 4

Contains methods to create types of objects locally or remotely, or obtain references to existing remote objects. This class cannot be inherited.
Inheritance Hierarchy

System.Object System.Activator Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[ComVisibleAttribute(true)] [ClassInterfaceAttribute(ClassInterfaceType.None)] public sealed class Activator : _Activator

The Activator type exposes the following members.


Methods

Show:

Inherited

Protected

Name

Description Creates an instance of the COM object whose name is specified, using the named assembly file and the constructor that best matches the specified parameters. Creates an instance of the COM object whose name is specified, using the named assembly file and the default constructor. Creates an instance of the type designated by the specified ActivationContext object. Creates an instance of the specified type using that type's default constructor. Creates an instance of the type that is designated by the specified ActivationContext object and activated with the specified custom activation data. Creates an instance of the type whose name is specified, using the named assembly and default constructor. Creates an instance of the specified type using that type's default constructor. Creates an instance of the specified type using the constructor that best matches the specified parameters. Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and default constructor. Creates an instance of the type whose name is specified, using the named assembly and default constructor.

CreateComInstanceFrom(String, String)

CreateComInstanceFrom(String, String, Byte[], AssemblyHashAlgorithm)

CreateInstance(ActivationContext)

CreateInstance(Type)

CreateInstance(ActivationContext, String[])

CreateInstance(String, String)

CreateInstance(Type, Boolean)

CreateInstance(Type, Object[])

CreateInstance(AppDomain, String, String)

CreateInstance(String, String, Object[])

CreateInstance(Type, Object[], Object[])

Creates an instance of the specified type using the constructor that best matches the specified parameters. Creates an instance of the specified type using the constructor that best matches the specified parameters. Creates an instance of the specified type using the constructor that best matches the specified parameters. Creates an instance of the type whose name is specified, using the named assembly and the constructor that best matches the specified parameters. Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and the constructor that best matches the specified parameters. Obsolete. Creates an instance of the type whose name is specified, using the named assembly and the constructor that best matches the specified parameters. Obsolete. Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and the constructor that best matches the specified parameters. Creates an instance of the type designated by the specified generic type parameter, using the parameterless constructor . Creates an instance of the type whose name is specified, using the named assembly file and default constructor.

CreateInstance(Type, BindingFlags, Binder, Object[], CultureInfo)

CreateInstance(Type, BindingFlags, Binder, Object[], CultureInfo, Object[])

CreateInstance(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

CreateInstance(AppDomain, String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

CreateInstance(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence)

CreateInstance(AppDomain, String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence)

CreateInstance<T>()

CreateInstanceFrom(String, String)

Creates an instance of the type whose name is specified in the specified remote domain, CreateInstanceFrom(AppDomain, String, String) using the named assembly file and default constructor. Creates an instance of the type whose name is specified, using the named assembly file and default constructor. Creates an instance of the type whose name is specified, using the named assembly file and the constructor that best matches the specified parameters.

CreateInstanceFrom(String, String, Object[])

CreateInstanceFrom(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

Creates an instance of the type whose name is CreateInstanceFrom(AppDomain, String, String, specified in the specified remote domain, Boolean, BindingFlags, Binder, Object[], using the named assembly file and the constructor that best matches the specified CultureInfo, Object[]) parameters. CreateInstanceFrom(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence) Obsolete. Creates an instance of the type whose name is specified, using the named assembly file and the constructor that best matches the specified parameters.

Obsolete. Creates an instance of the type CreateInstanceFrom(AppDomain, String, String, whose name is specified in the specified Boolean, BindingFlags, Binder, Object[], remote domain, using the named assembly file and the constructor that best matches the CultureInfo, Object[], Evidence) specified parameters. Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Serves as a hash function for a particular type. (Inherited from Object.)

Equals(Object)

Finalize

GetHashCode

GetObject(Type, String)

Creates a proxy for the well-known object indicated by the specified type and URL. Creates a proxy for the well-known object indicated by the specified type, URL, and channel data. Gets the Type of the current instance. (Inherited from Object.) Creates a shallow copy of the current Object. (Inherited from Object.) Returns a string that represents the current object. (Inherited from Object.)

GetObject(Type, String, Object)

GetType

MemberwiseClone

ToString Explicit Interface Implementations

Show:

Inherited Name

Protected Description Maps a set of names to a corresponding set of dispatch identifiers. Retrieves the type information for an object, which can then be used to get the type information for an interface. Retrieves the number of type information interfaces that an object provides (either 0 or 1). Provides access to properties and methods exposed by an object.

_Activator.GetIDsOfNames _Activator.GetTypeInfo

_Activator.GetTypeInfoCount _Activator.Invoke Remarks

The CreateInstance method creates an instance of a type defined in an assembly by invoking the constructor that best matches the specified arguments. If no arguments are specified, the constructor that takes no parameters, that is, the default constructor, is invoked. You must have sufficient permission to search for and call a constructor; otherwise, an exception is thrown. By default, only public constructors are considered during the search

for a constructor. If no constructor or default constructor can be found, an exception is thrown. A binder parameter specifies an object that searches an assembly for a suitable constructor. You can specify your own binder and search criteria. If no binder is specified, a default binder is used. For more information, see the System.Reflection.Binder and System.Reflection.BindingFlags classes. An evidence parameter affects the security policy and permissions for the constructor. For more information, see the System.Security.Policy.Evidence class. An instance of a type can be created at a local or remote site. If the type is created remotely, an activation attribute parameter specifies the URI of the remote site. The call to create the instance might pass through intermediary sites before it reaches the remote site. Other activation attributes can modify the environment, or context, in which the call operates at the remote and intermediary sites. If the instance is created locally, a reference to that object is returned. If the instance is created remotely, a reference to a proxy is returned. The remote object is manipulated through the proxy as if it were a local object. The GetObject method creates a proxy to a currently running remote object, serveractivated well-known object, or XML Web service. You can specify the connection medium, that is, the channel. For more information, see the System.Runtime.Remoting.Channels.ChannelServices class. Assemblies contain type definitions. The CreateInstance method creates an instance of a type from a currently running assembly. The CreateInstanceFrom method creates an instance from a file that contains an assembly. The CreateComInstanceFrom method creates an instance of a COM object from a file that contains an assembly.
Examples

The following example shows how to use the Activator class to dynamically construct objects at run time.
C#
using System; using System.Reflection; using System.Text; public class SomeType { public void DoSomething(int x) {

Console.WriteLine("100 / {0} = {1}", x, 100 / x); } } public class Example { static void Main() { // Create an instance of the StringBuilder type using // Activator.CreateInstance. Object o = Activator.CreateInstance(typeof(StringBuilder)); // Append a string into the StringBuilder object and display the // StringBuilder. StringBuilder sb = (StringBuilder) o; sb.Append("Hello, there."); Console.WriteLine(sb); // Create an instance of the SomeType class that is defined in this // assembly. System.Runtime.Remoting.ObjectHandle oh = Activator.CreateInstanceFrom(Assembly.GetEntryAssembly().CodeBase, typeof(SomeType).FullName); // Call an instance method defined by the SomeType type using this object. SomeType st = (SomeType) oh.Unwrap(); st.DoSomething(5); } } /* This code produces the following output: Hello, there. 100 / 5 = 20 */

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

AggregateException Class
.NET Framework 4

Represents one or more errors that occur during application execution.


Inheritance Hierarchy

System.Object System.Exception System.AggregateException Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[SerializableAttribute] public class AggregateException : Exception

The AggregateException type exposes the following members.


Constructors

Show:

Inherited

Protected Name Description Initializes a new instance of the AggregateException class with a systemsupplied message that describes the error. Initializes a new instance of the

AggregateException()

AggregateException(IEnumerable<Exception>)

AggregateException class with references to the inner exceptions that are the cause of this exception. Initializes a new instance of the AggregateException class with references to the inner exceptions that are the cause of this exception. Initializes a new instance of the AggregateException class with a specified message that describes the error. Initializes a new instance of the AggregateException class with serialized data. Initializes a new instance of the AggregateException class with a specified error message and references to the inner exceptions that are the cause of this exception. Initializes a new instance of the AggregateException class with a specified error message and a reference to the inner exception that is the cause of this exception. Initializes a new instance of the AggregateException class with a specified error message and references to the inner exceptions that are the cause of this exception.

AggregateException(Exception[])

AggregateException(String)

AggregateException(SerializationInfo, StreamingContext)

AggregateException(String, IEnumerable<Exception>)

AggregateException(String, Exception)

AggregateException(String, Exception[])

Properties

Show:

Inherited Name

Protected Description

Data HelpLink

Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.) Gets or sets a link to the help file associated with this exception. (Inherited from

Exception.) HResult Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.) Gets the Exception instance that caused the current exception. (Inherited from Exception.) Gets a read-only collection of the Exception instances that caused the current exception. Gets a message that describes the current exception. (Inherited from Exception.) Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.) Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.) Gets the method that throws the current exception. (Inherited from Exception.)

InnerException

InnerExceptions Message Source

StackTrace TargetSite Methods

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Flattens an AggregateException instances into a single, new instance. Returns the AggregateException that is the root cause of this exception. (Overrides Exception.GetBaseException().) Serves as a hash function for a particular type. (Inherited from Object.)

Equals(Object)

Finalize

Flatten GetBaseException GetHashCode

GetObjectData GetType Handle

Initializes a new instance of the AggregateException class with serialized data. (Overrides Exception.GetObjectData(SerializationInfo, StreamingContext).) Gets the runtime type of the current instance. (Inherited from Exception.) Invokes a handler on each Exception contained by this AggregateException.

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Events Creates and returns a string representation of the current AggregateException. (Overrides Exception.ToString().)

Show:

Inherited Name

Protected Description

Occurs when an exception is serialized to create an exception state object SerializeObjectState that contains serialized data about the exception. (Inherited from Exception.) Remarks

AggregateException is used to consolidate multiple failures into a single, throwable exception object. It is used extensively in the Task Parallel Library and Parallel LINQ (PLINQ). For additional information, see the Aggregating Exceptions entry in the .NET Matters blog. For an example, see How to: Handle Exceptions Thrown by Tasks and How to: Handle Exceptions in a PLINQ Query.
Version Information

.NET Framework
Supported in: 4

.NET Framework Client Profile


Supported in: 4

AppDomain Class
.NET Framework 4

Represents an application domain, which is an isolated environment where applications execute. This class cannot be inherited.
Inheritance Hierarchy

System.Object System.MarshalByRefObject System.AppDomain Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[ComVisibleAttribute(true)] [ClassInterfaceAttribute(ClassInterfaceType.None)] public sealed class AppDomain : MarshalByRefObject, _AppDomain, IEvidenceFactory

The AppDomain type exposes the following members.


Properties

Show:

Inherited Name

Protected Description Gets the activation context for the current application domain. Gets the identity of the application in the application domain.

ActivationContext

ApplicationIdentity

ApplicationTrust

Gets information describing permissions granted to an application and whether the application has a trust level that allows it to run. Gets the base directory that the assembly resolver uses to probe for assemblies. Gets the current application domain for the current Thread. Gets the domain manager that was provided by the host when the application domain was initialized. Gets the directory that the assembly resolver uses to probe for dynamically created assemblies. Gets the Evidence associated with this application domain. Gets the friendly name of this application domain. Gets an integer that uniquely identifies the application domain within the process. Gets a value that indicates whether assemblies that are loaded into the current application domain execute with full trust. Gets a value that indicates whether the current application domain has a set of permissions that is granted to all assemblies that are loaded into the application domain. Gets or sets a value that indicates whether CPU and memory monitoring of application domains is enabled for the current process. Once monitoring is enabled for a process, it cannot be disabled. Gets the number of bytes that survived the last full, blocking collection and that are known to be referenced by the current application domain.

BaseDirectory

CurrentDomain

DomainManager

DynamicDirectory

Evidence FriendlyName Id

IsFullyTrusted

IsHomogenous

MonitoringIsEnabled

MonitoringSurvivedMemorySize

MonitoringSurvivedProcessMemorySize Gets the total bytes that survived from the last full,

blocking collection for all application domains in the process. Gets the total size, in bytes, of all memory allocations that have been made by the application domain since it MonitoringTotalAllocatedMemorySize was created, without subtracting memory that has been collected. Gets the total processor time that has been used by all threads while executing in the current application domain, since the process started. Gets the permission set of a sandboxed application domain. Gets the path under the base directory where the assembly resolver should probe for private assemblies. Gets the application domain configuration information for this instance. Gets an indication whether the application domain is configured to shadow copy files.

MonitoringTotalProcessorTime

PermissionSet

RelativeSearchPath

SetupInformation

ShadowCopyFiles Methods

Show:

Inherited

Protected Name Description Obsolete. Appends the specified directory name to the private path list. Returns the assembly display name after policy has been applied. Obsolete. Resets the path that specifies the location of private assemblies to the empty string (""). Obsolete. Resets the list of directories containing

AppendPrivatePath

ApplyPolicy

ClearPrivatePath

ClearShadowCopyPath

shadow copied assemblies to the empty string (""). Creates a new instance of a specified COM type. Parameters specify the name of a file that contains an assembly containing the type and the name of the type. Creates a new instance of a specified COM type. Parameters specify the name of a file that contains an assembly containing the type and the name of the type. Creates a new application domain with the specified name. Creates a new application domain with the given name using the supplied evidence. Creates a new application domain using the specified name, evidence, and application domain setup information. Creates a new application domain using the specified name, evidence, application domain setup information, default permission set, and array of fully trusted assemblies. Creates a new application domain with the given name, using evidence, application base path, relative search path, and a parameter that specifies whether a shadow copy of an assembly is to be loaded into the application domain. Creates a new application domain with the given name, using evidence, application base path, relative search path, and a parameter that specifies whether a shadow copy of an assembly is to be loaded into the application domain. Specifies a callback method that is invoked when the application domain is initialized, and an array of string arguments to pass the callback method.

CreateComInstanceFrom(String, String)

CreateComInstanceFrom(String, String, Byte[], AssemblyHashAlgorithm)

CreateDomain(String)

CreateDomain(String, Evidence)

CreateDomain(String, Evidence, AppDomainSetup)

CreateDomain(String, Evidence, AppDomainSetup, PermissionSet, StrongName[])

CreateDomain(String, Evidence, String, String, Boolean)

CreateDomain(String, Evidence, String, String, Boolean, AppDomainInitializer, String[])

CreateInstance(String, String)

Creates a new instance of the specified type defined in the specified assembly. Creates a new instance of the specified type defined in the specified assembly. A parameter specifies an array of activation attributes. Creates a new instance of the specified type defined in the specified assembly. Parameters specify a binder, binding flags, constructor arguments, culture-specific information used to interpret arguments, and optional activation attributes. Obsolete. Creates a new instance of the specified type defined in the specified assembly. Parameters specify a binder, binding flags, constructor arguments, culture-specific information used to interpret arguments, activation attributes, and authorization to create the type. Creates a new instance of the specified type. Parameters specify the assembly where the type is defined, and the name of the type. Creates a new instance of the specified type. Parameters specify the assembly where the type is defined, the name of the type, and an array of activation attributes. Creates a new instance of the specified type defined in the specified assembly, specifying whether the case of the type name is ignored; the binding attributes and the binder that are used to select the type to be created; the arguments of the constructor; the culture; and the activation attributes. Obsolete. Creates a new instance of the specified type. Parameters specify the name of the type, and how it is found and created. Creates a new instance of the specified type defined

CreateInstance(String, String, Object[])

CreateInstance(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

CreateInstance(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence)

CreateInstanceAndUnwrap(String, String)

CreateInstanceAndUnwrap(String, String, Object[])

CreateInstanceAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

CreateInstanceAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence) CreateInstanceFrom(String, String)

in the specified assembly file. CreateInstanceFrom(String, String, Object[]) Creates a new instance of the specified type defined in the specified assembly file.

CreateInstanceFrom(String, String, Boolean, Creates a new instance of the specified type defined BindingFlags, Binder, Object[], CultureInfo, in the specified assembly file. Object[]) CreateInstanceFrom(String, String, Boolean, Obsolete. Creates a new instance of the specified BindingFlags, Binder, Object[], CultureInfo, type defined in the specified assembly file. Object[], Evidence) CreateInstanceFromAndUnwrap(String, String) CreateInstanceFromAndUnwrap(String, String, Object[]) Creates a new instance of the specified type defined in the specified assembly file. Creates a new instance of the specified type defined in the specified assembly file. Creates a new instance of the specified type defined in the specified assembly file, specifying whether the case of the type name is ignored; the binding attributes and the binder that are used to select the type to be created; the arguments of the constructor; the culture; and the activation attributes. Obsolete. Creates a new instance of the specified type defined in the specified assembly file. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.) Defines a dynamic assembly with the specified name and access mode. Defines a dynamic assembly with the specified name, access mode, and custom attributes.

CreateInstanceFromAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

CreateInstanceFromAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence)

CreateObjRef

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess) DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, IEnumerable<CustomAttributeBuilder>)

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, Evidence) DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String) DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, IEnumerable<CustomAttributeBuilder>, SecurityContextSource) DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence) DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, PermissionSet, PermissionSet, PermissionSet) DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Boolean, IEnumerable<CustomAttributeBuilder>) DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, Evidence, PermissionSet, PermissionSet, PermissionSet) DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, PermissionSet, PermissionSet, PermissionSet) DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence, PermissionSet, PermissionSet, PermissionSet) DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence, PermissionSet, PermissionSet, PermissionSet, Boolean)

Obsolete. Defines a dynamic assembly using the specified name, access mode, and evidence. Defines a dynamic assembly using the specified name, access mode, and storage directory. Defines a dynamic assembly with the specified name, access mode, and custom attributes, and using the specified source for its security context. Obsolete. Defines a dynamic assembly using the specified name, access mode, storage directory, and evidence. Obsolete. Defines a dynamic assembly using the specified name, access mode, and permission requests. Defines a dynamic assembly using the specified name, access mode, storage directory, and synchronization option. Obsolete. Defines a dynamic assembly using the specified name, access mode, evidence, and permission requests.

Obsolete. Defines a dynamic assembly using the specified name, access mode, storage directory, and permission requests.

Obsolete. Defines a dynamic assembly using the specified name, access mode, storage directory, evidence, and permission requests. Obsolete. Defines a dynamic assembly using the specified name, access mode, storage directory, evidence, permission requests, and synchronization option.

DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, String, Evidence, PermissionSet, PermissionSet, PermissionSet, Boolean, IEnumerable<CustomAttributeBuilder>) DoCallBack

Obsolete. Defines a dynamic assembly with the specified name, access mode, storage directory, evidence, permission requests, synchronization option, and custom attributes. Executes the code in another application domain that is identified by the specified delegate. Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Executes the assembly contained in the specified file. Obsolete. Executes the assembly contained in the specified file, using the specified evidence. Executes the assembly contained in the specified file, using the specified arguments.

Equals(Object)

ExecuteAssembly(String)

ExecuteAssembly(String, Evidence)

ExecuteAssembly(String, String[])

Obsolete. Executes the assembly contained in the ExecuteAssembly(String, Evidence, String[]) specified file, using the specified evidence and arguments. ExecuteAssembly(String, String[], Byte[], AssemblyHashAlgorithm) Executes the assembly contained in the specified file, using the specified arguments, hash value, and hash algorithm.

Obsolete. Executes the assembly contained in the ExecuteAssembly(String, Evidence, String[], specified file, using the specified evidence, Byte[], AssemblyHashAlgorithm) arguments, hash value, and hash algorithm. ExecuteAssemblyByName(String) ExecuteAssemblyByName(AssemblyName, String[]) ExecuteAssemblyByName(String, Evidence) Executes an assembly given its display name. Executes the assembly given an AssemblyName, using the specified arguments. Obsolete. Executes an assembly given its display name, using the specified evidence. Executes the assembly given its display name, using the specified arguments.

ExecuteAssemblyByName(String, String[])

ExecuteAssemblyByName(AssemblyName, Evidence, String[])

Obsolete. Executes the assembly given an AssemblyName, using the specified evidence and arguments.

ExecuteAssemblyByName(String, Evidence, Obsolete. Executes the assembly given its display String[]) name, using the specified evidence and arguments. Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Gets the assemblies that have been loaded into the execution context of this application domain. Obsolete. Gets the current thread identifier. Gets the value stored in the current application domain for the specified name. Serves as a hash function for a particular type. (Inherited from Object.) Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.) Gets the type of the current instance. GetType In XNA Framework 3.0, this member is inherited from Object.GetType(). Gives the AppDomain an infinite lifetime by preventing a lease from being created. (Overrides MarshalByRefObject.InitializeLifetimeService().) Gets a nullable Boolean value that indicates whether any compatibility switches are set, and if so, whether the specified compatibility switch is set. Returns a value that indicates whether the application domain is the default application domain for the process.

Finalize

GetAssemblies GetCurrentThreadId GetData

GetHashCode

GetLifetimeService

InitializeLifetimeService

IsCompatibilitySwitchSet

IsDefaultAppDomain

IsFinalizingForUnload

Indicates whether this application domain is unloading, and the objects it contains are being finalized by the common language runtime. Loads an Assembly given its AssemblyName. Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. Loads an Assembly given its display name. Obsolete. Loads an Assembly given its AssemblyName. Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. The raw bytes representing the symbols for the Assembly are also loaded. Obsolete. Loads an Assembly given its display name. Obsolete. Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. The raw bytes representing the symbols for the Assembly are also loaded. Creates a shallow copy of the current Object. (Inherited from Object.) Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.) Returns the assemblies that have been loaded into the reflection-only context of the application domain. Obsolete. Establishes the security policy level for this application domain. Obsolete. Establishes the specified directory path

Load(AssemblyName)

Load(Byte[])

Load(String) Load(AssemblyName, Evidence)

Load(Byte[], Byte[])

Load(String, Evidence)

Load(Byte[], Byte[], Evidence)

MemberwiseClone()

MemberwiseClone(Boolean)

ReflectionOnlyGetAssemblies

SetAppDomainPolicy SetCachePath

as the location where assemblies are shadow copied. SetData(String, Object) Assigns the specified value to the specified application domain property. Assigns the specified value to the specified application domain property, with a specified permission to demand of the caller when the property is retrieved. Obsolete. Establishes the specified directory path as the base directory for subdirectories where dynamically generated files are stored and accessed. Specifies how principal and identity objects should be attached to a thread if the thread attempts to bind to a principal while executing in this application domain. Obsolete. Turns on shadow copying. Obsolete. Establishes the specified directory path as the location of assemblies to be shadow copied. Sets the default principal object to be attached to threads if they attempt to bind to a principal while executing in this application domain. Obtains a string representation that includes the friendly name of the application domain and any context policies. (Overrides Object.ToString().) Unloads the specified application domain.

SetData(String, Object, IPermission)

SetDynamicBase

SetPrincipalPolicy

SetShadowCopyFiles SetShadowCopyPath

SetThreadPrincipal

ToString

Unload Events

Show:

Inherited Name

Protected Description

AssemblyLoad AssemblyResolve DomainUnload

Occurs when an assembly is loaded. Occurs when the resolution of an assembly fails. Occurs when an AppDomain is about to be unloaded. Occurs when an exception is thrown in managed code, before the runtime searches the call stack for an exception handler in the application domain. Occurs when the default application domain's parent process exits. Occurs when the resolution of an assembly fails in the reflectiononly context. Occurs when the resolution of a resource fails because the resource is not a valid linked or embedded resource in the assembly. Occurs when the resolution of a type fails. Occurs when an exception is not caught.

FirstChanceException

ProcessExit

ReflectionOnlyAssemblyResolve

ResourceResolve

TypeResolve UnhandledException

Explicit Interface Implementations

Show:

Inherited Name

Protected Description Maps a set of names to a corresponding set of dispatch identifiers. Retrieves the type information for an object, which can then be used to get the type information for an interface. Retrieves the number of type information interfaces that an object provides (either 0 or 1). Provides access to properties and methods exposed by an object.

_AppDomain.GetIDsOfNames

_AppDomain.GetTypeInfo

_AppDomain.GetTypeInfoCount

_AppDomain.Invoke

Remarks

Application domains, which are represented by AppDomain objects, help provide isolation, unloading, and security boundaries for executing managed code.

Use application domains to isolate tasks that might bring down a process. If the state of the AppDomain that's executing a task becomes unstable, the AppDomain can be unloaded without affecting the process. This is important when a process must run for long periods without restarting. You can also use application domains to isolate tasks that should not share data. If an assembly is loaded into the default application domain, it cannot be unloaded from memory while the process is running. However, if you open a second application domain to load and execute the assembly, the assembly is unloaded when that application domain is unloaded. Use this technique to minimize the working set of long-running processes that occasionally use large DLLs.

Multiple application domains can run in a single process; however, there is not a one-to-one correlation between application domains and threads. Several threads can belong to a single application domain, and while a given thread is not confined to a single application domain, at any given time, a thread executes in a single application domain. Application domains are created using the CreateDomain method. AppDomain instances are used to load and execute assemblies (Assembly). When an AppDomain is no longer in use, it can be unloaded. The AppDomain class implements a set of events that enable applications to respond when an assembly is loaded, when an application domain will be unloaded, or when an unhandled exception is thrown. For more information on using application domains, see Application Domains. This class implements the MarshalByRefObject, _AppDomain, and IEvidenceFactory interfaces. You should never create a remotable wrapper for an AppDomain object. Doing so could publish a remote reference to that AppDomain, exposing methods such as CreateInstance to remote access and effectively destroying code access security for that AppDomain. Malicious clients connecting to the remoted AppDomain could obtain access to any resource the AppDomain itself has access to. Do not create remotable wrappers for any type that extends MarshalByRefObject and that implements methods that could be used by malicious clients to bypass the security system.
Caution

The default value for the AppDomainSetup.DisallowCodeDownload property is false. This setting is unsafe for services. To prevent services from downloading partially trusted code, set this property to true.
Topic How to: Configure an Application Domain Location .NET Framework: Programming Fundamentals .NET Framework: Programming Fundamentals .NET Framework: Programming Fundamentals .NET Framework: Programming Fundamentals .NET Framework: Programming Fundamentals .NET Framework: Programming Fundamentals .NET Framework: Programming Fundamentals .NET Framework: Programming Fundamentals

How to: Load Assemblies into an Application Domain How to: Create an Application Domain

How to: Unload an Application Domain

How to: Configure an Application Domain

How to: Load Assemblies into an Application Domain How to: Create an Application Domain

How to: Unload an Application Domain

How to: Configure an Application Domain Examples

This example shows how to create a new AppDomain, instantiate a type in that new AppDomain, and communicate with that types object. In addition, this example shows how to unload the AppDomain causing the object to be garbage collected.
C#
using System; using System.Reflection; using System.Threading; class Module1

{ public static void Main() { // Get and display the friendly name of the default AppDomain. string callingDomainName = Thread.GetDomain().FriendlyName; Console.WriteLine(callingDomainName); // Get and display the full name of the EXE assembly. string exeAssembly = Assembly.GetEntryAssembly().FullName; Console.WriteLine(exeAssembly); // Construct and initialize settings for a second AppDomain. AppDomainSetup ads = new AppDomainSetup(); ads.ApplicationBase = System.Environment.CurrentDirectory; ads.DisallowBindingRedirects = false; ads.DisallowCodeDownload = true; ads.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; // Create the second AppDomain. AppDomain ad2 = AppDomain.CreateDomain("AD #2", null, ads); // Create an instance of MarshalbyRefType in the second AppDomain. // A proxy to the object is returned. MarshalByRefType mbrt = (MarshalByRefType) ad2.CreateInstanceAndUnwrap( exeAssembly, typeof(MarshalByRefType).FullName ); // Call a method on the object via the proxy, passing the // default AppDomain's friendly name in as a parameter. mbrt.SomeMethod(callingDomainName); // Unload the second AppDomain. This deletes its object and // invalidates the proxy object. AppDomain.Unload(ad2); try { // Call the method again. Note that this time it fails // because the second AppDomain was unloaded. mbrt.SomeMethod(callingDomainName); Console.WriteLine("Sucessful call."); } catch(AppDomainUnloadedException) { Console.WriteLine("Failed call; this is expected."); } } } // Because this class is derived from MarshalByRefObject, a proxy // to a MarshalByRefType object can be returned across an AppDomain // boundary. public class MarshalByRefType : MarshalByRefObject

{ // Call this method via a proxy. public void SomeMethod(string callingDomainName) { // Get this AppDomain's settings and display some of them. AppDomainSetup ads = AppDomain.CurrentDomain.SetupInformation; Console.WriteLine("AppName={0}, AppBase={1}, ConfigFile={2}", ads.ApplicationName, ads.ApplicationBase, ads.ConfigurationFile ); // Display the name of the calling AppDomain and the name // of the second domain. // NOTE: The application's thread has transitioned between // AppDomains. Console.WriteLine("Calling from '{0}' to '{1}'.", callingDomainName, Thread.GetDomain().FriendlyName ); } } /* This code produces output similar to the following: AppDomainX.exe AppDomainX, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null AppName=, AppBase=C:\AppDomain\bin, ConfigFile=C:\AppDomain\bin\AppDomainX.exe.config Calling from 'AppDomainX.exe' to 'AD #2'. Failed call; this is expected. */

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

AppDomainManager Class
.NET Framework 4

Provides a managed equivalent of an unmanaged host.


Inheritance Hierarchy

System.Object System.MarshalByRefObject System.AppDomainManager Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[ComVisibleAttribute(true)] [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.Infrastructure)] public class AppDomainManager : MarshalByRefObject

The AppDomainManager type exposes the following members.


Constructors

Show:

Inherited Name

Protected Description

AppDomainManager Initializes a new instance of the AppDomainManager class. Properties

Show:

Inherited Name

Protected Description Gets the application activator that handles the activation of addins and manifest-based applications for the domain.

ApplicationActivator

EntryAssembly HostExecutionContextManager

Gets the entry assembly for an application. Gets the host execution context manager that manages the flow of the execution context. Gets the host security manager that participates in security decisions for the application domain. Gets the initialization flags for custom application domain managers.

HostSecurityManager

InitializationFlags Methods

Show:

Inherited Name

Protected Description Indicates whether the specified operation is allowed in the application domain. Returns a new or existing application domain. Provides a helper method to create an application domain. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.) Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Serves as a hash function for a particular type. (Inherited from Object.) Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)

CheckSecuritySettings CreateDomain CreateDomainHelper

CreateObjRef

Equals(Object)

Finalize

GetHashCode

GetLifetimeService

GetType InitializeLifetimeService InitializeNewDomain MemberwiseClone()

Gets the Type of the current instance. (Inherited from Object.) Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.) Initializes the new application domain. Creates a shallow copy of the current Object. (Inherited from Object.) Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.) Returns a string that represents the current object. (Inherited from Object.)

MemberwiseClone(Boolean)

ToString Exceptions

Exception

Condition

SecurityException The caller does not have the correct permissions. See the Requirements

section.
Remarks

Important

Do not use AppDomainManager to configure an application domain in ASP.NET. In ASP.NET, configuration must be handled by the host. Implementing the AppDomainManager class enables a hosting application to participate in the creation of new application domains. To replace the default AppDomainManager, identify the assembly and type of the replacement AppDomainManager in the APPDOMAIN_MANAGER_ASM and APPDOMAIN_MANAGER_TYPE environment variables, or use the <appDomainManagerAssembly> and <appDomainManagerType> elements in your configuration file. The assembly must be fully trusted and be contained in the global assembly cache or the directory of the starting application. The type and assembly names must be fully qualified in the environment variables. For example: set APPDOMAIN_MANAGER_TYPE=MyNamespace.TestAppDomainManager set APPDOMAIN_MANAGER_ASM=customappDomainmanager, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f1368f7b12a08d72

Important

If the assembly that contains your subclass of AppDomainManager depends on assemblies that are marked with the conditional AllowPartiallyTrustedCallersAttribute (APTCA) attribute, you must include those assemblies in the list that you pass to the PartialTrustVisibleAssemblies property of the AppDomainSetup you use to create application domains. Otherwise, the assemblies that are marked with the conditional APTCA attribute will be disabled. The AppDomainManager is the managed equivalent of the unmanaged host. An AppDomainManager object participates in the creation of new application domains in a process and can customize the new AppDomain before other managed code runs. The AppDomainManager can also supply host managers that participate in other aspects of common language runtime execution. For example, an AppDomainManager can identify a HostSecurityManager object that participates in the security decisions of the application domain.
Note

Only assemblies granted FullTrust, such as assemblies in the global assembly cache or identified as fullTrustAssemblies in the AppDomain.CreateDomain(String, Evidence, AppDomainSetup, PermissionSet, StrongName[]) method can be loaded in the AppDomainManager constructor and the InitializeNewDomain method.
Note

This class contains a link demand and an inheritance demand at the class level. A SecurityException is thrown when either the immediate caller or the derived class does not have infrastructure permission. For details about security demands, see Link Demands and Inheritance Demands.
Examples

The following example shows a very simple implementation of AppDomainManager.


C#
// To replace the default AppDomainManager, identify the // replacement assembly and replacement type in the // APPDOMAIN_MANAGER_ASM and APPDOMAIN_MANAGER_TYPE // environment variables. For example: // set APPDOMAIN_MANAGER_TYPE=library.TestAppDomainManager // set APPDOMAIN_MANAGER_ASM=library, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f1368f7b12a08d72 using System; using System.Collections; using System.Net;

using using using using using using using

System.Reflection; System.Security; System.Security.Permissions; System.Security.Policy; System.Security.Principal; System.Threading; System.Runtime.InteropServices;

[assembly: System.Security.AllowPartiallyTrustedCallersAttribute()] namespace MyNamespace { [GuidAttribute("F4D15099-3407-4A7E-A607-DEA440CF3891")] [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)] [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.Infrastructure)] public class MyAppDomainManager : AppDomainManager { private HostSecurityManager mySecurityManager = null; public MyAppDomainManager() { Console.WriteLine(" My AppDomain Manager "); mySecurityManager = AppDomain.CurrentDomain.CreateInstanceAndUnwrap( "CustomSecurityManager, Version=1.0.0.3, Culture=neutral, " + "PublicKeyToken=5659fc598c2a503e", "MyNamespace.MySecurityManager") as HostSecurityManager; Console.WriteLine(" Custom Security Manager Created."); } public override void InitializeNewDomain(AppDomainSetup appDomainInfo) { Console.Write("Initialize new domain called: "); Console.WriteLine(AppDomain.CurrentDomain.FriendlyName); InitializationFlags = AppDomainManagerInitializationOptions.RegisterWithHost; } public override HostSecurityManager HostSecurityManager { get { return mySecurityManager; } } } }

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 .NET Framework Security

SecurityCriticalAttribute

Requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code.

SecurityAction.InheritanceDemand

for derived classes to plug executable code into the common language runtime hosting infrastructure. Associated enumeration: SecurityPermissionFlag.Infrastructure.

AppDomainSetup Class
.NET Framework 4

Represents assembly binding information that can be added to an instance of AppDomain.


Inheritance Hierarchy

System.Object System.AppDomainSetup Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#

[SerializableAttribute] [ComVisibleAttribute(true)] [ClassInterfaceAttribute(ClassInterfaceType.None)] public sealed class AppDomainSetup : IAppDomainSetup

The AppDomainSetup type exposes the following members.


Constructors

Show:

Inherited Name

Protected Description Initializes a new instance of the AppDomainSetup class.

AppDomainSetup()

Initializes a new instance of the AppDomainSetup class AppDomainSetup(ActivationArguments) with the specified activation arguments required for manifest-based activation of an application domain. Initializes a new instance of the AppDomainSetup class with the specified activation context to use for manifestbased activation of an application domain.

AppDomainSetup(ActivationContext)

Properties

Show:

Inherited Name

Protected Description Gets or sets data about the activation of an application domain. Gets or sets the AppDomainInitializer delegate, which represents a callback method that is invoked when the application domain is initialized.

ActivationArguments

AppDomainInitializer

Gets or sets the arguments passed to the callback method AppDomainInitializerArguments represented by the AppDomainInitializer delegate. The callback method is invoked when the application domain is initialized. AppDomainManagerAssembly Gets or sets the display name of the assembly that provides the type of the application domain manager for application domains

created using this AppDomainSetup object. Gets or sets the full name of the type that provides the application domain manager for application domains created using this AppDomainSetup object. Gets or sets the name of the directory containing the application. Gets or sets the name of the application. Gets or sets an object containing security and trust information. Gets or sets the name of an area specific to the application where files are shadow copied. Gets or sets the name of the configuration file for an application domain. Specifies whether the application base path and private binary path are probed when searching for assemblies to load. Gets or sets a value that indicates whether an application domain allows assembly binding redirection. Gets or sets a value that indicates whether HTTP download of assemblies is allowed for an application domain. Gets or sets a value that indicates whether the <publisherPolicy> section of the configuration file is applied to an application domain. Gets or sets the base directory where the directory for dynamically generated files is located. Gets or sets the location of the license file associated with this domain. Specifies the optimization policy used to load an executable. Gets or sets a list of assemblies marked with the NotVisibleByDefault flag that are made visible to partial-trust code running in a sandboxed application domain.

AppDomainManagerType

ApplicationBase ApplicationName ApplicationTrust CachePath

ConfigurationFile

DisallowApplicationBaseProbing

DisallowBindingRedirects

DisallowCodeDownload

DisallowPublisherPolicy

DynamicBase

LicenseFile LoaderOptimization

PartialTrustVisibleAssemblies

PrivateBinPath

Gets or sets the list of directories under the application base directory that are probed for private assemblies. Gets or sets a string value that includes or excludes ApplicationBase from the search path for the application, and searches only PrivateBinPath. Gets or sets a value that indicates whether interface caching is disabled for interop calls in the application domain, so that a QueryInterface is performed on each call. Gets or sets the names of the directories containing assemblies to be shadow copied. Gets or sets a string that indicates whether shadow copying is turned on or off.

PrivateBinPathProbe

SandboxInterop

ShadowCopyDirectories

ShadowCopyFiles Methods

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Returns the XML configuration information set by the SetConfigurationBytes method, which overrides the application's XML configuration information. Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.) Creates a shallow copy of the current Object. (Inherited from Object.)

Equals(Object)

Finalize

GetConfigurationBytes

GetHashCode GetType MemberwiseClone

SetCompatibilitySwitches Sets the specified switches, making the application domain compatible

with previous versions of the .NET Framework for the specified issues. SetConfigurationBytes Provides XML configuration information for the application domain, replacing the application's XML configuration information. Returns a string that represents the current object. (Inherited from Object.)

ToString Remarks

Changing the properties of an AppDomainSetup instance does not affect any existing AppDomain. It can affect only the creation of a new AppDomain, when the CreateDomain method is called with the AppDomainSetup instance as a parameter. This class implements the IAppDomainSetup interface.
Caution

The default value for the DisallowCodeDownload property is false. This setting is unsafe for services. To help prevent services from downloading partially trusted code, set this property to true
Topic How to: Configure an Application Domain How to: Configure an Application Domain How to: Configure an Application Domain Version Information Location .NET Framework: Programming Fundamentals .NET Framework: Programming Fundamentals

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

AppDomainUnloadedException Class
.NET Framework 4

The exception that is thrown when an attempt is made to access an unloaded application domain.
Inheritance Hierarchy

System.Object System.Exception System.SystemException System.AppDomainUnloadedException Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[SerializableAttribute] [ComVisibleAttribute(true)] public class AppDomainUnloadedException : SystemException

The AppDomainUnloadedException type exposes the following members.


Constructors

Show:

Inherited

Protected Name Description Initializes a new instance of the AppDomainUnloadedException class. Initializes a new instance of the AppDomainUnloadedException class with a specified error message.

AppDomainUnloadedException()

AppDomainUnloadedException(String)

AppDomainUnloadedException(SerializationInfo, StreamingContext)

Initializes a new instance of the AppDomainUnloadedException class with serialized data.

Initializes a new instance of the AppDomainUnloadedException class with a AppDomainUnloadedException(String, Exception) specified error message and a reference to the inner exception that is the cause of this exception. Properties

Show:

Inherited

Protected Description

Name Data

Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.) Gets or sets a link to the help file associated with this exception. (Inherited from Exception.) Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.) Gets the Exception instance that caused the current exception. (Inherited from Exception.) Gets a message that describes the current exception. (Inherited from Exception.) Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.) Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.) Gets the method that throws the current exception. (Inherited from Exception.)

HelpLink

HResult

InnerException Message Source

StackTrace TargetSite Methods

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.) Serves as a hash function for a particular type. (Inherited from Object.) When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.) Gets the runtime type of the current instance. (Inherited from Exception.)

Equals(Object)

Finalize

GetBaseException GetHashCode GetObjectData

GetType In XNA Framework 3.0, this member is inherited from Object.GetType(). MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Events Creates and returns a string representation of the current exception. (Inherited from Exception.)

Show:

Inherited Name

Protected Description

Occurs when an exception is serialized to create an exception state object SerializeObjectState that contains serialized data about the exception. (Inherited from Exception.) Remarks

In the .NET Framework version 2.0, an AppDomainUnloadedException that is not handled in user code has the following effect:

If a thread was started in managed code, it is terminated. The unhandled exception is not allowed to terminate the application. If a task is executing on a ThreadPool thread, it is terminated and the thread is returned to the thread pool. The unhandled exception is not allowed to terminate the application. If a thread started in unmanaged code, such as the main application thread, it is terminated. The unhandled exception is allowed to proceed, and the operating system terminates the application.

AppDomainUnloadedException uses the HRESULT COR_E_APPDOMAINUNLOADED, which has the value 0x80131014. For a list of initial property values for an instance of AppDomainUnloadedException, see the AppDomainUnloadedException constructors.
Examples

This section contains two code examples. The first example demonstrates the effects of an AppDomainUnloadedException on various threads, and the second shows elementary application domain unloading. Example 1 The following code example defines a TestClass class that can be marshaled across application domain boundaries and an Example class containing a static (Shared in Visual Basic) ThreadProc method. The ThreadProc method creates an application domain, creates a TestClass object in the domain, and calls a method of TestClass that unloads the executing domain, causing an AppDomainUnloadedException. The TestClass method is executed without exception handling from a ThreadPool thread and from an ordinary thread, demonstrating that the unhandled exception terminates the task or thread but not the application. It is then executed with and without exception handling from the main application thread, demonstrating that it terminates the application if not handled.
C#
using System; using System.Threading; using System.Runtime.InteropServices; public class Example {

public static void Main() { // 1. Queue ThreadProc as a task for a ThreadPool thread. ThreadPool.QueueUserWorkItem(ThreadProc, " from a ThreadPool thread"); Thread.Sleep(1000); // 2. Execute ThreadProc on an ordinary thread. Thread t = new Thread(ThreadProc); t.Start(" from an ordinary thread"); t.Join(); // 3. Execute ThreadProc on the main thread, with // exception handling. try { ThreadProc(" from the main application thread (handled)"); } catch (AppDomainUnloadedException adue) { Console.WriteLine("Main thread caught AppDomainUnloadedException: {0}", adue.Message); } // 4. Execute ThreadProc on the main thread without // exception handling. ThreadProc(" from the main application thread (unhandled)"); Console.WriteLine("Main: This message is never displayed."); } private static void ThreadProc(object state) { // Create an application domain, and create an instance // of TestClass in the application domain. The first // parameter of CreateInstanceAndUnwrap is the name of // this executable. If you compile the example code using // any name other than "Sample.exe", you must change the // parameter appropriately. AppDomain ad = AppDomain.CreateDomain("TestDomain"); TestClass tc = (TestClass)ad.CreateInstanceAndUnwrap("Sample", "TestClass"); // In the new application domain, execute a method that // unloads the AppDomain. The unhandled exception this // causes ends the current thread. tc.UnloadCurrentDomain(state); Console.WriteLine("ThreadProc: This message is never displayed."); } } // TestClass derives from MarshalByRefObject, so it can be marshaled // across application domain boundaries. // public class TestClass : MarshalByRefObject

{ public void UnloadCurrentDomain(object state) { Console.WriteLine("\nUnloading the current AppDomain{0}.", state); // Unload the current application domain. This causes // an AppDomainUnloadedException to be thrown. // AppDomain.Unload(AppDomain.CurrentDomain); } } /* This code example produces output similar to the following: Unloading the current AppDomain from a ThreadPool thread. Unloading the current AppDomain from an ordinary thread. Unloading the current AppDomain from the main application thread (handled). Main thread caught AppDomainUnloadedException: The application domain in which the thread was running has been unloaded. Unloading the current AppDomain from the main application thread (unhandled). Unhandled Exception: System.AppDomainUnloadedException: The application domain in which the thread was running has been unloaded. at TestClass.UnloadCurrentDomain(Object state) at Example.ThreadProc(Object state) at Example.Main() */

Example 2 The following code example creates and unloads an application domain, and demonstrates that an AppDomainUnloadedException is thrown on a subsequent attempt to access the unloaded domain.
C#
using using using class { System; System.Reflection; System.Security.Policy; ADUnload

//for evidence object

public static void Main() { //Create evidence for the new appdomain. Evidence adevidence = AppDomain.CurrentDomain.Evidence; // Create the new application domain.

AppDomain domain = AppDomain.CreateDomain("MyDomain", adevidence); Console.WriteLine("Host domain: " + AppDomain.CurrentDomain.FriendlyName); Console.WriteLine("child domain: " + domain.FriendlyName); // Unload the application domain. AppDomain.Unload(domain); try { Console.WriteLine(); // Note that the following statement creates an exception because the domain no longer exists. Console.WriteLine("child domain: " + domain.FriendlyName); } catch (AppDomainUnloadedException e) { Console.WriteLine("The appdomain MyDomain does not exist."); } } }

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

ApplicationException Class
.NET Framework 4

The exception that is thrown when a non-fatal application error occurs.


Inheritance Hierarchy

System.Object System.Exception System.ApplicationException More... Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[SerializableAttribute] [ComVisibleAttribute(true)] public class ApplicationException : Exception

The ApplicationException type exposes the following members.


Constructors

Show:

Inherited

Protected Description Initializes a new instance of the ApplicationException class. Initializes a new instance of the ApplicationException class with a specified error message. Initializes a new instance of the ApplicationException class with serialized data. Initializes a new instance of the ApplicationException class with a specified error message and a reference to the inner exception that is the cause of this exception.

Name ApplicationException()

ApplicationException(String) ApplicationException(SerializationInfo, StreamingContext)

ApplicationException(String, Exception)

Properties

Show:

Inherited

Protected Description

Name Data

Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.) Gets or sets a link to the help file associated with this exception. (Inherited from Exception.) Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.) Gets the Exception instance that caused the current exception. (Inherited from Exception.) Gets a message that describes the current exception. (Inherited from Exception.) Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.) Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.) Gets the method that throws the current exception. (Inherited from Exception.)

HelpLink

HResult

InnerException Message Source

StackTrace TargetSite Methods

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)

Equals(Object)

Finalize

GetBaseException

GetHashCode GetObjectData

Serves as a hash function for a particular type. (Inherited from Object.) When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.) Gets the runtime type of the current instance. (Inherited from Exception.)

GetType In XNA Framework 3.0, this member is inherited from Object.GetType(). MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Events Creates and returns a string representation of the current exception. (Inherited from Exception.)

Show:

Inherited Name

Protected Description

Occurs when an exception is serialized to create an exception state object SerializeObjectState that contains serialized data about the exception. (Inherited from Exception.) Remarks

User applications, not the common language runtime, throw custom exceptions derived from the ApplicationException class. The ApplicationException class differentiates between exceptions defined by applications versus exceptions defined by the system. If you are designing an application that needs to create its own exceptions, you are advised to derive custom exceptions from the Exception class. It was originally thought that custom exceptions should derive from the ApplicationException class; however in practice this has not been found to add significant value. For more information, see Best Practices for Handling Exceptions. ApplicationException uses the HRESULT COR_E_APPLICATION, which has the value 0x80131600. For a list of initial property values for an instance of ApplicationException, see the ApplicationException constructors.

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

ApplicationId Class
.NET Framework 4

Contains information used to uniquely identify a manifest-based application. This class cannot be inherited.
Inheritance Hierarchy

System.Object System.ApplicationId Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[SerializableAttribute] [ComVisibleAttribute(true)] public sealed class ApplicationId

The ApplicationId type exposes the following members.


Constructors

Show: Name

Inherited

Protected Description

ApplicationId Initializes a new instance of the ApplicationId class. Properties

Show:

Inherited Name

Protected Description Gets a string representing the culture information for the application. Gets the name of the application.

Culture Name

ProcessorArchitecture Gets the target processor architecture for the application. PublicKeyToken Version Methods Gets the public key token for the application. Gets the version of the application.

Show:

Inherited Name

Protected Description Creates and returns an identical copy of the current application identity. Determines whether the specified ApplicationId object is equivalent to the current ApplicationId. (Overrides Object.Equals(Object).) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Gets the hash code for the current application identity. (Overrides Object.GetHashCode().)

Copy Equals

Finalize

GetHashCode

GetType

Gets the Type of the current instance. (Inherited from Object.)

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Remarks Creates and returns a string representation of the application identity. (Overrides Object.ToString().)

An application identity consists of the publisher's public key, the application name, the target processor architecture, the application culture, and the application version. The application identity properties values correspond to information contained in the application manifest. For more information about the application manifest, see ClickOnce Application Manifest. ApplicationId is used by the ApplicationSecurityInfo class to identify a manifest-based application.
Examples

The following code example displays the ApplicationId properties by obtaining the ApplicationId from an ApplicationSecurityInfo instance created using the ActivationContext for the currently executing manifest-based application.
C#
using using using using using using using System; System.Collections; System.Text; System.Security.Policy; System.Reflection; System.Security; System.Security.Permissions;

namespace ActivationContextSample { public class Program : MarshalByRefObject { [SecurityPermission(SecurityAction.Demand, ControlDomainPolicy = true)] public static void Main(string[] args) { Console.WriteLine("Full name = " + AppDomain.CurrentDomain.ActivationContext.Identity.FullName); Console.WriteLine("Code base = " +

AppDomain.CurrentDomain.ActivationContext.Identity.CodeBase); ApplicationSecurityInfo asi = new ApplicationSecurityInfo(AppDomain.CurrentDomain.ActivationContext); Console.WriteLine("ApplicationId.Name property = " + asi.ApplicationId.Name); if (asi.ApplicationId.Culture != null) Console.WriteLine("ApplicationId.Culture property = " + asi.ApplicationId.Culture.ToString()); Console.WriteLine("ApplicationId.ProcessorArchitecture property = " + asi.ApplicationId.ProcessorArchitecture); Console.WriteLine("ApplicationId.Version property = " + asi.ApplicationId.Version); // To display the value of the public key, enumerate the Byte array for the property. Console.Write("ApplicationId.PublicKeyToken property = "); byte[] pk = asi.ApplicationId.PublicKeyToken; for (int i = 0; i < pk.GetLength(0); i++) Console.Write("{0:x}", pk[i]); Console.Read(); } public void Run() { Main(new string[] { }); Console.ReadLine(); } } }

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

ApplicationIdentity Class
.NET Framework 4

Provides the ability to uniquely identify a manifest-activated application. This class cannot be inherited.
Inheritance Hierarchy

System.Object System.ApplicationIdentity Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[SerializableAttribute] [ComVisibleAttribute(false)] public sealed class ApplicationIdentity : ISerializable

The ApplicationIdentity type exposes the following members.


Constructors

Show:

Inherited Name

Protected Description

ApplicationIdentity Initializes a new instance of the ApplicationIdentity class. Properties

Show: Name

Inherited

Protected Description

CodeBase Gets the location of the deployment manifest as a URL. FullName Gets the full name of the application.

Methods

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.)

Equals(Object)

Finalize

GetHashCode GetType

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Infrastructure. Returns the full name of the manifest-activated application. (Overrides Object.ToString().)

Explicit Interface Implementations

Show:

Inherited Name

Protected Description Infrastructure. Populates a SerializationInfo object with the data needed to serialize the target object.

ISerializable.GetObjectData Remarks

The ApplicationIdentity class is used in the activation of manifest-based applications.


Examples

The following code example demonstrates the use of an ActivationContext object to obtain the ApplicationIdentity for a manifest-based application. This code example is part of a larger example provided for the ActivationContext class.
C#
ActivationContext ac = AppDomain.CurrentDomain.ActivationContext; ApplicationIdentity ai = ac.Identity;

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

ArgumentException Class
.NET Framework 4

The exception that is thrown when one of the arguments provided to a method is not valid.
Inheritance Hierarchy

System.Object System.Exception System.SystemException System.ArgumentException More... Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[SerializableAttribute] [ComVisibleAttribute(true)] public class ArgumentException : SystemException, ISerializable

The ArgumentException type exposes the following members.


Constructors

Show:

Inherited

Protected Name Description Initializes a new instance of the ArgumentException class. Initializes a new instance of the ArgumentException class with a specified error message. Initializes a new instance of the ArgumentException class with serialized data. Initializes a new instance of the ArgumentException class with a specified error message and a reference to the inner exception that is the cause of this exception. Initializes a new instance of the ArgumentException class with a specified error message and the name of the parameter that causes this exception. Initializes a new instance of the ArgumentException class with a specified error message, the parameter name, and a reference to the inner exception that is the cause of this exception.

ArgumentException()

ArgumentException(String) ArgumentException(SerializationInfo, StreamingContext)

ArgumentException(String, Exception)

ArgumentException(String, String)

ArgumentException(String, String, Exception)

Properties

Show:

Inherited

Protected

Name Data

Description Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.) Gets or sets a link to the help file associated with this exception. (Inherited from Exception.) Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.) Gets the Exception instance that caused the current exception. (Inherited from Exception.) Gets the error message and the parameter name, or only the error message if no parameter name is set. (Overrides Exception.Message.)

HelpLink

HResult

InnerException

Message

In XNA Framework 3.0, this member is inherited from Exception.Message. In Portable Class Library Portable Class Library, this member is inherited from Exception.Message.

ParamName Source

Gets the name of the parameter that causes this exception. Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.) Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.) Gets the method that throws the current exception. (Inherited from Exception.)

StackTrace

TargetSite Methods

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.)

Equals(Object)

Finalize

Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.) Serves as a hash function for a particular type. (Inherited from Object.) Sets the SerializationInfo object with the parameter name and additional exception information. (Overrides Exception.GetObjectData(SerializationInfo, StreamingContext).) Gets the runtime type of the current instance. (Inherited from Exception.) In XNA Framework 3.0, this member is inherited from Object.GetType(). In Portable Class Library Portable Class Library, this member is inherited from Object.GetType().

GetBaseException GetHashCode

GetObjectData

GetType

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Events Creates and returns a string representation of the current exception. (Inherited from Exception.)

Show:

Inherited Name

Protected Description

Occurs when an exception is serialized to create an exception state object SerializeObjectState that contains serialized data about the exception. (Inherited from Exception.) Remarks

ArgumentException is thrown when a method is invoked and at least one of the passed arguments does not meet the parameter specification of the called method. All instances of

ArgumentException should carry a meaningful error message describing the invalid argument, as well as the expected range of values for the argument. The primary derived classes of ArgumentException are ArgumentNullException and ArgumentOutOfRangeException. These derived classes should be used instead of ArgumentException, except in situations where neither of the derived classes is acceptable. For example, exceptions should be thrown by:

ArgumentNullException whenever null is passed to a method that does not accept it as a valid argument. ArgumentOutOfRangeException when the value of an argument is outside the range of acceptable values; for example, when the value "46" is passed as the month argument during the creation of a DateTime.

If the method call does not have any argument or if the failure does not involve the arguments themselves, then InvalidOperationException should be used. ArgumentException uses the HRESULT COR_E_ARGUMENT, which has the value 0x80070057. For a list of initial property values for an instance of ArgumentException, see the ArgumentException constructors.
Examples

The following example demonstrates how to throw and catch an ArgumentException.


C#
using System; public sealed class App { static void Main() { // ArgumentException is not thrown because 10 is an even number. Console.WriteLine("10 divided by 2 is {0}", DivideByTwo(10)); try { // ArgumentException is thrown because 7 is not an even number. Console.WriteLine("7 divided by 2 is {0}", DivideByTwo(7)); } catch (ArgumentException) { // Show the user that 7 cannot be divided by 2. Console.WriteLine("7 is not divided by 2 integrally."); }

} static int DivideByTwo(int num) { // If num is an odd number, throw an ArgumentException. if ((num & 1) == 1) throw new ArgumentException("Number must be even", "num"); // num is even, return half of its value. return num / 2; } } // This code produces the following output. // // 10 divided by 2 is 5 // 7 is not divided by 2 integrally.

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

Portable Class Library


Supported in: Portable Class Library

ArgumentNullException Class
.NET Framework 4

The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.
Inheritance Hierarchy

System.Object System.Exception System.SystemException System.ArgumentException System.ArgumentNullException Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[SerializableAttribute] [ComVisibleAttribute(true)] public class ArgumentNullException : ArgumentException

The ArgumentNullException type exposes the following members.


Constructors

Show:

Inherited

Protected Name Description Initializes a new instance of the ArgumentNullException class. Initializes a new instance of the ArgumentNullException class with the name of the parameter that causes this exception. Initializes a new instance of the ArgumentNullException class with serialized data. Initializes a new instance of the ArgumentNullException class with a specified error message and the exception that is the cause of this exception.

ArgumentNullException()

ArgumentNullException(String)

ArgumentNullException(SerializationInfo, StreamingContext)

ArgumentNullException(String, Exception)

ArgumentNullException(String, String)

Initializes an instance of the ArgumentNullException class with a specified error message and the name of the parameter that causes this exception.

Properties

Show:

Inherited Name

Protected Description

Data

Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.) Gets or sets a link to the help file associated with this exception. (Inherited from Exception.) Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.) Gets the Exception instance that caused the current exception. (Inherited from Exception.) Gets the error message and the parameter name, or only the error message if no parameter name is set. (Inherited from ArgumentException.)

HelpLink

HResult

InnerException

Message

In XNA Framework 3.0, this member is inherited from Exception.Message. In Portable Class Library Portable Class Library, this member is inherited from Exception.Message.

ParamName

Gets the name of the parameter that causes this exception. (Inherited from ArgumentException.) Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.) Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.) Gets the method that throws the current exception. (Inherited from

Source

StackTrace TargetSite

Exception.) Methods

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.) Serves as a hash function for a particular type. (Inherited from Object.) Sets the SerializationInfo object with the parameter name and additional exception information. (Inherited from ArgumentException.) Gets the runtime type of the current instance. (Inherited from Exception.) In XNA Framework 3.0, this member is inherited from Object.GetType(). In Portable Class Library Portable Class Library, this member is inherited from Object.GetType().

Equals(Object)

Finalize

GetBaseException GetHashCode GetObjectData

GetType

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Events Creates and returns a string representation of the current exception. (Inherited from Exception.)

Show:

Inherited

Protected

Name

Description

Occurs when an exception is serialized to create an exception state object SerializeObjectState that contains serialized data about the exception. (Inherited from Exception.) Remarks

ArgumentNullException is thrown when a method is invoked and at least one of the passed arguments is null but should never be null. ArgumentNullException behaves identically to ArgumentException. It is provided so that application code can differentiate between exceptions caused by null arguments and exceptions caused by arguments that are not null. For errors caused by arguments that are not null, see ArgumentOutOfRangeException. ArgumentNullException uses the HRESULT E_POINTER, which has the value 0x80004003. For a list of initial property values for an instance of ArgumentNullException, see the ArgumentNullException constructors.
Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

Portable Class Library


Supported in: Portable Class Library

ArgumentOutOfRangeException Class
.NET Framework 4

The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.
Inheritance Hierarchy

System.Object System.Exception System.SystemException System.ArgumentException System.ArgumentOutOfRangeException Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[SerializableAttribute] [ComVisibleAttribute(true)] public class ArgumentOutOfRangeException : ArgumentException, ISerializable

The ArgumentOutOfRangeException type exposes the following members.


Constructors

Show:

Inherited

Protected Name Description Initializes a new instance of the ArgumentOutOfRangeException class. Initializes a new instance of the ArgumentOutOfRangeException class with the name of the parameter that causes this exception. Initializes a new instance of the ArgumentOutOfRangeException class with

ArgumentOutOfRangeException()

ArgumentOutOfRangeException(String)

ArgumentOutOfRangeException(SerializationInfo,

StreamingContext)

serialized data.

Initializes a new instance of the ArgumentOutOfRangeException class with ArgumentOutOfRangeException(String, Exception) a specified error message and the exception that is the cause of this exception. Initializes a new instance of the ArgumentOutOfRangeException class with a specified error message and the name of the parameter that causes this exception. Initializes a new instance of the ArgumentOutOfRangeException class with a specified error message, the parameter name, and the value of the argument.

ArgumentOutOfRangeException(String, String)

ArgumentOutOfRangeException(String, Object, String)

Properties

Show:

Inherited Name

Protected Description

ActualValue Data

Gets the argument value that causes this exception. Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.) Gets or sets a link to the help file associated with this exception. (Inherited from Exception.) Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.) Gets the Exception instance that caused the current exception. (Inherited from Exception.) Gets the error message and the string representation of the invalid argument value, or only the error message if the argument value is null. (Overrides ArgumentException.Message.)

HelpLink

HResult

InnerException

Message

In XNA Framework 3.0, this member is inherited from Exception.Message. In Portable Class Library Portable Class Library, this member is inherited from Exception.Message. ParamName Gets the name of the parameter that causes this exception. (Inherited from ArgumentException.) Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.) Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.) Gets the method that throws the current exception. (Inherited from Exception.)

Source

StackTrace

TargetSite Methods

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.) Serves as a hash function for a particular type. (Inherited from Object.) Sets the SerializationInfo object with the invalid argument value and additional exception information. (Overrides ArgumentException.GetObjectData(SerializationInfo, StreamingContext).) Gets the runtime type of the current instance. (Inherited from Exception.)

Equals(Object)

Finalize

GetBaseException GetHashCode

GetObjectData

GetType

In XNA Framework 3.0, this member is inherited from Object.GetType(). In Portable Class Library Portable Class Library, this member is inherited from Object.GetType(). MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Events Creates and returns a string representation of the current exception. (Inherited from Exception.)

Show:

Inherited Name

Protected Description

Occurs when an exception is serialized to create an exception state object SerializeObjectState that contains serialized data about the exception. (Inherited from Exception.) Remarks

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 value. ArgumentOutOfRangeException is used extensively by:

Classes in the System.Collections and System.IO namespaces. The Array class.

ArgumentOutOfRangeException behaves identically to 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 ArgumentNullException. ArgumentOutOfRangeException uses the HRESULT COR_E_ARGUMENTOUTOFRANGE, which has the value 0x80131502. For a list of initial property values for an instance of ArgumentOutOfRangeException, see the ArgumentOutOfRangeException constructors.

Examples

The following example defines a class to contain information about an invited guest. If the guest is younger than 21, an ArgumentOutOfRangeException exception is thrown.
C#
using System; class Program { static void Main(string[] args) { try { Guest guest1 = new Guest("Ben", "Miller", 17); Console.WriteLine(guest1.GuestInfo()); } catch (ArgumentOutOfRangeException outOfRange) { Console.WriteLine("Error: {0}", outOfRange.Message); } } } class Guest { private string FirstName; private string LastName; private int Age; public Guest(string fName, string lName, int age) { FirstName = fName; LastName = lName; if (age < 21) throw new ArgumentOutOfRangeException("age","All guests must be 21-years-old or older."); else Age = age; } public string GuestInfo() { string gInfo = FirstName + " " + LastName + ", " + Age.ToString(); return(gInfo); } }

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

Portable Class Library


Supported in: Portable Class Library

ArithmeticException Class
.NET Framework 4

The exception that is thrown for errors in an arithmetic, casting, or conversion operation.
Inheritance Hierarchy

System.Object System.Exception System.SystemException System.ArithmeticException System.DivideByZeroException System.NotFiniteNumberException System.OverflowException Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[SerializableAttribute] [ComVisibleAttribute(true)] public class ArithmeticException : SystemException

The ArithmeticException type exposes the following members.


Constructors

Show:

Inherited

Protected Name Description Initializes a new instance of the ArithmeticException class. Initializes a new instance of the ArithmeticException class with a specified error message. Initializes a new instance of the ArithmeticException class with serialized data. Initializes a new instance of the ArithmeticException class with a specified error message and a reference to the inner exception that is the cause of this exception.

ArithmeticException()

ArithmeticException(String) ArithmeticException(SerializationInfo, StreamingContext)

ArithmeticException(String, Exception)

Properties

Show:

Inherited Name

Protected Description

Data

Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.) Gets or sets a link to the help file associated with this exception. (Inherited from Exception.) Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.) Gets the Exception instance that caused the current exception. (Inherited from Exception.)

HelpLink

HResult

InnerException

Message

Gets a message that describes the current exception. (Inherited from Exception.) Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.) Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.) Gets the method that throws the current exception. (Inherited from Exception.)

Source

StackTrace

TargetSite Methods

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.) Serves as a hash function for a particular type. (Inherited from Object.) When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.) Gets the runtime type of the current instance. (Inherited from Exception.) In XNA Framework 3.0, this member is inherited from Object.GetType(). In Portable Class Library Portable Class Library, this member is inherited from Object.GetType().

Equals(Object)

Finalize

GetBaseException GetHashCode GetObjectData

GetType

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)

ToString Events

Creates and returns a string representation of the current exception. (Inherited from Exception.)

Show:

Inherited Name

Protected Description

Occurs when an exception is serialized to create an exception state object SerializeObjectState that contains serialized data about the exception. (Inherited from Exception.) Remarks

ArithmeticException is the base class for DivideByZeroException, NotFiniteNumberException, and OverflowException. In general, use one of the derived classes of ArithmeticException to more precisely indicate the exact nature of the error. Throw an ArithmeticException if you are only interested in capturing a general arithmetic error. ArithmeticException uses the HRESULT COR_E_ARITHMETIC, which has the value 0x80070216. For a list of initial property values for an instance of ArithmeticException, see the ArithmeticException constructors.
Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

Array Class
.NET Framework 4

Provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the base class for all arrays in the common language runtime.
Inheritance Hierarchy

System.Object System.Array Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[SerializableAttribute] [ComVisibleAttribute(true)] public abstract class Array : ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable

The Array type exposes the following members.


Properties

Show:

Inherited Name

Protected Description

IsFixedSize IsReadOnly

Gets a value indicating whether the Array has a fixed size. Gets a value indicating whether the Array is read-only.

IsSynchronized

Gets a value indicating whether access to the Array is synchronized (thread safe). Gets a 32-bit integer that represents the total number of elements in all the dimensions of the Array. Gets a 64-bit integer that represents the total number of elements in all the dimensions of the Array. Gets the rank (number of dimensions) of the Array. Gets an object that can be used to synchronize access to the Array.

Length

LongLength Rank SyncRoot Methods

Show:

Inherited Name

Protected Description Returns a read-only wrapper for the specified array. Searches an entire one-dimensional sorted Array for a specific element, using the IComparable interface implemented by each element of the Array and by the specified object. Searches an entire one-dimensional sorted Array for a value using the specified IComparer interface. Searches a range of elements in a one-dimensional sorted Array for a value, using the IComparable interface implemented by each element of the Array and by the specified value. Searches a range of elements in a one-dimensional sorted Array for a value, using the specified IComparer interface. Searches an entire one-dimensional sorted Array for a specific element, using the IComparable<T> generic interface implemented by each element of the Array and by the specified object. Searches an entire one-dimensional sorted Array for a value

AsReadOnly<T>

BinarySearch(Array, Object)

BinarySearch(Array, Object, IComparer) BinarySearch(Array, Int32, Int32, Object) BinarySearch(Array, Int32, Int32, Object, IComparer)

BinarySearch<T>(T[], T)

BinarySearch<T>(T[], T,

IComparer<T>)

using the specified IComparer<T> generic interface. Searches a range of elements in a one-dimensional sorted Array for a value, using the IComparable<T> generic interface implemented by each element of the Array and by the specified value. Searches a range of elements in a one-dimensional sorted Array for a value, using the specified IComparer<T> generic interface. Sets a range of elements in the Array to zero, to false, or to null, depending on the element type. Creates a shallow copy of the Array. Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. Guarantees that all changes are undone if the copy does not succeed completely.

BinarySearch<T>(T[], Int32, Int32, T)

BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>) Clear Clone

ConstrainedCopy

ConvertAll<TInput, TOutput> Converts an array of one type to an array of another type. Copies a range of elements from an Array starting at the first element and pastes them into another Array starting at the first element. The length is specified as a 32-bit integer. Copies a range of elements from an Array starting at the first element and pastes them into another Array starting at the first element. The length is specified as a 64-bit integer. Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. The length and the indexes are specified as 32-bit integers. Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. The length and the indexes are specified as 64-bit integers. Copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index. The index is specified as a 32-bit

Copy(Array, Array, Int32)

Copy(Array, Array, Int64)

Copy(Array, Int32, Array, Int32, Int32)

Copy(Array, Int64, Array, Int64, Int64)

CopyTo(Array, Int32)

integer. Copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index. The index is specified as a 64-bit integer. Creates a one-dimensional Array of the specified Type and length, with zero-based indexing.

CopyTo(Array, Int64)

CreateInstance(Type, Int32)

Creates a multidimensional Array of the specified Type and CreateInstance(Type, Int32[]) dimension lengths, with zero-based indexing. The dimension lengths are specified in an array of 32-bit integers. Creates a multidimensional Array of the specified Type and CreateInstance(Type, Int64[]) dimension lengths, with zero-based indexing. The dimension lengths are specified in an array of 64-bit integers. CreateInstance(Type, Int32, Int32) Creates a two-dimensional Array of the specified Type and dimension lengths, with zero-based indexing.

CreateInstance(Type, Int32[], Creates a multidimensional Array of the specified Type and Int32[]) dimension lengths, with the specified lower bounds. CreateInstance(Type, Int32, Int32, Int32) Equals(Object) Creates a three-dimensional Array of the specified Type and dimension lengths, with zero-based indexing. Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Determines whether the specified array contains elements that match the conditions defined by the specified predicate. Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Array. Retrieves all the elements that match the conditions defined by the specified predicate.

Exists<T>

Finalize

Find<T>

FindAll<T>

FindIndex<T>(T[], Predicate<T>)

Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the entire Array. Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the range of elements in the Array that extends from the specified index to the last element.

FindIndex<T>(T[], Int32, Predicate<T>)

Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the FindIndex<T>(T[], Int32, Int32, first occurrence within the range of elements in the Array that Predicate<T>) starts at the specified index and contains the specified number of elements. Searches for an element that matches the conditions defined by the specified predicate, and returns the last occurrence within the entire Array. Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the entire Array. Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the range of elements in the Array that extends from the first element to the specified index. Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the last occurrence within the range of elements in the Array that contains the specified number of elements and ends at the specified index. Performs the specified action on each element of the specified array. Returns an IEnumerator for the Array. Serves as a hash function for a particular type. (Inherited from Object.)

FindLast<T>

FindLastIndex<T>(T[], Predicate<T>)

FindLastIndex<T>(T[], Int32, Predicate<T>)

FindLastIndex<T>(T[], Int32, Int32, Predicate<T>)

ForEach<T> GetEnumerator GetHashCode

GetLength

Gets a 32-bit integer that represents the number of elements in the specified dimension of the Array. Gets a 64-bit integer that represents the number of elements in the specified dimension of the Array. Gets the lower bound of the specified dimension in the Array. Gets the Type of the current instance. (Inherited from Object.) Gets the upper bound of the specified dimension in the Array. Gets the value at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer. Gets the value at the specified position in the multidimensional Array. The indexes are specified as an array of 32-bit integers. Gets the value at the specified position in the one-dimensional Array. The index is specified as a 64-bit integer. Gets the value at the specified position in the multidimensional Array. The indexes are specified as an array of 64-bit integers. Gets the value at the specified position in the two-dimensional Array. The indexes are specified as 32-bit integers. Gets the value at the specified position in the two-dimensional Array. The indexes are specified as 64-bit integers. Gets the value at the specified position in the three-dimensional Array. The indexes are specified as 32-bit integers. Gets the value at the specified position in the three-dimensional Array. The indexes are specified as 64-bit integers. Searches for the specified object and returns the index of the first occurrence within the entire one-dimensional Array.

GetLongLength GetLowerBound GetType GetUpperBound GetValue(Int32)

GetValue(Int32[])

GetValue(Int64)

GetValue(Int64[])

GetValue(Int32, Int32)

GetValue(Int64, Int64)

GetValue(Int32, Int32, Int32)

GetValue(Int64, Int64, Int64)

IndexOf(Array, Object)

Searches for the specified object and returns the index of the first occurrence within the range of elements in the oneIndexOf(Array, Object, Int32) dimensional Array that extends from the specified index to the last element.

Searches for the specified object and returns the index of the IndexOf(Array, Object, Int32, first occurrence within the range of elements in the onedimensional Array that starts at the specified index and contains Int32) the specified number of elements. IndexOf<T>(T[], T) Searches for the specified object and returns the index of the first occurrence within the entire Array. Searches for the specified object and returns the index of the first occurrence within the range of elements in the Array that extends from the specified index to the last element. Searches for the specified object and returns the index of the first occurrence within the range of elements in the Array that starts at the specified index and contains the specified number of elements. Initializes every element of the value-type Array by calling the default constructor of the value type. Searches for the specified object and returns the index of the last occurrence within the entire one-dimensional Array. Searches for the specified object and returns the index of the last occurrence within the range of elements in the onedimensional Array that extends from the first element to the specified index. Searches for the specified object and returns the index of the last occurrence within the range of elements in the onedimensional Array that contains the specified number of elements and ends at the specified index. Searches for the specified object and returns the index of the last occurrence within the entire Array. Searches for the specified object and returns the index of the last occurrence within the range of elements in the Array that extends from the first element to the specified index. Searches for the specified object and returns the index of the last occurrence within the range of elements in the Array that contains the specified number of elements and ends at the

IndexOf<T>(T[], T, Int32)

IndexOf<T>(T[], T, Int32, Int32)

Initialize

LastIndexOf(Array, Object)

LastIndexOf(Array, Object, Int32)

LastIndexOf(Array, Object, Int32, Int32)

LastIndexOf<T>(T[], T)

LastIndexOf<T>(T[], T, Int32)

LastIndexOf<T>(T[], T, Int32, Int32)

specified index. MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) Changes the number of elements of an array to the specified new size. Reverses the sequence of the elements in the entire onedimensional Array. Reverses the sequence of the elements in a range of elements in the one-dimensional Array. Sets a value to the element at the specified position in the onedimensional Array. The index is specified as a 32-bit integer. Sets a value to the element at the specified position in the multidimensional Array. The indexes are specified as an array of 32-bit integers. Sets a value to the element at the specified position in the onedimensional Array. The index is specified as a 64-bit integer. Sets a value to the element at the specified position in the multidimensional Array. The indexes are specified as an array of 64-bit integers. Sets a value to the element at the specified position in the twodimensional Array. The indexes are specified as 32-bit integers. Sets a value to the element at the specified position in the twodimensional Array. The indexes are specified as 64-bit integers.

Resize<T>

Reverse(Array)

Reverse(Array, Int32, Int32)

SetValue(Object, Int32)

SetValue(Object, Int32[])

SetValue(Object, Int64)

SetValue(Object, Int64[])

SetValue(Object, Int32, Int32)

SetValue(Object, Int64, Int64)

Sets a value to the element at the specified position in the SetValue(Object, Int32, Int32, three-dimensional Array. The indexes are specified as 32-bit Int32) integers. Sets a value to the element at the specified position in the SetValue(Object, Int64, Int64, three-dimensional Array. The indexes are specified as 64-bit Int64) integers. Sort(Array) Sorts the elements in an entire one-dimensional Array using the

IComparable implementation of each element of the Array. Sorts a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable implementation of each key. Sorts the elements in a one-dimensional Array using the specified IComparer.

Sort(Array, Array)

Sort(Array, IComparer)

Sorts a pair of one-dimensional Array objects (one contains the Sort(Array, Array, IComparer) keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer. Sorts the elements in a range of elements in a one-dimensional Array using the IComparable implementation of each element of the Array. Sorts a range of elements in a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable implementation of each key. Sorts the elements in a range of elements in a one-dimensional Array using the specified IComparer.

Sort(Array, Int32, Int32)

Sort(Array, Array, Int32, Int32)

Sort(Array, Int32, Int32, IComparer)

Sorts a range of elements in a pair of one-dimensional Array Sort(Array, Array, Int32, Int32, objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using IComparer) the specified IComparer. Sort<T>(T[]) Sorts the elements in an entire Array using the IComparable<T> generic interface implementation of each element of the Array. Sorts the elements in an Array using the specified IComparer<T> generic interface. Sorts the elements in an Array using the specified Comparison<T>. Sorts the elements in a range of elements in an Array using the IComparable<T> generic interface implementation of each element of the Array.

Sort<T>(T[], IComparer<T>)

Sort<T>(T[], Comparison<T>)

Sort<T>(T[], Int32, Int32)

Sort<T>(T[], Int32, Int32, IComparer<T>)

Sorts the elements in a range of elements in an Array using the specified IComparer<T> generic interface. Sorts a pair of Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable<T> generic interface implementation of each key. Sorts a pair of Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer<T> generic interface. Sorts a range of elements in a pair of Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable<T> generic interface implementation of each key. Sorts a range of elements in a pair of Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer<T> generic interface. Returns a string that represents the current object. (Inherited from Object.) Determines whether every element in the array matches the conditions defined by the specified predicate.

Sort<TKey, TValue>(TKey[], TValue[])

Sort<TKey, TValue>(TKey[], TValue[], IComparer<TKey>)

Sort<TKey, TValue>(TKey[], TValue[], Int32, Int32)

Sort<TKey, TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)

ToString

TrueForAll<T> Extension Methods

Show:

Inherited Name

Protected Description Enables parallelization of a query. (Defined by ParallelEnumerable.) Converts an IEnumerable to an IQueryable. (Defined by Queryable.) Casts the elements of an IEnumerable to the specified type. (Defined by Enumerable.)

AsParallel AsQueryable Cast<TResult>

OfType<TResult>

Filters the elements of an IEnumerable based on a specified type. (Defined by Enumerable.)

Explicit Interface Implementations

Show:

Inherited Name

Protected Description Copies the elements of the Array to another Array, starting at the specified index. Gets the number of elements contained in the Array. Gets a value that indicates whether access to the Array is synchronized (thread safe). Gets an object that can be used to synchronize access to the Array. Adds an item to IList. Removes all items from the IList. Determines whether an element is in the IList. Determines the index of a specific item in the IList. Inserts an item to the IList at the specified index. Gets a value that indicates whether the Array has a fixed size. Gets a value that indicates whether the Array is read-only. Gets or sets the element at the specified index. Removes the first occurrence of a specific object from the IList.

ICollection.CopyTo

ICollection.Count

ICollection.IsSynchronized

ICollection.SyncRoot IList.Add IList.Clear IList.Contains IList.IndexOf IList.Insert IList.IsFixedSize

IList.IsReadOnly IList.Item

IList.Remove

IList.RemoveAt

Removes the IList item at the specified index.

Determines whether the current collection object IStructuralComparable.CompareTo precedes, occurs in the same position as, or follows another object in the sort order. IStructuralEquatable.Equals Determines whether an object is equal to the current instance.

IStructuralEquatable.GetHashCode Returns a hash code for the current instance. Remarks

The Array class is the base class for language implementations that support arrays. However, only the system and compilers can derive explicitly from the Array class. Users should employ the array constructs provided by the language. An element is a value in an Array. The length of an Array is the total number of elements it can contain. The rank of an Array is the number of dimensions in the Array. The lower bound of a dimension of an Array is the starting index of that dimension of the Array; a multidimensional Array can have different bounds for each dimension. An array can have a maximum of 32 dimensions.
Important

In the .NET Framework version 2.0, the Array class implements the System.Collections.Generic.IList<T>, System.Collections.Generic.ICollection<T>, and System.Collections.Generic.IEnumerable<T> generic interfaces. The implementations are provided to arrays at run time, and therefore are not visible to the documentation build tools. As a result, the generic interfaces do not appear in the declaration syntax for the Array class, and there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations). The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw NotSupportedException. Type objects provide information about array type declarations. Array objects with the same array type share the same Type object. Type.IsArray and Type.GetElementType might not return the expected results with Array because if an array is cast to the type Array, the result is an object, not an array. That is, typeof(System.Array).IsArray returns false, and typeof(System.Array).GetElementType returns null.

Unlike most classes, Array provides the CreateInstance method, instead of public constructors, to allow for late bound access. The Array.Copy method copies elements not only between arrays of the same type but also between standard arrays of different types; it handles type casting automatically. Some methods, such as CreateInstance, Copy, CopyTo, GetValue, and SetValue, provide overloads that accept 64-bit integers as parameters to accommodate large capacity arrays. LongLength and GetLongLength return 64-bit integers indicating the length of the array. The Array is not guaranteed to be sorted. You must sort the Array prior to performing operations (such as BinarySearch) that require the Array to be sorted. Using an Array object of pointers in native code is not supported and will throw a NotSupportedException for several methods.
Examples

The following code example shows how Array.Copy copies elements between an array of type integer and an array of type Object.
C#
public class SamplesArray { {

public static void Main() array.

// Creates and initializes a new integer array and a new Object int[] myIntArray = new int[5] { 1, 2, 3, 4, 5 }; Object[] myObjArray = new Object[5] { 26, 27, 28, 29, 30 }; // Prints the initial values of Console.WriteLine( "Initially," Console.Write( "integer array:" PrintValues( myIntArray ); Console.Write( "Object array: " PrintValues( myObjArray ); both arrays. ); ); );

// Copies the first two elements from the integer array to the Object array. System.Array.Copy( myIntArray, myObjArray, 2 ); // Prints the values of the modified arrays. Console.WriteLine( "\nAfter copying the first two elements of the integer array to the Object array," ); Console.Write( "integer array:" ); PrintValues( myIntArray ); Console.Write( "Object array: " ); PrintValues( myObjArray );

// Copies the last two elements from the Object array to the integer array. System.Array.Copy( myObjArray, myObjArray.GetUpperBound(0) - 1, myIntArray, myIntArray.GetUpperBound(0) - 1, 2 ); // Prints the values of the modified arrays. Console.WriteLine( "\nAfter copying the last two elements of the Object array to the integer array," ); Console.Write( "integer array:" ); PrintValues( myIntArray ); Console.Write( "Object array: " ); PrintValues( myObjArray ); } public static void PrintValues( Object[] myArr ) foreach ( Object i in myArr ) { Console.Write( "\t{0}", i ); } Console.WriteLine(); } public static void PrintValues( int[] myArr ) foreach ( int i in myArr ) { Console.Write( "\t{0}", i ); } Console.WriteLine(); } } /* This code produces the following output. Initially, integer array: Object array: 1 26 2 27 3 28 4 29 5 30 { {

After copying the first two elements of the integer array to the Object array, integer array: 1 2 3 4 5 Object array: 1 2 28 29 30 After copying the last two elements of the Object array to the integer array, integer array: 1 2 3 29 30 Object array: 1 2 28 29 30 */

The following code example creates and initializes an Array and displays its properties and its elements.
C#
public class SamplesArray2{

public static void Main() Int32.

// Creates and initializes a new three-dimensional Array of type Array myArr = Array.CreateInstance( typeof(Int32), 2, 3, 4 ); for ( int i = myArr.GetLowerBound(0); i <= myArr.GetUpperBound(0); i++ ) for ( int j = myArr.GetLowerBound(1); j <= myArr.GetUpperBound(1); j++ ) for ( int k = myArr.GetLowerBound(2); k <= myArr.GetUpperBound(2); k++ ) { myArr.SetValue( (i*100)+(j*10)+k, i, j, k ); } // Displays the properties of the Array. Console.WriteLine( "The Array has {0} dimension(s) and a total of {1} elements.", myArr.Rank, myArr.Length ); Console.WriteLine( "\tLength\tLower\tUpper" ); for ( int i = 0; i < myArr.Rank; i++ ) { Console.Write( "{0}:\t{1}", i, myArr.GetLength(i) ); Console.WriteLine( "\t{0}\t{1}", myArr.GetLowerBound(i), myArr.GetUpperBound(i) ); } // Displays the contents of the Array. Console.WriteLine( "The Array contains the following values:" ); PrintValues( myArr ); } public static void PrintValues( Array myArr ) { System.Collections.IEnumerator myEnumerator = myArr.GetEnumerator(); int i = 0; int cols = myArr.GetLength( myArr.Rank - 1 ); while ( myEnumerator.MoveNext() ) { if ( i < cols ) { i++; } else { Console.WriteLine(); i = 1; } Console.Write( "\t{0}", myEnumerator.Current ); } Console.WriteLine(); } } /* This code produces the following output. The Array has 3 dimension(s) and a total of 24 elements. Length Lower Upper 0: 2 0 1 1: 3 0 2 2: 4 0 3 The Array contains the following values:

0 10 20 100 110 120 */

1 11 21 101 111 121

2 12 22

3 13 23 102 112 122 103 113 123

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

Portable Class Library


Supported in: Portable Class Library Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements. Thread Safety

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe. This implementation does not provide a synchronized (thread safe) wrapper for an Array; however, .NET Framework classes based on Array provide their own synchronized version of the collection using the SyncRoot property.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can 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.

ArrayTypeMismatchException Class
.NET Framework 4

The exception that is thrown when an attempt is made to store an element of the wrong type within an array.
Inheritance Hierarchy

System.Object System.Exception System.SystemException System.ArrayTypeMismatchException Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[SerializableAttribute] [ComVisibleAttribute(true)] public class ArrayTypeMismatchException : SystemException

The ArrayTypeMismatchException type exposes the following members.


Constructors

Show:

Inherited

Protected

Name ArrayTypeMismatchException()

Description Initializes a new instance of the ArrayTypeMismatchException class. Initializes a new instance of the ArrayTypeMismatchException class with a specified error message. Initializes a new instance of the ArrayTypeMismatchException class with serialized data.

ArrayTypeMismatchException(String)

ArrayTypeMismatchException(SerializationInfo, StreamingContext)

Initializes a new instance of the ArrayTypeMismatchException class with a ArrayTypeMismatchException(String, Exception) specified error message and a reference to the inner exception that is the cause of this exception. Properties

Show:

Inherited Name

Protected Description

Data

Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.) Gets or sets a link to the help file associated with this exception. (Inherited from Exception.) Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.) Gets the Exception instance that caused the current exception. (Inherited from Exception.) Gets a message that describes the current exception. (Inherited from Exception.) Gets or sets the name of the application or the object that causes the error.

HelpLink

HResult

InnerException

Message Source

(Inherited from Exception.) StackTrace Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.) Gets the method that throws the current exception. (Inherited from Exception.)

TargetSite Methods

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.) Serves as a hash function for a particular type. (Inherited from Object.) When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.) Gets the runtime type of the current instance. (Inherited from Exception.) In XNA Framework 3.0, this member is inherited from Object.GetType(). In Portable Class Library Portable Class Library, this member is inherited from Object.GetType().

Equals(Object)

Finalize

GetBaseException GetHashCode GetObjectData

GetType

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Events Creates and returns a string representation of the current exception. (Inherited from Exception.)

Show:

Inherited Name

Protected Description

Occurs when an exception is serialized to create an exception state object SerializeObjectState that contains serialized data about the exception. (Inherited from Exception.) Remarks

ArrayTypeMismatchException is thrown when the system cannot convert the element to the type declared for the array. For example, an element of type String cannot be stored in an Int32 array because conversion between these types is not supported. It is generally unnecessary for applications to throw this exception. The following Microsoft intermediate language (MSIL) instructions throw ArrayTypeMismatchException :

ldelem.<type> ldelema stelem.<type>

ArrayTypeMismatchException uses the HRESULT COR_E_ARRAYTYPEMISMATCH, which has the value 0x80131503. For a list of initial property values for an instance of ArrayTypeMismatchException, see the ArrayTypeMismatchException constructors.
Examples

The following code example demonstrates scenarios where ArrayTypeMismatchException is thrown.


C#
using System; namespace ArrayTypeMismatch { class Class1 {

static void Main(string[] args) { string[] names = {"Dog", "Cat", "Fish"}; Object[] objs = (Object[]) names; try { objs[2] = "Mouse"; foreach (object animalName in objs) { System.Console.WriteLine(animalName); } } catch (System.ArrayTypeMismatchException) { // Not reached; "Mouse" is of the correct type. System.Console.WriteLine("Exception Thrown."); } try { Object obj = (Object) 13; objs[2] = obj; } catch (System.ArrayTypeMismatchException) { // Always reached, 13 is not a string. System.Console.WriteLine( "New element is not of the correct type."); } // Set objs // an array objs = new try { objs[0] objs[1] objs[2] to an array of objects instead of of strings. Object[3]; = (Object) "Turtle"; = (Object) 12; = (Object) 2.341;

foreach (object element in objs) { System.Console.WriteLine(element); } } catch (System.ArrayTypeMismatchException) { // ArrayTypeMismatchException is not thrown this time. System.Console.WriteLine("Exception Thrown."); } } } }

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

Portable Class Library


Supported in: Portable Class Library

AssemblyLoadEventArgs Class
.NET Framework 4

Provides data for the AssemblyLoad event.


Inheritance Hierarchy

System.Object System.EventArgs System.AssemblyLoadEventArgs Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[ComVisibleAttribute(true)] public class AssemblyLoadEventArgs : EventArgs

The AssemblyLoadEventArgs type exposes the following members.


Constructors

Show:

Inherited Name

Protected Description Initializes a new instance of the AssemblyLoadEventArgs class using the specified Assembly.

AssemblyLoadEventArgs Properties

Show:

Inherited Name

Protected Description

LoadedAssembly Gets an Assembly that represents the currently loaded assembly. Methods

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.)

Equals(Object)

Finalize

GetHashCode GetType

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Version Information Returns a string that represents the current object. (Inherited from Object.)

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1 Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Attribute Class
.NET Framework 4

Represents the base class for custom attributes.


Inheritance Hierarchy

System.Object System.Attribute More... Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[SerializableAttribute] [ClassInterfaceAttribute(ClassInterfaceType.None)]

[ComVisibleAttribute(true)] [AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple = false)] public abstract class Attribute : _Attribute

The Attribute type exposes the following members.


Constructors

Show:

Inherited

Protected Description

Name

Attribute Initializes a new instance of the Attribute class. Properties

Show: Name

Inherited

Protected Description

TypeId When implemented in a derived class, gets a unique identifier for this Attribute. Methods

Show:

Inherited

Protected Description Infrastructure. Returns a value that indicates whether this instance is equal to a specified object. (Overrides Object.Equals(Object).) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Retrieves a custom attribute applied to a specified assembly. Parameters specify the assembly and the

Name

Equals

Finalize

GetCustomAttribute(Assembly, Type)

type of the custom attribute to search for. GetCustomAttribute(MemberInfo, Type) Retrieves a custom attribute applied to a member of a type. Parameters specify the member, and the type of the custom attribute to search for. Retrieves a custom attribute applied to a module. Parameters specify the module, and the type of the custom attribute to search for. Retrieves a custom attribute applied to a method parameter. Parameters specify the method parameter, and the type of the custom attribute to search for. Retrieves a custom attribute applied to an assembly. Parameters specify the assembly, the type of the custom attribute to search for, and an ignored search option. Retrieves a custom attribute applied to a member of a type. Parameters specify the member, the type of the custom attribute to search for, and whether to search ancestors of the member. Retrieves a custom attribute applied to a module. Parameters specify the module, the type of the custom attribute to search for, and an ignored search option. Retrieves a custom attribute applied to a method parameter. Parameters specify the method parameter, the type of the custom attribute to search for, and whether to search ancestors of the method parameter. Retrieves an array of the custom attributes applied to an assembly. A parameter specifies the assembly. Retrieves an array of the custom attributes applied to a member of a type. A parameter specifies the member.

GetCustomAttribute(Module, Type)

GetCustomAttribute(ParameterInfo, Type)

GetCustomAttribute(Assembly, Type, Boolean)

GetCustomAttribute(MemberInfo, Type, Boolean)

GetCustomAttribute(Module, Type, Boolean)

GetCustomAttribute(ParameterInfo, Type, Boolean)

GetCustomAttributes(Assembly)

GetCustomAttributes(MemberInfo)

GetCustomAttributes(Module)

Retrieves an array of the custom attributes applied to a module. A parameter specifies the module. Retrieves an array of the custom attributes applied to a method parameter. A parameter specifies the method parameter. Retrieves an array of the custom attributes applied to an assembly. Parameters specify the assembly, and an ignored search option.

GetCustomAttributes(ParameterInfo)

GetCustomAttributes(Assembly, Boolean)

Retrieves an array of the custom attributes applied to GetCustomAttributes(Assembly, Type) an assembly. Parameters specify the assembly, and the type of the custom attribute to search for. Retrieves an array of the custom attributes applied to a member of a type. Parameters specify the member, the type of the custom attribute to search for, and whether to search ancestors of the member. Retrieves an array of the custom attributes applied to a member of a type. Parameters specify the member, and the type of the custom attribute to search for. Retrieves an array of the custom attributes applied to a module. Parameters specify the module, and an ignored search option. Retrieves an array of the custom attributes applied to a module. Parameters specify the module, and the type of the custom attribute to search for. Retrieves an array of the custom attributes applied to a method parameter. Parameters specify the method parameter, and whether to search ancestors of the method parameter. Retrieves an array of the custom attributes applied to a method parameter. Parameters specify the method parameter, and the type of the custom attribute to search for.

GetCustomAttributes(MemberInfo, Boolean)

GetCustomAttributes(MemberInfo, Type)

GetCustomAttributes(Module, Boolean)

GetCustomAttributes(Module, Type)

GetCustomAttributes(ParameterInfo, Boolean)

GetCustomAttributes(ParameterInfo, Type)

GetCustomAttributes(Assembly, Type, Retrieves an array of the custom attributes applied to

Boolean)

an assembly. Parameters specify the assembly, the type of the custom attribute to search for, and an ignored search option. Retrieves an array of the custom attributes applied to a member of a type. Parameters specify the member, the type of the custom attribute to search for, and whether to search ancestors of the member. Retrieves an array of the custom attributes applied to a module. Parameters specify the module, the type of the custom attribute to search for, and an ignored search option. Retrieves an array of the custom attributes applied to a method parameter. Parameters specify the method parameter, the type of the custom attribute to search for, and whether to search ancestors of the method parameter. Returns the hash code for this instance. (Overrides Object.GetHashCode().) Gets the Type of the current instance. (Inherited from Object.) When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. Determines whether any custom attributes are applied to an assembly. Parameters specify the assembly, and the type of the custom attribute to search for. Determines whether any custom attributes are applied to a member of a type. Parameters specify the member, and the type of the custom attribute to search for. Determines whether any custom attributes of a specified type are applied to a module. Parameters specify the module, and the type of the custom

GetCustomAttributes(MemberInfo, Type, Boolean)

GetCustomAttributes(Module, Type, Boolean)

GetCustomAttributes(ParameterInfo, Type, Boolean)

GetHashCode

GetType

IsDefaultAttribute

IsDefined(Assembly, Type)

IsDefined(MemberInfo, Type)

IsDefined(Module, Type)

attribute to search for. Determines whether any custom attributes are applied to a method parameter. Parameters specify the method parameter, and the type of the custom attribute to search for. Determines whether any custom attributes are applied to an assembly. Parameters specify the assembly, the type of the custom attribute to search for, and an ignored search option.

IsDefined(ParameterInfo, Type)

IsDefined(Assembly, Type, Boolean)

Determines whether any custom attributes are applied to a member of a type. Parameters specify the IsDefined(MemberInfo, Type, Boolean) member, the type of the custom attribute to search for, and whether to search ancestors of the member. Determines whether any custom attributes are applied to a module. Parameters specify the module, the type of the custom attribute to search for, and an ignored search option. Determines whether any custom attributes are applied to a method parameter. Parameters specify the method parameter, the type of the custom attribute to search for, and whether to search ancestors of the method parameter. When overridden in a derived class, returns a value that indicates whether this instance equals a specified object. Creates a shallow copy of the current Object. (Inherited from Object.) Returns a string that represents the current object. (Inherited from Object.)

IsDefined(Module, Type, Boolean)

IsDefined(ParameterInfo, Type, Boolean)

Match

MemberwiseClone

ToString Explicit Interface Implementations

Show:

Inherited

Protected

Name _Attribute.GetIDsOfNames _Attribute.GetTypeInfo

Description Maps a set of names to a corresponding set of dispatch identifiers. Retrieves the type information for an object, which can be used to get the type information for an interface. Retrieves the number of type information interfaces that an object provides (either 0 or 1). Provides access to properties and methods exposed by an object.

_Attribute.GetTypeInfoCount _Attribute.Invoke Remarks

The Attribute class associates predefined system information or user-defined custom information with a target element. A target element can be an assembly, class, constructor, delegate, enum, event, field, interface, method, portable executable file module, parameter, property, return value, struct, or another attribute. Information provided by an attribute is also known as metadata. Metadata can be examined at run time by your application to control how your program processes data, or before run time by external tools to control how your application itself is processed or maintained. For example, the .NET Framework predefines and uses attribute types to control run-time behavior, and some programming languages use attribute types to represent language features not directly supported by the .NET Framework common type system. All attribute types derive directly or indirectly from the Attribute class. Attributes can be applied to any target element; multiple attributes can be applied to the same target element; and attributes can be inherited by an element derived from a target element. Use the AttributeTargets class to specify the target element to which the attribute is applied. The Attribute class provides convenient methods to retrieve and test custom attributes. For more information about using attributes, see Applying Attributes and Extending Metadata Using Attributes.
Examples

The following code example demonstrates the usage of Attribute.


C#
using System;

using System.Reflection; // An enumeration of animals. Start at 1 (0 = uninitialized). public enum Animal { // Pets. Dog = 1, Cat, Bird, } // A custom attribute to allow a target to have a pet. public class AnimalTypeAttribute : Attribute { // The constructor is called when the attribute is set. public AnimalTypeAttribute(Animal pet) { thePet = pet; } // Keep a variable internally ... protected Animal thePet; // .. and show a copy to the outside world. public Animal Pet { get { return thePet; } set { thePet = value; } } } // A test class where each method has its own pet. class AnimalTypeTestClass { [AnimalType(Animal.Dog)] public void DogMethod() {} [AnimalType(Animal.Cat)] public void CatMethod() {} [AnimalType(Animal.Bird)] public void BirdMethod() {} } class DemoClass { static void Main(string[] args) { AnimalTypeTestClass testClass = new AnimalTypeTestClass(); Type type = testClass.GetType(); // Iterate through all the methods of the class. foreach(MethodInfo mInfo in type.GetMethods()) { // Iterate through all the Attributes for each method. foreach (Attribute attr in Attribute.GetCustomAttributes(mInfo)) { // Check for the AnimalType attribute. if (attr.GetType() == typeof(AnimalTypeAttribute)) Console.WriteLine( "Method {0} has a pet {1} attribute.", mInfo.Name, ((AnimalTypeAttribute)attr).Pet); } } }

} /* * Output: * Method DogMethod has a pet Dog attribute. * Method CatMethod has a pet Cat attribute. * Method BirdMethod has a pet Bird attribute. */

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

Portable Class Library


Supported in: Portable Class Library

AttributeUsageAttribute Class
.NET Framework 4

Specifies the usage of another attribute class. This class cannot be inherited.
Inheritance Hierarchy

System.Object System.Attribute System.AttributeUsageAttribute Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[SerializableAttribute] [AttributeUsageAttribute(AttributeTargets.Class, Inherited = true)] [ComVisibleAttribute(true)] public sealed class AttributeUsageAttribute : Attribute

The AttributeUsageAttribute type exposes the following members.


Constructors

Show:

Inherited Name

Protected Description

Initializes a new instance of the AttributeUsageAttribute class with AttributeUsageAttribute the specified list of AttributeTargets, the AllowMultiple value, and the Inherited value. Properties

Show:

Inherited Name

Protected Description

AllowMultiple

Gets or sets a Boolean value indicating whether more than one instance of the indicated attribute can be specified for a single program element. Gets or sets a Boolean value indicating whether the indicated attribute can be inherited by derived classes and overriding members. When implemented in a derived class, gets a unique identifier for this Attribute. (Inherited from Attribute.) Gets a set of values identifying which program elements that the indicated attribute can be applied to.

Inherited

TypeId

ValidOn Methods

Show:

Inherited

Protected

Name Equals

Description Infrastructure. Returns a value that indicates whether this instance is equal to a specified object. (Inherited from Attribute.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Returns the hash code for this instance. (Inherited from Attribute.) Gets the Type of the current instance. (Inherited from Object.)

Finalize

GetHashCode GetType

When overridden in a derived class, indicates whether the value of this IsDefaultAttribute instance is the default value for the derived class. (Inherited from Attribute.) Match When overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Inherited from Attribute.)

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Returns a string that represents the current object. (Inherited from Object.)

Explicit Interface Implementations

Show:

Inherited Name

Protected Description Maps a set of names to a corresponding set of dispatch identifiers. (Inherited from Attribute.) Retrieves the type information for an object, which can be used to get the type information for an interface. (Inherited from Attribute.) Retrieves the number of type information interfaces that an object provides (either 0 or 1). (Inherited from Attribute.) Provides access to properties and methods exposed by an object.

_Attribute.GetIDsOfNames

_Attribute.GetTypeInfo

_Attribute.GetTypeInfoCount _Attribute.Invoke

(Inherited from Attribute.) Remarks

When you are defining your own attribute class, you can control the manner in which it is used by placing an AttributeUsageAttribute on your attribute class. The indicated attribute class must derive from Attribute, either directly or indirectly. Attribute classes have positional and named parameters. Each public constructor for an attribute class defines a valid sequence of positional parameters for that class. Named parameters are defined by the non-static, public, and read-write fields or properties of the attribute class. The three properties of AttributeUsageAttribute are set by defining the following parameters:

ValidOn

This positional parameter specifies the program elements that the indicated attribute can be placed on. The set of all possible elements that you can place an attribute on is listed in the AttributeTargets enumeration. You can combine several AttributeTargets values using a bitwise OR operation to get the desired combination of valid program elements.

AllowMultiple

This named parameter specifies whether the indicated attribute can be specified more than once for a given program element.

Inherited

This named parameter specifies whether the indicated attribute can be inherited by derived classes and overriding members. For more information about using attributes, see Attribute and Extending Metadata Using Attributes.
Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

Portable Class Library


Supported in: Portable Class Library

BadImageFormatException Class
.NET Framework 4

The exception that is thrown when the file image of a dynamic link library (DLL) or an executable program is invalid.
Inheritance Hierarchy

System.Object System.Exception System.SystemException System.BadImageFormatException Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[SerializableAttribute] [ComVisibleAttribute(true)] public class BadImageFormatException : SystemException

The BadImageFormatException type exposes the following members.


Constructors

Show:

Inherited

Protected

Name BadImageFormatException()

Description Initializes a new instance of the BadImageFormatException class. Initializes a new instance of the BadImageFormatException class with a specified error message. Initializes a new instance of the BadImageFormatException class with serialized data. Initializes a new instance of the BadImageFormatException class with a specified error message and a reference to the inner exception that is the cause of this exception. Initializes a new instance of the BadImageFormatException class with a specified error message and file name. Initializes a new instance of the BadImageFormatException class with a specified error message and a reference to the inner exception that is the cause of this exception.

BadImageFormatException(String)

BadImageFormatException(SerializationInfo, StreamingContext)

BadImageFormatException(String, Exception)

BadImageFormatException(String, String)

BadImageFormatException(String, String, Exception)

Properties

Show:

Inherited Name

Protected Description

Data FileName FusionLog

Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.) Gets the name of the file that causes this exception. Gets the log file that describes why an assembly load failed.

HelpLink

Gets or sets a link to the help file associated with this exception. (Inherited from Exception.) Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.) Gets the Exception instance that caused the current exception. (Inherited from Exception.) Gets the error message and the name of the file that caused this exception. (Overrides Exception.Message.)

HResult

InnerException

Message

In XNA Framework 3.0, this member is inherited from Exception.Message. In Portable Class Library Portable Class Library, this member is inherited from Exception.Message.

Source

Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.) Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.) Gets the method that throws the current exception. (Inherited from Exception.)

StackTrace

TargetSite Methods

Show:

Inherited Name

Protected Description Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)

Equals(Object)

Finalize

GetBaseException

GetHashCode

Serves as a hash function for a particular type. (Inherited from Object.) Sets the SerializationInfo object with the file name, assembly cache log, and additional exception information. (Overrides Exception.GetObjectData(SerializationInfo, StreamingContext).) Gets the runtime type of the current instance. (Inherited from Exception.) In XNA Framework 3.0, this member is inherited from Object.GetType(). In Portable Class Library Portable Class Library, this member is inherited from Object.GetType().

GetObjectData

GetType

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) Returns the fully qualified name of this exception and possibly the error message, the name of the inner exception, and the stack trace. (Overrides Exception.ToString().) ToString In XNA Framework, this member is overridden by ToString(). In Portable Class Library, this member is overridden by ToString(). Events

Show:

Inherited Name

Protected Description

Occurs when an exception is serialized to create an exception state object SerializeObjectState that contains serialized data about the exception. (Inherited from Exception.) Remarks

This exception is thrown when the file format of a dynamic link library (.dll file) or an executable (.exe file) does not conform to the format that is expected by the common language runtime. In particular, the exception is thrown under the following conditions:

An earlier version of a .NET Framework utility, such as ILDasm.exe or installutil.exe, is used with an assembly that was developed with a later version of the .NET Framework. To address this exception, use the version of the tool that corresponds to the version of the .NET Framework that was used to develop the assembly. This may require modifying the Path environment variable or providing a fully qualified path to the correct executable.

An attempt is made to load an unmanaged dynamic link library or executable (such as a Windows system DLL) as if it were a .NET Framework assembly. The following example illustrates this by using the Assembly.LoadFile method to load Kernel32.dll.
C#
// Windows DLL (non-.NET assembly) string filePath = Environment.ExpandEnvironmentVariables("%windir%"); if (! filePath.Trim().EndsWith(@"\")) filePath += @"\"; filePath += @"System32\Kernel32.dll"; try { Assembly assem = Assembly.LoadFile(filePath); } catch (BadImageFormatException e) { Console.WriteLine("Unable to load {0}.", filePath); Console.WriteLine(e.Message.Substring(0, e.Message.IndexOf(".") + 1)); } // The example displays an error message like the following: // Unable to load C:\WINDOWS\System32\Kernel32.dll. // The module was expected to contain an assembly manifest.

To address this exception, access the methods defined in the DLL by using the features provided by your development language, such as the Declare statement in Visual Basic or the DllImportAttribute attribute with the extern keyword in C#.

A DLL or executable is loaded as a 64-bit assembly, but it contains 32-bit features or resources. For example, it relies on COM interop or calls methods in a 32-bit dynamic link library. To address this exception, set the project's Platform target property to x86 (instead of x64 or AnyCPU) and recompile.

Components have been created using different versions of the .NET Framework. Typically, this exception occurs when an application or component that was

developed using the .NET Framework 1.0 or the .NET Framework 1.1 attempts to load an assembly that was developed using the .NET Framework 2.0 SP1 or later, or when an application that was developed using the .NET Framework 2.0 SP1 or .NET Framework 3.5 attempts to load an assembly that was developed using the .NET Framework 4. The BadImageFormatException may be reported as a compiletime error, or the exception may be thrown at run time. The following example illustrates this scenario. It defines a StringLib class that has a single member, ToProperCase, and that resides in an assembly named StringLib.dll.
C# using System;

public class StringLib { private string[] exceptionList = { "a", "an", "the", "in", "on", "of" }; private char[] separators = { ' ' }; public string ToProperCase(string title) { bool isException = false; string[] words = title.Split( separators, StringSplitOptions.RemoveEmptyEntries); string[] newWords = new string[words.Length]; for (int ctr = 0; ctr <= words.Length - 1; ctr++) { isException = false; foreach (string exception in exceptionList) { if (words[ctr].Equals(exception) && ctr > 0) { isException = true; break; } } if (! isException) newWords[ctr] = words[ctr].Substring(0, 1).ToUpper() + words[ctr].Substring(1); else newWords[ctr] = words[ctr]; } return String.Join(" ", newWords); } } // Attempting to load the StringLib.dll assembly produces the following output: // Unhandled Exception: System.BadImageFormatException:

// is invalid.

The format of the file 'StringLib.dll'

The following example uses reflection to load an assembly named StringLib.dll. If the source code is compiled with a .NET Framework 1.1 compiler, a BadImageFormatException is thrown by the Assembly.LoadFrom method.
C#
using System; using System.Reflection; public class Example { public static void Main() { string title = "a tale of two cities"; // object[] args = { title} // Load assembly containing StateInfo type. Assembly assem = Assembly.LoadFrom(@".\StringLib.dll"); // Get type representing StateInfo class. Type stateInfoType = assem.GetType("StringLib"); // Get Display method. MethodInfo mi = stateInfoType.GetMethod("ToProperCase"); // Call the Display method. string properTitle = (string) mi.Invoke(null, new object[] { title } ); Console.WriteLine(properTitle); } }

To address this exception, ensure that the assembly from which the exception is thrown attempts to load an assembly that was developed by using a compatible version of the .NET Framework. BadImageFormatException uses the HRESULT COR_E_BADIMAGEFORMAT, which has the value 0x8007000B. For a list of initial property values for an instance of BadImageFormatException, see the BadImageFormatException constructors.
Version Information

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

Portable Class Library


Supported in: Portable Class Library

BitConverter Class
.NET Framework 4

Converts base data types to an array of bytes, and an array of bytes to base data types.
Inheritance Hierarchy

System.Object System.BitConverter Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
public static class BitConverter

The BitConverter type exposes the following members.


Methods

Name DoubleToInt64Bits

Description Converts the specified double-precision floating point number to a 64-

bit signed integer. GetBytes(Boolean) GetBytes(Char) GetBytes(Double) GetBytes(Int16) GetBytes(Int32) GetBytes(Int64) GetBytes(Single) Returns the specified Boolean value as an array of bytes. Returns the specified Unicode character value as an array of bytes. Returns the specified double-precision floating point value as an array of bytes. Returns the specified 16-bit signed integer value as an array of bytes. Returns the specified 32-bit signed integer value as an array of bytes. Returns the specified 64-bit signed integer value as an array of bytes. Returns the specified single-precision floating point value as an array of bytes. Returns the specified 16-bit unsigned integer value as an array of bytes. Returns the specified 32-bit unsigned integer value as an array of bytes. Returns the specified 64-bit unsigned integer value as an array of bytes. Converts the specified 64-bit signed integer to a double-precision floating point number. Returns a Boolean value converted from one byte at a specified position in a byte array. Returns a Unicode character converted from two bytes at a specified position in a byte array. Returns a double-precision floating point number converted from eight bytes at a specified position in a byte array. Returns a 16-bit signed integer converted from two bytes at a specified position in a byte array. Returns a 32-bit signed integer converted from four bytes at a

GetBytes(UInt16)

GetBytes(UInt32)

GetBytes(UInt64)

Int64BitsToDouble

ToBoolean

ToChar

ToDouble

ToInt16 ToInt32

specified position in a byte array. ToInt64 Returns a 64-bit signed integer converted from eight bytes at a specified position in a byte array. Returns a single-precision floating point number converted from four bytes at a specified position in a byte array. Converts the numeric value of each element of a specified array of bytes to its equivalent hexadecimal string representation. Converts the numeric value of each element of a specified subarray of bytes to its equivalent hexadecimal string representation.

ToSingle

ToString(Byte[])

ToString(Byte[], Int32)

ToString(Byte[], Int32, Converts the numeric value of each element of a specified subarray of Int32) bytes to its equivalent hexadecimal string representation. ToUInt16 Returns a 16-bit unsigned integer converted from two bytes at a specified position in a byte array. Returns a 32-bit unsigned integer converted from four bytes at a specified position in a byte array. Returns a 64-bit unsigned integer converted from eight bytes at a specified position in a byte array.

ToUInt32

ToUInt64 Fields

Name IsLittleEndian Remarks

Description Indicates the byte order ("endianness") in which data is stored in this computer architecture.

The BitConverter class helps manipulate value types in their fundamental form, as a series of bytes. A byte is defined as an 8-bit unsigned integer. The BitConverter class includes static methods to convert each of the primitive types to and from an array of bytes, as the following table illustrates. Type To byte conversion From byte conversion

Boolean GetBytes(Boolean) Char GetBytes(Char) GetBytes(Double) Double -or-

ToBoolean ToChar ToDouble -or-

DoubleToInt64Bits(Double) Int64BitsToDouble Int16 GetBytes(Int16) ToInt16 Int32 GetBytes(Int32) ToInt32 Int64 GetBytes(Int64) ToInt64 Single GetBytes(Single) ToSingle UInt16 GetBytes(UInt16) ToUInt16 UInt32 GetBytes(UInt32) ToUInt32 UInt64 GetBytes(UInt64) ToUInt64 If you use BitConverter methods to round-trip data, make sure that the GetBytes overload and the ToType method specify the same type. As the following example illustrates, restoring an array that represents a signed integer by calling the ToUInt32 method can result in a value that is different from the original. For more information, see the entry Working with Signed Non-Decimal and Bitwise Values in the BCL Team Blog.
C#
using System; public class Example { public static void Main() { int value = -16; Byte[] bytes = BitConverter.GetBytes(value); // Convert bytes back to Int32. int intValue = BitConverter.ToInt32(bytes, 0); Console.WriteLine("{0} = {1}: {2}", value, intValue, value.Equals(intValue) ? "Round-trips" : "Does not round-trip"); // Convert bytes to UInt32. uint uintValue = BitConverter.ToUInt32(bytes, 0); Console.WriteLine("{0} = {1}: {2}", value, uintValue, value.Equals(uintValue) ? "Round-trips" : "Does not round-trip"); } } // The example displays the following output: // -16 = -16: Round-trips // -16 = 4294967280: Does not round-trip

The order of bytes in the array returned by the GetBytes method overloads (as well as the order of bits in the integer returned by the DoubleToInt64Bits method and the order of hexadecimal strings returned by the ToString(Byte[]) method) depends on whether the computer architecture is little-endian or big-endian. Similarly, the order of bytes in the array and returned by the ToIntegerValue methods and the ToChar method depends on whether the computer architecture is little-endian or big-endian. The endianness of an architecture is indicated by the IsLittleEndian property, which returns true on little-endian systems and false on big-endian systems. On little-endian systems, lower-order bytes precede higher-order bytes. On big-endian system, higher-order bytes precede lower-order bytes. The following table illustrates the difference in the byte arrays that result from passing the integer 1,234,567,890 (0x499602D2) to the GetBytes(Int32) method. The bytes are listed in order from the byte at index 0 to the byte at index 3. Little-endian D2-02-96-49 Big-endian 49-96-02-D2 Because the return value of some methods depends on system architecture, be careful when transmitting byte data beyond machine boundaries:

If all systems sending and receiving data are guaranteed to have the same endianness, nothing has be done to the data. If systems sending and receiving data can have different endianness, always transmit data in a particular order. This means that the order of bytes in the array may have to be reversed either before sending them or after receiving them. A common convention is to transmit data in network byte order (big-endian order). The following example provides an implementation for sending an integer value in network byte order.
C#
using System; public class Example { public static void Main() { int value = 12345678; byte[] bytes = BitConverter.GetBytes(value); Console.WriteLine(BitConverter.ToString(bytes)); if (BitConverter.IsLittleEndian) Array.Reverse(bytes); Console.WriteLine(BitConverter.ToString(bytes)); // Call method to send byte stream across machine boundaries. // Receive byte stream from beyond machine boundaries.

Console.WriteLine(BitConverter.ToString(bytes)); if (BitConverter.IsLittleEndian) Array.Reverse(bytes); Console.WriteLine(BitConverter.ToString(bytes)); int result = BitConverter.ToInt32(bytes, 0); Console.WriteLine("Original value: {0}", value); Console.WriteLine("Returned value: {0}", result); } } // The example displays the following output on a little-endian system: // 4E-61-BC-00 // 00-BC-61-4E // 00-BC-61-4E // 4E-61-BC-00 // Original value: 12345678 // Returned value: 12345678

If systems sending and receiving data can have different endianness and the data to be transmitted consists of signed integers, call the IPAddress.HostToNetworkOrder method to convert the data to network byte order and the IPAddress.NetworkToHostOrder method to convert it to the order required by the recipient.

Examples

The following code example illustrates the use of several BitConverter class methods.
C#
// Example of BitConverter class methods. using System; class BitConverterDemo { public static void Main( ) { const string formatter = "{0,25}{1,30}"; double float long int short char bool aDoubl aSingl aLong anInt aShort aChar aBool = = = = = = = 0.1111111111111111111; 0.1111111111111111111F; 1111111111111111111; 1111111111; 11111; '*'; true;

Console.WriteLine( "This example of methods of the BitConverter class" +

"\ngenerates the following output.\n" ); Console.WriteLine( formatter, "argument", "byte array" ); Console.WriteLine( formatter, "--------", "----------" ); // Convert values to Byte arrays and display them. Console.WriteLine( formatter, aDoubl, BitConverter.ToString( BitConverter.GetBytes( aDoubl ) ) ); Console.WriteLine( formatter, aSingl, BitConverter.ToString( BitConverter.GetBytes( aSingl ) ) ); Console.WriteLine( formatter, aLong, BitConverter.ToString( BitConverter.GetBytes( aLong ) ) ); Console.WriteLine( formatter, anInt, BitConverter.ToString( BitConverter.GetBytes( anInt ) ) ); Console.WriteLine( formatter, aShort, BitConverter.ToString( BitConverter.GetBytes( aShort ) ) ); Console.WriteLine( formatter, aChar, BitConverter.ToString( BitConverter.GetBytes( aChar ) ) ); Console.WriteLine( formatter, aBool, BitConverter.ToString( BitConverter.GetBytes( aBool ) ) ); } } /* This example of methods of the BitConverter class generates the following output. argument -------0.111111111111111 0.1111111 1111111111111111111 1111111111 11111 * True */ byte array ---------1C-C7-71-1C-C7-71-BC-3F 39-8E-E3-3D C7-71-C4-2B-AB-75-6B-0F C7-35-3A-42 67-2B 2A-00 01

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

Portable Class Library


Supported in: Portable Class Library

Buffer Class
.NET Framework 4

Manipulates arrays of primitive types.


Inheritance Hierarchy

System.Object System.Buffer Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[ComVisibleAttribute(true)] public static class Buffer

The Buffer type exposes the following members.


Methods

Name BlockCopy

Description Copies a specified number of bytes from a source array starting at a particular offset to a destination array starting at a particular offset.

ByteLength Returns the number of bytes in the specified array. GetByte SetByte Remarks Retrieves the byte at a specified location in a specified array. Assigns a specified value to a byte at a particular location in a specified array.

Buffer only affects arrays of primitive types; this class does not apply to objects. Each primitive type is treated as a series of bytes without regard to any behavior or limitation associated with the primitive type. Buffer provides methods to copy bytes from one array of primitive types to another array of primitive types, get a byte from an array, set a byte in an array, and obtain the length of an array. This class provides better performance for manipulating primitive types than similar methods in the System.Array class. Buffer is applicable to the following primitive types: Boolean, Char, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Single, and Double.
Examples

The following code example illustrates the use of several Buffer class methods.
C#
// Example of the Buffer class methods. using System; class BufferClassDemo { // Display the array elements from right to left in hexadecimal. public static void DisplayArray( short[ ] arr ) { Console.Write( " arr:" ); for( int loopX = arr.Length - 1; loopX >= 0; loopX-- ) Console.Write( " {0:X4}", arr[ loopX ] ); Console.WriteLine( ); } public static void Main( ) { // This array is to be modified and displayed. short[ ] arr = { 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271 }; Console.WriteLine( "This example of the Buffer class " + "methods generates the following output.\n" + "Note: The array is displayed from right to left.\n" ); Console.WriteLine( "Initial values of array:\n" ); // Display the initial array values and ByteLength. DisplayArray( arr ); Console.WriteLine( "\nBuffer.ByteLength( arr ): {0}", Buffer.ByteLength( arr ) ); // Copy a region of the array; set a byte within the array. Console.WriteLine( "\nCall these methods: \n" + " Buffer.BlockCopy( arr, 5, arr, 16, 9 ),\n" +

"

Buffer.SetByte( arr, 7, 170 ).\n" );

Buffer.BlockCopy( arr, 5, arr, 16, 9 ); Buffer.SetByte( arr, 7, 170 ); // Display the array and a byte within the array. Console.WriteLine( "Final values of array:\n" ); DisplayArray( arr ); Console.WriteLine( "\nBuffer.GetByte( arr, 26 ): {0}", Buffer.GetByte( arr, 26 ) ); } } /* This example of the Buffer class methods generates the following output. Note: The array is displayed from right to left. Initial values of array: arr: 010F 010E 010D 010C 010B 010A 0109 0108 0107 0106 0105 0104 0103 0102 Buffer.ByteLength( arr ): 28 Call these methods: Buffer.BlockCopy( arr, 5, arr, 16, 9 ), Buffer.SetByte( arr, 7, 170 ). Final values of array: arr: 010F 0101 0801 0701 0601 0501 0109 0108 0107 0106 AA05 0104 0103 0102 Buffer.GetByte( arr, 26 ): 15 */

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

CannotUnloadAppDomainException Class

.NET Framework 4

The exception that is thrown when an attempt to unload an application domain fails.
Inheritance Hierarchy

System.Object System.Exception System.SystemException System.CannotUnloadAppDomainException Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[SerializableAttribute] [ComVisibleAttribute(true)] public class CannotUnloadAppDomainException : SystemException

The CannotUnloadAppDomainException type exposes the following members.


Constructors

Show:

Inherited

Protected Name Description Initializes a new instance of the CannotUnloadAppDomainException class. Initializes a new instance of the CannotUnloadAppDomainException class with a specified error message.

CannotUnloadAppDomainException()

CannotUnloadAppDomainException(String)

Initializes a new instance of the CannotUnloadAppDomainException(SerializationInfo, CannotUnloadAppDomainException class StreamingContext) from serialized data.

Initializes a new instance of the CannotUnloadAppDomainException class CannotUnloadAppDomainException(String, Exception) with a specified error message and a reference to the inner exception that is the cause of this exception. Properties

Show:

Inherited

Protected Description

Name Data

Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.) Gets or sets a link to the help file associated with this exception. (Inherited from Exception.) Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.) Gets the Exception instance that caused the current exception. (Inherited from Exception.) Gets a message that describes the current exception. (Inherited from Exception.) Gets or sets the name of the application or the object that causes the error. (Inherited from Exception.) Gets a string representation of the immediate frames on the call stack. (Inherited from Exception.) Gets the method that throws the current exception. (Inherited from Exception.)

HelpLink

HResult

InnerException Message Source

StackTrace TargetSite Methods

Show:

Inherited Name

Protected Description

Equals(Object)

Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.) Serves as a hash function for a particular type. (Inherited from Object.) When overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.) Gets the runtime type of the current instance. (Inherited from Exception.)

Finalize

GetBaseException GetHashCode GetObjectData

GetType In XNA Framework 3.0, this member is inherited from Object.GetType(). MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Events Creates and returns a string representation of the current exception. (Inherited from Exception.)

Show:

Inherited Name

Protected Description

Occurs when an exception is serialized to create an exception state object SerializeObjectState that contains serialized data about the exception. (Inherited from Exception.) Remarks

CannotUnloadAppDomainException is thrown when there is an attempt to unload the following:

The default application domain, which must remain loaded during the lifetime of the application.

An application domain with a running thread that cannot immediately stop execution. An application domain that has already been unloaded.

CannotUnloadAppDomainException uses the HRESULT COR_E_CANNOTUNLOADAPPDOMAIN, which has the value 0x80131015. For a list of initial property values for an instance of CannotUnloadAppDomainException, see the CannotUnloadAppDomainException constructors.
Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

CharEnumerator Class
.NET Framework 4

Supports iterating over a String object and reading its individual characters. This class cannot be inherited.
Inheritance Hierarchy

System.Object System.CharEnumerator Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#

[SerializableAttribute] [ComVisibleAttribute(true)] public sealed class CharEnumerator : ICloneable, IEnumerator<char>, IEnumerator, IDisposable

The CharEnumerator type exposes the following members.


Properties

Show: Name Current Methods

Inherited

Protected Description

Gets the currently referenced character in the string enumerated by this CharEnumerator object.

Show:

Inherited Name

Protected Description Creates a copy of the current CharEnumerator object. Releases all resources used by the current instance of the CharEnumerator class. Determines whether the specified Object is equal to the current Object. (Inherited from Object.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Serves as a hash function for a particular type. (Inherited from Object.) Gets the Type of the current instance. (Inherited from Object.)

Clone Dispose

Equals(Object)

Finalize

GetHashCode GetType

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) MoveNext Increments the internal index of the current CharEnumerator object to the

next character of the enumerated string. Reset ToString Initializes the index to a position logically before the first character of the enumerated string. Returns a string that represents the current object. (Inherited from Object.)

Explicit Interface Implementations

Show:

Inherited Name

Protected Description

IDisposable.Dispose Releases all resources used by the CharEnumerator class. Infrastructure. Gets the currently referenced character in the string IEnumerator.Current enumerated by this CharEnumerator object. For a description of this member, see IEnumerator.Current. Remarks

A CharEnumerator provides read-only access to the characters in a referenced String object. For example, the foreach statement of the Microsoft Visual Basic and C# programming languages, which iterates through the elements of a collection, retrieves a CharEnumerator from a String object in order to iterate through the characters in that object. There is no public constructor for CharEnumerator. Instead, call a String object's GetEnumerator method to obtain a CharEnumerator that is initialized to reference the string. A CharEnumerator maintains an internal index to the characters in the string the CharEnumerator references. The state of the index is invalid when it references a character position logically before the first character or after the last character in the string, and valid when it references a character within the string. The index is initialized to a position logically before the first character, and is set to a position after the last character when the iteration is complete. An exception is thrown if you attempt to access a character while the index is invalid. The MoveNext method increments the index by one, so the first and subsequent characters are accessed in turn. The Reset method sets the index to a position logically before the first

character. The Current property retrieves the character currently referenced by index. The Clone method creates a copy of the CharEnumerator.
Note

Several independent instances of CharEnumerator across one or more threads can have access to a single instance of String. This class is implemented to support the IEnumerator interface. For more information regarding the use of an enumerator, see the IEnumerator topic.
Examples

The following example uses the CharEnumerator class to enumerate the individual characters in a string. It instantiates a CharEnumerator object by calling the String.GetEnumerator method, moves from one character to the next by calling the MoveNext method, and displays the current character by retrieving the value of the Current property.
C#
string title = "A Tale of Two Cities"; CharEnumerator chEnum = title.GetEnumerator(); int ctr = 1; string outputLine1 = null; string outputLine2 = null; string outputLine3 = null; while (chEnum.MoveNext()) { outputLine1 += ctr < 10 || ctr % 10 != 0 ? " outputLine2 += (ctr % 10) + " "; outputLine3 += chEnum.Current + " "; ctr++; }

" : (ctr / 10) + " ";

Console.WriteLine("The length of the string is {0} characters:", title.Length); Console.WriteLine(outputLine1); Console.WriteLine(outputLine2); Console.WriteLine(outputLine3); // The example displays the following output to the console: // The length of the string is 20 characters: // 1 2 // 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 // A T a l e o f T w o C i t i e s

Note, however, that the same operation can be performed somewhat more intuitively by using foreach (in C#) or For Each (in Visual Basic), as the following example shows.

C#
string title = "A Tale of Two Cities"; int ctr = 1; string outputLine1 = null; string outputLine2 = null; string outputLine3 = null; foreach (char ch in title) { outputLine1 += ctr < 10 || ctr % 10 != 0 ? " outputLine2 += (ctr % 10) + " "; outputLine3 += ch + " "; ctr++; }

" : (ctr / 10) + " ";

Console.WriteLine("The length of the string is {0} characters:", title.Length); Console.WriteLine(outputLine1); Console.WriteLine(outputLine2); Console.WriteLine(outputLine3); // The example displays the following output to the console: // The length of the string is 20 characters: // 1 2 // 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 // A T a l e o f T w o C i t i e s

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

CLSCompliantAttribute Class
.NET Framework 4

Indicates whether a program element is compliant with the Common Language Specification (CLS). This class cannot be inherited.
Inheritance Hierarchy

System.Object System.Attribute System.CLSCompliantAttribute Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
[SerializableAttribute] [AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple = false)] [ComVisibleAttribute(true)] public sealed class CLSCompliantAttribute : Attribute

The CLSCompliantAttribute type exposes the following members.


Constructors

Show:

Inherited Name

Protected Description

Initializes an instance of the CLSCompliantAttribute class with a CLSCompliantAttribute Boolean value indicating whether the indicated program element is CLS-compliant. Properties

Show:

Inherited Name

Protected Description

IsCompliant

Gets the Boolean value indicating whether the indicated program element is CLScompliant.

TypeId Methods

When implemented in a derived class, gets a unique identifier for this Attribute. (Inherited from Attribute.)

Show:

Inherited Name

Protected Description Infrastructure. Returns a value that indicates whether this instance is equal to a specified object. (Inherited from Attribute.) Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) Returns the hash code for this instance. (Inherited from Attribute.) Gets the Type of the current instance. (Inherited from Object.)

Equals

Finalize

GetHashCode GetType

When overridden in a derived class, indicates whether the value of this IsDefaultAttribute instance is the default value for the derived class. (Inherited from Attribute.) Match When overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Inherited from Attribute.)

MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.) ToString Returns a string that represents the current object. (Inherited from Object.)

Explicit Interface Implementations

Show:

Inherited Name

Protected Description Maps a set of names to a corresponding set of dispatch identifiers. (Inherited from Attribute.)

_Attribute.GetIDsOfNames

_Attribute.GetTypeInfo

Retrieves the type information for an object, which can be used to get the type information for an interface. (Inherited from Attribute.) Retrieves the number of type information interfaces that an object provides (either 0 or 1). (Inherited from Attribute.) Provides access to properties and methods exposed by an object. (Inherited from Attribute.)

_Attribute.GetTypeInfoCount

_Attribute.Invoke Remarks

You can apply the CLSCompliantAttribute attribute to the following program elements: assembly, module, class, struct, enum, constructor, method, property, field, event, interface, delegate, parameter, and return value. However, the notion of CLS compliance is only meaningful for assemblies, modules, types, and members of types, not parts of a member signature. Consequently, CLSCompliantAttribute is ignored when applied to parameter or return value program elements. If no CLSCompliantAttribute is applied to a program element, then by default:

The assembly is not CLS-compliant. The type is CLS-compliant only if its enclosing type or assembly is CLS-compliant. The member of a type is CLS-compliant only if the type is CLS-compliant.

If an assembly is marked as CLS-compliant, any publicly exposed type in the assembly that is not CLS-compliant must be marked with CLSCompliantAttribute using a false argument. Similarly, if a class is marked as CLS-compliant, you must individually mark all members that are not CLS-compliant. All non-compliant members must provide corresponding CLScompliant alternatives. Attributes that are applied to assemblies or modules must occur after the C# using (Imports in Visual Basic) clauses and before the code. For more information about using attributes, see Extending Metadata Using Attributes.
Note

The current Microsoft Visual Basic compiler intentionally does not generate a CLScompliance warning, however, a future release of the compiler will issue that warning.
Examples

The following example applies a CLSCompliantAttribute to the entire assembly.


using System; [assembly: CLSCompliant(true)]

The following declaration generates a CLS-compliance warning because the type UInt32 is not specified in the CLS.
public int SetValue(UInt32 value);

If the declaration is marked with a CLSCompliantAttribute, no compiler warning or error is generated.


[CLSCompliant(false)] public int SetValue(UInt32 value);

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

Portable Class Library


Supported in: Portable Class Library

Console Class
.NET Framework 4

Represents the standard input, output, and error streams for console applications. This class cannot be inherited.
Inheritance Hierarchy

System.Object System.Console Namespace: System Assembly: mscorlib (in mscorlib.dll) Syntax

C#
public static class Console

The Console type exposes the following members.


Properties

Name BackgroundColor BufferHeight BufferWidth CapsLock CursorLeft CursorSize CursorTop CursorVisible Error ForegroundColor In InputEncoding

Description Gets or sets the background color of the console. Gets or sets the height of the buffer area. Gets or sets the width of the buffer area. Gets a value indicating whether the CAPS LOCK keyboard toggle is turned on or turned off. Gets or sets the column position of the cursor within the buffer area. Gets or sets the height of the cursor within a character cell. Gets or sets the row position of the cursor within the buffer area. Gets or sets a value indicating whether the cursor is visible. Gets the standard error output stream. Gets or sets the foreground color of the console. Gets the standard input stream. Gets or sets the encoding the console uses to read input.

KeyAvailable

Gets a value indicating whether a key press is available in the input stream. Gets the largest possible number of console window rows, based on the current font and screen resolution. Gets the largest possible number of console window columns, based on the current font and screen resolution. Gets a value indicating whether the NUM LOCK keyboard toggle is turned on or turned off. Gets the standard output stream. Gets or sets the encoding the console uses to write output. Gets or sets the title to display in the console title bar.

LargestWindowHeight

LargestWindowWidth

NumberLock Out OutputEncoding Title

Gets or sets a value indicating whether the combination of the Control TreatControlCAsInput modifier key and C console key (CTRL+C) is treated as ordinary input or as an interruption that is handled by the operating system. WindowHeight WindowLeft Gets or sets the height of the console window area. Gets or sets the leftmost position of the console window area relative to the screen buffer. Gets or sets the top position of the console window area relative to the screen buffer. Gets or sets the width of the console window.

WindowTop WindowWidth Methods

Name Beep()

Description Plays the sound of a beep through the console speaker. Plays the sound of a beep of a specified frequency and duration through the console speaker.

Beep(Int32, Int32)

Clear MoveBufferArea(Int32, Int32, Int32, Int32, Int32, Int32) MoveBufferArea(Int32, Int32, Int32, Int32, Int32, Int32, Char, ConsoleColor, ConsoleColor) OpenStandardError() OpenStandardError(Int32) OpenStandardInput() OpenStandardInput(Int32) OpenStandardOutput() OpenStandardOutput(Int32)

Clears the console buffer and corresponding console window of display information. Copies a specified source area of the screen buffer to a specified destination area. Copies a specified source area of the screen buffer to a specified destination area. Acquires the standard error stream. Acquires the standard error stream, which is set to a specified buffer size. Acquires the standard input stream. Acquires the standard input stream, which is set to a specified buffer size. Acquires the standard output stream. Acquires the standard output stream, which is set to a specified buffer size. Reads the next character from the standard input stream. Obtains the next character or function key pressed by the user. The pressed key is displayed in the console window. Obtains the next character or function key pressed by the user. The pressed key is optionally displayed in the console window. Reads the next line of characters from the standard input stream. Sets the foreground and background console colors to their defaults. Sets the height and width of the screen buffer area to

Read

ReadKey()

ReadKey(Boolean)

ReadLine

ResetColor SetBufferSize

the specified values. SetCursorPosition SetError Sets the position of the cursor. Sets the Error property to the specified TextWriter object. Sets the In property to the specified TextReader object. Sets the Out property to the specified TextWriter object. Sets the position of the console window relative to the screen buffer. Sets the height and width of the console window to the specified values. Writes the text representation of the specified Boolean value to the standard output stream. Writes the specified Unicode character value to the standard output stream. Writes the specified array of Unicode characters to the standard output stream. Writes the text representation of the specified Decimal value to the standard output stream. Writes the text representation of the specified doubleprecision floating-point value to the standard output stream. Writes the text representation of the specified 32-bit signed integer value to the standard output stream. Writes the text representation of the specified 64-bit signed integer value to the standard output stream. Writes the text representation of the specified object to the standard output stream.

SetIn

SetOut

SetWindowPosition

SetWindowSize

Write(Boolean)

Write(Char)

Write(Char[])

Write(Decimal)

Write(Double)

Write(Int32)

Write(Int64)

Write(Object)

Write(Single)

Writes the text representation of the specified singleprecision floating-point value to the standard output stream. Writes the specified string value to the standard output stream. Writes the text representation of the specified 32-bit unsigned integer value to the standard output stream. Writes the text representation of the specified 64-bit unsigned integer value to the standard output stream. Writes the text representation of the specified object to the standard output stream using the specified format information. Writes the text representation of the specified array of objects to the standard output stream using the specified format information. Writes the specified subarray of Unicode characters to the standard output stream. Writes the text representation of the specified objects to the standard output stream using the specified format information. Writes the text representation of the specified objects to the standard output stream using the specified format information. Writes the text representation of the specified objects and variable-length parameter list to the standard output stream using the specified format information. Writes the current line terminator to the standard output stream. Writes the text representation of the specified Boolean value, followed by the current line terminator, to the standard output stream.

Write(String)

Write(UInt32)

Write(UInt64)

Write(String, Object)

Write(String, Object[])

Write(Char[], Int32, Int32)

Write(String, Object, Object)

Write(String, Object, Object, Object)

Write(String, Object, Object, Object, Object)

WriteLine()

WriteLine(Boolean)

WriteLine(Char)

Writes the specified Unicode character, followed by the current line terminator, value to the standard output stream. Writes the specified array of Unicode characters, followed by the current line terminator, to the standard output stream. Writes the text representation of the specified Decimal value, followed by the current line terminator, to the standard output stream. Writes the text representation of the specified doubleprecision floating-point value, followed by the current line terminator, to the standard output stream. Writes the text representation of the specified 32-bit signed integer value, followed by the current line terminator, to the standard output stream. Writes the text representation of the specified 64-bit signed integer value, followed by the current line terminator, to the standard output stream. Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream. Writes the text representation of the specified singleprecision floating-point value, followed by the current line terminator, to the standard output stream. Writes the specified string value, followed by the current line terminator, to the standard output stream. Writes the text representation of the specified 32-bit unsigned integer value, followed by the current line terminator, to the standard output stream. Writes the text representation of the specified 64-bit unsigned integer value, followed by the current line

WriteLine(Char[])

WriteLine(Decimal)

WriteLine(Double)

WriteLine(Int32)

WriteLine(Int64)

WriteLine(Object)

WriteLine(Single)

WriteLine(String)

WriteLine(UInt32)

WriteLine(UInt64)

terminator, to the standard output stream. Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream using the specified format information. Writes the text representation of the specified array of objects, followed by the current line terminator, to the standard output stream using the specified format information. Writes the specified subarray of Unicode characters, followed by the current line terminator, to the standard output stream. Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.

WriteLine(String, Object)

WriteLine(String, Object[])

WriteLine(Char[], Int32, Int32)

WriteLine(String, Object, Object)

Writes the text representation of the specified objects, followed by the current line terminator, to the WriteLine(String, Object, Object, Object) standard output stream using the specified format information. Writes the text representation of the specified objects WriteLine(String, Object, Object, Object, and variable-length parameter list, followed by the current line terminator, to the standard output stream Object) using the specified format information. Events

Name CancelKeyPress Remarks

Description Occurs when the Control modifier key (CTRL) and C console key (C) are pressed simultaneously (CTRL+C).

The console is an operating system window where users interact with the operating system or a text-based console application by entering text input through the computer keyboard, and reading text output from the computer terminal. For example, in Windows the console is called the command prompt window and accepts MS-DOS commands. The Console class provides basic support for applications that read characters from, and write characters to, the console. For information about developing with the Console class, see the following sections:

Console I/O Streams Screen Buffer and Console Window Common Operations

Console I/O Streams

When a console application starts, the operating system automatically associates three I/O streams with the console. Your application can read user input from the standard input stream; write normal data to the standard output stream; and write error data to the standard error output stream. These streams are presented to your application as the values of the In, Out, and Error properties. By default, the value of the In property is a System.IO.TextReader object, and the values of the Out and Error properties are System.IO.TextWriter objects. However, you can set these properties to streams that do not represent the console; for example, you can set these properties to streams that represent files. To redirect the standard input, standard output, or standard error stream, call the SetIn, SetOut, or SetError method, respectively. I/O operations using these streams are synchronized, which means multiple threads can read from, or write to, the streams.
Note

You should not use the Console class to display output in unattended applications, such as server applications. Similarly, calls to methods such as Write and WriteLine have no effect in Windows applications. Console class members that work normally when the underlying stream is directed to a console might throw an exception if the stream is redirected, for example, to a file. Consequently, program your application to catch System.IO.IOException if you redirect a standard stream. It is sometimes useful to explicitly invoke the members of the stream objects represented by the In, Out, and Error properties. For example, by default, the Console.ReadLine method reads input from the standard input stream. Similarly, the Console.WriteLine method writes data to the standard output stream followed by the default line termination string; that is, data is followed by a carriage return and line feed ("\r\n"). However, the Console class does

not provide a corresponding method to write data to the standard error output stream, or a property to change the line termination string for data written to that stream. You can solve this problem by setting the TextWriter.NewLine property of the Out or Error property to another line termination string. For example, the C# statement, Console.Error.NewLine = "\r\n\r\n";, sets the line termination string for the standard error output stream to two carriage return and line feed sequences. Then you can explicitly call the WriteLine method of the error output stream object, as in the C# statement, Console.Error.WriteLine();.
Screen Buffer and Console Window

Two closely related features of the console are the screen buffer and the console window. Text is actually read from or written to streams owned by the console, but appear to be read from or written to an area owned by the console called the screen buffer. The screen buffer is an attribute of the console, and is organized as a rectangular grid of rows and columns where each grid intersection, or character cell, can contain a character. Each character has its own foreground color and each character cell has its own background color. The screen buffer is viewed through a rectangular region called the console window. The console window is another attribute of the console; it is not the console itself, which is an operating system window. The console window is arranged in rows and columns, is less than or equal to the size of the screen buffer, and can be moved to view different areas of the underlying screen buffer. If the screen buffer is larger than the console window, the console automatically displays scroll bars so the console window can be repositioned over the screen buffer area. A cursor indicates the screen buffer position where text is currently read or written. The cursor can be hidden or made visible, and its height can be changed. If the cursor is visible, the console window position is moved automatically so the cursor is always in view. The origin for character cell coordinates in the screen buffer is the upper left corner, and the position of the cursor and the console window are measured relative to that origin. Use zero-based indexes to specify positions; that is, specify the topmost row as row 0, and the leftmost column as column 0. The maximum value for the row and column indexes is Int16.MaxValue.
Common Operations

The Console class contains the following methods for reading console input and writing console output:

The overloads of the ReadKey method read an individual character. The ReadLine method reads an entire line of input.

The Write method overloads convert an instance of a value type, an array of characters, or a set of objects to a formatted or unformatted string, and then write that string to the console. A parallel set of WriteLine method overloads output the same string as the Write overloads but also add a line termination string.

The Console class also contains methods and properties to perform the following operations:

Get or set the size of the screen buffer. The BufferHeight and BufferWidth properties let you get or set the buffer height and width, respectively, and the SetBufferSize method lets you set the buffer size in a single method call. Get or set the size of the console window. The WindowHeight and WindowWidth properties let you get or set the window height and width, respectively, and the SetWindowSize method lets you set the window size in a single method call. Get or set the size of the cursor. The CursorSize property specifies the height of the cursor in a character cell. Get or set the position of the console window relative to the screen buffer. The WindowTop and WindowLeft properties let you get or set the top row and leftmost column of the screen buffer that appears in the console window, and the SetWindowPosition method lets you set these values in a single method call. Get or set the position of the cursor by getting or setting the CursorTop and CursorLeft properties, or set the position of the cursor by calling the SetCursorPosition method. Move or clear data in the screen buffer by calling the MoveBufferArea or Clear method. Get or set the foreground and background colors by using the ForegroundColor and BackgroundColor properties, or reset the background and foreground to their default colors by calling the ResetColor method. Play the sound of a beep through the console speaker by calling the Beep method.

Examples

The following example demonstrates how to read data from, and write data to, the standard input and output streams. Note that these streams can be redirected by using the SetIn and SetOut methods.
C#
using System; public class Example { public static void Main() { Console.Write("Hello "); Console.WriteLine("World!");

Console.Write("Enter your name: "); String name = Console.ReadLine(); Console.Write("Good day, "); Console.Write(name); Console.WriteLine("!"); } } // The example displays output similar to the following: // Hello World! // Enter your name: James // Good day, James!

Version Information

.NET Framework
Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

CONTINUA -

Structures Structure ArgIterator ArraySegment<T> Boolean Byte Char ConsoleKeyInfo DateTime Description Represents a variable-length argument list; that is, the parameters of a function that takes a variable number of arguments. Delimits a section of a one-dimensional array. Represents a Boolean value. Represents an 8-bit unsigned integer. Represents a character as a UTF-16 code unit. Describes the console key that was pressed, including the character represented by the console key and the state of the SHIFT, ALT, and CTRL modifier keys. Represents an instant in time, typically expressed as a date and time of day.

Represents a point in time, typically expressed as a date DateTimeOffset and time of day, relative to Coordinated Universal Time (UTC). Decimal Represents a decimal number. Double Represents a double-precision floating-point number. Guid Represents a globally unique identifier (GUID). Int16 Represents a 16-bit signed integer. Int32 Represents a 32-bit signed integer. Int64 Represents a 64-bit signed integer. A platform-specific type that is used to represent a pointer IntPtr or a handle. ModuleHandle Represents a runtime handle for a module. Represents an object whose underlying type is a value type Nullable<T> that can also be assigned null like a reference type. RuntimeArgumentHandle References a variable-length argument list. RuntimeFieldHandle Represents a field using an internal metadata token. RuntimeMethodHandle is a handle to the internal metadata RuntimeMethodHandle representation of a method. RuntimeTypeHandle Represents a type using an internal metadata token. SByte Represents an 8-bit signed integer. Single Represents a single-precision floating-point number. TimeSpan Represents a time interval. Provides information about a specific time change, such as TimeZoneInfo.TransitionTime the change from daylight saving time to standard time or vice versa, in a particular time zone. Describes objects that contain both a managed pointer to a TypedReference location and a runtime representation of the type that may be stored at that location. UInt16 Represents a 16-bit unsigned integer. UInt32 Represents a 32-bit unsigned integer. UInt64 Represents a 64-bit unsigned integer. A platform-specific type that is used to represent a pointer UIntPtr or a handle. Specifies a return value type for a method that does not Void return a value. Interfaces Description Exposes the public members of the System.AppDomain class to _AppDomain unmanaged code. IAppDomainSetup Represents assembly binding information that can be added to an Interface

instance of AppDomain. IAsyncResult Represents the status of an asynchronous operation. Supports cloning, which creates a new instance of a class with the ICloneable same value as an existing instance. Defines a generalized type-specific comparison method that a value IComparable type or class implements to order or sort its instances. Defines a generalized comparison method that a value type or class IComparable<T> implements to create a type-specific comparison method for ordering instances. Defines methods that convert the value of the implementing reference IConvertible or value type to a common language runtime type that has an equivalent value. Defines a method that supports custom formatting of the value of an ICustomFormatter object. IDisposable Defines a method to release allocated resources. Defines a generalized method that a value type or class implements to IEquatable<T> create a type-specific method for determining equality of instances. IFormatProvider Provides a mechanism for retrieving an object to control formatting. Provides functionality to format the value of an object into a string IFormattable representation. IObservable<T> Defines a provider for push-based notification. IObserver<T> Provides a mechanism for receiving push-based notifications. Defines a mechanism for retrieving a service object; that is, an object IServiceProvider that provides custom support to other objects. Delegates Delegate Action Action<T> Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> Action<T1, T2, T3, T4, T5, T6, T7, T8, Description Encapsulates a method that has no parameters and does not return a value. Encapsulates a method that has a single parameter and does not return a value. Encapsulates a method that has 10 parameters and does not return a value. Encapsulates a method that has 11 parameters and does not return a value. Encapsulates a method that has 12 parameters and does not return a value. Encapsulates a method that has 13 parameters and does not return a value. Encapsulates a method that has 14 parameters and does not return a value. Encapsulates a method that has 15 parameters

T9, T10, T11, T12, T13, T14, T15> and does not return a value. Action<T1, T2, T3, T4, T5, T6, T7, T8, Encapsulates a method that has 16 parameters T9, T10, T11, T12, T13, T14, T15, T16> and does not return a value. Encapsulates a method that has two parameters Action<T1, T2> and does not return a value. Encapsulates a method that has three Action<T1, T2, T3> parameters and does not return a value. Encapsulates a method that has four Action<T1, T2, T3, T4> parameters and does not return a value. Encapsulates a method that has five Action<T1, T2, T3, T4, T5> parameters and does not return a value. Encapsulates a method that has six parameters Action<T1, T2, T3, T4, T5, T6> and does not return a value. Encapsulates a method that has seven Action<T1, T2, T3, T4, T5, T6, T7> parameters and does not return a value. Encapsulates a method that has eight Action<T1, T2, T3, T4, T5, T6, T7, T8> parameters and does not return a value. Action<T1, T2, T3, T4, T5, T6, T7, T8, Encapsulates a method that has nine T9> parameters and does not return a value. Represents the callback method to invoke AppDomainInitializer when the application domain is initialized. Represents the method that handles the AssemblyLoadEventHandler AssemblyLoad event of an AppDomain. References a method to be called when a AsyncCallback corresponding asynchronous operation completes. Represents the method that compares two Comparison<T> objects of the same type. Represents the method that will handle the ConsoleCancelEventHandler CancelKeyPress event of a System.Console. Represents a method that converts an object Converter<TInput, TOutput> from one type to another type. Used by DoCallBack for cross-application CrossAppDomainDelegate domain calls. Represents the method that will handle an EventHandler event that has no event data. Represents the method that will handle an EventHandler<TEventArgs> event. Encapsulates a method that has no parameters Func<TResult> and returns a value of the type specified by the TResult parameter. Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, Encapsulates a method that has nine

TResult> Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult> Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult> Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult> Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult> Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult> Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult> Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult> Func<T, TResult>

Func<T1, T2, TResult>

Func<T1, T2, T3, TResult>

Func<T1, T2, T3, T4, TResult>

Func<T1, T2, T3, T4, T5, TResult>

Func<T1, T2, T3, T4, T5, T6, TResult> Func<T1, T2, T3, T4, T5, T6, T7, TResult>

parameters and returns a value of the type specified by the TResult parameter. Encapsulates a method that has 10 parameters and returns a value of the type specified by the TResult parameter. Encapsulates a method that has 11 parameters and returns a value of the type specified by the TResult parameter. Encapsulates a method that has 12 parameters and returns a value of the type specified by the TResult parameter. Encapsulates a method that has 13 parameters and returns a value of the type specified by the TResult parameter. Encapsulates a method that has 14 parameters and returns a value of the type specified by the TResult parameter. Encapsulates a method that has 15 parameters and returns a value of the type specified by the TResult parameter. Encapsulates a method that has 16 parameters and returns a value of the type specified by the TResult parameter. Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter. Encapsulates a method that has two parameters and returns a value of the type specified by the TResult parameter. Encapsulates a method that has three parameters and returns a value of the type specified by the TResult parameter. Encapsulates a method that has four parameters and returns a value of the type specified by the TResult parameter. Encapsulates a method that has five parameters and returns a value of the type specified by the TResult parameter. Encapsulates a method that has six parameters and returns a value of the type specified by the TResult parameter. Encapsulates a method that has seven parameters and returns a value of the type

Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult> Predicate<T>

ResolveEventHandler

UnhandledExceptionEventHandler Enumerations

specified by the TResult parameter. Encapsulates a method that has eight parameters and returns a value of the type specified by the TResult parameter. Represents the method that defines a set of criteria and determines whether the specified object meets those criteria. Represents a method that handles the AppDomain.TypeResolve, AppDomain.ResourceResolve, or AssemblyResolve event of an AppDomain. Represents the method that will handle the event raised by an exception that is not handled by the application domain.

Description Indicates the context for a manifest-activated ActivationContext.ContextForm application. Specifies the action that a custom application AppDomainManagerInitializationOptions domain manager takes when initializing a new domain. Specifies the application elements on which it AttributeTargets is valid to apply an attribute. Specifies whether relevant Convert.ToBase64CharArray and Base64FormattingOptions Convert.ToBase64String methods insert line breaks in their output. Specifies constants that define foreground and ConsoleColor background colors for the console. ConsoleKey Specifies the standard keys on a console. Represents the SHIFT, ALT, and CTRL ConsoleModifiers modifier keys on a keyboard. Specifies combinations of modifier and console ConsoleSpecialKey keys that can interrupt the current process. Specifies whether a DateTime object represents a local time, a Coordinated Universal Time DateTimeKind (UTC), or is not specified as either local time or UTC. DayOfWeek Specifies the day of the week. Specifies enumerated constants used to retrieve Environment.SpecialFolder directory paths to system special folders. Environment.SpecialFolderOption Specifies options to use for getting the path to a

Enumeration

EnvironmentVariableTarget GCCollectionMode GCNotificationStatus GenericUriParserOptions LoaderOptimization

MidpointRounding PlatformID StringComparison

StringSplitOptions TypeCode UriComponents UriFormat UriHostNameType

UriIdnScope

UriKind UriPartial

special folder. Specifies the location where an environment variable is stored or retrieved in a set or get operation. Specifies the behavior for a forced garbage collection. Provides information about the current registration for notification of the next full garbage collection. Specifies options for a UriParser. An enumeration used with the LoaderOptimizationAttribute class to specify loader optimizations for an executable. Specifies how mathematical rounding methods should process a number that is midway between two numbers. Identifies the operating system, or platform, supported by an assembly. Specifies the culture, case, and sort rules to be used by certain overloads of the String.Compare and String.Equals methods. Specifies whether applicable String.Split method overloads include or omit empty substrings from the return value. Specifies the type of an object. Specifies the parts of a Uri. Controls how URI information is escaped. Defines host name types for the Uri.CheckHostName method. Provides the possible values for the configuration setting of the System.Configuration.IdnElement in the System.Configuration namespace. Defines the kinds of Uris for the Uri.IsWellFormedUriString(String, UriKind) and several Uri.Uri methods. Defines the parts of a URI for the Uri.GetLeftPart method.

System.Collections Namespace
.NET Framework 4 The System.Collections namespace contains interfaces and classes that define various collections of objects, such as lists, queues, bit arrays, hash tables and dictionaries. Classes Description Implements the IList interface using an array whose ArrayList size is dynamically increased as required. Manages a compact array of bit values, which are BitArray represented as Booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0). Compares two objects for equivalence, ignoring the CaseInsensitiveComparer case of strings. Obsolete. Supplies a hash code for an object, using a CaseInsensitiveHashCodeProvider hashing algorithm that ignores the case of strings. Provides the abstract base class for a strongly typed CollectionBase collection. Compares two objects for equivalence, where string Comparer comparisons are case-sensitive. Provides the abstract base class for a strongly typed DictionaryBase collection of key/value pairs. Represents a collection of key/value pairs that are Hashtable organized based on the hash code of the key. Queue Represents a first-in, first-out collection of objects. Provides the abstract base class for a strongly typed ReadOnlyCollectionBase non-generic read-only collection. Represents a collection of key/value pairs that are SortedList sorted by the keys and are accessible by key and by index. Represents a simple last-in-first-out (LIFO) nonStack generic collection of objects. Provides objects for performing a structural StructuralComparisons comparison of two collection objects. Structures Structure Description DictionaryEntry Defines a dictionary key/value pair that can be set or retrieved. Interfaces Class

Description Defines size, enumerators, and synchronization methods for all ICollection nongeneric collections. IComparer Exposes a method that compares two objects. IDictionary Represents a nongeneric collection of key/value pairs. IDictionaryEnumerator Enumerates the elements of a nongeneric dictionary. Exposes the enumerator, which supports a simple iteration over a IEnumerable non-generic collection. IEnumerator Supports a simple iteration over a nongeneric collection. IEqualityComparer Defines methods to support the comparison of objects for equality. Obsolete. Supplies a hash code for an object, using a custom hash IHashCodeProvider function. Represents a non-generic collection of objects that can be IList individually accessed by index. IStructuralComparable Supports the structural comparison of collection objects. Defines methods to support the comparison of objects for IStructuralEquatable structural equality.

Interface

System.Collections.Specialized Namespace
.NET Framework 4 The System.Collections.Specialized namespace contains specialized and strongly-typed collections; for example, a linked list dictionary, a bit vector, and collections that contain only strings. Classes Class CollectionChangedEventManager Description Provides a WeakEventManager implementation so that you can use the "weak event listener" pattern to attach listeners for the CollectionChanged event. Creates collections that ignore the case in strings. Implements IDictionary by using a ListDictionary while the collection is small, and then switching to a Hashtable when the

CollectionsUtil HybridDictionary

collection gets large. Implements IDictionary using a singly linked ListDictionary list. Recommended for collections that typically contain 10 items or less. Provides the abstract base class for a collection of associated String keys and NameObjectCollectionBase Object values that can be accessed either with the key or with the index. Represents a collection of the String keys of a NameObjectCollectionBase.KeysCollection collection. Represents a collection of associated String NameValueCollection keys and String values that can be accessed either with the key or with the index. Provides data for the CollectionChanged NotifyCollectionChangedEventArgs event. Represents a collection of key/value pairs OrderedDictionary that are accessible by the key or index. StringCollection Represents a collection of strings. Implements a hash table with the key and the StringDictionary value strongly typed to be strings rather than objects. Supports a simple iteration over a StringEnumerator StringCollection. Structures Description Provides a simple structure that stores Boolean values and small BitVector32 integers in 32 bits of memory. BitVector32.Section Represents a section of the vector that can contain an integer number. Interfaces Description Notifies listeners of dynamic changes, such as when items get INotifyCollectionChanged added and removed or the whole list is refreshed. IOrderedDictionary Represents an indexed collection of key/value pairs. Delegates Description Represents the method that handles the NotifyCollectionChangedEventHandler CollectionChanged event. Enumerations Delegate Interface Structure

Description Describes the action that caused a CollectionChanged NotifyCollectionChangedAction event.

Enumeration

System.ComponentModel Namespace
.NET Framework 4

The System.ComponentModel namespace provides classes that are used to implement the run-time and design-time behavior of components and controls. This namespace includes the base classes and interfaces for implementing attributes and type converters, binding to data sources, and licensing components. The classes in this namespace divide into the following categories:

Core component classes. See the Component, IComponent, Container, and IContainer classes. Component licensing. See the License, LicenseManager, LicenseProvider, and LicenseProviderAttribute classes. Attributes. See the Attribute class. Descriptors and persistence. See the TypeDescriptor, EventDescriptor, and PropertyDescriptor classes. Type converters. See the TypeConverter class.

Classes

Class AddingNewEventArgs

Description Provides data for the BindingSource.AddingNew event. Specifies the value to pass to a property to cause the property to get its value from another source. This is known as ambience. This class cannot be inherited. Provides a type converter to convert Array objects to and from various other representations.

AmbientValueAttribute

ArrayConverter

AsyncCompletedEventArgs AsyncOperation

Provides data for the MethodNameCompleted event. Tracks the lifetime of an asynchronous operation. Provides concurrency management for classes that support asynchronous method calls. This class cannot be inherited. Represents a collection of attributes. Enables attribute redirection. This class cannot be inherited. Executes an operation on a separate thread. Provides a base type converter for nonfloating-point numerical types. Specifies whether a member is typically used for binding. This class cannot be inherited. Provides a generic collection that supports data binding. Provides a type converter to convert Boolean objects to and from various other representations. Specifies whether a property or event should be displayed in a Properties window. Provides a type converter to convert 8-bit unsigned integer objects to and from various other representations. Provides data for a cancelable event. Specifies the name of the category in which to group the property or event when displayed in a PropertyGrid control set to Categorized mode. Provides a type converter to convert Unicode character objects to and from various other representations.

AsyncOperationManager

AttributeCollection AttributeProviderAttribute BackgroundWorker BaseNumberConverter

BindableAttribute

BindingList<T>

BooleanConverter

BrowsableAttribute

ByteConverter

CancelEventArgs

CategoryAttribute

CharConverter

CollectionChangeEventArgs CollectionConverter

Provides data for the CollectionChanged event. Provides a type converter to convert collection objects to and from various other representations. Specifies the data source and data member properties for a component that supports complex data binding. This class cannot be inherited. Provides the base implementation for the IComponent interface and enables object sharing between applications. Provides a read-only container for a collection of IComponent objects. Provides a type converter to convert components to and from various other representations. Provides the base class for a custom component editor. Provides simple functionality for enumerating resources for a component or object. The ComponentResourceManager class is a ResourceManager. Encapsulates zero or more components. Provides a base class for the container filter service. Provides a type converter to convert CultureInfo objects to and from various other representations. Provides a WeakEventManager implementation so that you can use the "weak event listener" pattern to attach listeners for the CurrentChanged event. Provides information for the CurrentChanging event. Provides a WeakEventManager implementation so that you can use the "weak event listener" pattern to attach listeners for the CurrentChanging event.

ComplexBindingPropertiesAttribute

Component

ComponentCollection

ComponentConverter

ComponentEditor

ComponentResourceManager

Container ContainerFilterService CultureInfoConverter

CurrentChangedEventManager

CurrentChangingEventArgs

CurrentChangingEventManager

CustomTypeDescriptor

Provides a simple default implementation of the ICustomTypeDescriptor interface. Identifies a type as an object suitable for binding to an ObjectDataSource object. This class cannot be inherited. Provides metadata for a property representing a data field. This class cannot be inherited. Identifies a data operation method exposed by a type, what type of operation the method performs, and whether the method is the default data method. This class cannot be inherited. Provides a type converter to convert DateTime objects to and from various other representations. Provides a type converter to convert DateTimeOffset structures to and from various other representations. Provides a type converter to convert Decimal objects to and from various other representations. Specifies the default binding property for a component. This class cannot be inherited. Specifies the default event for a component. Specifies the default property for a component. Specifies the default value for a property. Provides an extension of PropertyDescriptor that accounts for the additional property characteristics of a dependency property. Specifies a description for a property or event. Specifies the class used to implement design-time services for a component.

DataObjectAttribute

DataObjectFieldAttribute

DataObjectMethodAttribute

DateTimeConverter

DateTimeOffsetConverter

DecimalConverter

DefaultBindingPropertyAttribute DefaultEventAttribute DefaultPropertyAttribute DefaultValueAttribute

DependencyPropertyDescriptor

DescriptionAttribute DesignerAttribute

DesignerCategoryAttribute

Specifies that the designer for a class belongs to a certain category. Provides attached properties used to communicate with a designer. Specifies the type of persistence to use when serializing a property on a component at design time. Specifies whether a property can only be set at design time. DesignTimeVisibleAttribute marks a component's visibility. If Yes is present, a visual designer can show this component on a designer. Specifies the display name for a property, event, or public void method which takes no arguments. Provides a type converter to convert doubleprecision, floating point number objects to and from various other representations. Provides data for the DoWork event handler. Specifies the editor to use to change a property. This class cannot be inherited. Specifies that a property or method is viewable in an editor. This class cannot be inherited. Provides a type converter to convert Enum objects to and from various other representations. Provides information about an event. Represents a collection of EventDescriptor objects. Provides a simple list of delegates. This class cannot be inherited. Provides a type converter to convert expandable objects to and from various other representations.

DesignerProperties

DesignerSerializationVisibilityAttribute

DesignOnlyAttribute

DesignTimeVisibleAttribute

DisplayNameAttribute

DoubleConverter

DoWorkEventArgs EditorAttribute

EditorBrowsableAttribute

EnumConverter EventDescriptor EventDescriptorCollection EventHandlerList

ExpandableObjectConverter

ExtenderProvidedPropertyAttribute

Specifies a property that is offered by an extender provider. This class cannot be inherited. Provides an abstract base class for types that describe how to divide the items in a collection into groups. Provides a type converter to convert Guid objects to and from various other representations. Provides data for events that can be handled completely in an event handler. Specifies that an object has no subproperties capable of being edited. This class cannot be inherited. Indicates whether the component associated with this attribute has been inherited from a base class. This class cannot be inherited. Specifies which event is raised on initialization. This class cannot be inherited. Specifies the installer for a type that installs components. Creates an instance of a particular type of property from a drop-down box within the PropertyGrid. Provides a type converter to convert 16-bit signed integer objects to and from other representations. Provides a type converter to convert 32-bit signed integer objects to and from other representations. Provides a type converter to convert 64-bit signed integer objects to and from various other representations. Thrown when a thread on which an operation should execute no longer exists or has no message loop. The exception thrown when using invalid arguments

GroupDescription

GuidConverter

HandledEventArgs

ImmutableObjectAttribute

InheritanceAttribute

InitializationEventAttribute

InstallerTypeAttribute

InstanceCreationEditor

Int16Converter

Int32Converter

Int64Converter

InvalidAsynchronousStateException InvalidEnumArgumentException

that are enumerators. ItemPropertyInfo Contains information about a property. Provides the abstract base class for all licenses. A license is granted to a specific instance of a component. Specifies when you can use a licensed object and provides a way of obtaining additional services needed to support licenses running within its domain. Represents the exception thrown when a component cannot be granted a license. Provides properties and methods to add a license to a component and to manage a LicenseProvider. This class cannot be inherited. Provides the abstract base class for implementing a license provider. Specifies the LicenseProvider to use with a class. This class cannot be inherited. Provides an implementation of a LicenseProvider. The provider works in a similar fashion to the Microsoft .NET Framework standard licensing model. Specifies that a list can be used as a data source. A visual designer should use this attribute to determine whether to display a particular list in a data-binding picker. This class cannot be inherited. Provides data for the ListChanged event. Provides a description of the sort operation applied to a data source. Represents a collection of ListSortDescription objects.

License

LicenseContext

LicenseException

LicenseManager

LicenseProvider

LicenseProviderAttribute

LicFileLicenseProvider

ListBindableAttribute

ListChangedEventArgs ListSortDescription

ListSortDescriptionCollection

LocalizableAttribute

Specifies whether a property should be localized. This class cannot be inherited. Specifies the properties that support lookup-based binding. This class cannot be inherited. Implements IComponent and provides the base implementation for remotable components that are marshaled by value (a copy of the serialized object is passed). Represents a mask-parsing service that can be used by any number of controls that support masking, such as the MaskedTextBox control. Represents a class member, such as a property or event. This is an abstract base class. Specifies that this property can be combined with properties belonging to other objects in a Properties window. Provides a type converter to convert multiline strings to a simple string. Provides the base implementation for the INestedContainer interface, which enables containers to have an owning component. Indicates that the parent property is notified when the value of the property that this attribute is applied to is modified. This class cannot be inherited. Provides automatic conversion between a nullable type and its underlying primitive type. Indicates whether the name of the associated property is displayed with parentheses in the Properties window. This class cannot be inherited. Indicates that an object's text representation is obscured by characters such as asterisks. This class cannot be inherited.

LookupBindingPropertiesAttribute

MarshalByValueComponent

MaskedTextProvider

MemberDescriptor

MergablePropertyAttribute

MultilineStringConverter

NestedContainer

NotifyParentPropertyAttribute

NullableConverter

ParenthesizePropertyNameAttribute

PasswordPropertyTextAttribute

ProgressChangedEventArgs PropertyChangedEventArgs

Provides data for the ProgressChanged event. Provides data for the PropertyChanged event. Provides a WeakEventManager implementation so that you can use the "weak event listener" pattern to attach listeners for the PropertyChanged event. Provides data for the PropertyChanging event. Provides an abstraction of a property on a class. Represents a collection of PropertyDescriptor objects. Specifies which properties should be reported by type descriptors, specifically the GetProperties method. Identifies the property tab or tabs to display for the specified class or classes. Specifies the name of the property that an implementer of IExtenderProvider offers to other components. This class cannot be inherited Specifies whether the property this attribute is bound to is read-only or read/write. This class cannot be inherited Obsolete. Specifies that the property can be used as an application setting. Provides a type converter to convert object references to and from other representations. Provides data for the Refreshed event. Indicates that the property grid should refresh when the associated property value changes. This class cannot be inherited. Specifies whether the Visual Studio Custom Action Installer or the Installutil.exe (Installer Tool) should

PropertyChangedEventManager

PropertyChangingEventArgs PropertyDescriptor PropertyDescriptorCollection

PropertyFilterAttribute

PropertyTabAttribute

ProvidePropertyAttribute

ReadOnlyAttribute

RecommendedAsConfigurableAttribute

ReferenceConverter RefreshEventArgs

RefreshPropertiesAttribute

RunInstallerAttribute

be invoked when the assembly is installed. RunWorkerCompletedEventArgs SByteConverter Provides data for the MethodNameCompleted event. Provides a type converter to convert 8-bit unsigned integer objects to and from a string. Specifies when a component property can be bound to an application setting. Provides a type converter to convert single-precision, floating point number objects to and from various other representations. Represents a collection of SortDescription objects. Provides a type converter to convert string objects to and from other representations. Infrastructure. Provides methods to verify the machine name and path conform to a specific syntax. This class cannot be inherited. Provides a type converter to convert TimeSpan objects to and from other representations. Represents an attribute of a toolbox item. Specifies the filter string and filter type to use for a toolbox item. Provides a unified way of converting types of values to other types, as well as for accessing standard values and subproperties. Represents an abstract class that provides properties for objects that do not have properties.

SettingsBindableAttribute

SingleConverter

SortDescriptionCollection StringConverter

SyntaxCheck

TimeSpanConverter ToolboxItemAttribute ToolboxItemFilterAttribute

TypeConverter

TypeConverter.SimplePropertyDescriptor

TypeConverter.StandardValuesCollection Represents a collection of values. TypeConverterAttribute Specifies what type to use as a converter for the object this attribute is bound to.

TypeDescriptionProvider

Provides supplemental metadata to the TypeDescriptor. Specifies the custom type description provider for a class. This class cannot be inherited. Provides information about the characteristics for a component, such as its attributes, properties, and events. This class cannot be inherited. Provides a type converter that can be used to populate a list box with available types. Provides a type converter to convert 16-bit unsigned integer objects to and from other representations. Provides a type converter to convert 32-bit unsigned integer objects to and from various other representations. Provides a type converter to convert 64-bit unsigned integer objects to and from other representations. Specifies an exception that is handled as a warning instead of an error. Throws an exception for a Win32 error code.

TypeDescriptionProviderAttribute

TypeDescriptor

TypeListConverter

UInt16Converter

UInt32Converter

UInt64Converter

WarningException Win32Exception Structures

Structure SortDescription Interfaces

Description Defines the direction and the property name to be used as the criteria for sorting a collection.

Interface IBindingList

Description Provides the features required to support both complex

and simple scenarios when binding to a data source. IBindingListView Extends the IBindingList interface by providing advanced sorting and filtering capabilities. Adds transactional capability when adding a new item to a collection. Defines the mechanism for querying the object for changes and resetting of the changed status. Enables collections to have the functionalities of current record management, custom sorting, filtering, and grouping. An interface that enables implementing collections to create a view to their data. Normally, user code does not call methods on this interface. Obsolete. Provides a top-level mapping layer between a COM object and a TypeDescriptor. Provides functionality required by all components. Provides functionality for containers. Containers are objects that logically contain zero or more components. Provides an interface that supplies dynamic custom type information for an object. Provides the functionality to offer custom error information that a user interface can bind to. Defines methods and properties that a CollectionView implements to provide editing capabilities to a collection.

ICancelAddNew

IChangeTracking

ICollectionView

ICollectionViewFactory

IComNativeDescriptorHandler IComponent IContainer

ICustomTypeDescriptor

IDataErrorInfo

IEditableCollectionView

Defines methods and properties that a CollectionView IEditableCollectionViewAddNewItem implements to enable specifying adding items of a specific type. IEditableObject Provides functionality to commit or rollback changes to an object that is used as a data source.

IExtenderProvider

Defines the interface for extending properties to other components in a container. Provides an interface to facilitate the retrieval of the builder's name and to display the builder. Defines a property that provides information about an object's properties. Provides functionality to an object to return a list that can be bound to a data source. Provides functionality for nested containers, which logically contain zero or more other components and are owned by a parent component. Provides the ability to retrieve the full nested name of a component. Notifies clients that a property value has changed. Notifies clients that a property value is changing. Indicates whether a class converts property change events to ListChanged events. Provides support for rolling back the changes Provides functionality required by sites. Specifies that this object supports a simple, transacted notification for batch initialization. Allows coordination of initialization for a component and its dependent properties. Provides a way to synchronously or asynchronously execute a delegate. Provides contextual information about a component, such as its container and property descriptor. Provides functionality to discover the schema for a bindable list, where the properties available for binding differ from

IIntellisenseBuilder

IItemProperties

IListSource

INestedContainer

INestedSite INotifyPropertyChanged INotifyPropertyChanging IRaiseItemChangedEvents IRevertibleChangeTracking ISite ISupportInitialize

ISupportInitializeNotification

ISynchronizeInvoke

ITypeDescriptorContext

ITypedList

the public properties of the object to bind to. Delegates

Delegate AddingNewEventHandler

Description Represents the method that will handle the BindingSource.AddingNew event. Represents the method that will handle the MethodNameCompleted event of an asynchronous operation. Represents the method that handles a cancelable event. Represents the method that handles the CollectionChanged event raised when adding elements to or removing elements from a collection. Represents the method that handles the CurrentChanging event. Represents the method that will handle the DoWork event. This class cannot be inherited. Represents a method that can handle events which may or may not require further processing after the event handler has returned. Represents the method that will handle the ListChanged event of the IBindingList class. Represents the method that will handle the ProgressChanged event of the BackgroundWorker class. This class cannot be inherited. Represents the method that will handle the PropertyChanged event raised when a property is changed on a component. Represents the method that will handle the PropertyChanging event of an INotifyPropertyChanging

AsyncCompletedEventHandler

CancelEventHandler

CollectionChangeEventHandler

CurrentChangingEventHandler

DoWorkEventHandler

HandledEventHandler

ListChangedEventHandler

ProgressChangedEventHandler

PropertyChangedEventHandler

PropertyChangingEventHandler

interface. Represents the method that handles the Refreshed event raised when a Type or component is changed during design time. Represents the method that will handle the RunWorkerCompleted event of a BackgroundWorker class.

RefreshEventHandler

RunWorkerCompletedEventHandler Enumerations

Enumeration BindableSupport

Description Specifies values to indicate whether a property can be bound to a data element or another property. Specifies whether the template can be bound one way or two ways. Specifies how the collection is changed. Identifies the type of data operation performed by a method, as specified by the DataObjectMethodAttribute applied to the method.

BindingDirection CollectionChangeAction

DataObjectMethodType

DesignerSerializationVisibility Specifies the visibility a property has to the design-time serializer. EditorBrowsableState InheritanceLevel LicenseUsageMode ListChangedType ListSortDirection MaskedTextResultHint Specifies the browsable state of a property or method from within an editor. Defines identifiers for types of inheritance levels. Specifies when the License can be used. Specifies how the list changed. Specifies the direction of a sort operation. Specifies values that succinctly describe the results of a masked text parsing operation.

NewItemPlaceholderPosition Specifies where the placeholder for a new item appears in the

collection. Specifies which properties should be reported by type descriptors, specifically the GetProperties method. This enumeration is used to specify the value of the PropertyFilterAttribute.Filter property. Defines identifiers that indicate the persistence scope of a tab in the Properties window. Defines identifiers that indicate the type of a refresh of the Properties window. Defines identifiers used to indicate the type of filter that a ToolboxItemFilterAttribute uses.

PropertyFilterOptions

PropertyTabScope

RefreshProperties

ToolboxItemFilterType

System.ComponentModel.Design Namespace
.NET Framework 4 The System.ComponentModel.Design namespace contains classes that developers can use to build custom design-time behavior for components and user interfaces for configuring components at design time. The design time environment provides systems that enable developers to arrange components and configure their properties. Some components may require specific design-time only behavior to function properly in a design time environment. It may also be valuable to provide custom user interfaces which assist developers in configuring components or the values of complex data types. The classes and interfaces defined within this namespace can be used to build design-time behavior for components, access design-time services, and implement customized design-time configuration interfaces. The classes in this namespace include:

A basic IDesigner interface that you can use to customize design-time behavior for specific types of components. A ComponentDesigner class that provides a more sophisticated designer base class which implements the IDesigner, IDisposable, and IDesignerFilter interfaces. Designer interfaces and services that enable a designer to support additional functionality, including: o IComponentChangeService

IDesignerEventService IDesignerFilter IDesignerHost IDesignerOptionService IDictionaryService IEventBindingService IExtenderListService IExtenderProviderService IHelpService IInheritanceService IMenuCommandService IReferenceService IResourceService IRootDesigner ISelectionService IServiceContainer ITypeDescriptorFilterService ITypeResolutionService Classes that can be used to customize design-time license context management and serialization: DesigntimeLicenseContext and DesigntimeLicenseContextSerializer. Simple collection editors that can be extended: ArrayEditor and CollectionEditor.

o o o o o o o o o o o o o o o o o o

Classes Class ActiveDesignerEventArgs ActiveDesignSurfaceChangedEventArgs ArrayEditor BinaryEditor ByteViewer Description Provides data for the ActiveDesigner event. Provides data for the ActiveDesignSurfaceChanged event. Provides a user interface for editing arrays at design time. Provides a user interface for editing binary data. Displays byte arrays in hexadecimal, ANSI, and Unicode formats. The exception that is thrown when an attempt to check out a file that is checked into a source code management program is canceled or fails. Provides a user interface that can edit most types of collections at design time. Provides a modal dialog box for editing the contents of a collection

CheckoutException

CollectionEditor CollectionEditor.CollectionForm

CommandID

ComponentChangedEventArgs

ComponentChangingEventArgs ComponentDesigner

ComponentDesigner.ShadowPropertyCollection

ComponentEventArgs

ComponentRenameEventArgs DateTimeEditor

DesignerActionHeaderItem

DesignerActionItem DesignerActionItemCollection DesignerActionList DesignerActionListCollection DesignerActionListsChangedEventArgs

using a UITypeEditor. Represents a unique command identifier that consists of a numeric command ID and a GUID menu group identifier. Provides data for the ComponentChanged event. This class cannot be inherited. Provides data for the ComponentChanging event. This class cannot be inherited. Extends the design mode behavior of a component. Represents a collection of shadow properties that should override inherited default or assigned values for specific properties. This class cannot be inherited. Provides data for the ComponentAdded, ComponentAdding, ComponentRemoved, and ComponentRemoving events. Provides data for the ComponentRename event. This date time editor is a UITypeEditor suitable for visually editing DateTime objects. Represents a static header item on a smart tag panel. This class cannot be inherited. Provides the base class for types that represent a panel item on a smart tag panel. Represents a collection of DesignerActionItem objects. Provides the base class for types that define a list of items used to create a smart tag panel. Represents a collection of DesignerActionList objects. Provides data for the DesignerActionListsChanged event.

Represents a smart tag panel item that is associated with a method in a DesignerActionMethodItem class derived from DesignerActionList. Represents a panel item that is associated with a property in a class DesignerActionPropertyItem derived from DesignerActionList. This class cannot be inherited. Establishes a design-time service that manages the collection of DesignerActionService DesignerActionItem objects for components. Represents a static text item on a DesignerActionTextItem smart tag panel. Manages the user interface (UI) for a DesignerActionUIService smart tag panel. This class cannot be inherited. Provides data for the DesignerActionUIStateChangeEventArgs DesignerActionUIStateChange event. DesignerCollection Represents a collection of designers. Represents a base class for designtime tools, not derived from DesignerCommandSet ComponentDesigner, that provide smart tag or designer verb capabilities. Provides data for the DesignerEventArgs DesignerCreated and DesignerDisposed events. Provides a base class for getting and DesignerOptionService setting option values for a designer. Contains a collection of designer DesignerOptionService.DesignerOptionCollection options. This class cannot be inherited. Provides a way to group a series of design-time actions to improve DesignerTransaction performance and enable most types of changes to be undone. Provides data for the DesignerTransactionCloseEventArgs TransactionClosed and TransactionClosing events. Represents a verb that can be DesignerVerb invoked from a designer. DesignerVerbCollection Represents a collection of

DesignSurface DesignSurfaceCollection DesignSurfaceEventArgs DesignSurfaceManager DesigntimeLicenseContext DesigntimeLicenseContextSerializer EventBindingService ExceptionCollection HelpKeywordAttribute InheritanceService LoadedEventArgs LocalizationExtenderProvider MenuCommand MenuCommandsChangedEventArgs MenuCommandService MultilineStringEditor

ObjectSelectorEditor

DesignerVerb objects. Presents a user interface for designing components. Contains a collection of design surfaces. This class cannot be inherited. Provides data for the DesignSurfaceCreated event. Manages a collection of DesignSurface objects. Represents a design-time license context that can support a license provider at design time. Provides support for design-time license context serialization. A default implementation of the IEventBindingService interface. Represents the collection of exceptions. Specifies the context keyword for a class or member. This class cannot be inherited. Provides a set of methods for identifying inherited components. Provides data for the Loaded event. This class cannot be inherited. Obsolete. Provides design-time support for localization features to a root designer. Represents a Windows menu or toolbar command item. Provides data for the MenuCommandsChanged event. Implements the IMenuCommandService interface. Displays a dialog for editing multiline strings in design mode. Implements the basic functionality that can be used to design value editors. These editors can, in turn, provide a user interface for representing and editing the values of objects of the supported data types.

ObjectSelectorEditor.Selector ObjectSelectorEditor.SelectorNode ProjectTargetFrameworkAttribute ServiceContainer

StandardCommands

StandardToolWindows

TypeDescriptionProviderService UndoEngine UndoEngine.UndoUnit Interfaces

Displays a hierarchical collection of labeled items, each represented by a TreeNode. Represents a node of a TreeView. Specifies the target framework for a project. Provides a simple implementation of the IServiceContainer interface. This class cannot be inherited. Defines identifiers for the standard set of commands that are available to most applications. Defines GUID identifiers that correspond to the standard set of tool windows that are available in the design environment. Provides a type description provider for a specified type. Specifies generic undo/redo functionality at design time. Encapsulates a unit of work that a user can undo.

Description Provides an interface to add and remove the event handlers for events that add, change, remove or IComponentChangeService rename components, and provides methods to raise a ComponentChanged or ComponentChanging event. Provides debugging services in a design-time IComponentDesignerDebugService environment. IComponentDesignerStateService Allows a designer to store and retrieve its state. IComponentDiscoveryService Enables enumeration of components at design time. Provides a set of recommended default values during IComponentInitializer component creation. Provides the basic framework for building a custom IDesigner designer. Provides event notifications when root designers are IDesignerEventService added and removed, when a selected component changes, and when the current root designer changes. Provides an interface that enables a designer to access IDesignerFilter and filter the dictionaries of a TypeDescriptor that stores the property, attribute, and event descriptors

Interface

IDesignerHost IDesignerHostTransactionState IDesignerOptionService IDesignTimeAssemblyLoader IDictionaryService IEventBindingService IExtenderListService IExtenderProviderService IHelpService IInheritanceService IMenuCommandService IMultitargetHelperService

IReferenceService

IResourceService IRootDesigner ISelectionService IServiceContainer ITreeDesigner ITypeDescriptorFilterService

that a component designer can expose to the designtime environment. Provides an interface for managing designer transactions and components. Specifies methods for the designer host to report on the state of transactions. Provides access to the designer options located on the Tools menu under the Options command in the Visual Studio development environment. Utility for loading assemblies in a designer. Provides a basic, component site-specific, key-value pair dictionary through a service that a designer can use to store user-defined data. Provides a service for registering event handlers for component events. Provides an interface that can list extender providers. Provides an interface for adding and removing extender providers at design time. Provides methods for showing Help topics and adding and removing Help keywords at design time. Provides methods for identifying the components of a component. Provides methods to manage the global designer verbs and menu commands available in design mode, and to show some types of shortcut menus. Defines multi-target type name resolution services in a design-time environment. Provides an interface for obtaining references to objects within a project by name or type, obtaining the name of a specified object, and for locating the parent of a specified object within a designer project. Provides an interface for designers to access resource readers and writers for specific CultureInfo resource types. Provides support for root-level designer view technologies. Provides an interface for a designer to select components. Provides a container for services. Provides support for building a set of related custom designers. Provides an interface to modify the set of member

ITypeDiscoveryService ITypeResolutionService Delegates

descriptors for a component in design mode. Discovers available types at design time. Provides an interface to retrieve an assembly or type by name.

Description Represents the method that will handle the ActiveDesignerEventHandler ActiveDesignerChanged event. Represents the method that will handle the ActiveDesignSurfaceChanged event of a ActiveDesignSurfaceChangedEventHandler DesignSurfaceManager. This class cannot be inherited. Represents the method that will handle a ComponentChangedEventHandler ComponentChanged event. Represents the method that will handle a ComponentChangingEventHandler ComponentChanging event. Represents the method that will handle the ComponentAdding, ComponentAdded, ComponentEventHandler ComponentRemoving, and ComponentRemoved events raised for component-level events. Represents the method that will handle a ComponentRenameEventHandler ComponentRename event. Represents the method that will handle the DesignerActionListsChanged event of a DesignerActionListsChangedEventHandler DesignerActionService. This class cannot be inherited. Represents the method that will handle the DesignerActionUIStateChangeEventHandler DesignerActionUIStateChange event of a DesignerActionUIService. Represents the method that will handle the DesignerCreated and DesignerDisposed DesignerEventHandler events that are raised when a document is created or disposed of. Represents the method that handles the DesignerTransactionCloseEventHandler TransactionClosed and TransactionClosing events of a designer. Represents the method that will handle the DesignSurfaceCreated event of a DesignSurfaceEventHandler DesignSurfaceManager class. This class cannot be inherited. LoadedEventHandler Represents the method that will handle the

Delegate

MenuCommandsChangedEventHandler

ServiceCreatorCallback Enumerations

Loaded event of the DesignSurface class. This class cannot be inherited. Represents the method that will handle the MenuCommandsChanged event of a MenuCommandService. This class cannot be inherited. Provides a callback mechanism that can create an instance of a service on demand.

Description Specifies the type of object-bound smart tag with ComponentActionsType respect to how it was associated with the component. Specifies the type of change occurring in a collection DesignerActionListsChangedType of DesignerActionList objects. DesignerActionUIStateChangeType Specifies the display state of a smart tag panel. Defines identifiers that indicate the display modes DisplayMode used by ByteViewer. Defines identifiers that indicate information about the HelpContextType context in which a request for Help information originated. Defines identifiers that indicate the type of a Help HelpKeywordType keyword. Specifies the type of action that occurred to the MenuCommandsChangedType related object's MenuCommands collection. Defines identifiers that indicate the type of a SelectionTypes selection. Defines identifiers for a set of technologies that ViewTechnology designer hosts support.

Enumeration

System.Configuration Namespace
.NET Framework 4

The System.Configuration namespace contains the types that provide the programming model for handling configuration data.
Classes

Class

Description Specifies that an application settings property has a common value for all users of an application. This class cannot be inherited. Acts as a base class for deriving concrete wrapper classes to implement the application settings feature in Window Forms applications. Represents a grouping of related application settings sections within a configuration file. This class cannot be inherited. Provides a method for reading values of a particular type from the configuration. Provides configuration system support for the appSettings configuration section. This class cannot be inherited. Provides dynamic validation of an object. Specifies a CallbackValidator object to use for code validation. This class cannot be inherited. Represents a group of user-scoped application settings in a configuration file. Represents a collection of string elements separated by commas. This class cannot be inherited.

ApplicationScopedSettingAttribute

ApplicationSettingsBase

ApplicationSettingsGroup

AppSettingsReader

AppSettingsSection

CallbackValidator CallbackValidatorAttribute

ClientSettingsSection

CommaDelimitedStringCollection

Converts a comma-delimited string value to and from CommaDelimitedStringCollectionConverter a CommaDelimitedStringCollection object. This class cannot be inherited. Represents a configuration file that is applicable to a particular computer, application, or resource. This class cannot be inherited. Declaratively instructs the .NET Framework to create an instance of a configuration element collection. This class cannot be inherited.

Configuration

ConfigurationCollectionAttribute

ConfigurationConverterBase ConfigurationElement

The base class for the configuration converter types. Represents a configuration element within a configuration file. Represents a configuration element containing a collection of child elements. Specifies the property of a configuration element. This class cannot be inherited. The current value is not one of the EnableSessionState values. The exception that is thrown when a configuration system error has occurred. Defines the configuration file mapping for the machine configuration file. Represents a location element within a configuration file. Contains a collection of ConfigurationLocationCollection objects. Contains a collection of locked configuration objects. This class cannot be inherited. Provides access to configuration files for client applications. This class cannot be inherited. Provides a permission structure that allows methods or classes to access configuration files. Creates a ConfigurationPermission object that either grants or denies the marked target permission to access sections of configuration files. Infrastructure. Represents an attribute or a child of a configuration element. This class cannot be inherited. Declaratively instructs the .NET Framework to instantiate a configuration property. This class

ConfigurationElementCollection

ConfigurationElementProperty

ConfigurationErrorsException

ConfigurationException

ConfigurationFileMap

ConfigurationLocation

ConfigurationLocationCollection

ConfigurationLockCollection

ConfigurationManager

ConfigurationPermission

ConfigurationPermissionAttribute

ConfigurationProperty

ConfigurationPropertyAttribute

cannot be inherited. ConfigurationPropertyCollection ConfigurationSection ConfigurationSectionCollection Represents a collection of configuration-element properties. Represents a section within a configuration file. Represents a collection of related sections within a configuration file. Represents a group of related sections within a configuration file. Represents a collection of ConfigurationSectionGroup objects. Provides runtime versions 1.0 and 1.1 support for reading configuration sections and common configuration settings. Serves as the base class for the System.Configuration validator attribute types. Acts as a base class for deriving a validation class so that a value of an object can be verified. Infrastructure. Wraps the corresponding XmlDocument type and also carries the necessary information for reporting file-name and line numbers. Represents a single, named connection string in the connection strings configuration file section. Contains a collection of ConnectionStringSettings objects. Provides programmatic access to the connection strings configuration-file section. Encapsulates the context information that is associated with a ConfigurationElement object. This class cannot be inherited.

ConfigurationSectionGroup

ConfigurationSectionGroupCollection

ConfigurationSettings

ConfigurationValidatorAttribute

ConfigurationValidatorBase

ConfigXmlDocument

ConnectionStringSettings

ConnectionStringSettingsCollection

ConnectionStringsSection

ContextInformation

DefaultSection

Represents a basic configuration-section handler that exposes the configuration section's XML for both read and write access. Specifies the default value for an application settings property. Provides validation of an object. This class cannot be inherited. Provides key/value pair configuration information from a configuration section. Provides a ProtectedConfigurationProvider object that uses the Windows data protection API (DPAPI) to encrypt and decrypt configuration data. Contains meta-information about an individual element within the configuration. This class cannot be inherited. Defines the configuration file mapping for an .exe application. This class cannot be inherited. Manages the path context for the current application. This class cannot be inherited. Converts between a string and an enumeration type. Provides the configuration setting for International Domain Name (IDN) processing in the System.Uri class. Provides a wrapper type definition for configuration sections that are not handled by the System.Configuration types. Provides a legacy section-handler definition for configuration sections that are not handled by the System.Configuration types. Converts between a string and the standard infinite or integer value.

DefaultSettingValueAttribute

DefaultValidator

DictionarySectionHandler

DpapiProtectedConfigurationProvider

ElementInformation

ExeConfigurationFileMap

ExeContext GenericEnumConverter

IdnElement

IgnoreSection

IgnoreSectionHandler

InfiniteIntConverter

InfiniteTimeSpanConverter IntegerValidator

Converts between a string and the standard infinite TimeSpan value. Provides validation of an Int32 value. Declaratively instructs the .NET Framework to perform integer validation on a configuration property. This class cannot be inherited. Provides the configuration setting for International Resource Identifier (IRI) processing in the System.Uri class. Contains a collection of KeyValueConfigurationElement objects. Represents a configuration element that contains a key/value pair. Provides persistence for application settings classes. Provides validation of an Int64 value. Declaratively instructs the .NET Framework to perform long-integer validation on a configuration property. This class cannot be inherited. Contains a collection of NameValueConfigurationElement objects. This class cannot be inherited. A configuration element that contains a String name and String value. This class cannot be inherited. Provides access to a configuration file. This type supports the .NET Framework configuration infrastructure and is not intended to be used directly from your code. Provides name/value-pair configuration information from a configuration section. Specifies that a settings provider should disable any

IntegerValidatorAttribute

IriParsingElement

KeyValueConfigurationCollection

KeyValueConfigurationElement LocalFileSettingsProvider LongValidator

LongValidatorAttribute

NameValueConfigurationCollection

NameValueConfigurationElement

NameValueFileSectionHandler

NameValueSectionHandler NoSettingsVersionUpgradeAttribute

logic that gets invoked when an application upgrade is detected. This class cannot be inherited. PositiveTimeSpanValidator Provides validation of a TimeSpan object. This class cannot be inherited. Declaratively instructs the .NET Framework to perform time validation on a configuration property. This class cannot be inherited. Contains meta-information on an individual property within the configuration. This type cannot be inherited. Contains a collection of PropertyInformation objects. This class cannot be inherited. Provides access to the protected-configuration providers for the current application's configuration file. Is the base class to create providers for encrypting and decrypting protected-configuration data. Provides a collection of ProtectedConfigurationProvider objects. Provides programmatic access to the configProtectedData configuration section. This class cannot be inherited. Represents a group of configuration elements that configure the providers for the <configProtectedData> configuration section. Represents the configuration elements associated with a provider. Represents a collection of ProviderSettings objects. Provides validation of a string based on the rules provided by a regular expression.

PositiveTimeSpanValidatorAttribute

PropertyInformation

PropertyInformationCollection

ProtectedConfiguration

ProtectedConfigurationProvider

ProtectedConfigurationProviderCollection

ProtectedConfigurationSection

ProtectedProviderSettings

ProviderSettings ProviderSettingsCollection RegexStringValidator

RegexStringValidatorAttribute

Declaratively instructs the .NET Framework to perform string validation on a configuration property using a regular expression. This class cannot be inherited. Provides a ProtectedConfigurationProvider instance that uses RSA encryption to encrypt and decrypt configuration data. Represents an element in a SchemeSettingElementCollection class. Represents a collection of SchemeSettingElement objects. Contains metadata about an individual section within the configuration hierarchy. This class cannot be inherited. Represents a custom settings attribute used to associate settings information with a settings property. Provides data for the SettingChanging event. Represents a simplified configuration element used for updating elements in the configuration. This class cannot be inherited. Contains a collection of SettingElement objects. This class cannot be inherited. Represents a collection of key/value pairs used to describe a configuration object as well as a SettingsProperty object. Provides the base class used to support user property settings. Provides contextual information that the provider can use when persisting settings. Provides a string that describes an individual

RsaProtectedConfigurationProvider

SchemeSettingElement

SchemeSettingElementCollection

SectionInformation

SettingAttribute

SettingChangingEventArgs

SettingElement

SettingElementCollection

SettingsAttributeDictionary

SettingsBase

SettingsContext SettingsDescriptionAttribute

configuration property. This class cannot be inherited. Provides a string that describes an application settings property group. This class cannot be inherited. Specifies a name for application settings property group. This class cannot be inherited. Provides data for the SettingsLoaded event. Specifies special services for application settings properties. This class cannot be inherited. Used internally as the class that represents metadata about an individual configuration property. Contains a collection of SettingsProperty objects. Provides an exception for read-only SettingsProperty objects. Provides an exception for SettingsProperty objects that are not found. Contains the value of a settings property that can be loaded and stored by an instance of SettingsBase. Contains a collection of settings property values that map SettingsProperty objects to SettingsPropertyValue objects. Provides an exception that is thrown when an invalid type is used with a SettingsProperty object. Acts as a base class for deriving custom settings providers in the application settings architecture. Specifies the settings provider used to provide storage for the current application settings class or property. This class cannot be inherited.

SettingsGroupDescriptionAttribute

SettingsGroupNameAttribute SettingsLoadedEventArgs SettingsManageabilityAttribute

SettingsProperty SettingsPropertyCollection SettingsPropertyIsReadOnlyException

SettingsPropertyNotFoundException

SettingsPropertyValue

SettingsPropertyValueCollection

SettingsPropertyWrongTypeException

SettingsProvider

SettingsProviderAttribute

SettingsProviderCollection

Represents a collection of application settings providers. Specifies the serialization mechanism that the settings provider should use. This class cannot be inherited. Contains the XML representing the serialized value of the setting. This class cannot be inherited. Infrastructure. Handles configuration sections that are represented by a single XML tag in the .config file. Indicates that an application settings property has a special significance. This class cannot be inherited. Provides validation of a string. Declaratively instructs the .NET Framework to perform string validation on a configuration property. This class cannot be inherited. Validates that an object is a derived class of a specified type. Declaratively instructs the .NET Framework to perform validation on a configuration property. This class cannot be inherited. Converts a time span expressed in minutes. Converts a TimeSpan expressed in minutes or as a standard infinite time span. Converts a time span expressed in seconds. Converts a TimeSpan expressed in seconds or as a standard infinite time span. Provides validation of a TimeSpan object. Declaratively instructs the .NET Framework to perform time validation on a configuration property.

SettingsSerializeAsAttribute

SettingValueElement

SingleTagSectionHandler

SpecialSettingAttribute StringValidator

StringValidatorAttribute

SubclassTypeValidator

SubclassTypeValidatorAttribute

TimeSpanMinutesConverter TimeSpanMinutesOrInfiniteConverter TimeSpanSecondsConverter TimeSpanSecondsOrInfiniteConverter TimeSpanValidator TimeSpanValidatorAttribute

This class cannot be inherited. TypeNameConverter UriSection Converts between type and string values. This class cannot be inherited. Represents the Uri section within a configuration file. Specifies that an application settings group or property contains distinct values for each user of an application. This class cannot be inherited. Represents a grouping of related user settings sections within a configuration file. This class cannot be inherited. Converts a string to its canonical format.

UserScopedSettingAttribute

UserSettingsGroup

WhiteSpaceTrimStringConverter Interfaces

Interface IApplicationSettingsProvider

Description Defines extended capabilities for client-based application settings providers.

IConfigurationSectionHandler Handles the access to certain configuration sections. IConfigurationSystem IPersistComponentSettings Infrastructure. Provides standard configuration methods. Defines standard functionality for controls or libraries that store and retrieve application settings. Provides an interface for defining an alternate application settings provider.

ISettingsProviderService Delegates

Delegate SettingChangingEventHandler

Description Represents the method that will handle the SettingChanging event.

SettingsLoadedEventHandler Represents the method that will handle the SettingsLoaded event. SettingsSavingEventHandler ValidatorCallback Enumerations Represents the method that will handle the SettingsSaving event. Represents a method to be called after the validation of an object.

Enumeration

Description Specifies the locations within the configuration-file hierarchy that can set or override the properties contained within a ConfigurationSection object. Specifies the locations within the configuration-file hierarchy that can set or override the properties contained within a ConfigurationSection object. Specifies the type of a ConfigurationElementCollectionType object. Specifies the options to apply to a property. Determines which properties are written out to a configuration file. Used to specify which configuration file is to be represented by the Configuration object. Specifies the override behavior of a configuration element for configuration elements in child directories. Specifies the level in the configuration hierarchy where a configuration property value originated. Provides values to indicate which services should be made available to application settings. Determines the serialization scheme used to store application settings. Specifies the special setting category of a application

ConfigurationAllowDefinition

ConfigurationAllowExeDefinition

ConfigurationElementCollectionType ConfigurationPropertyOptions ConfigurationSaveMode

ConfigurationUserLevel

OverrideMode

PropertyValueOrigin

SettingsManageability

SettingsSerializeAs SpecialSetting

settings property.

System.Configuration.Assemblies Namespace
.NET Framework 4

The System.Configuration.Assemblies namespace contains classes that are used to configure an assembly.
Structures

Structure

Description

AssemblyHash Obsolete. Represents a hash of an assembly manifest's contents. Enumerations

Enumeration AssemblyHashAlgorithm

Description Specifies all the hash algorithms used for hashing files and for generating the strong name. Defines the different types of assembly version compatibility. This feature is not available in version 1.0 of the .NET Framework.

AssemblyVersionCompatibility

System.Configuration.Install Namespace
.NET Framework 4

The System.Configuration.Install namespace provides classes that allow you to write custom installers for your own components. The Installer class is the base class for all custom installers in the.NET Framework. Through the Installers property, an installer contains a collection of other installers as children. As the installer is executed, it cycles through its children and calls Install, Commit, Rollback, or Uninstall. For an example of an object in the Installers collection, see EventLogInstaller. The Context property contains information about the installation. For example, information about the location of the log file for the installation, the location of the file that saves information required by the Uninstall method, and the command line that was entered when the installation executable was run. For an example of an installation executable, see Installutil.exe (Installer Tool). The Install, Commit, Rollback, and Uninstall methods are not always called on the same instance of Installer. For example, you might use an Installer to install and commit an application, and then release the reference to that Installer. Later, uninstalling the application creates a new reference to an Installer, which means that the Uninstall method is called on a different instance of Installer. For this reason, do not save the state of a computer in an installer. Instead, use an IDictionary that is preserved across calls and passed into the Install, Commit, Rollback, and Uninstall methods.
Classes

Class AssemblyInstaller ComponentInstaller InstallContext Installer InstallerCollection

Description Loads an assembly, and runs all the installers in it. Specifies an installer that copies properties from a component to use at install time. Contains information about the current installation. Provides the foundation for custom installations. Contains a collection of installers to be run during an installation. Provides data for the events: BeforeInstall, AfterInstall, Committing, Committed, BeforeRollback, AfterRollback, BeforeUninstall, AfterUninstall. The exception that is thrown when an error occurs during the commit,

InstallEventArgs

InstallException

rollback, or uninstall phase of an installation. ManagedInstallerClass Infrastructure. Represents a managed install. TransactedInstaller Interfaces Defines an installer that either succeeds completely or fails and leaves the computer in its initial state.

Interface

Description

IManagedInstaller Infrastructure. Provides an interface for a managed installer. Delegates

Delegate

Description

Represents the method that will handle the BeforeInstall, AfterInstall, InstallEventHandler Committing, Committed, BeforeRollback, AfterRollback, BeforeUninstall, or AfterUninstall event of an Installer. Enumerations

Enumeration

Description

UninstallAction Specifies what an installer should do during an uninstallation.

System.Data Namespace
.NET Framework 4

The System.Data namespace provides access to classes that represent the ADO.NET architecture. ADO.NET lets you build components that efficiently manage data from multiple data sources.

In a disconnected scenario such as the Internet, ADO.NET provides the tools to request, update, and reconcile data in multiple tier systems. The ADO.NET architecture is also implemented in client applications, such as Windows Forms, or HTML pages created by ASP.NET. The centerpiece of the ADO.NET architecture is the DataSet class. Each DataSet can contain multiple DataTable objects, with each DataTable containing data from a single data source, such as SQL Server. Each DataTable contains a DataColumnCollection--a collection of DataColumn objects-that determines the schema of each DataTable. The DataType property determines the type of data held by the DataColumn. The ReadOnly and AllowDBNull properties let you further guarantee data integrity. The Expression property lets you construct calculated columns. If a DataTable participates in a parent/child relationship with another DataTable, the relationship is constructed by adding a DataRelation to the DataRelationCollection of a DataSet object. When such a relation is added, a UniqueConstraint and a ForeignKeyConstraint are both created automatically, depending on the parameter settings for the constructor. The UniqueConstraint guarantees that values that are contained in a column are unique. The ForeignKeyConstraint determines what action will happen to the child row or column when a primary key value is changed or deleted. Using the System.Data.SqlClient namespace (the.NET Framework Data Provider for SQL Server), the System.Data.Odbc namespace (the.NET Framework Data Provider for ODBC), the System.Data.OleDb namespace (the.NET Framework Data Provider for OLE DB), or the System.Data.OracleClient namespace (the .NET Framework Data Provider for Oracle), you can access a data source to use together with a DataSet. Each.NET Framework data provider has a corresponding DataAdapter that you use as a bridge between a data source and a DataSet.
Classes

Class Constraint ConstraintCollection ConstraintException

Description Represents a constraint that can be enforced on one or more DataColumn objects. Represents a collection of constraints for a DataTable. Represents the exception that is thrown when attempting an action that violates a constraint.

DataColumn DataColumnChangeEventArgs DataColumnCollection

Represents the schema of a column in a DataTable. Provides data for the ColumnChanging event. Represents a collection of DataColumn objects for a DataTable. Represents the exception that is thrown when errors are generated using ADO.NET components. Represents a parent/child relationship between two DataTable objects. Represents the collection of DataRelation objects for this DataSet. Represents a row of data in a DataTable. Infrastructure. The DataRowBuilder type supports the .NET Framework infrastructure and is not intended to be used directly from your code. Provides data for the RowChanged, RowChanging, OnRowDeleting, and OnRowDeleted events. Represents a collection of rows for a DataTable. Returns a singleton instance of the DataRowComparer<TRow> class. Compares two DataRow objects for equivalence by using value-based comparison. Defines the extension methods to the DataRow class. This is a static class. Represents a customized view of a DataRow. Represents an in-memory cache of data. This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.

DataException

DataRelation

DataRelationCollection DataRow

DataRowBuilder

DataRowChangeEventArgs DataRowCollection DataRowComparer

DataRowComparer<TRow>

DataRowExtensions DataRowView DataSet

DataSetSchemaImporterExtension

DataSysDescriptionAttribute

Obsolete. Marks a property, event, or extender with a description. Visual designers can display this description when referencing the member. Represents one table of in-memory data. Provides data for the Clear method. Represents the collection of tables for the DataSet. Defines the extension methods to the DataTable class. DataTableExtensions is a static class. Provides data for the NewRow method. The DataTableReader obtains the contents of one or more DataTable objects in the form of one or more read-only, forward-only result sets. Represents a databindable, customized view of a DataTable for sorting, filtering, searching, editing, and navigation. Contains a default DataViewSettingCollection for each DataTable in a DataSet. Represents the default settings for ApplyDefaultSort, DataViewManager, RowFilter, RowStateFilter, Sort, and Table for DataViews created from the DataViewManager. Contains a read-only collection of DataViewSetting objects for each DataTable in a DataSet. The exception that is thrown by the DataAdapter during an insert, update, or delete operation if the number of rows affected equals zero. Represents the exception that is thrown when an action is tried on a DataRow that has been deleted. Represents the exception that is thrown when a duplicate database object name is encountered

DataTable DataTableClearEventArgs DataTableCollection DataTableExtensions DataTableNewRowEventArgs

DataTableReader

DataView

DataViewManager

DataViewSetting

DataViewSettingCollection

DBConcurrencyException

DeletedRowInaccessibleException

DuplicateNameException

during an add operation in a DataSet -related object. Represents errors that occur during command compilation; when a command tree could not be produced to represent the command text. Represents errors that occur when the underlying storage provider could not execute the specified command. This exception usually wraps a providerspecific exception. Represents Entity Framework-related errors that occur in the EntityClient namespace. The EntityException is the base class for all Entity Framework exceptions thrown by the EntityClient. Provides a durable reference to an object that is an instance of an entity type. Represents a key name and value pair that is part of an EntityKey. Represents errors that occur when parsing Entity SQL command text. This exception is thrown when syntactic or semantic rules are violated. Represents a collection of DataRow objects returned from a LINQ to DataSet query. This API supports the .NET Framework infrastructure and is not intended to be used directly from your code. Represents a collection of DataRow objects returned from a query. This API supports the .NET Framework infrastructure and is not intended to be used directly from your code. Contains the extension methods for the data row collection classes. This API supports the .NET Framework infrastructure and is not intended to be used directly from your code. Represents the exception that is thrown when the Expression property of a DataColumn cannot be

EntityCommandCompilationException

EntityCommandExecutionException

EntityException

EntityKey

EntityKeyMember

EntitySqlException

EnumerableRowCollection

EnumerableRowCollection<TRow>

EnumerableRowCollectionExtensions

EvaluateException

evaluated. FillErrorEventArgs Provides data for the FillError event of a DbDataAdapter. Represents an action restriction enforced on a set of columns in a primary key/foreign key relationship when a value or row is either deleted or updated. Represents the exception that is thrown when you call the EndEdit method within the RowChanging event. Provides the base functionality for creating collections. The exception that is thrown to indicate that a command tree is invalid. This exception is currently not thrown anywhere in the Entity Framework. Represents the exception that is thrown when incorrectly trying to create or access a relation. Represents the exception that is thrown when you try to add a DataColumn that contains an invalid Expression to a DataColumnCollection. The exception that is thrown when mapping related service requests fail. Occurs when a target and source DataRow have the same primary key value, and the EnforceConstraints property is set to true. The exception that is thrown when metadata related service requests fails. Represents the exception that is thrown when you try to access a row in a table that has no primary key. Represents the exception that is thrown when you try to insert a null value into a column where AllowDBNull is set to false.

ForeignKeyConstraint

InRowChangingEventException

InternalDataCollectionBase

InvalidCommandTreeException

InvalidConstraintException

InvalidExpressionException

MappingException

MergeFailedEventArgs

MetadataException

MissingPrimaryKeyException

NoNullAllowedException

ObjectNotFoundException

The exception that is thrown when an object is not present. This exception is thrown when an ongoing operation is aborted by the user. The exception that is thrown when an optimistic concurrency violation occurs.

OperationAbortedException

OptimisticConcurrencyException

This API supports the .NET Framework infrastructure and is not intended to be used directly from your OrderedEnumerableRowCollection<TRow> code. Represents a collection of ordered DataRow objects returned from a query. PropertyCollection Represents a collection of properties that can be added to DataColumn, DataSet, or DataTable. The exception that is thrown when the underlying data provider is incompatible with the Entity Framework. Represents the exception that is thrown when you try to change the value of a read-only column. Represents the exception that is thrown when you try to perform an operation on a DataRow that is not in a DataTable. Provides data for the state change event of a .NET Framework data provider. Provides additional information for the StatementCompleted event. The exception that is thrown by a strongly typed DataSet when the user accesses a DBNull value. Represents the exception that is thrown when the Expression property of a DataColumn contains a syntax error. Obsolete. Used to create a strongly typed DataSet.

ProviderIncompatibleException

ReadOnlyException

RowNotInTableException

StateChangeEventArgs

StatementCompletedEventArgs

StrongTypingException

SyntaxErrorException

TypedDataSetGenerator

TypedDataSetGeneratorException

The exception that is thrown when a name conflict occurs while generating a strongly typed DataSet. This type is used as a base class for typed-DataTable object generation by Visual Studio and the XSD.exe .NET Framework tool, and is not intended to be used directly from your code. Contains the extension methods for the TypedTableBase<T> class. Represents a restriction on a set of columns in which all values must be unique. The exception that is thrown when modifications to object instances cannot be persisted to the data source. Represents the exception that is thrown when you try to return a version of a DataRow that has been deleted.

TypedTableBase<T>

TypedTableBaseExtensions

UniqueConstraint

UpdateException

VersionNotFoundException

Interfaces

Interface

Description Associates a data source column with a DataSet column, and is implemented by the DataColumnMapping class, which is used in common by .NET Framework data providers.

IColumnMapping

Contains a collection of DataColumnMapping objects, and is IColumnMappingCollection implemented by the DataColumnMappingCollection, which is used in common by .NET Framework data providers. Allows an object to implement a DataAdapter, and represents a set of methods and mapping action-related properties that are used to fill and update a DataSet and update a data source. Represents a parameter to a Command object, and optionally, its mapping to DataSet columns; and is implemented by .NET Framework data providers that access data sources.

IDataAdapter

IDataParameter

Collects all parameters relevant to a Command object and their IDataParameterCollection mappings to DataSet columns, and is implemented by .NET Framework data providers that access data sources. Provides a means of reading one or more forward-only streams of result sets obtained by executing a command at a data source, and is implemented by .NET Framework data providers that access relational databases. Provides access to the column values within each row for a DataReader, and is implemented by .NET Framework data providers that access relational databases. Represents an SQL statement that is executed while connected to a data source, and is implemented by .NET Framework data providers that access relational databases. Represents an open connection to a data source, and is implemented by .NET Framework data providers that access relational databases. Represents a set of command-related properties that are used to fill the DataSet and update a data source, and is implemented by .NET Framework data providers that access relational databases. Used by the Visual Basic .NET Data Designers to represent a parameter to a Command object, and optionally, its mapping to DataSet columns. Represents a transaction to be performed at a data source, and is implemented by .NET Framework data providers that access relational databases. Provides access to the column values within each row of a DbDataRecord for a DbDataReader. Associates a source table with a table in a DataSet, and is implemented by the DataTableMapping class, which is used in common by .NET Framework data providers. Contains a collection of TableMapping objects, and is implemented by the DataTableMappingCollection, which is used in common by .NET Framework data providers.

IDataReader

IDataRecord

IDbCommand

IDbConnection

IDbDataAdapter

IDbDataParameter

IDbTransaction

IExtendedDataRecord

ITableMapping

ITableMappingCollection

Delegates

Delegate DataColumnChangeEventHandler

Description Represents the method that will handle the ColumnChanging event. Represents the method that will handle the RowChanging, RowChanged, RowDeleting, and RowDeleted events of a DataTable. Represents the method that handles the Clear method. Represents the method that handles the NewRow method. Represents the method that will handle the FillError event. Represents the method that will handle the MergeFailed event. Represents the method that will handle the StateChange event. The delegate type for the event handlers of the StatementCompleted event.

DataRowChangeEventHandler

DataTableClearEventHandler DataTableNewRowEventHandler FillErrorEventHandler MergeFailedEventHandler

StateChangeEventHandler

StatementCompletedEventHandler Enumerations

Enumeration

Description Determines the action that occurs when the AcceptChanges or RejectChanges method is invoked on a DataTable with a ForeignKeyConstraint. Provides a description of the results of the query and its effect on the database. Specifies how a command string is interpreted. Specifies how conflicting changes to the data source will be detected

AcceptRejectRule

CommandBehavior CommandType ConflictOption

and resolved. ConnectionState DataRowAction DataRowState DataRowVersion DataSetDateTime DataViewRowState DbType EntityState IsolationLevel KeyRestrictionBehavior Describes the current state of the connection to a data source. Describes an action performed on a DataRow. Gets the state of a DataRow object. Describes the version of a DataRow. Describes the serialization format for DateTime columns in a DataSet. Describes the version of data in a DataRow. Specifies the data type of a field, a property, or a Parameter object of a .NET Framework data provider. The state of an entity object. Specifies the transaction locking behavior for the connection. Identifies a list of connection string parameters identified by the KeyRestrictions property that are either allowed or not allowed. Controls how the values from the data source will be applied to existing rows when using the Load or Load method. Specifies how a DataColumn is mapped. Determines the action that occurs when a mapping is missing from a source table or a source column. Specifies the action to take when adding data to the DataSet and the required DataTable or DataColumn is missing. Specifies the type of a parameter within a query relative to the DataSet. Obsolete. Specifies the attributes of a property. Indicates the action that occurs when a ForeignKeyConstraint is enforced.

LoadOption MappingType MissingMappingAction

MissingSchemaAction

ParameterDirection PropertyAttributes Rule

SchemaSerializationMode Indicates the schema serialization mode for a typed DataSet.

SchemaType SerializationFormat SqlDbType

Specifies how to handle existing schema mappings when performing a FillSchema operation. Determines the serialization format for a DataSet. Specifies SQL Server-specific data type of a field, property, for use in a SqlParameter. Specifies the type of SQL query to be used by the OleDbRowUpdatedEventArgs, OleDbRowUpdatingEventArgs, SqlRowUpdatedEventArgs, or SqlRowUpdatingEventArgs class. Specifies how query command results are applied to the row being updated. Specifies the action to take with regard to the current and remaining rows during an Update. Specifies how to read XML data and a relational schema into a DataSet. Specifies how to write XML data and a relational schema from a DataSet.

StatementType

UpdateRowSource

UpdateStatus

XmlReadMode

XmlWriteMode

System.Data.Common Namespace
.NET Framework 4

The System.Data.Common namespace contains classes shared by the .NET Framework data providers. A .NET Framework data provider describes a collection of classes used to access a data source, such as a database, in the managed space. Supported providers include the .NET Framework Data Provider for ODBC, the .NET Framework Data Provider for OLEDB, the .NET Framework Data Provider for Oracle, and the .NET Framework Data Provider for SQL Server. The classes in System.Data.Common are intended to give developers a way to write ADO.NET code that will work against all .NET Framework data providers. For conceptual information about how to use this namespace when programming with the.NET Framework, see Writing Provider Independent Code with ADO.NET.

Classes

Class

Description Represents a set of SQL commands and a database connection that are used to fill the DataSet and update the data source. Contains a generic column mapping for an object that inherits from DataAdapter. This class cannot be inherited. Contains a collection of DataColumnMapping objects. Provides access to information about the structural type and column information for a DbDataRecord. Contains a description of a mapped relationship between a source table and a DataTable. This class is used by a DataAdapter when populating a DataSet. A collection of DataTableMapping objects. This class cannot be inherited. Represents an SQL statement or stored procedure to execute against a data source. Provides a base class for database-specific classes that represent commands. Automatically generates single-table commands used to reconcile changes made to a DataSet with the associated database. This is an abstract class that can only be inherited. Defines a cacheable command plan. Represents a connection to a database. Provides a base class for strongly typed connection string builders.

DataAdapter

DataColumnMapping

DataColumnMappingCollection DataRecordInfo

DataTableMapping

DataTableMappingCollection

DbCommand

DbCommandBuilder

DbCommandDefinition DbConnection DbConnectionStringBuilder

DbDataAdapter

Aids implementation of the IDbDataAdapter interface. Inheritors of DbDataAdapter implement a set of functions to provide strong typing, but inherit most of the functionality needed to fully implement a DataAdapter. Enables a .NET Framework data provider to help ensure that a user has a security level adequate for accessing data. Associates a security action with a custom security attribute. Reads a forward-only stream of rows from a data source. Implements IDataRecord and ICustomTypeDescriptor, and provides data binding support for DbEnumerator. Provides a mechanism for enumerating all available instances of database servers within the local network. Exposes the GetEnumerator method, which supports a simple iteration over a collection by a .NET Framework data provider. The base class for all exceptions thrown on behalf of the data source. Provides a list of constants for the well-known MetaDataCollections: DataSourceInformation, DataTypes, MetaDataCollections, ReservedWords, and Restrictions. Provides static values that are used for the column names in the MetaDataCollection objects contained in the DataTable. The DataTable is created by the GetSchema method. Represents a parameter to a DbCommand and optionally, its mapping to a DataSet column. For more information on parameters, see Configuring

DBDataPermission

DBDataPermissionAttribute

DbDataReader

DbDataRecord

DbDataSourceEnumerator

DbEnumerator

DbException

DbMetaDataCollectionNames

DbMetaDataColumnNames

DbParameter

Parameters and Parameter Data Types (ADO.NET). DbParameterCollection The base class for a collection of parameters relevant to a DbCommand. Infrastructure. This class can be used by any provider to support a provider-specific configuration section. Represents a set of static methods for creating one or more instances of DbProviderFactory classes.

DbProviderConfigurationHandler

DbProviderFactories

Infrastructure. This type supports the .NET Framework DbProviderFactoriesConfigurationHandler infrastructure and is not intended to be used directly from your code. DbProviderFactory DbProviderManifest Represents a set of methods for creating instances of a provider's implementation of the data source classes. Represents the metadata interface for all CLR types. Represents a set of methods for creating correct command definition objects and accessing provider manifest information.

DbProviderServices

Identifies which provider-specific property in the DbProviderSpecificTypePropertyAttribute strongly typed parameter classes is to be used when setting a provider-specific type. DbTransaction The base class for a transaction. Represents a base class that implements the DbProviderManifest based on an XML definition. You can use the DbXmlEnabledProviderManifest class to obtain provider-specific information at runtime. Provides access to entity metadata. Provides data for the RowUpdated event of a .NET Framework data provider. Provides the data for the RowUpdating event of a .NET Framework data provider.

DbXmlEnabledProviderManifest

EntityRecordInfo RowUpdatedEventArgs

RowUpdatingEventArgs

SchemaTableColumn

Describes the column metadata of the schema for a database table. Describes optional column metadata of the schema for a database table.

SchemaTableOptionalColumn Structures

Structure

Description

FieldMetadata Provides access to field metadata for a DataRecordInfo object. Enumerations

Enumeration CatalogLocation

Description Indicates the position of the catalog name in a qualified table name in a text command. Specifies the relationship between the columns in a GROUP BY clause and the non-aggregated columns in the select-list of a SELECT statement. Specifies how identifiers are treated by the data source when searching the system catalog. Specifies what types of Transact-SQL join statements are supported by the data source.

GroupByBehavior

IdentifierCase

SupportedJoinOperators

System.Data.Odbc Namespace
.NET Framework 4

The System.Data.Odbc namespace is the .NET Framework Data Provider for ODBC.

The .NET Framework Data Provider for ODBC describes a collection of classes used to access an ODBC data source in the managed space. Using the OdbcDataAdapter class, you can fill a memory-resident DataSet that you can use to query and update the data source. For more information about how to use this namespace, see the OdbcDataReader, OdbcCommand, and OdbcConnection classes.
Classes

Class OdbcCommand

Description Represents an SQL statement or stored procedure to execute against a data source. This class cannot be inherited. Automatically generates single-table commands that are used to reconcile changes made to a DataSet with the associated data source. This class cannot be inherited. Represents an open connection to a data source. Provides a simple way to create and manage the contents of connection strings used by the OdbcConnection class. Represents a set of data commands and a connection to a data source that are used to fill the DataSet and update the data source. This class cannot be inherited. Provides a way of reading a forward-only stream of data rows from a data source. This class cannot be inherited. Collects information relevant to a warning or error returned by the data source. Collects all errors generated by the OdbcDataAdapter. This class cannot be inherited. The exception that is generated when a warning or error is returned by an ODBC data source. This class cannot be inherited. Represents a set of methods for creating instances of the ODBC provider's implementation of the data source classes.

OdbcCommandBuilder

OdbcConnection OdbcConnectionStringBuilder

OdbcDataAdapter

OdbcDataReader

OdbcError

OdbcErrorCollection

OdbcException

OdbcFactory

OdbcInfoMessageEventArgs OdbcMetaDataCollectionNames

Provides data for the InfoMessage event. Provides a list of constants for use with the GetSchema method to retrieve metadata collections. Provides static values that are used for the column names in the OdbcMetaDataCollectionNames objects contained in the DataTable. The DataTable is created by the GetSchema method. Represents a parameter to an OdbcCommand and optionally, its mapping to a DataColumn. This class cannot be inherited. Represents a collection of parameters relevant to an OdbcCommand and their respective mappings to columns in a DataSet. This class cannot be inherited. Enables the .NET Framework Data Provider for ODBC to help make sure that a user has a security level sufficient to access an ODBC data source. This class cannot be inherited. Associates a security action with a custom security attribute. Provides data for the RowUpdated event. Provides data for the RowUpdating event. Represents an SQL transaction to be made at a data source. This class cannot be inherited.

OdbcMetaDataColumnNames

OdbcParameter

OdbcParameterCollection

OdbcPermission

OdbcPermissionAttribute OdbcRowUpdatedEventArgs OdbcRowUpdatingEventArgs OdbcTransaction Delegates

Delegate OdbcInfoMessageEventHandler

Description Represents the method that will handle the InfoMessage event of an OdbcConnection. Represents the method that will handle the RowUpdated event of an OdbcDataAdapter. Represents the method that will handle the RowUpdating event of an OdbcDataAdapter.

OdbcRowUpdatedEventHandler

OdbcRowUpdatingEventHandler Enumerations

Enumeration OdbcType

Description Specifies the data type of a field, property, for use in an OdbcParameter.

System.Data.SqlClient Namespace
.NET Framework 4

The System.Data.SqlClient namespace is the.NET Framework Data Provider for SQL Server. The.NET Framework Data Provider for SQL Server describes a collection of classes used to access a SQL Server database in the managed space. Using the SqlDataAdapter, you can fill a memory-resident DataSet that you can use to query and update the database.
Note

For conceptual information about using this namespace when programming with the .NET Framework, see SQL Server and ADO.NET. Caution ADO.NET 2.0 does not support Asynchronous commands over shared memory for SQL Server 2000 or lower. However, you can force TCP instead of shared memory. You can do that by prefixing tcp: to the server name in the connection string or you can use localhost.
Classes

Class SqlBulkCopy

Description Lets you efficiently bulk load a SQL Server table with data from another source. Defines the mapping between a column in a SqlBulkCopy instance's data source and a column in the instance's destination table. Collection of SqlBulkCopyColumnMapping objects that inherits from CollectionBase.

SqlBulkCopyColumnMapping

SqlBulkCopyColumnMappingCollection

SqlClientFactory

Represents a set of methods for creating instances of the System.Data.SqlClient provider's implementation of the data source classes. Provides a list of constants for use with the GetSchema method to retrieve metadata collections. Enables the .NET Framework Data Provider for SQL Server to help make sure that a user has a security level sufficient to access a data source. Associates a security action with a custom security attribute. Represents a Transact-SQL statement or stored procedure to execute against a SQL Server database. This class cannot be inherited. Automatically generates single-table commands that are used to reconcile changes made to a DataSet with the associated SQL Server database. This class cannot be inherited. Represents an open connection to a SQL Server database. This class cannot be inherited. Provides a simple way to create and manage the contents of connection strings used by the SqlConnection class. Represents a set of data commands and a database connection that are used to fill the DataSet and update a SQL Server database. This class cannot be inherited. Provides a way of reading a forward-only stream of rows from a SQL Server database. This class cannot be inherited. Infrastructure. Included to support debugging applications. Not intended for direct use. The SqlDependency object represents a query notification dependency between an application and an instance of SQL Server 2005. An application can create a

SqlClientMetaDataCollectionNames

SqlClientPermission

SqlClientPermissionAttribute

SqlCommand

SqlCommandBuilder

SqlConnection

SqlConnectionStringBuilder

SqlDataAdapter

SqlDataReader

SQLDebugging

SqlDependency

SqlDependency object and register to receive notifications via the OnChangeEventHandler event handler. SqlError Collects information relevant to a warning or error returned by SQL Server. Collects all errors generated by the .NET Framework Data Provider for SQL Server. This class cannot be inherited. The exception that is thrown when SQL Server returns a warning or error. This class cannot be inherited. Provides data for the InfoMessage event. Represents the set of arguments passed to the notification event handler. Represents a parameter to a SqlCommand and optionally its mapping to DataSet columns. This class cannot be inherited. For more information on parameters, see Configuring Parameters and Parameter Data Types (ADO.NET). Represents a collection of parameters associated with a SqlCommand and their respective mappings to columns in a DataSet. This class cannot be inherited. Represents the set of arguments passed to the SqlRowsCopiedEventHandler. Provides data for the RowUpdated event. Provides data for the RowUpdating event. Represents a Transact-SQL transaction to be made in a SQL Server database. This class cannot be inherited.

SqlErrorCollection

SqlException SqlInfoMessageEventArgs SqlNotificationEventArgs

SqlParameter

SqlParameterCollection

SqlRowsCopiedEventArgs SqlRowUpdatedEventArgs SqlRowUpdatingEventArgs SqlTransaction Delegates

Delegate

Description

OnChangeEventHandler

Handles the OnChange event that is fired when a notification is received for any of the commands associated with a SqlDependency object. Represents the method that will handle the InfoMessage event of a SqlConnection. Represents the method that handles the SqlRowsCopied event of a SqlBulkCopy. Represents the method that will handle the RowUpdated event of a SqlDataAdapter. Represents the method that will handle the RowUpdating event of a SqlDataAdapter.

SqlInfoMessageEventHandler

SqlRowsCopiedEventHandler

SqlRowUpdatedEventHandler

SqlRowUpdatingEventHandler Enumerations

Enumeration ApplicationIntent SortOrder SqlBulkCopyOptions

Description Specifies a value for ApplicationIntent. Possible values are ReadWrite and ReadOnly. Specifies how rows of data are sorted. Bitwise flag that specifies one or more options to use with an instance of SqlBulkCopy. This enumeration provides additional information about the different notifications that can be received by the dependency event handler. Indicates the source of the notification received by the dependency event handler. Describes the different notification types that can be received by an OnChangeEventHandler event handler through the SqlNotificationEventArgs parameter.

SqlNotificationInfo

SqlNotificationSource

SqlNotificationType

System.Data.SqlServerCe Namespace
Visual Studio 2010 The System.Data.SqlServerCe namespace is the managed data provider for SQL Server Compact 4.0. This namespace is a collection of classes that provide access to SQL Server Compact 4.0 databases. By using System.Data.SqlServerCe, you can create and manage SQL Server Compact 4.0 databases from a computer. The following features are available for creating SQL Server Compact 4.0 desktop and Web applications.

Support for the TransactionScope class. SQL Server Compact 4.0 provider for the ADO.NET Entity Framework (System.Data.SqlServerCe.Entity.dll). Support for Visual C# and Visual Basic application development in Visual Studio 2010 SP1. Support for working in Medium (Partial) Trust environment. The flag SQLServerCompactEditionUnderWebHosting was required to be set, to use SQL Server Compact in ASP.NET Web applications. The flag is removed and SQL Server Compact 4.0 can be used easily as an embedded database in Web applications.

Classes Class Description An enumerator that can be used to iterate through a collection of records in a ResultSet object. The ResultSetEnumerator is not designed to be used directly from within your code. You will get more functionality by working directly with the SqlCeResultSet object. Implements data binding interfaces and provides a bridge between user interface controls and the SqlCeResultSet. Infrastructure. Provides methods that can be used to track changes to tables in a SQL Server Compact database. Represents an SQL statement to execute against a data source. Provides a means of automatically generating single-table commands used to reconcile changes made to a DataSet with the associated database.

ResultSetEnumerator

ResultSetView RowView SqlCeChangeTracking SqlCeCommand SqlCeCommandBuilder

This class cannot be inherited. Represents an open connection to a SQL Server SqlCeConnection Compact data source. Provides a simple way to create and manage the SqlCeConnectionStringBuilder contents of connection strings used by the SqlCeConnection class. Represents a set of data commands and a database SqlCeDataAdapter connection that are used to fill the DataSet and update the data source. Provides a way of reading a forward-only stream SqlCeDataReader of data rows from a data source. This class cannot be inherited. Represents the properties, methods, and other SqlCeEngine objects of the SQL Server Compact Engine object. This class cannot be inherited. Collects information relevant to a warning or SqlCeError error returned by the data source. This class cannot be inherited. Collects all errors generated by the .NET SqlCeErrorCollection Compact Framework Data Provider for SQL Server Compact. This class cannot be inherited. The exception thrown when the underlying provider returns a warning or error from a SQL SqlCeException Server Compact data source. This class cannot be inherited. Encapsulates event arguments for the SqlCeFlushFailureEventArgs FlushFailure event. Provides data for the InfoMessage event. This SqlCeInfoMessageEventArgs class cannot be inherited. The exception thrown when the underlying provider returns an error from a Microsoft SQL SqlCeInvalidDatabaseFormatException Server Compact data source when SQL Server Compact attempts to open a database file of an older or newer version. This exception is thrown if the lock timeout has SqlCeLockTimeoutException been reached. Represents a parameter to a SqlCeCommand and, SqlCeParameter optionally, its mapping to a DataSet column. This class cannot be inherited. Collects all parameters relevant to a SqlCeParameterCollection SqlCeCommand as well as their respective mappings to DataSet columns. SqlCeProviderFactory Represents a set of methods for creating instances

of a provider's implementation of the data source classes. Initializes a new instance of the SqlCeRemoteDataAccess object. For more SqlCeRemoteDataAccess information about Remote Data Access, see Using Remote Data Access (RDA). Initializes a new instance of the SqlCeReplication object. For more information about SQL Server replication, see the SQL Server Books Online. SqlCeReplication For more information about merge replication with SQL Server Compact, see the SQL Server Compact Books Online. SqlCeResultSet An updateable, scrollable, and bindable cursor. SqlCeRowUpdatedEventArgs Provides data for the RowUpdated event. SqlCeRowUpdatingEventArgs Provides data for the RowUpdating event. Represents an SQL transaction to be made at a SqlCeTransaction data source. This class cannot be inherited. The exception thrown when the underlying provider returns an error from a Microsoft SQL SqlCeTransactionInProgressException Server Compact data source when an operation is attempted while a transaction is in progress. SqlCeType Infrastructure. Represents a row of updatable values from the SqlCeUpdatableRecord data source. A SqlCeResultSet object contains one or more UpdatableRecords. Infrastructure. Specifies and retrieves metadata information from parameters and columns SqlMetaData retrieved from a database. This class cannot be inherited. Delegates Description A user-defined delegate to the event that fires at the OnStartTableDownload start of downloading table changes from the server. A user-defined delegate to the event that fires at the OnStartTableUpload start of uploading table changes to the server. A user-defined delegate that consumes the ongoing OnSynchronization synchronization events reported during the reconciler work. The delegate that must be implemented to listen for SqlCeFlushFailureEventHandler FlushFailure events. Represents the method that will handle the SqlCeInfoMessageEventHandler InfoMessage event of a SqlCeConnection. Delegate

Represents the method that will handle the RowUpdated event of a SqlCeDataAdapter. Represents the method that handles the RowUpdating SqlCeRowUpdatingEventHandler event of a SqlCeDataAdapter. Enumerations SqlCeRowUpdatedEventHandler Description Determines whether the subscription will be added to an existing AddOption database or whether a new database will be created when the subscription is added. When passed to the Commit function, the CommitMode specifies CommitMode when the commit occurs. Specifies the options to use when using the DbInsertOptions [System.Data.SqlServerCe.SqlCeResultSet.Insert] method. Specifies the options used by the SetRange method when DbRangeOptions specifying the index range over which to seek. DbSeekOptions Options that specify how the Seek method will seek on an index. Specifies whether to leave or delete the database when dropping a DropOption subscription using the DropSubscription method. Specifies whether data is merged up to the Publisher only, or ExchangeType merge in both directions between the Publisher and the Subscriber. Specifies the network protocol to use when setting the NetworkType DistributorNetwork or PublisherNetwork properties of the SqlCeReplication object. Specifies the criteria to use to purge metadata when using the PurgeTombstoneTableData method or the PurgeType PurgeTransactionSequenceData method of the SqlCeChangeTracking class. Specifies whether or not the rows associated with the Push should RdaBatchOption be batched together in a single transaction. Specifies whether or not the table being pulled to the device is RdaTrackOption tracked. When passed to the Repair method, RepairOption specifies the RepairOption type of database repair to perform. ResultSetOptions Sets options for the ResultSetEnumerator. ResultSetSensitivity Sets the sensitivity of the ResultSetEnumerator. Specifies the mode of security to use when connecting to the SecurityType Publisher or Distributor during Replication. Controls how snapshot files are transferred from the Distributor to SnapshotTransferType the computer running IIS. TrackingKeyType Specifies the type of key used to identify tracking data. TrackingOptions Specifies which operations on a table are tracked. Enumeration

ValidateType VerifyOption

Specifies the type of data validation to perform. These options determine the level of database verification to use.

System.Data.SqlTypes Namespace
.NET Framework 4

The System.Data.SqlTypes namespace provides classes for native data types in SQL Server. These classes provide a safer, faster alternative to the data types provided by the .NET Framework common language runtime (CLR). Using the classes in this namespace helps prevent type conversion errors caused by loss of precision. Because other data types are converted to and from SqlTypes behind the scenes, explicitly creating and using objects within this namespace also yields faster code. Each data type in SqlTypes has its equivalent data type in SQL Server, with the same underlying data representation. Many of them also have equivalent data types in the CLR. However, SqlDateTime, SqlDecimal, and SqlString have different underlying data structures with their corresponding .NET Framework data types. The following table maps the members of the SqlTypes namespace to Microsoft SQL Server data types and to the members of the SqlDbType enumeration. .NET Framework SqlTypes SqlBinary SqlBoolean SqlByte SqlDateTime SqlDecimal SqlDouble SqlFileStream SqlGuid SqlInt16 SqlInt32 SqlInt64 SqlMoney SqlSingle SqlString Native SQL Server binary, image, timestamp, varbinary bit tinyint datetime, smalldatetime numeric, decimal float varbinary uniqueidentifier smallint int bigint money, smallmoney real char, nchar, text, ntext, .NET Framework SqlDbType Binary, Image, TimeStamp, VarBinary Bit TinyInt DateTime, SmallDateTime Decimal Float VarBinary UniqueIdentifier SmallInt Int BigInt Money, SmallMoney Real Char, NChar, Text, Ntext,

SqlXml
Classes

nvarchar, varchar xml

NVarChar, VarChar Xml

Class

Description The SqlAlreadyFilledException class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. Represents a mutable reference type that wraps either a Buffer or a Stream. SqlChars is a mutable reference type that wraps a Char array or a SqlString instance. Exposes SQL Server data that is stored with the FILESTREAM column attribute as a sequence of bytes. The SqlNotFilledException class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. The exception that is thrown when the Value property of a System.Data.SqlTypes structure is set to null. The exception that is thrown when you set a value into a System.Data.SqlTypes structure would truncate that value. The base exception class for the System.Data.SqlTypes. The SqlTypesSchemaImporterExtensionHelper class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality.

SqlAlreadyFilledException

SqlBytes

SqlChars

SqlFileStream

SqlNotFilledException

SqlNullValueException

SqlTruncateException

SqlTypeException

SqlTypesSchemaImporterExtensionHelper

SqlXml

Represents XML data stored in or retrieved from a server. The TypeBigIntSchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. The TypeBinarySchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. The TypeBitSchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. The TypeCharSchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. The TypeDateTimeSchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. The TypeDecimalSchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. The TypeFloatSchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. The TypeIntSchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality.

TypeBigIntSchemaImporterExtension

TypeBinarySchemaImporterExtension

TypeBitSchemaImporterExtension

TypeCharSchemaImporterExtension

TypeDateTimeSchemaImporterExtension

TypeDecimalSchemaImporterExtension

TypeFloatSchemaImporterExtension

TypeIntSchemaImporterExtension

TypeMoneySchemaImporterExtension

The TypeMoneySchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. The TypeNCharSchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. The TypeNTextSchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. The TypeNumericSchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. The TypeNVarCharSchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. The TypeRealSchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality.

TypeNCharSchemaImporterExtension

TypeNTextSchemaImporterExtension

TypeNumericSchemaImporterExtension

TypeNVarCharSchemaImporterExtension

TypeRealSchemaImporterExtension

The TypeSmallDateTimeSchemaImporterExtension TypeSmallDateTimeSchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. The TypeSmallIntSchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. The TypeSmallMoneySchemaImporterExtension class is not intended for use as a stand-alone

TypeSmallIntSchemaImporterExtension

TypeSmallMoneySchemaImporterExtension

component, but as a class from which other classes derive standard functionality. The TypeTextSchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. The TypeTinyIntSchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality.

TypeTextSchemaImporterExtension

TypeTinyIntSchemaImporterExtension

The TypeUniqueIdentifierSchemaImporterExtension TypeUniqueIdentifierSchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. The TypeVarBinarySchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. The TypeVarCharSchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality. The TypeVarImageSchemaImporterExtension class is not intended for use as a stand-alone component, but as a class from which other classes derive standard functionality.

TypeVarBinarySchemaImporterExtension

TypeVarCharSchemaImporterExtension

TypeVarImageSchemaImporterExtension

Structures

Structure SqlBinary

Description Represents a variable-length stream of binary data to be stored in or retrieved from a database.

SqlBoolean

Represents an integer value that is either 1 or 0 to be stored in or retrieved from a database. Represents an 8-bit unsigned integer, in the range of 0 through 255, to be stored in or retrieved from a database.

SqlByte

Represents the date and time data ranging in value from January 1, 1753 to December 31, 9999 to an accuracy of 3.33 milliseconds to be stored in or retrieved from a database. The SqlDateTime structure has a different underlying data structure from its corresponding .NET Framework type, DateTime, which can SqlDateTime represent any time between 12:00:00 AM 1/1/0001 and 11:59:59 PM 12/31/9999, to the accuracy of 100 nanoseconds. SqlDateTime actually stores the relative difference to 00:00:00 AM 1/1/1900. Therefore, a conversion from "00:00:00 AM 1/1/1900" to an integer will return 0. SqlDecimal Represents a numeric value between - 10^38 +1 and 10^38 - 1, with fixed precision and scale. Represents a floating-point number within the range of -1.79E +308 through 1.79E +308 to be stored in or retrieved from a database. Represents a GUID to be stored in or retrieved from a database. Represents a 16-bit signed integer to be stored in or retrieved from a database. Represents a 32-bit signed integer to be stored in or retrieved from a database. Represents a 64-bit signed integer to be stored in or retrieved from a database. Represents a currency value ranging from -2 63 (or -922,337,203,685,477.5808) to 2 63 -1 (or +922,337,203,685,477.5807) with an accuracy to a ten-thousandth of currency unit to be stored in or retrieved from a database. Represents a floating point number within the range of -3.40E +38 through 3.40E +38 to be stored in or retrieved from a database. Represents a variable-length stream of characters to be stored in or retrieved from the database. SqlString has a different underlying data structure from its corresponding .NET Framework String data type.

SqlDouble SqlGuid SqlInt16 SqlInt32 SqlInt64

SqlMoney

SqlSingle

SqlString

Interfaces

Interface

Description

INullable All the System.Data.SqlTypes objects and structures implement the INullable interface. Enumerations

Enumeration

Description

SqlCompareOptions Specifies the compare option values for a SqlString structure. The StorageState enumeration is not intended for use as a stand-alone component, but as an enumeration from which other classes derive standard functionality.

StorageState

System.Diagnostics Namespace
.NET Framework 4 The System.Diagnostics namespace provides classes that allow you to interact with system processes, event logs, and performance counters.

The EventLog component provides functionality to write to event logs, read event log entries, and create and delete event logs and event sources on the network. The EntryWrittenEventHandler provides a way to interact with event logs asynchronously. Supporting classes provide access to more detailed control, including: permission restrictions, the ability to specify event log types (which controls the type of default data that is written with an event log entry), and iterate through collections of event log entries. For more information about these tasks, see the EventLogPermission, EventLogEntryType, and EventLogEntryCollection classes. The Process class provides functionality to monitor system processes across the network, and to start and stop local system processes. In addition to retrieving lists of running processes (by specifying either the computer, the process name, or the process id) or viewing information about the process that currently has access to the processor, you can get detailed knowledge of process threads and modules both through the Process class itself, and by interacting with the ProcessThread and ProcessModule classes. The ProcessStartInfo class enables you to specify a variety of elements with which to start a new process, such as input, output, and error streams, working directories, and command line verbs and arguments. These give

you fine control over the behavior of your processes. Other related classes let you specify window styles, process and thread priorities, and interact with collections of threads and modules. The PerformanceCounter class enables you to monitor system performance, while the PerformanceCounterCategory class provides a way to create new custom counters and categories. You can write to local custom counters and read from both local and remote counters (system as well as custom). You can sample counters using the PerformanceCounter class, and calculate results from successive performance counter samples using the CounterSample class. The CounterCreationData class enables you to create multiple counters in a category and specify their types. Other classes associated with the performance counter component provide access to collections of counters, counter permission, and counter types.

The System.Diagnostics namespace also provides classes that allow you to debug your application and to trace the execution of your code. For more information, see the Trace and Debug classes. Classes Class BooleanSwitch Description Provides a simple on/off switch that controls debugging and tracing output. Indicates to compilers that a method call or attribute should be ignored unless a specified conditional compilation symbol is defined. Directs tracing or debugging output to either the standard output or the standard error stream. Correlates traces that are part of a logical transaction. Defines the counter type, name, and Help string for a custom counter. Provides a strongly typed collection of CounterCreationData objects. Provides a set of utility functions for interpreting performance counter data. Provides data for the OutputDataReceived and ErrorDataReceived events. Provides a set of methods and properties that help debug your code. This class cannot be inherited.

ConditionalAttribute

ConsoleTraceListener CorrelationManager CounterCreationData CounterCreationDataCollection CounterSampleCalculator DataReceivedEventArgs

Debug

DebuggableAttribute Debugger DebuggerBrowsableAttribute

DebuggerDisplayAttribute DebuggerHiddenAttribute DebuggerNonUserCodeAttribute DebuggerStepperBoundaryAttribute DebuggerStepThroughAttribute DebuggerTypeProxyAttribute DebuggerVisualizerAttribute DefaultTraceListener DelimitedListTraceListener DiagnosticsConfigurationHandler EntryWrittenEventArgs EventInstance EventLog EventLogEntry EventLogEntryCollection EventLogInstaller

Modifies code generation for runtime just-in-time (JIT) debugging. This class cannot be inherited. Enables communication with a debugger. This class cannot be inherited. Determines if and how a member is displayed in the debugger variable windows. This class cannot be inherited. Determines how a class or field is displayed in the debugger variable windows. Specifies the DebuggerHiddenAttribute. This class cannot be inherited. Identifies a type or member that is not part of the user code for an application. Indicates the code following the attribute is to be executed in run, not step, mode. Instructs the debugger to step through the code instead of stepping into the code. This class cannot be inherited. Specifies the display proxy for a type. Specifies that the type has a visualizer. This class cannot be inherited. Provides the default output methods and behavior for tracing. Directs tracing or debugging output to a text writer, such as a stream writer, or to a stream, such as a file stream. Infrastructure. Obsolete. Handles the diagnostics section of configuration files. Provides data for the EntryWritten event. Represents language-neutral information for an event log entry. Provides interaction with Windows event logs. Encapsulates a single record in the event log. This class cannot be inherited. Defines size and enumerators for a collection of EventLogEntry instances. Allows you to install and configure an event log that your application reads from or writes to when running.

EventLogPermission EventLogPermissionAttribute EventLogPermissionEntry EventLogPermissionEntryCollection EventLogTraceListener

EventSchemaTraceListener

EventSourceCreationData EventTypeFilter FileVersionInfo InstanceData InstanceDataCollection InstanceDataCollectionCollection MonitoringDescriptionAttribute PerformanceCounter PerformanceCounterCategory PerformanceCounterInstaller

PerformanceCounterManager

PerformanceCounterPermission

Controls code access permissions for event logging. Allows declaritive permission checks for event logging. Defines the smallest unit of a code access security permission that is set for an EventLog. Contains a strongly typed collection of EventLogPermissionEntry objects. Provides a simple listener that directs tracing or debugging output to an EventLog. Directs tracing or debugging output of end-to-end events to an XML-encoded, schema-compliant log file. Represents the configuration settings used to create an event log source on the local computer or a remote computer. Indicates whether a listener should trace based on the event type. Provides version information for a physical file on disk. Holds instance data associated with a performance counter sample. Provides a strongly typed collection of InstanceData objects. Provides a strongly typed collection of InstanceDataCollection objects. Specifies a description for a property or event. Represents a Windows NT performance counter component. Represents a performance object, which defines a category of performance counters. Specifies an installer for the PerformanceCounter component. Infrastructure. Obsolete. Prepares performance data for the performance.dll the system loads when working with performance counters. Allows control of code access permissions for PerformanceCounter.

Allows declaritive performance counter permission checks. Defines the smallest unit of a code access PerformanceCounterPermissionEntry security permission that is set for a PerformanceCounter. Contains a strongly typed collection of PerformanceCounterPermissionEntryCollection PerformanceCounterPermissionEntry objects. Provides debug tracing support that is specifically targeted for Windows PresentationTraceSources Presentation Foundation (WPF) applications. Provides access to local and remote Process processes and enables you to start and stop local system processes. Represents a.dll or .exe file that is loaded ProcessModule into a particular process. Provides a strongly typed collection of ProcessModuleCollection ProcessModule objects. Specifies a set of values that are used ProcessStartInfo when you start a process. Represents an operating system process ProcessThread thread. Provides a strongly typed collection of ProcessThreadCollection ProcessThread objects. Indicates whether a listener should trace a SourceFilter message based on the source of a trace. Provides a multilevel switch to control SourceSwitch tracing and debug output without recompiling your code. Provides information about a StackFrame, which represents a function StackFrame call on the call stack for the current thread. Represents a stack trace, which is an StackTrace ordered collection of one or more stack frames. Provides a set of methods and properties Stopwatch that you can use to accurately measure elapsed time. Provides an abstract base class to create Switch new debugging and tracing switches. SwitchAttribute Identifies a switch used in an assembly, PerformanceCounterPermissionAttribute

SwitchLevelAttribute TextWriterTraceListener

Trace TraceEventCache TraceFilter TraceListener TraceListenerCollection

TraceSource

TraceSwitch UnescapedXmlDiagnosticData XmlWriterTraceListener Structures

class, or member. Identifies the level type for a switch. Directs tracing or debugging output to a TextWriter or to a Stream, such as FileStream. Provides a set of methods and properties that help you trace the execution of your code. This class cannot be inherited. Provides trace event data specific to a thread and a process. Provides the base class for trace filter implementations. Provides the abstract base class for the listeners who monitor trace and debug output. Provides a thread-safe list of TraceListener objects. Provides a set of methods and properties that enable applications to trace the execution of code and associate trace messages with their source. Provides a multilevel switch to control tracing and debug output without recompiling your code. Provides unescaped XML data for the logging of user-provided trace data. Directs tracing or debugging output as XML-encoded data to a TextWriter or to a Stream, such as a FileStream.

Structure Description CounterSample Defines a structure that holds the raw data for a performance counter. Interfaces Description Infrastructure. Prepares performance data for the performance DLL the ICollectData system loads when working with performance counters. Delegates Delegate Description DataReceivedEventHandler Represents the method that will handle the Interface

OutputDataReceived event or ErrorDataReceived event of a Process. Represents the method that will handle the EntryWritten EntryWrittenEventHandler event of an EventLog. Enumerations Description Specifies the debugging mode for the just-in-time DebuggableAttribute.DebuggingModes (JIT) compiler. DebuggerBrowsableState Provides display instructions for the debugger. EventLogEntryType Specifies the event type of an event log entry. Defines access levels used by EventLog EventLogPermissionAccess permission classes. Specifies how to handle entries in an event log OverflowAction that has reached its maximum file size. Indicates whether the performance counter PerformanceCounterCategoryType category can have multiple instances. Specifies the lifetime of a performance counter PerformanceCounterInstanceLifetime instance. Defines access levels used by PerformanceCounterPermissionAccess PerformanceCounter permission classes. Specifies the formula used to calculate the PerformanceCounterType NextValue method for a PerformanceCounter instance. Describes the level of detail to trace about a PresentationTraceLevel particular object. Indicates the priority that the system associates with a process. This value, together with the ProcessPriorityClass priority value of each thread of the process, determines each thread's base priority level. Specified how a new window should appear when ProcessWindowStyle the system starts a process. Specifies the levels of trace messages filtered by SourceLevels the source switch and event type filter. ThreadPriorityLevel Specifies the priority level of a thread. ThreadState Specifies the current execution state of the thread. ThreadWaitReason Specifies the reason a thread is waiting. Identifies the type of event that has caused the TraceEventType trace. Specifies what messages to output for the Debug, TraceLevel Trace and TraceSwitch classes. TraceLogRetentionOption Specifies the file structure that will be used for the Enumeration

TraceOptions

EventSchemaTraceListener log. Specifies trace data options to be written to the trace output.

System.DirectoryServices Namespace
.NET Framework 4 The System.DirectoryServices namespace provides easy access to Active Directory Domain Services from managed code. The namespace contains two component classes, DirectoryEntry and DirectorySearcher, which use the Active Directory Services Interfaces (ADSI) technology. ADSI is the set of interfaces that Microsoft provides as a flexible tool for working with a variety of network providers. ADSI gives the administrator the ability to locate and manage resources on a network with relative ease, regardless of the size of the network. The classes in this namespace can be used with any of the Active Directory Domain Services service providers. The current providers are: Internet Information Services (IIS), Lightweight Directory Access Protocol (LDAP), Novell NetWare Directory Service (NDS), and WinNT. ADSI is a programmatic interface for Microsoft Active Directory Domain Services that enables your applications to interact with diverse directories on a network using a single interface. Using ADSI, you can create applications that perform common tasks, such as backing up databases, accessing printers, and administering user accounts. It is assumed that you have a general understanding of Active Directory Domain Services before using these classes. For more information on Active Directory Domain Services, see the topics Introduction to Active Directory Objects and Active Directory Technology Backgrounder, as well as the following topics in the MSDN library at http://msdn.microsoft.com/library:

Using Active Directory Domain Services Active Directory Service Interfaces Lightweight Directory Access Protocol Implementing Active Directory Service Interfaces Providers Binding to an ADSI Object IADsOpenDSObject::OpenDSObject

Active Directory Domain Services use a tree structure. Each node in the tree contains a set of properties. Use this namespace to traverse, search, and modify the tree, and read and write to the properties of a node.

The DirectoryEntry class encapsulates a node or object in the Active Directory Domain Services hierarchy. Use this class for binding to objects, reading properties, and updating attributes. Together with helper classes, DirectoryEntry provides support for life-cycle management and navigation methods, including creating, deleting, renaming, moving a child node, and enumerating children. Use the DirectorySearcher class to perform queries against the Active Directory Domain Services hierarchy. LDAP is the only system-supplied Active Directory Service Interfaces (ADSI) provider that supports searching. A search of the Active Directory Domain Services hierarchy through DirectorySearcher returns instances of SearchResult, which are contained in an instance of the SearchResultCollection class. Note: Many of the classes, methods, and properties in the System.DirectoryServices namespace use the LinkDemand code access security option. This means that the code access security demand only occurs during just-in-time compilation and that the demand is performed only on the calling assembly and not up the entire call stack. Because of this, callers should not pass objects that are created from this namespace at runtime to code that is not trusted. Classes Class Description The ActiveDirectoryAccessRule class is used to represent an access control entry (ACE) in the discretionary access control list (DACL) of an Active Directory Domain Services object. The ActiveDirectoryAuditRule is used to set an access control entry (ACE) on a system access control list (SACL). The ActiveDirectoryAccessRule contains the trustee, which is represented as an IdentityReference object. It also contains information about the access control type, access mask, and other properties such as inheritance flags. This rule is set on an ActiveDirectorySecurity object. After the ActiveDirectorySecurity is committed to the directory store, it will modify the security descriptor object according to the rules that are set on ActiveDirectoryAuditRule. Uses the object security layer of the managed ACL library to wrap access control functionality for directory objects.

ActiveDirectoryAccessRule

ActiveDirectoryAuditRule

ActiveDirectorySecurity

The CreateChildAccessRule class represents a specific type of access rule that is used to CreateChildAccessRule allow or deny an Active Directory Domain Services object the right to create child objects. The DeleteChildAccessRule class represents a specific type of access rule that is used to DeleteChildAccessRule allow or deny an Active Directory Domain Services object the right to delete child objects. The DeleteTreeAccessRule class represents a specific type of access rule that is used to allow or deny an Active Directory Domain DeleteTreeAccessRule Services object the right to delete all child objects, regardless of the permissions that the child objects have. Contains a collection of DirectoryEntry DirectoryEntries objects. The DirectoryEntry class encapsulates a DirectoryEntry node or object in the Active Directory Domain Services hierarchy. The DirectoryEntryConfiguration class provides a direct way to specify and obtain provider-specific options for manipulating a DirectoryEntryConfiguration directory object. Typically, the options apply to search operations of the underlying directory store. The supported options are provider-specific. Performs queries against Active Directory DirectorySearcher Domain Services. Contains extended error information about DirectoryServicesCOMException an error that occurred when the Invoke method is called. The DirectoryServicesPermission class DirectoryServicesPermission allows you to control code access security permissions for System.DirectoryServices. Allows declarative DirectoryServicesPermissionAttribute System.DirectoryServices permission checks. The DirectoryServicesPermissionEntry class defines the smallest unit of a code access DirectoryServicesPermissionEntry security permission set for System.DirectoryServices. DirectoryServicesPermissionEntryCollection Contains a strongly-typed collection of

DirectorySynchronization

DirectoryVirtualListView

DirectoryVirtualListViewContext DSDescriptionAttribute

ExtendedRightAccessRule

ListChildrenAccessRule

PropertyAccessRule

PropertyCollection PropertySetAccessRule

DirectoryServicesPermissionEntry objects. Specifies how to synchronize a directory within a domain. The DirectoryVirtualListView class specifies how to conduct a virtual list view search. A virtual list view search enables users to view search results as address-book style virtual list views. It is specifically designed for very large result sets. Search data is retrieved in contiguous subsets of a sorted directory search. Specifies how to construct directory virtual list view response. Supports the .NET Framework infrastructure and is not intended to be used directly from code. Represents a specific type of access rule that is used to allow or deny an Active Directory object an extended right. Extended rights are special operations that are not covered by the standard set of access rights. An example of an extended right is Send-As, which gives a user the right to send e-mail for another user. For a list of possible extended rights, see the topic Extended Rights in the MSDN Library at http://msdn.microsoft.com/library. For more information about extended rights, see the topic Control Access Rights, also in the MSDN Library. The ListChildrenAccessRule class represents a specific type of access rule that is used to allow or deny an Active Directory Domain Services object the right to list child objects. The PropertyAccessRule class represents a specific type of access rule that is used to allow or deny access to an Active Directory Domain Services property. The PropertyCollection class contains the properties of a DirectoryEntry. The PropertySetAccessRule class represents a specific type of access rule that is used to allow or deny access to an Active Directory

PropertyValueCollection ResultPropertyCollection ResultPropertyValueCollection SchemaNameCollection

SearchResult

SearchResultCollection SortOption Enumerations Enumeration

Domain Services property set. For a list of property sets that are defined for Active Directory Domain Services, see the topic Property Sets in the MSDN Library at http://msdn.microsoft.com/library. Contains the values of a DirectoryEntry property. Contains the properties of a SearchResult instance. Contains the values of a SearchResult property. Contains a list of the schema names that the SchemaFilter property of a DirectoryEntries object can use. The SearchResult class encapsulates a node in the Active Directory Domain Services hierarchy that is returned during a search through DirectorySearcher. The SearchResultCollection class contains the SearchResult instances that the Active Directory hierarchy returned during a DirectorySearcher query. Specifies how to sort the results of a search.

Description The ActiveDirectoryRights enumeration specifies the ActiveDirectoryRights access rights that are assigned to an Active Directory Domain Services object. The ActiveDirectorySecurityInheritance enumeration ActiveDirectorySecurityInheritance specifies if, and how, ACE information is applied to an object and its descendents. The AuthenticationTypes enumeration specifies the types of authentication used in AuthenticationTypes System.DirectoryServices. This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values. The DereferenceAlias enumeration specifies how DereferenceAlias aliases are resolved. This enumeration provides values for the DirectorySearcher.DerefAlias property. The DirectoryServicesPermissionAccess enumeration DirectoryServicesPermissionAccess defines access levels that are used by System.DirectoryServices permission classes. This

DirectorySynchronizationOptions

ExtendedDN

PasswordEncodingMethod

PropertyAccess

ReferralChasingOption SearchScope

SecurityMasks

SortDirection

enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values. Contains flags that determine how directories within a domain will be synchronized. These options can be set for the DirectorySynchronization.Option property. The ExtendedDN enumeration specifies the format in which to return the extended distinguished name. This enumeration is used with the DirectorySearcher.ExtendedDN property. Specifies whether SSL is used when you set or change a password. This enumeration is used with the DirectoryEntryConfiguration.PasswordEncoding property. The PropertyAccess enumeration is used with the PropertyAccessRule and PropertySetAccessRule classes to indicate the type of access that is applied to an Active Directory property or property set. The ReferralChasingOption enumeration specifies if and how referral chasing is pursued. Specifies the possible scopes for a directory search that is performed using the DirectorySearcher object. Specifies the available options for examining security information of a directory object. This enumeration is used with the DirectorySearcher.SecurityMasks and DirectoryEntryConfiguration.SecurityMasks properties. The SortDirection enumeration specifies how to sort the results of an Active Directory Domain Services query.

System.Drawing Namespace
.NET Framework 4 The System.Drawing namespace provides access to GDI+ basic graphics functionality. More advanced functionality is provided in the System.Drawing.Drawing2D, System.Drawing.Imaging, and System.Drawing.Text namespaces. The Graphics class provides methods for drawing to the display device. Classes such as Rectangle and Point encapsulate GDI+ primitives. The Pen class is used to draw lines and

curves, while classes derived from the abstract class Brush are used to fill the interiors of shapes. Caution Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and runtime exceptions. For a supported alternative, see Windows Imaging Components. Classes Description Encapsulates a GDI+ bitmap, which consists of the pixel data for a graphics image and its attributes. A Bitmap Bitmap is an object used to work with images defined by pixel data. Defines objects used to fill the interiors of graphical Brush shapes such as rectangles, ellipses, pies, polygons, and paths. Brushes for all the standard colors. This class cannot Brushes be inherited. BufferedGraphics Provides a graphics buffer for double buffering. Provides methods for creating graphics buffers that BufferedGraphicsContext can be used for double buffering. Provides access to the main buffered graphics context BufferedGraphicsManager object for the application domain. Converts colors from one data type to another. Access ColorConverter this class through the TypeDescriptor. Translates colors to and from GDI+ Color structures. ColorTranslator This class cannot be inherited. Defines a particular format for text, including font Font face, size, and style attributes. This class cannot be inherited. FontConverter Converts Font objects from one data type to another. Infrastructure. FontConverter.FontNameConverter is FontConverter.FontNameConverter a type converter that is used to convert a font name to and from various other representations. Infrastructure. Converts font units to and from other FontConverter.FontUnitConverter unit types. Defines a group of type faces having a similar basic FontFamily design and certain variations in styles. This class cannot be inherited. Encapsulates a GDI+ drawing surface. This class Graphics cannot be inherited. Class

Icon

IconConverter Image ImageAnimator ImageConverter

ImageFormatConverter

Pen Pens PointConverter RectangleConverter Region

SizeConverter SizeFConverter SolidBrush

StringFormat

SystemBrushes SystemColors

Represents a Windows icon, which is a small bitmap image that is used to represent an object. Icons can be thought of as transparent bitmaps, although their size is determined by the system. Converts an Icon object from one data type to another. Access this class through the TypeDescriptor object. An abstract base class that provides functionality for the Bitmap and Metafile descended classes. Animates an image that has time-based frames. ImageConverter is a class that can be used to convert Image objects from one data type to another. Access this class through the TypeDescriptor object. ImageFormatConverter is a class that can be used to convert ImageFormat objects from one data type to another. Access this class through the TypeDescriptor object. Defines an object used to draw lines and curves. This class cannot be inherited. Pens for all the standard colors. This class cannot be inherited. Converts a Point object from one data type to another. Converts rectangles from one data type to another. Access this class through the TypeDescriptor. Describes the interior of a graphics shape composed of rectangles and paths. This class cannot be inherited. The SizeConverter class is used to convert from one data type to another. Access this class through the TypeDescriptor object. Converts SizeF objects from one type to another. Defines a brush of a single color. Brushes are used to fill graphics shapes, such as rectangles, ellipses, pies, polygons, and paths. This class cannot be inherited. Encapsulates text layout information (such as alignment, orientation and tab stops) display manipulations (such as ellipsis insertion and national digit substitution) and OpenType features. This class cannot be inherited. Each property of the SystemBrushes class is a SolidBrush that is the color of a Windows display element. Each property of the SystemColors class is a Color

SystemFonts SystemIcons

SystemPens

TextureBrush

ToolboxBitmapAttribute Structures

structure that is the color of a Windows display element. Specifies the fonts used to display text in Windows display elements. Each property of the SystemIcons class is an Icon object for Windows system-wide icons. This class cannot be inherited. Each property of the SystemPens class is a Pen that is the color of a Windows display element and that has a width of 1 pixel. Each property of the TextureBrush class is a Brush object that uses an image to fill the interior of a shape. This class cannot be inherited. Allows you to specify an icon to represent a control in a container, such as the Microsoft Visual Studio Form Designer.

Structure Description CharacterRange Specifies a range of character positions within a string. Color Represents an ARGB (alpha, red, green, blue) color. Represents an ordered pair of integer x- and y-coordinates that defines a Point point in a two-dimensional plane. Represents an ordered pair of floating-point x- and y-coordinates that PointF defines a point in a two-dimensional plane. Stores a set of four integers that represent the location and size of a Rectangle rectangle Stores a set of four floating-point numbers that represent the location and RectangleF size of a rectangle. For more advanced region functions, use a Region object. Size Stores an ordered pair of integers, which specify a Height and Width. Stores an ordered pair of floating-point numbers, typically the width and SizeF height of a rectangle. Interfaces Description Defines methods for obtaining and releasing an existing handle to a IDeviceContext Windows device context. Delegates Delegate Graphics.DrawImageAbort Description Provides a callback method for deciding when the Interface

DrawImage method should prematurely cancel execution and stop drawing an image. Provides a callback method for the EnumerateMetafile Graphics.EnumerateMetafileProc method. Provides a callback method for determining when the Image.GetThumbnailImageAbort GetThumbnailImage method should prematurely cancel execution. Enumerations Enumeration ContentAlignment Description Specifies alignment of content on the drawing surface. Determines how the source color in a copy pixel operation is CopyPixelOperation combined with the destination color to result in a final color. FontStyle Specifies style information applied to text. GraphicsUnit Specifies the unit of measure for the given data. KnownColor Specifies the known system colors. Specifies how much an image is rotated and the axis used to flip the RotateFlipType image. Specifies the alignment of a text string relative to its layout StringAlignment rectangle. The StringDigitSubstitute enumeration specifies how to substitute StringDigitSubstitute digits in a string according to a user's locale or language. StringFormatFlags Specifies the display and layout information for text strings. Specifies how to trim characters from a string that does not StringTrimming completely fit into a layout shape. StringUnit Specifies the units of measure for a text string.

System.Drawing.Design Namespace
.NET Framework 4 The System.Drawing.Design namespace contains classes that extend design-time user interface (UI) logic and drawing. The classes in this namespace can be used to create custom toolbox items, type-specific value editors that can edit and graphically represent values of their supported types, and type converters that can convert values between certain types. This namespace provides the basic frameworks for developing extensions to the design-time UI.

Caution Classes within the System.Drawing.Design namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions. Classes Description Provides a user interface for selecting bitmap BitmapEditor files in a property browser. CategoryNameCollection Represents a collection of category name strings. Provides a UITypeEditor for visually picking a ColorEditor color. Provides a UITypeEditor for visually editing ContentAlignmentEditor content alignment. Provides a UITypeEditor that can perform CursorEditor default file searching for cursor (.cur) files. Provides a user interface to select and configure a FontEditor Font object. Provides a UITypeEditor that paints a glyph for FontNameEditor the font name. Provides a UITypeEditor for visually choosing IconEditor an icon. Provides a user interface for selecting an image ImageEditor for a property in a property grid. Infrastructure. Provides a UITypeEditor that can MetafileEditor perform default file searching for metafile (.emf) files. PaintValueEventArgs Provides data for the PaintValue method. Provides information about a property displayed in the Properties window, including the PropertyValueUIItem associated event handler, pop-up information string, and the icon to display for the property. Provides data for the ComponentsCreated event ToolboxComponentsCreatedEventArgs that occurs when components are added to the toolbox. Provides data for the ComponentsCreating event ToolboxComponentsCreatingEventArgs that occurs when components are added to the toolbox. Provides a base implementation of a toolbox ToolboxItem item. ToolboxItemCollection Represents a collection of toolbox items. Class

ToolboxItemContainer ToolboxItemCreator ToolboxService

UITypeEditor Interfaces

Encapsulates a ToolboxItem. Encapsulates a ToolboxItemCreatorCallback. This class cannot be inherited. Provides a default implementation of the IToolboxService interface. Provides a base class that can be used to design value editors that can provide a user interface (UI) for representing and editing the values of objects of the supported data types.

Description Provides an interface to manage the images, ToolTips, and IPropertyValueUIService event handlers for the properties of a component displayed in a property browser. IToolboxItemProvider Exposes a collection of toolbox items. Provides methods and properties to manage and query the IToolboxService toolbox in the development environment. Defines an interface for setting the currently selected toolbox IToolboxUser item and indicating whether a designer supports a particular toolbox item. Delegates Description Represents the method that adds a delegate to PropertyValueUIHandler an implementation of IPropertyValueUIService. Represents the method that will handle the PropertyValueUIItemInvokeHandler InvokeHandler event of a PropertyValueUIItem. Represents the method that handles the ToolboxComponentsCreatedEventHandler ComponentsCreated event. Represents the method that handles the ToolboxComponentsCreatingEventHandler ComponentsCreating event. Provides a callback mechanism that can create ToolboxItemCreatorCallback a ToolboxItem. Enumerations Description Specifies identifiers that indicate the value editing style of a UITypeEditorEditStyle UITypeEditor. Enumeration Delegate

Interface

System.Drawing.Drawing2D Namespace
.NET Framework 4

The System.Drawing.Drawing2D namespace provides advanced two-dimensional and vector graphics functionality. The following table lists some of the important classes and enumerations in theSystem.Drawing.Drawing2D namespace, grouped into categories. Class category

Graphics and Graphics paths

Details The GraphicsState and GraphicsContainer classes report information about the current Graphics object. GraphicsPath classes represent a series of lines and curves. The GraphicsPathIterator and PathData classes provide detailed information about the contents of a GraphicsPath object. The Matrix class represents a matrix for geometric transforms. The MatrixOrder enumeration specifies the order for matrix transformations.

Matrix and transformation related types Brush classes

The PathGradientBrush and HatchBrush classes enable you to fill shapes with either a gradient, or hatch pattern, respectively. The LineCap and CustomLineCap enumerations enable you to specify cap styles for a line. The, LineJoin enumeration Enumeration related enables you to specify how two lines are joined in a path. to lines The PenAlignment enumeration enables you specify the alignment of the drawing tip, when you draw a line. The PenType enumeration specifies the pattern a line should be filled with. Enumerations related The HatchStyle enumeration specifies fill styles for a to filling shapes and HatchBrush. The Blend class specifies a blend pattern for a paths LinearGradientBrush. The FillMode enumeration specifies the fill style for a GraphicsPath.
Caution

Classes in the System.Drawing.Drawing2D namespace are not supported for use in a Windows or ASP.NET service. Attempting to use these classes in one of these application types may produce unexpected problems, such as diminished service performance and runtime exceptions.
Classes

Class AdjustableArrowCap

Description Represents an adjustable arrow-shaped line cap. This class cannot be inherited. Defines a blend pattern for a LinearGradientBrush object. This class cannot be inherited. Defines arrays of colors and positions used for interpolating color blending in a multicolor gradient. This class cannot be inherited. Encapsulates a custom user-defined line cap. Represents the internal data of a graphics container. This class is used when saving the state of a Graphics object using the BeginContainer and EndContainer methods. This class cannot be inherited. Represents a series of connected lines and curves. This class cannot be inherited.

Blend

ColorBlend CustomLineCap

GraphicsContainer

GraphicsPath

Provides the ability to iterate through subpaths in a GraphicsPath and test GraphicsPathIterator the types of shapes contained in each subpath. This class cannot be inherited. GraphicsState Represents the state of a Graphics object. This object is returned by a call to the Save methods. This class cannot be inherited. Defines a rectangular brush with a hatch style, a foreground color, and a background color. This class cannot be inherited.

HatchBrush

LinearGradientBrush Encapsulates a Brush with a linear gradient. This class cannot be inherited. Matrix Encapsulates a 3-by-3 affine matrix that represents a geometric transform. This class cannot be inherited. Contains the graphical data that makes up a GraphicsPath object. This class cannot be inherited. Encapsulates a Brush object that fills the interior of a GraphicsPath object with a gradient. This class cannot be inherited.

PathData

PathGradientBrush

RegionData Enumerations

Encapsulates the data that makes up a Region object. This class cannot be inherited.

Enumeration CombineMode CompositingMode

Description Specifies how different clipping regions can be combined. Specifies how the source colors are combined with the background colors.

CompositingQuality Specifies the quality level to use during compositing. CoordinateSpace DashCap DashStyle FillMode FlushIntention HatchStyle InterpolationMode Specifies the system to use when evaluating coordinates. Specifies the type of graphic shape to use on both ends of each dash in a dashed line. Specifies the style of dashed lines drawn with a Pen object. Specifies how the interior of a closed path is filled. Specifies whether commands in the graphics stack are terminated (flushed) immediately or executed as soon as possible. Specifies the different patterns available for HatchBrush objects. The InterpolationMode enumeration specifies the algorithm that is used when images are scaled or rotated.

LinearGradientMode Specifies the direction of a linear gradient. LineCap LineJoin MatrixOrder PathPointType PenAlignment Specifies the available cap styles with which a Pen object can end a line. Specifies how to join consecutive line or curve segments in a figure (subpath) contained in a GraphicsPath object. Specifies the order for matrix transform operations. Specifies the type of point in a GraphicsPath object. Specifies the alignment of a Pen object in relation to the theoretical, zero-

width line. PenType PixelOffsetMode QualityMode SmoothingMode WarpMode WrapMode Specifies the type of fill a Pen object uses to fill lines. Specifies how pixels are offset during rendering. Specifies the overall quality when rendering GDI+ objects. Specifies whether smoothing (antialiasing) is applied to lines and curves and the edges of filled areas. Specifies the type of warp transformation applied in a Warp method. Specifies how a texture or gradient is tiled when it is smaller than the area being filled.

System.Drawing.Imaging Namespace
.NET Framework 4 The System.Drawing.Imaging namespace provides advanced GDI+ imaging functionality. Basic graphics functionality is provided by the System.Drawing namespace. The Metafile class provides methods for recording and saving metafiles. The Encoder class enables users to extend GDI+ to support any image format. The PropertyItem class provides methods for storing and retrieving metadata in image files. Caution Classes within the System.Drawing.Imaging namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions. Classes Class BitmapData ColorMap Description Specifies the attributes of a bitmap image. The BitmapData class is used by the LockBits and UnlockBits methods of the Bitmap class. Not inheritable. Defines a map for converting colors. Several methods of the ImageAttributes class adjust image colors by using a color-

remap table, which is an array of ColorMap structures. Not inheritable. Defines a 5 x 5 matrix that contains the coordinates for the RGBAW space. Several methods of the ImageAttributes class ColorMatrix adjust image colors by using a color matrix. This class cannot be inherited. Defines an array of colors that make up a color palette. The ColorPalette colors are 32-bit ARGB colors. Not inheritable. An Encoder object encapsulates a globally unique identifier Encoder (GUID) that identifies the category of an image encoder parameter. EncoderParameter Used to pass a value, or an array of values, to an image encoder. EncoderParameters Encapsulates an array of EncoderParameter objects. Provides properties that get the frame dimensions of an image. FrameDimension Not inheritable. Contains information about how bitmap and metafile colors are ImageAttributes manipulated during rendering. The ImageCodecInfo class provides the necessary storage members and methods to retrieve all pertinent information ImageCodecInfo about the installed image encoders and decoders (called codecs). Not inheritable. ImageFormat Specifies the file format of the image. Not inheritable. Defines a graphic metafile. A metafile contains records that describe a sequence of graphics operations that can be recorded Metafile (constructed) and played back (displayed). This class is not inheritable. MetafileHeader Contains attributes of an associated Metafile. Not inheritable. MetaHeader Contains information about a windows-format (WMF) metafile. Encapsulates a metadata property to be included in an image PropertyItem file. Not inheritable. WmfPlaceableFileHeader Defines a placeable metafile. Not inheritable. Delegates Description This delegate is not used. For an example of enumerating the records PlayRecordCallback of a metafile, see EnumerateMetafile. Enumerations Enumeration ColorAdjustType ColorChannelFlag Description Specifies which GDI+ objects use color adjustment information. Specifies individual channels in the CMYK (cyan, magenta, Delegate

yellow, black) color space. This enumeration is used by the SetOutputChannel methods. ColorMapType Specifies the types of color maps. Specifies the types of images and colors that will be ColorMatrixFlag affected by the color and grayscale adjustment settings of an ImageAttributes. ColorMode Specifies two modes for color component values. Specifies the methods available for use with a metafile to EmfPlusRecordType read and write graphic commands. Specifies the nature of the records that are placed in an EmfType Enhanced Metafile (EMF) file. This enumeration is used by several constructors in the Metafile class. Used to specify the data type of the EncoderParameter used EncoderParameterValueType with the Save or SaveAdd method of an image. Used to specify the parameter value passed to a JPEG or EncoderValue TIFF image encoder when using the Image.Save or Image.SaveAdd methods. ImageCodecFlags Provides attributes of an image encoder/decoder (codec). Specifies the attributes of the pixel data contained in an ImageFlags Image object. The Flags property returns a member of this enumeration. Specifies flags that are passed to the flags parameter of the ImageLockMode LockBits method. The LockBits method locks a portion of an image so that you can read or write the pixel data. Specifies the unit of measurement for the rectangle used to MetafileFrameUnit size and position a metafile. This is specified during the creation of the Metafile object. Specifies types of metafiles. The MetafileHeader.Type MetafileType property returns a member of this enumeration. Specifies the type of color data in the system palette. The PaletteFlags data can be color data with alpha, grayscale data only, or halftone data. Specifies the format of the color data for each pixel in the PixelFormat image.

System.Drawing.Printing Namespace
.NET Framework 4

The System.Drawing.Printing namespace provides print-related services for Windows Forms applications. Typically, when you print from a Windows Forms application, you create a new instance of the PrintDocument class, set properties, such as DefaultPageSettings and PrinterSettings, that describe how to print, and call the Print method to actually print the document. Calling the PrintDocument.Print method raises the PrintDocument.PrintPage event, which should be handled to perform the document layout for printing. Use the Graphics property of the PrintPageEventArgs object obtained from the PrintDocument.PrintPage event to specify the output to print. If you are printing a text file, use StreamReader to read one line at a time from the stream and call the DrawString method to draw the line in the graphics object. For more information about this process, see the Graphics and StreamReader classes. You can view an example of printing a text document in the PrintDocument class overview topic. Note The DrawText methods of the TextRenderer class are not supported for printing. Instead, use the DrawString methods of the Graphics class. When implemented in a derived class, the PrintController controls how a PrintDocument is printed. The PrintDocument.Print method invokes the print controller's OnStartPrint, OnEndPrint, OnStartPage, and OnEndPage methods, which in turn tell the printer how to print the document. For more information about printing dialog boxes, see PrintDialog and PageSetupDialog. The print-preview process uses a specialized print controller, dialog box, and control. For an example of such a print controller and dialog box, see PreviewPrintController, PrintPreviewDialog, and PrintPreviewControl. Caution Classes within the System.Drawing.Printing namespace are not supported for use within a Windows service or ASP.NET application or service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions. If you want to print from a Windows Presentation Foundation (WPF) application, see the System.Printing namespace. Classes Class InvalidPrinterException Description Represents the exception that is thrown when you try to access a printer using printer settings that are not valid.

Specifies the dimensions of the margins of a printed page. MarginsConverter Provides a MarginsConverter for Margins. Specifies settings that apply to a single, PageSettings printed page. PaperSize Specifies the size of a piece of paper. Specifies the paper tray from which the PaperSource printer gets paper. Specifies print preview information for a PreviewPageInfo single page. This class cannot be inherited. Specifies a print controller that displays a PreviewPrintController document on a screen as a series of images. Controls how a document is printed, when PrintController printing from a Windows Forms application. Defines a reusable object that sends output to PrintDocument a printer, when printing from a Windows Forms application. Represents the resolution supported by a PrinterResolution printer. Specifies information about how a document is printed, including the printer that prints it, PrinterSettings when printing from a Windows Forms application. PrinterSettings.PaperSizeCollection Contains a collection of PaperSize objects. PrinterSettings.PaperSourceCollection Contains a collection of PaperSource objects. Contains a collection of PrinterResolution PrinterSettings.PrinterResolutionCollection objects. Infrastructure. Contains a collection of String PrinterSettings.StringCollection objects. Specifies a series of conversion methods that are useful when interoperating with the PrinterUnitConvert Win32 printing API. This class cannot be inherited. Provides data for the BeginPrint and EndPrint PrintEventArgs events. Controls access to printers. This class cannot PrintingPermission be inherited. Allows declarative printing permission PrintingPermissionAttribute checks. PrintPageEventArgs Provides data for the PrintPage event. Provides data for the QueryPageSettings QueryPageSettingsEventArgs event. Margins

StandardPrintController Delegates

Specifies a print controller that sends information to a printer.

Description Represents the method that will handle the BeginPrint or PrintEventHandler EndPrint event of a PrintDocument. Represents the method that will handle the PrintPage PrintPageEventHandler event of a PrintDocument. Represents the method that handles the QueryPageSettingsEventHandler QueryPageSettings event of a PrintDocument. Enumerations Enumeration Description Duplex Specifies the printer's duplex setting. PaperKind Specifies the standard paper sizes. PaperSourceKind Standard paper sources. PrintAction Specifies the type of print operation occurring. PrinterResolutionKind Specifies a printer resolution. PrinterUnit Specifies several of the units of measure used for printing. PrintingPermissionLevel Specifies the type of printing that code is allowed to do. PrintRange Specifies the part of the document to print.

Delegate

System.Drawing.Text Namespace
.NET Framework 4 The System.Drawing.Text namespace provides advanced GDI+ typography functionality. Basic graphics functionality is provided by the System.Drawing namespace. The classes in this namespace allow users to create and use collections of fonts. Caution Classes within the System.Drawing.Text namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions. Classes

Description Provides a base class for installed and private font collections. Represents the fonts installed on the system. This class cannot be InstalledFontCollection inherited. Provides a collection of font families built from font files that are PrivateFontCollection provided by the client application. Enumerations Enumeration Description GenericFontFamilies Specifies a generic FontFamily object. HotkeyPrefix Specifies the type of display for hot-key prefixes that relate to text. TextRenderingHint Specifies the quality of text rendering.

Class FontCollection

System.EnterpriseServices Namespace
.NET Framework 4

The System.EnterpriseServices namespace provides an important infrastructure for enterprise applications. COM+ provides a services architecture for component programming models deployed in an enterprise environment. This namespace provides .NET objects with access to COM+ services making the .NET Framework objects more practical for enterprise applications. For information about using System.EnterpriseServices, see Writing Serviced Components
Classes

Class

Description Creates an activity to do synchronous or asynchronous batch work that can use COM+ services without needing to create a COM+ component. This class cannot be inherited. Specifies access controls to an assembly containing ServicedComponent classes. Specifies whether components in the assembly run in the

Activity

ApplicationAccessControlAttribute ApplicationActivationAttribute

creator's process or in a system process. ApplicationIDAttribute Specifies the application ID (as a GUID) for this assembly. This class cannot be inherited. Specifies the name of the COM+ application to be used for the install of the components in the assembly. This class cannot be inherited. Enables queuing support for the marked assembly and enables the application to read method calls from Message Queuing queues. This class cannot be inherited. Marks the attributed method as an AutoComplete object. This class cannot be inherited. Wraps the COM+ ByotServerEx class and the COM+ DTC interfaces ICreateWithTransactionEx and ICreateWithTipTransactionEx. This class cannot be inherited. Enables security checking on calls to a component. This class cannot be inherited. Enables you to pass context properties from the COM Transaction Integrator (COMTI) into the COM+ context. Enables COM+ object construction support. This class cannot be inherited. Obtains information about the COM+ object context. This class cannot be inherited. Sets the description on an assembly (application), component, method, or interface. This class cannot be inherited. Marks the attributed class as an event class. This class cannot be inherited. Enables event tracking for a component. This class cannot be inherited. Sets the queuing exception class for the queued class. This

ApplicationNameAttribute

ApplicationQueuingAttribute

AutoCompleteAttribute

BYOT

ComponentAccessControlAttribute

COMTIIntrinsicsAttribute

ConstructionEnabledAttribute

ContextUtil

DescriptionAttribute

EventClassAttribute

EventTrackingEnabledAttribute ExceptionClassAttribute

class cannot be inherited. Enables access to ASP intrinsic values from ContextUtil.GetNamedProperty. This class cannot be inherited. Enables queuing support for the marked interface. This class cannot be inherited. Turns just-in-time (JIT) activation on or off. This class cannot be inherited.

IISIntrinsicsAttribute

InterfaceQueuingAttribute

JustInTimeActivationAttribute

Determines whether the component participates in load LoadBalancingSupportedAttribute balancing, if the component load balancing service is installed and enabled on the server. MustRunInClientContextAttribute Forces the attributed object to be created in the context of the creator, if possible. This class cannot be inherited. Enables and configures object pooling for a component. This class cannot be inherited. Identifies a component as a private component that is only seen and activated by components in the same application. This class cannot be inherited. Provides configuration information for installing assemblies into the COM+ catalog. Retrieves extended error information about methods related to multiple COM+ objects. This also includes methods that install, import, and export COM+ applications and components. This class cannot be inherited. The exception that is thrown when a registration error is detected. Installs and configures assemblies in the COM+ catalog. This class cannot be inherited. Infrastructure. Obsolete. Used by the .NET Framework infrastructure to install and configure assemblies in the COM+ catalog while maintaining a newly established

ObjectPoolingAttribute

PrivateComponentAttribute

RegistrationConfig

RegistrationErrorInfo

RegistrationException

RegistrationHelper

RegistrationHelperTx

transaction. ResourcePool Stores objects in the current transaction. This class cannot be inherited. Ensures that the infrastructure calls through an interface for a method or for each method in a class when using the security service. Classes need to use interfaces to use security services. This class cannot be inherited. Describes the chain of callers leading up to the current method call. Provides an ordered collection of identities in the current call chain. Contains information that regards an identity in a COM+ call chain. Configures a role for an application or component. This class cannot be inherited. Specifies and configures the services that are to be active in the domain which is entered when calling Enter or creating an Activity. This class cannot be inherited. Represents the base class of all classes using COM+ services. The exception that is thrown when an error is detected in a serviced component. Allows a code segment identified by Enter and Leave to run in its own context and behave as if it were a method that is called on an object created within the context. This class cannot be inherited. Accesses a shared property. This class cannot be inherited. Represents a collection of shared properties. This class cannot be inherited. Controls access to shared property groups. This class cannot be inherited.

SecureMethodAttribute

SecurityCallContext

SecurityCallers

SecurityIdentity

SecurityRoleAttribute

ServiceConfig

ServicedComponent ServicedComponentException

ServiceDomain

SharedProperty SharedPropertyGroup

SharedPropertyGroupManager

SynchronizationAttribute

Sets the synchronization value of the component. This class cannot be inherited. Specifies the type of transaction that is available to the attributed object. Permissible values are members of the TransactionOption enumeration.

TransactionAttribute

Structures

Structure BOID

Description Represents the unit of work associated with a transaction. This structure is used in XACTTRANSINFO.

XACTTRANSINFO Represents a structure used in the ITransaction interface. Interfaces

Interface IAsyncErrorNotify

Description Implements error trapping on the asynchronous batch work that is submitted by the Activity object. Functions in Queued Components in the abnormal handling of serverside playback errors and client-side failures of the Message Queuing delivery mechanism. Supports setting the time-out for the Startup method. Supports methods that can be called when a COM component starts up or shuts down. Installs and configures assemblies in the COM+ catalog. Infrastructure. Implemented by the ServicedComponent class to determine if the AutoCompleteAttribute class attribute is set to true or false for a remote method invocation. Implements the batch work that is submitted through the activity created by Activity.

IPlaybackControl

IProcessInitControl IProcessInitializer IRegistrationHelper

IRemoteDispatch

IServiceCall

IServicedComponentInfo

Infrastructure. Implemented by the ServicedComponent class to obtain information about the component via the GetComponentInfo method. Corresponds to the Distributed Transaction Coordinator (DTC) ITransaction interface and is supported by objects obtained through ContextUtil.Transaction.

ITransaction

Delegates

Delegate ResourcePool.TransactionEndDelegate Enumerations

Description Represents the method that handles the ending of a transaction.

Enumeration

Description

Specifies the level of access checking for an application, either at the AccessChecksLevelOption process level only or at all levels, including component, interface, and method levels. ActivationOption Specifies the manner in which serviced components are activated in the application. Specifies the remote procedure call (RPC) authentication mechanism. Applicable only when the ActivationOption is set to Server. Indicates whether all work submitted by Activity should be bound to only one single-threaded apartment (STA). This enumeration has no impact on the multithreaded apartment (MTA). Specifies the level of impersonation allowed when calling targets of a server application. Indicates whether to create a new context based on the current context or on the information in ServiceConfig. Flags used with the RegistrationHelper class.

AuthenticationOption

BindingOption

ImpersonationLevelOption

InheritanceOption InstallationFlags

PartitionOption PropertyLockMode

Indicates the context in which to run the COM+ partition. Specifies the mode for accessing shared properties in the shared property group manager. Specifies the release mode for the properties in the new shared property group. Indicates how side-by-side assemblies are configured for ServiceConfig. Specifies the type of automatic synchronization requested by the component. Indicates the thread pool in which the work, submitted by Activity, runs.

PropertyReleaseMode

SxsOption

SynchronizationOption

ThreadPoolOption

TransactionIsolationLevel Specifies the value of the TransactionAttribute. TransactionOption TransactionStatus TransactionVote Specifies the automatic transaction type requested by the component. Indicates the transaction status. Specifies the values allowed for transaction outcome voting.

También podría gustarte