Type System.Xml.XmlWriter

extends System.Object

Variables:

public System.Xml.WriteState WriteState

public System.String XmlLang

public System.Xml.XmlSpace XmlSpace

Constructors:

protected System.Xml.XmlWriter()

Constructs a new instance of the System.Xml.XmlWriter class.

Functions:

public System.Void Close()

Closes the writer.

This method closes any remaining open elements or attributes. This method calls the System.Xml.XmlWriter.Flush method to flush the underlying buffered stream and then closes the stream. This method sets the System.Xml.XmlWriter.WriteState to System.Xml.WriteState.Closed. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.Void Flush()

Clears all buffers and causes any buffered data to be written to the underlying stream.

As described above. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.String LookupPrefix(System.String ns)

Retrieves the prefix defined in the current namespace scope for the specified namespace URI.

Parameter ns: A System.String specifying the namespace URI.

Returns: A System.String containing the corresponding prefix, or System.String.Empty if the prefix is not found and ns is the default namespace, or null if no matching namespace URI is found in the current scope.

Throws: : ns is null or System.String.Empty.

As described above. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public virtual System.Void WriteAttributes(System.Xml.XmlReader reader, System.Boolean defattr)

Writes the attributes found at the current position of a System.Xml.XmlReader.

Parameter reader: A System.Xml.XmlReader from which to copy the attributes.

Parameter defattr: A System.Boolean where true specifies to copy the default attributes from reader; otherwise, false.

Throws: : reader is null.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

Throws: : reader is not positioned on a node of System.Xml.XmlNodeType Attribute, Element, or XmlDeclaration.

If the reader is positioned on an Element or XmlDeclaration node, this method writes all the contained attributes. If the reader is positioned on an Attribute node, this method writes the current attribute, then the rest of the attributes until the closing tag is reached. If the reader is positioned on any other node type, this method throws an exception. This method positions the reader by calling its System.Xml.XmlReader.MoveToFirstAttribute and System.Xml.XmlReader.MoveToNextAttribute methods, and retrieves the value of the attributes by calling the System.Xml.XmlReader.ReadAttributeValue method of the reader. Override this method to remove any content that would invalidate the document. Use this method to write all the attributes found at the current position.

public System.Void WriteAttributeString(System.String prefix, System.String localName, System.String ns, System.String value)

Writes a new attribute with the specified prefix, local name, namespace URI, and value.

Parameter prefix: A System.String specifying the namespace prefix of the attribute.

Parameter localName: A System.String specifying the local name of the attribute.

Parameter ns: A System.String specifying the namespace URI of the attribute.

Parameter value: A System.String specifying the value of the attribute.

Throws: : localName is null or System.String.Empty .

Throws: : The System.Xml.XmlWriter.WriteState is not System.Xml.WriteState.Element.

This method calls the following methods in order to write a complete attribute: System.Xml.XmlWriter.WriteStartAttribute(System.String,System.String)(prefix, localName, ns) System.Xml.XmlWriter.WriteString(System.String)(value) System.Xml.XmlWriter.WriteEndAttribute()

public System.Void WriteAttributeString(System.String localName, System.String value)

Writes a new attribute with the specified local name and value.

Parameter localName: A System.String specifying the local name of the attribute.

Parameter value: A System.String specifying the value of the attribute.

Throws: : localName is null or System.String.Empty.

Throws: : The System.Xml.XmlWriter.WriteState is not System.Xml.WriteState.Element.

This method calls the following methods in order to write a complete attribute: System.Xml.XmlWriter.XmlWriter.WriteStartAttribute(null, localName, null) System.Xml.XmlWriter.WriteString(System.String)(value) System.Xml.XmlWriter.WriteEndAttribute()

public System.Void WriteAttributeString(System.String localName, System.String ns, System.String value)

Writes a new attribute with the specified local name, namespace URI, and value.

Parameter localName: A System.String specifying the local name of the attribute.

Parameter ns: A System.String specifying the namespace URI of the attribute.

Parameter value: A System.String specifying the value of the attribute.

Throws: : localName is null or System.String.Empty.

Throws: : The System.Xml.XmlWriter.WriteState is not System.Xml.WriteState.Element.

This method calls the following methods in order to write a complete attribute: System.Xml.XmlWriter.WriteStartAttribute(System.String,System.String)(null, localName, ns) System.Xml.XmlWriter.WriteString(System.String)(value) System.Xml.XmlWriter.WriteEndAttribute()

public System.Void WriteBase64(System.Byte[] buffer, System.Int32 index, System.Int32 count)

Encodes the specified binary bytes as Base64 and writes out the resulting text.

Parameter buffer: A System.Byte array containing the bytes to encode.

Parameter index: A System.Int32 specifying the position within the array of the first byte to encode.

Parameter count: A System.Int32 specifying the number of bytes to encode.

Throws: : buffer is null.

Throws: : The buffer length minus index is less than count.

Throws: : index or count is less than zero.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

Base64 encoding represents byte sequences in a text form comprised of the 65 US-ASCII characters (A-Z, a-z, 0-9, +, / ,= ) where each character encodes 6 bits of the binary data. For more information on Base64 encoding, see RFC 2045 ( http://www.ietf.org/rfc/rfc2045). As described above. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.Void WriteBinHex(System.Byte[] buffer, System.Int32 index, System.Int32 count)

Encodes the specified binary bytes as BinHex and writes the resulting text.

Parameter buffer: A System.Byte array containing the bytes to encode.

Parameter index: A System.Int32 specifying the position within the array of the first byte to encode.

Parameter count: A System.Int32 specifying the number of bytes to encode.

Throws: : buffer is null.

Throws: : The buffer length minus index is less than count.

Throws: : index or count is less than zero.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

For information on BinHex encoding, see RFC 1741 (http://www.ietf.org/rfc/rfc1741). As described above. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.Void WriteCData(System.String text)

Writes out a CDATA block containing the specified text.

Parameter text: A System.String specifying the text to place inside the CDATA block.

Throws: : The text would result in a non-well formed XML document.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

This method writes <![CDATA[ text ]]>. If text is null or System.String.Empty, this method writes an empty CDATA block, <![CDATA[]]>. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.Void WriteCharEntity(System.Char ch)

Forces the generation of a character entity for the specified Unicode character value.

Parameter ch: The System.Char for which to generate the entity.

Throws: : The character is in the surrogate pair character range, 0xd800 - 0xdfff, or the text would result in a non-well formed XML document.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

This method forces the generation of a character entity for the specified Unicode character value and writes the Unicode character in hexadecimal character entity reference format. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.Void WriteChars(System.Char[] buffer, System.Int32 index, System.Int32 count)

Writes text a buffer at a time.

Parameter buffer: A System.Char array containing the text to write.

Parameter index: A System.Int32 specifying the position within the array of the start of the text to write.

Parameter count: A System.Int32 specifying the number of characters to write.

Throws: : buffer is null.

Throws: : The buffer length minus index is less than count.

Throws: : index or count is less than zero.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

As described above. When overriding this method, throw an exception if surrogate pair characters would be split across multiple buffer writes. This exception must be caught in order to continue writing the next surrogate pair characters. The XML specification defines the valid ranges for surrogate pairs.

public System.Void WriteComment(System.String text)

Writes a comment containing the specified text.

Parameter text: A System.String containing the text to place inside the comment.

Throws: : The text would result in a non-well formed XML document.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

This method writes <!-- text -->. If text is null or System.String.Empty, this method writes a comment with no content, <!---->. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.Void WriteDocType(System.String name, System.String pubid, System.String sysid, System.String subset)

Writes the document type declaration with the specified name and optional attributes.

Parameter name: A System.String specifying the name of the document type.

Parameter pubid: A System.String specifying the public identifier, which is an alternative to the system identifier.

Parameter sysid: A System.String specifying the system identifier, which is the URI of the DTD (document type definition) for the document.

Parameter subset: A System.String specifying a URI that contains markup declarations.

Throws: : name is null or System.String.Empty. -or- The value for name would result in invalid XML.

Throws: : This method was called outside the prolog (after the root element).

This method writes the document type declaration with the specified name and optional attributes. The optional attributes, pubid, sysid, and subset, are not checked for invalid characters. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.Void WriteElementString(System.String localName, System.String ns, System.String value)

Writes an element with the specified local name, namespace URI, and value.

Parameter localName: A System.String specifying the local name of the element.

Parameter ns: A System.String specifying the namespace URI to associate with the element.

Parameter value: A System.String specifying the value of the element.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

This method calls the following methods to write a complete element: System.Xml.XmlWriter.WriteStartElement(System.String,System.String)(localName, ns) System.Xml.XmlWriter.WriteString(System.String)(value) - this method is not called if value is either null or System.String.Empty System.Xml.XmlWriter.WriteEndElement() If any of the input parameters are null or System.String.Empty, the element is written with that parameter missing.

public System.Void WriteElementString(System.String localName, System.String value)

Writes an element with the specified local name and value.

Parameter localName: A System.String specifying the local name of the element.

Parameter value: A System.String specifying the value of the element.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

This method is equivalent to System.Xml.XmlWriter.WriteElementString(System.String,System.String)(localName, null, value).

public System.Void WriteEndAttribute()

Closes the attribute started with the System.Xml.XmlWriter.WriteStartAttribute(System.String,System.String) method.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

As described above. Override the System.Xml.XmlWriter.WriteStartAttribute(System.String,System.String), System.Xml.XmlWriter.WriteAttributeString(System.String,System.String,System.String), and System.Xml.XmlWriter.WriteEndElement methods so these methods also close any attributes that are open when they are called.

public System.Void WriteEndDocument()

Closes open elements and attributes and sets the System.Xml.XmlWriter.WriteState back to the System.Xml.WriteState.Start state.

Throws: : The current instance is in the wrong System.Xml.WriteState, or the document does not have a root element.

This method closes all elements and attributes created by the System.Xml.XmlWriter.WriteStartElement(System.String,System.String) and System.Xml.XmlWriter.WriteStartAttribute(System.String,System.String) methods, respectively, that are open when the System.Xml.XmlWriter.WriteEndDocument method is called. This method must be overridden in order to provide the functionality as described herein, as there is no default implementation. After calling this method, the current instance can be used to write a new XML document.

public System.Void WriteEndElement()

Closes an open element and pops the corresponding namespace scope.

Throws: : No element was open, or the System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

This method closes one element and pops the corresponding namespace scope. If the open element does not contain content, it is closed as an empty element using " />"; otherwise an end element is written. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.Void WriteEntityRef(System.String name)

Writes an entity reference with the specified name.

Parameter name: A System.String specifying the name of the entity reference.

Throws: : name is either null or System.String.Empty.

This method writes % name ;. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.Void WriteFullEndElement()

Closes an open element and pops the corresponding namespace scope.

Throws: : No element was open, or the System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

This method closes one element and pops the corresponding namespace scope. This method writes an end element regardless of whether there is any content in the element. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.Void WriteName(System.String name)

Writes the specified name, ensuring it is a valid name according to the W3C XML 1.0 recommendation (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).

Parameter name: A System.String specifying the name to write.

Throws: : name is null or System.String.Empty; or name is not a valid XML Name.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

This method writes the specified name, ensuring it is a valid name according to the W3C XML 1.0 recommendation. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.Void WriteNmToken(System.String name)

Writes the specified name, ensuring it is a valid name token (Nmtoken) according to the W3C XML 1.0 recommendation (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).

Parameter name: A System.String specifying the name to write.

Throws: : name is null or System.String.Empty; or name is not a valid XML Nmtoken.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

As described above. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public virtual System.Void WriteNode(System.Xml.XmlReader reader, System.Boolean defattr)

Writes the node found at the current position of the specified System.Xml.XmlReader, and all sub-nodes.

Parameter reader: A System.Xml.XmlReader from which to copy the attributes.

Parameter defattr: A System.Boolean where true specifies to copy the default attributes from reader; otherwise, false.

Throws: : reader is null.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

After the nodes are read, reader is moved to the next node at the same depth as the current node. If reader is in the System.Xml.ReadState.Initial System.Xml.XmlReader.ReadState, this method moves reader to the end of the stream. If reader is in the System.Xml.ReadState.EndOfFile System.Xml.XmlReader.ReadState, this method is non-operational. Override this method to customize the behavior of this method in types derived from the System.Xml.XmlWriter class. Use this method to write the node found at the current position and all sub-nodes.

Example:

The following example uses a System.Xml.XmlTextReader and a System.Xml.XmlTextWriter to copy an XML file, specified in the command line, to the console.

using System;
using System.Xml;

public class Copier {

  public static void Main(string[] args) {

    XmlTextReader xtReader = new XmlTextReader(args[0]);
    XmlTextWriter xtWriter =
      new XmlTextWriter(Console.Out);
    xtWriter.WriteNode(xtReader, false);
    xtWriter.Close();
    xtReader.Close();
  }
}

public System.Void WriteProcessingInstruction(System.String name, System.String text)

Writes a processing instruction with the specified name and text.

Parameter name: A System.String specifying the name of the processing instruction.

Parameter text: A System.String specifying the text to include in the processing instruction.

Throws: : The text would result in a non-well formed XML document. - or - name is null or System.String.Empty. - or - This method is being used to create an XML declaration after System.Xml.XmlWriter.WriteStartDocument has already been called.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

This method writes <? name text ?>. If text is null or System.String.Empty, this method writes a processing instruction with no text content, <? name ?>. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.Void WriteQualifiedName(System.String localName, System.String ns)

Writes the qualified name.

Parameter localName: A System.String specifying the local name to write.

Parameter ns: A System.String specifying the namespace URI to associate with localname.

Throws: : localName is null or System.String.Empty.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

Throws: : localName is not a valid XML name.

This method writes the qualified name. If ns maps to the current default namespace, no prefix is generated. When writing attribute values, this method generates a prefix if ns is not found. When writing element content, it throws an exception if ns is not found. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.Void WriteRaw(System.Char[] buffer, System.Int32 index, System.Int32 count)

Writes raw text from a character array.

Parameter buffer: A System.Char array containing the text to write.

Parameter index: A System.Int32 specifying the position within the array of the start of the text to write.

Parameter count: A System.Int32 specifying the number of characters to write.

Throws: : buffer is null.

Throws: : The buffer length minus index is less than count.

Throws: : index or count is less than zero.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

This method writes raw text from a character array. This method does not encode any characters. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.Void WriteRaw(System.String data)

Writes raw text from a string.

Parameter data: A System.String specifying the text to write.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

This method writes raw text from a string. This method does not encode any characters. If data is null, System.String.Empty is written. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.Void WriteStartAttribute(System.String prefix, System.String localName, System.String ns)

Writes the start of an attribute with the specified prefix and name, and associates the prefix with the specified namespace URI.

Parameter prefix: A System.String specifying the namespace prefix of the attribute.

Parameter localName: A System.String specifying the local name of the attribute.

Parameter ns: A System.String specifying the namespace URI associated with the attribute.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

If any of the input parameters are null or System.String.Empty, the start attribute is written with that parameter missing. When overriding this method, close any open attributes before writing the new attribute.

public System.Void WriteStartAttribute(System.String localName, System.String ns)

Writes the start of an attribute.

Parameter localName: A System.String specifying the local name of the attribute.

Parameter ns: A System.String specifying the namespace URI of the attribute.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

This method calls System.Xml.XmlWriter.WriteStartAttribute(System.String,System.String)(null, localName, ns).

public System.Void WriteStartDocument(System.Boolean standalone)

Writes the XML declaration with the version "1.0" and the standalone attribute.

Parameter standalone: A System.Boolean where true indicates to write "standalone= yes"; false indicates to write "standalone=no".

Throws: : The System.Xml.XmlWriter.WriteState is not System.Xml.WriteState.Start.

Character encoding is set when the class in instantiated. As described above. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.Void WriteStartDocument()

Writes the XML declaration with the version "1.0" and no standalone attribute.

Throws: : The System.Xml.XmlWriter.WriteState is not System.Xml.WriteState.Start.

Character encoding is set when the class in instantiated. As described above. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.Void WriteStartElement(System.String localName)

Writes a start element with the specified name.

Parameter localName: A System.String specifying the local name of the element.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

This method calls System.Xml.XmlWriter.WriteStartElement(System.String,System.String)(null, localName, null).

public System.Void WriteStartElement(System.String localName, System.String ns)

Writes a start element with the specified name, and associates it with the given namespace.

Parameter localName: A System.String specifying the local name of the element.

Parameter ns: A System.String specifying the namespace URI to associate with the element.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

This method calls System.Xml.XmlWriter.WriteStartElement(System.String,System.String)(null, localName, ns).

public System.Void WriteStartElement(System.String prefix, System.String localName, System.String ns)

Writes a start element with the specified name, and associates it with the given namespace and prefix.

Parameter prefix: A System.String specifying the namespace prefix of the element.

Parameter localName: A System.String specifying the local name of the element.

Parameter ns: A System.String specifying the namespace URI to associate with the element.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

This method writes a start element and name, and associates it with a namespace and prefix. If the namespace is already in scope and has an associated prefix, that prefix is automatically written also. If any of the input parameters are null or System.String.Empty, the start element is written with that parameter missing. When overriding this method, also override the System.Xml.XmlWriter.WriteEndElement, System.Xml.XmlWriter.WriteString(System.String), and System.Xml.XmlWriter.WriteRaw(System.Char[],System.Int32,System.Int32) methods so they close any open start element. Use this method to write a specified start element and name, and associate it with a given namespace and prefix. Write any attributes using the System.Xml.XmlWriter.WriteStartAttribute(System.String,System.String), System.Xml.XmlWriter.WriteString(System.String), and System.Xml.XmlWriter.WriteEndAttribute methods, then close the element using the System.Xml.XmlWriter.WriteEndElement method.

public System.Void WriteString(System.String text)

Writes the specified text.

Parameter text: A System.String specifying the text to write.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

This method performs the following conversions before writing the text: If text is null or System.String.Empty, this method writes a text node with no data content. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.Void WriteSurrogateCharEntity(System.Char lowChar, System.Char highChar)

Generates and writes the surrogate character entity for the surrogate character pair.

Parameter lowChar: A System.Char containing the low surrogate. This must be a value between 0xDC00 and 0xDFFF.

Parameter highChar: A System.Char containing the high surrogate. This must be a value between 0xD800 and 0xDBFF.

Throws: : An invalid surrogate character pair was passed.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

Applications encode DOM strings using UTF-16. For both HTML and XML, the document character set (and therefore the notation of numeric character references) is based on UCS [ISO-10646]. A single numeric character reference in a source document may therefore in some cases correspond to two 16-bit units in a DOM string (a high surrogate and a low surrogate). These 16-bit units are referred to as a surrogate pair. For more information regarding surrogates or characters, refer to section 3.7 of the Unicode 3.0/Unicode 2.0 standard located at http://www.unicode.org, or section 2.2 of the W3C XML 1.0 Recommendation located at http://www.w3.org/TR/REC-xml#charsets. This method generates and writes the surrogate character entity for a surrogate character pair. The surrogate character entity is written in hexadecimal format. The range for surrogate characters is #x10000 to #x10FFFF. The following formula is used to generate the surrogate character entity: ( highChar - 0xD800) * 0x400 + ( lowChar - 0xDC00) + 0x10000. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

public System.Void WriteWhitespace(System.String ws)

Writes the given white space.

Parameter ws: A System.String containing the white space characters.

Throws: : ws is null or System.String.Empty or contains non-white space characters.

Throws: : The System.Xml.XmlWriter.WriteState is System.Xml.WriteState.Closed.

As described above. This method must be overridden in order to provide the functionality described above, as there is no default implementation.

Functions inherited from System.Object:

public virtual System.Boolean Equals(System.Object obj)

Determines whether the specified System.Object is equal to the current instance.

Parameter obj: The System.Object to compare with the current instance.

Returns: true if obj is equal to the current instance; otherwise, false.

The statements listed below are required to be true for all implementations of the System.Object.Equals(System.Object) method. In the list, x, y, and z represent non-null object references. See System.Object.GetHashCode for additional required behaviors pertaining to the System.Object.Equals(System.Object) method. Implementations of System.Object.Equals(System.Object) should not throw exceptions. The System.Object.Equals(System.Object) method tests for referential equality , which means that System.Object.Equals(System.Object) returns true if the specified instance of Object and the current instance are the same instance; otherwise, it returns false . An implementation of the System.Object.Equals(System.Object) method is shown in the following C# code: public virtual bool Equals(Object obj) { return this == obj; } For some kinds of objects, it is desirable to have System.Object.Equals(System.Object) test for value equality instead of referential equality. Such implementations of Equals return true if the two objects have the same "value", even if they are not the same instance. The definition of what constitutes an object's "value" is up to the implementer of the type, but it is typically some or all of the data stored in the instance variables of the object. For example, the value of a System.String is based on the characters of the string; the Equals method of the System.String class returns true for any two string instances that contain exactly the same characters in the same order. When the Equals method of a base class provides value equality, an override of Equals in a class derived from that base class should invoke the inherited implementation of Equals . It is recommended (but not required) that types overriding System.Object.Equals(System.Object) also override System.Object.GetHashCode. Hashtables cannot be relied on to work correctly if this recommendation is not followed. If your programming language supports operator overloading, and if you choose to overload the equality operator for a given type, that type should override the Equals method. Such implementations of the Equals method should return the same results as the equality operator. Following this guideline will help ensure that class library code using Equals (such as System.Collections.ArrayList and System.Collections.Hashtable ) behaves in a manner that is consistent with the way the equality operator is used by application code. If you are implementing a value type, you should follow these guidelines: For reference types, the guidelines are as follows: If you implement System.IComparable on a given type, you should override Equals on that type. The System.Object.Equals(System.Object) method is called by methods in collections classes that perform search operations, including the System.Array.IndexOf(System.Array,System.Object) method and the System.Collections.ArrayList.Contains(System.Object) method.

Example:

Example 1:

The following example contains two calls to the default implementation of System.Object.Equals(System.Object) .

using System;
class MyClass {
   static void Main() {
      Object obj1 = new Object();
      Object obj2 = new Object();
      Console.WriteLine(obj1.Equals(obj2));
      obj1 = obj2; 
      Console.WriteLine(obj1.Equals(obj2)); 
   }
}

The output is

False

True

Example 2:

The following example shows a Point class that overrides the System.Object.Equals(System.Object) method to provide value equality and a class Point3D, which is derived from Point . Because Point's override of System.Object.Equals(System.Object) is the first in the inheritance chain to introduce value equality, the Equals method of the base class (which is inherited from System.Object and checks for referential equality) is not invoked. However, Point3D.Equals invokes Point.Equals because Point implements Equals in a manner that provides value equality.

using System;
public class Point: object {
 int x, y;
 public override bool Equals(Object obj) {
 //Check for null and compare run-time types.
 if (obj == null || GetType() != obj.GetType()) return false;
 Point p = (Point)obj;
 return (x == p.x) && (y == p.y);
 }
 public override int GetHashCode() {
 return x ^ y;
 }
}

class Point3D: Point {
 int z;
 public override bool Equals(Object obj) {
 return base.Equals(obj) && z == ((Point3D)obj).z;
 }
 public override int GetHashCode() {
 return base.GetHashCode() ^ z;
 }
}

The Point.Equals method checks that the obj argument is non-null and that it references an instance of the same type as this object. If either of those checks fail, the method returns false. The System.Object.Equals(System.Object) method uses System.Object.GetType to determine whether the run-time types of the two objects are identical. (Note that typeof is not used here because it returns the static type.) If instead the method had used a check of the form

<doc:param name="obj"/>
is Point , the check would return true in cases where obj is an instance of a subclass of Point , even though obj and the current instance are not of the same runtime type. Having verified that both objects are of the same type, the method casts obj to type Point and returns the result of comparing the instance variables of the two objects.

In Point3D.Equals , the inherited Equals method is invoked before anything else is done; the inherited Equals method checks to see that obj is non-null, that obj is an instance of the same class as this object, and that the inherited instance variables match. Only when the inherited Equals returns true does the method compare the instance variables introduced in the subclass. Specifically, the cast to Point3D is not executed unless obj has been determined to be of type Point3D or a subclass of Point3D .

Example 3:

In the previous example, operator == (the equality operator) is used to compare the individual instance variables. In some cases, it is appropriate to use the System.Object.Equals(System.Object) method to compare instance variables in an Equals implementation, as shown in the following example:

using System;
class Rectangle {
 Point a, b;
 public override bool Equals(Object obj) {
 if (obj == null || GetType() != obj.GetType()) return false;
 Rectangle r = (Rectangle)obj;
 //Use Equals to compare instance variables
 return a.Equals(r.a) && b.Equals(r.b);
 }
 public override int GetHashCode() {
 return a.GetHashCode() ^ b.GetHashCode();
 }
}

Example 4:

In some languages, such as C#, operator overloading is supported. When a type overloads operator ==, it should also override the System.Object.Equals(System.Object) method to provide the same functionality. This is typically accomplished by writing the Equals method in terms of the overloaded operator ==. For example:

using System;
public struct Complex {
 double re, im;
 public override bool Equals(Object obj) {
 return obj is Complex && this == (Complex)obj;
 }
 public override int GetHashCode() {
 return re.GetHashCode() ^ im.GetHashCode();
 }
 public static bool operator ==(Complex x, Complex y) {
 return x.re == y.re && x.im == y.im;
 }
 public static bool operator !=(Complex x, Complex y) {
 return !(x == y);
 }
}

Because Complex is a C# struct (a value type), it is known that there will be no subclasses of Complex . Therefore, the System.Object.Equals(System.Object) method need not compare the GetType() results for each object, but can instead use the is operator to check the type of the obj parameter.

public static System.Boolean Equals(System.Object objA, System.Object objB)

Determines whether two object references are equal.

Parameter objA: First object to compare.

Parameter objB: Second object to compare.

Returns: true if one or more of the following statements is true: otherwise returns false.

This static method checks for null references before it calls objA.Equals(objB ) and returns false if either objA or objB is null. If the Equals(object obj) implementation throws an exception, this method throws an exception.

Example:

The following example demonstrates the System.Object.Equals(System.Object) method.

using System;

public class MyClass {
   public static void Main() {
   string s1 = "Tom";
   string s2 = "Carol";
   Console.WriteLine("Object.Equals(\"{0}\", \"{1}\") => {2}", 
      s1, s2, Object.Equals(s1, s2));

   s1 = "Tom";
   s2 = "Tom";
   Console.WriteLine("Object.Equals(\"{0}\", \"{1}\") => {2}", 
      s1, s2, Object.Equals(s1, s2));

   s1 = null;
   s2 = "Tom";
   Console.WriteLine("Object.Equals(null, \"{1}\") => {2}",
       s1, s2, Object.Equals(s1, s2));

   s1 = "Carol";
   s2 = null;
   Console.WriteLine("Object.Equals(\"{0}\", null) => {2}", 
       s1, s2, Object.Equals(s1, s2));

   s1 = null;
   s2 = null;
   Console.WriteLine("Object.Equals(null, null) => {2}", 
       s1, s2, Object.Equals(s1, s2));
   }
}
   

The output is

Object.Equals("Tom", "Carol") => False

Object.Equals("Tom", "Tom") => True

Object.Equals(null, "Tom") => False

Object.Equals("Carol", null) => False

Object.Equals(null, null) => True

public System.Void Finalize()

Allows a System.Object to perform cleanup operations before the memory allocated for the System.Object is automatically reclaimed.

During execution, System.Object.Finalize is automatically called after an object becomes inaccessible, unless the object has been exempted from finalization by a call to System.GC.SuppressFinalize(System.Object). During shutdown of an application domain, System.Object.Finalize is automatically called on objects that are not exempt from finalization, even those that are still accessible. System.Object.Finalize is automatically called only once on a given instance, unless the object is re-registered using a mechanism such as System.GC.ReRegisterForFinalize(System.Object) and System.GC.SuppressFinalize(System.Object) has not been subsequently called. Conforming implementations of the CLI are required to make every effort to ensure that for every object that has not been exempted from finalization, the System.Object.Finalize method is called after the object becomes inaccessible. However, there may be some circumstances under which Finalize is not called. Conforming CLI implementations are required to explicitly specify the conditions under which Finalize is not guaranteed to be called. For example, Finalize might not be guaranteed to be called in the event of equipment failure, power failure, or other catastrophic system failures. In addition to System.GC.ReRegisterForFinalize(System.Object) and System.GC.SuppressFinalize(System.Object), conforming implementations of the CLI are allowed to provide other mechanisms that affect the behavior of System.Object.Finalize . Any mechanisms provided are required to be specified by the CLI implementation. The order in which the Finalize methods of two objects are run is unspecified, even if one object refers to the other. The thread on which Finalize is run is unspecified. Every implementation of System.Object.Finalize in a derived type is required to call its base type's implementation of Finalize . This is the only case in which application code calls System.Object.Finalize . The System.Object.Finalize implementation does nothing. A type should implement Finalize when it uses unmanaged resources such as file handles or database connections that must be released when the managed object that uses them is reclaimed. Because Finalize methods may be invoked in any order (including from multiple threads), synchronization may be necessary if the Finalize method may interact with other objects, whether accessible or not. Furthermore, since the order in which Finalize is called is unspecified, implementers of Finalize (or of destructors implemented through overriding Finalize) must take care to correctly handle references to other objects, as their Finalize method may already have been invoked. In general, referenced objects should not be considered valid during finalization. See the System.IDisposable interface for an alternate means of disposing of resources. For C# developers: Destructors are the C# mechanism for performing cleanup operations. Destructors provide appropriate safeguards, such as automatically calling the base type's destructor. In C# code, System.Object.Finalize cannot be called or overridden.

public virtual System.Int32 GetHashCode()

Generates a hash code for the current instance.

Returns: A System.Int32 containing the hash code for the current instance.

System.Object.GetHashCode serves as a hash function for a specific type. A hash function is used to quickly generate a number (a hash code) corresponding to the value of an object. Hash functions are used with hashtables. A good hash function algorithm rarely generates hash codes that collide. For more information about hash functions, see The Art of Computer Programming , Vol. 3, by Donald E. Knuth. All implementations of System.Object.GetHashCode are required to ensure that for any two object references x and y, if x.Equals(y) == true, then x.GetHashCode() == y.GetHashCode(). Hash codes generated by System.Object.GetHashCode need not be unique. Implementations of System.Object.GetHashCode are not permitted to throw exceptions. The System.Object.GetHashCode implementation attempts to produce a unique hash code for every object, but the hash codes generated by this method are not guaranteed to be unique. Therefore, System.Object.GetHashCode may generate the same hash code for two different instances. It is recommended (but not required) that types overriding System.Object.GetHashCode also override System.Object.Equals(System.Object) . Hashtables cannot be relied on to work correctly if this recommendation is not followed. Use this method to obtain the hash code of an object. Hash codes should not be persisted (i.e. in a database or file) as they are allowed to change from run to run.

Example:

Example 1

In some cases, System.Object.GetHashCode is implemented to simply return an integer value. The following example illustrates an implementation of System.Int32.GetHashCode , which returns an integer value:

using System;
public struct Int32 {
 int value;
 //other methods...

 public override int GetHashCode() {
 return value;
 }
}

Example 2

Frequently, a type has multiple data members that can participate in generating the hash code. One way to generate a hash code is to combine these fields using an xor (exclusive or) operation, as shown in the following example:

using System;
public struct Point {
 int x;
 int y; 
 //other methods
 
 public override int GetHashCode() {
 return x ^ y;
 }
}

Example 3

The following example illustrates another case where the type's fields are combined using xor (exclusive or) to generate the hash code. Notice that in this example, the fields represent user-defined types, each of which implements System.Object.GetHashCode (and should implement System.Object.Equals(System.Object) as well):

using System;
public class SomeType {
 public override int GetHashCode() {
 return 0;
 }
}

public class AnotherType {
 public override int GetHashCode() {
 return 1;
 }
}

public class LastType {
 public override int GetHashCode() {
 return 2;
 }
}
public class MyClass {
 SomeType a = new SomeType();
 AnotherType b = new AnotherType();
 LastType c = new LastType();

 public override int GetHashCode () {
 return a.GetHashCode() ^ b.GetHashCode() ^ c.GetHashCode();
 }
}

Avoid implementing System.Object.GetHashCode in a manner that results in circular references. In other words, if AClass.GetHashCode calls BClass.GetHashCode, it should not be the case that BClass.GetHashCode calls AClass.GetHashCode.

Example 4

In some cases, the data member of the class in which you are implementing System.Object.GetHashCode is bigger than a System.Int32. In such cases, you could combine the high order bits of the value with the low order bits using an XOR operation, as shown in the following example:

using System;
public struct Int64 {
 long value;
 //other methods...

 public override int GetHashCode() {
 return ((int)value ^ (int)(value >> 32));
 }
}

public System.Type GetType()

Gets the type of the current instance.

Returns: The instance of System.Type that represents the run-time type (the exact type) of the current instance.

For two objects x and y that have identical run-time types, System.Object.ReferenceEquals(System.Object,System.Object)(x.GetType(),y.GetType()) returns true .

Example:

The following example demonstrates the fact that System.Object.GetType returns the run-time type of the current instance:

using System;
public class MyBaseClass: Object {
}
public class MyDerivedClass: MyBaseClass {
}
public class Test {
   public static void Main() {
   MyBaseClass myBase = new MyBaseClass();
   MyDerivedClass myDerived = new MyDerivedClass();

   object o = myDerived;
   MyBaseClass b = myDerived;

   Console.WriteLine("mybase: Type is {0}", myBase.GetType());
   Console.WriteLine("myDerived: Type is {0}", myDerived.GetType());
   Console.WriteLine("object o = myDerived: Type is {0}", o.GetType());
   Console.WriteLine("MyBaseClass b = myDerived: Type is {0}", b.GetType());
   }
}

The output is

mybase: Type is MyBaseClass

myDerived: Type is MyDerivedClass

object o = myDerived: Type is MyDerivedClass

MyBaseClass b = myDerived: Type is MyDerivedClass

protected System.Object MemberwiseClone()

Creates a shallow copy of the current instance.

Returns: A shallow copy of the current instance. The run-time type (the exact type) of the returned object is the same as the run-time type of the object that was copied.

System.Object.MemberwiseClone creates a new instance of the same type as the current instance and then copies each of the object's non-static fields in a manner that depends on whether the field is a value type or a reference type. If the field is a value type, a bit-by-bit copy of all the field's bits is performed. If the field is a reference type, only the reference is copied. The algorithm for performing a shallow copy is as follows (in pseudo-code): for each instance field f in this instance if (f is a value type) bitwise copy the field if (f is a reference type) copy the reference end for loop This mechanism is referred to as a shallow copy because it copies rather than clones the non-static fields. Because System.Object.MemberwiseClone implements the above algorithm, for any object, a, the following statements are required to be true: System.Object.MemberwiseClone does not call any of the type's constructors. If System.Object.Equals(System.Object) has been overridden, a.MemberwiseClone().Equals(a) might return false . For an alternate copying mechanism, see System.ICloneable . System.Object.MemberwiseClone is protected (rather than public) to ensure that from verifiable code it is only possible to clone objects of the same class as the one performing the operation (or one of its subclasses). Although cloning an object does not directly open security holes, it does allow an object to be created without running any of its constructors. Since these constructors may establish important invariants, objects created by cloning may not have these invariants established, and this may lead to incorrect program behavior. For example, a constructor might add the new object to a linked list of all objects of this class, and cloning the object would not add the new object to that list -- thus operations that relied on the list to locate all instances would fail to notice the cloned object. By making the method protected, only objects of the same class (or a subclass) can produce a clone and implementers of those classes are (presumably) aware of the appropriate invariants and can arrange for them to be true without necessarily calling a constructor.

Example:

The following example shows a class called MyClass as well as a representation of the instance of MyClass returned by System.Object.MemberwiseClone .

using System;
class MyBaseClass {
   public static string CompanyName = "My Company";
   public int age;
   public string name;
}

class MyDerivedClass: MyBaseClass {

   static void Main() {
   
   //Create an instance of MyDerivedClass
   //and assign values to its fields.
   MyDerivedClass m1 = new MyDerivedClass();
   m1.age = 42;
   m1.name = "Sam";

   //Do a shallow copy of m1
   //and assign it to m2.
   MyDerivedClass m2 = (MyDerivedClass) m1.MemberwiseClone();
   }
}

A graphical representation of m1 and m2 might look like this


+---------------+

|     42        |                           m1 

+---------------+

|     +---------|-----------------> "Sam" 

+---------------+                    /|\ 

                                      | 

+---------------+                     | 

|     42        |                     |      m2 

+---------------+                     | 

|      +--------|---------------------| 

+---------------+

public static System.Boolean ReferenceEquals(System.Object objA, System.Object objB)

Determines whether two object references are identical.

Parameter objA: First object to compare.

Parameter objB: Second object to compare.

Returns: True if a and b refer to the same object or are both null references; otherwise, false.

This static method provides a way to compare two objects for reference equality. It does not call any user-defined code, including overrides of System.Object.Equals(System.Object) .

Example:

using System;
class MyClass {
   static void Main() {
   object o = null;
   object p = null;
   object q = new Object();
   Console.WriteLine(Object.ReferenceEquals(o, p));
   p = q;
   Console.WriteLine(Object.ReferenceEquals(p, q));
   Console.WriteLine(Object.ReferenceEquals(o, p));
   }
}
   

The output is

True

True

False

public virtual System.String ToString()

Creates and returns a System.String representation of the current instance.

Returns: A System.String representation of the current instance.

System.Object.ToString returns a string whose content is intended to be understood by humans. Where the object contains culture-sensitive data, the string representation returned by System.Object.ToString takes into account the current system culture. For example, for an instance of the System.Double class whose value is zero, the implementation of System.Double.ToString might return "0.00" or "0,00" depending on the current UI culture. Although there are no exact requirements for the format of the returned string, it should as much as possible reflect the value of the object as perceived by the user. System.Object.ToString is equivalent to calling System.Object.GetType to obtain the System.Type object for the current instance and then returning the result of calling the System.Object.ToString implementation for that type. The value returned includes the full name of the type. It is recommended, but not required, that System.Object.ToString be overridden in a derived class to return values that are meaningful for that type. For example, the base data types, such as System.Int32, implement System.Object.ToString so that it returns the string form of the value the object represents. Subclasses that require more control over the formatting of strings than System.Object.ToString provides should implement System.IFormattable, whose System.Object.ToString method uses the culture of the current thread.

Example:

The following example outputs the textual description of the value of an object of type System.Object to the console.

using System;

class MyClass {
   static void Main() {
      object o = new object();
      Console.WriteLine (o.ToString());
   }
}
      

The output is

System.Object