extends System.IO.Stream
extends System.IDisposable
| Variables: |
|---|
public System.Boolean CanRead |
public System.Boolean CanSeek |
public System.Boolean CanWrite |
public virtual System.Int32 Capacity |
public System.Int64 Length |
public System.Int64 Position |
| Constructors: |
|---|
public System.IO.MemoryStream(System.Byte[] buffer, System.Int32 index, System.Int32 count, System.Boolean writable, System.Boolean publiclyVisible) Constructs and initializes a new instance of the System.IO.MemoryStream class. Parameter buffer: The System.Byte array from which to create the new stream. Parameter index: A System.Int32 that specifies the index into buffer at which the stream begins. Parameter count: A System.Int32 that specifies the length of the stream in bytes. Parameter writable: A System.Boolean that specifies whether the new stream instance supports writing. Parameter publiclyVisible: A System.Boolean that specifies whether buffer is exposed via the System.IO.MemoryStream.GetBuffer, which returns the System.Byte array from which the stream was created. Specify true to expose buffer; otherwise, specify false. Throws: : buffer is null. Throws: : index or count is negative. Throws: : (index + count ) is greater than the length of buffer. The System.IO.MemoryStream.CanRead and System.IO.MemoryStream.CanSeek properties of the new System.IO.MemoryStream instance are set to true. The System.IO.MemoryStream.Capacity property is set to count. The System.IO.Stream.CanWrite property is set to writable. The new stream instance can be written to, but the System.IO.MemoryStream.Capacity of the underlying System.Byte array cannot be changed. The length of the stream cannot be set to a value larger than System.IO.MemoryStream.Capacity, but the stream can be truncated (see System.IO.MemoryStream.SetLength(System.Int64)). |
public System.IO.MemoryStream(System.Byte[] buffer, System.Int32 index, System.Int32 count, System.Boolean writable) Constructs and initializes a new non-resizable instance of the System.IO.MemoryStream class. Parameter buffer: The System.Byte array from which to create the new stream. Parameter index: A System.Int32 that specifies the index in buffer at which the stream begins. Parameter count: A System.Int32 that specifies the length of the stream in bytes. Parameter writable: A System.Boolean that specifies whether the new stream instance supports writing. Throws: : buffer is null. Throws: : index or count are negative. Throws: : (index + count ) is greater than the length of buffer. The System.IO.MemoryStream.CanRead and System.IO.MemoryStream.CanSeek properties of the new System.IO.MemoryStream are set to true. The System.IO.MemoryStream.Capacity property is set to count. The System.IO.Stream.CanWrite property is set to writable. The new stream instance can be written to, but the System.IO.MemoryStream.Capacity of the underlying byte array cannot be changed. The length of the stream cannot be set to a value larger than System.IO.MemoryStream.Capacity, but the stream can be truncated (see System.IO.MemoryStream.SetLength(System.Int64)). The new stream does not expose the underlying byte buffer, and calls to the System.IO.MemoryStream.GetBuffer method throw System.UnauthorizedAccessException. |
public System.IO.MemoryStream() Constructs and initializes a new resizable instance of the System.IO.MemoryStream class. The System.IO.Stream.CanRead, System.IO.Stream.CanSeek, and System.IO.Stream.CanWrite properties of the new instance of the System.IO.MemoryStream class are set to true. The capacity of the new stream instance can be increased by using the System.IO.MemoryStream.SetLength(System.Int64) method or by setting the System.IO.MemoryStream.Capacity property. The new stream exposes the underlying byte buffer, which can be accessed through the System.IO.MemoryStream.GetBuffer method. |
public System.IO.MemoryStream(System.Int32 capacity) Constructs and initializes a new resizable instance of the System.IO.MemoryStream class. Parameter capacity: A System.Int32 that specifies the initial size of the internal System.Byte array. Throws: : capacity is negative. The System.IO.Stream.CanRead, System.IO.Stream.CanSeek, and System.IO.Stream.CanWrite properties of the new instance of the System.IO.MemoryStream class are set to true. The System.IO.MemoryStream.Capacity of the new stream instance is set to capacity can be increased by using the System.IO.MemoryStream.SetLength(System.Int64) method Write operations at the end of the new instance of the System.IO.MemoryStream class expand the System.IO.MemoryStream. The new stream exposes the underlying byte buffer, which can be accessed through the System.IO.MemoryStream.GetBuffer method. |
public System.IO.MemoryStream(System.Byte[] buffer) Constructs and initializes a new non-resizable instance of the System.IO.MemoryStream class. Parameter buffer: The System.Byte array from which to create the new stream. Throws: : The buffer parameter is null. The System.IO.Stream.CanRead, System.IO.Stream.CanSeek, and System.IO.Stream.CanWrite properties of the new instance of the System.IO.MemoryStream class are set to true. System.IO.MemoryStream.Capacity is set to the length of the specified System.Byte array. The new stream instance can be written to, but the System.IO.MemoryStream.Capacity of the underlying System.Byte array cannot be changed. The length of the stream cannot be set to a value greater than System.IO.MemoryStream.Capacity , but the stream can be truncated (see System.IO.MemoryStream.SetLength(System.Int64)). The new stream does not expose the underlying byte buffer, and calls to the System.IO.MemoryStream.GetBuffer method throw System.UnauthorizedAccessException. |
public System.IO.MemoryStream(System.Byte[] buffer, System.Boolean writable) Constructs and initializes a new non-resizable instance of the System.IO.MemoryStream class. Parameter buffer: The System.Byte array from which to create the new stream. Parameter writable: A System.Boolean that specifies whether the new stream instance supports writing. Throws: : buffer is null. The System.IO.Stream.CanRead and System.IO.Stream.CanSeek properties of the new instance of the System.IO.MemoryStream class are set to true. The System.IO.MemoryStream.Capacity property is set to the length of the specified System.Byte array. The System.IO.Stream.CanWrite property is set to writable . The new stream instance can be written to, but the System.IO.MemoryStream.Capacity of the underlying System.Byte array cannot be changed. The length of the stream cannot be set to a value larger than System.IO.MemoryStream.Capacity, but the stream can be truncated (see System.IO.MemoryStream.SetLength(System.Int64)). The new stream does not expose the underlying System.Byte buffer, and calls to the System.IO.MemoryStream.GetBuffer method throw System.UnauthorizedAccessException. |
public System.IO.MemoryStream(System.Byte[] buffer, System.Int32 index, System.Int32 count) Constructs and initializes a new non-resizable instance of the System.IO.MemoryStream class. Parameter buffer: The System.Byte array from which to create the new stream. Parameter index: A System.Int32 that specifies the index into buffer at which the stream begins. Parameter count: A System.Int32 that specifies the length of the stream in bytes. Throws: : buffer is null. Throws: : index or count is less than zero. Throws: : (index + count ) is greater than the length of buffer. The System.IO.Stream.CanRead, System.IO.Stream.CanSeek, and System.IO.Stream.CanWrite properties of the new System.IO.MemoryStream instance are set to true. The System.IO.MemoryStream.Capacity property is set to count . The new stream instance can be written to, but the System.IO.MemoryStream.Capacity of the underlying System.Byte array cannot be changed. The length of the stream cannot be set to a value larger than System.IO.MemoryStream.Capacity, but the stream can be truncated (see System.IO.MemoryStream.SetLength(System.Int64)). The new stream does not expose the underlying System.Byte buffer, and calls to the System.IO.MemoryStream.GetBuffer method throw System.UnauthorizedAccessException . |
| Functions: |
|---|
public System.Void Close() Closes the current System.IO.MemoryStream instance. The stream will not support reading or writing after this method is invoked. Following a call to System.IO.MemoryStream.Close , operations on the stream can raise an exception. The buffer of a closed System.IO.MemoryStream is still available, and the System.IO.MemoryStream.ToArray and System.IO.MemoryStream.GetBuffer methods can be called successfully. This method overrides System.IO.Stream.Close . |
public System.Void Flush() Overrides System.IO.Stream.Flush so that no action is performed. Since any data written to a System.IO.MemoryStream is written into RAM, this method is redundant. This method overrides System.IO.Stream.Flush. |
public virtual System.Byte[] GetBuffer() Returns the array of unsigned bytes from which this stream was created. Returns: The System.Byte array from which the current stream was created, or the underlying array if a System.Byte array was not provided to the System.IO.MemoryStream constructor during construction of the current instance. Throws: : The current instance was not created with a publicly visible buffer. To create a System.IO.MemoryStream instance with a publicly visible buffer use the default constructor, or System.IO.MemoryStream( System.Byte [], System.Int32, System.Int32, System.Boolean, System.Boolean) or System.IO.MemoryStream(System.Int32 ) constructor. If the current stream is resizable, multiple calls to this method do not return the same array if the underlying System.Byte array is resized between calls. For additional information, see System.IO.MemoryStream.Capacity . This method works when the System.IO.MemoryStream is closed. As described above. Example: The following example demonstrates that two calls to the System.IO.MemoryStream.GetBuffer method on a resizable stream do not return the same array if the underlying byte array is reallocated. using System;
using System.IO;
public class MemoryStreamTest {
public static void Main() {
MemoryStream ms = new MemoryStream(10);
byte[] a = ms.GetBuffer();
byte[] b = ms.GetBuffer();
//Force reallocation of the underlying byte array.
ms.Capacity = 10240;
byte[] c = ms.GetBuffer();
if(Object.ReferenceEquals(a, b))
Console.WriteLine("a and b represent the same instance.");
else
Console.WriteLine("a and b represent the different instances.");
if(Object.ReferenceEquals(a, c))
Console.WriteLine("a and c represent the same instance.");
else
Console.WriteLine("a and c represent the different instances.");
}
}
The output is a and b represent the same instance. a and c represent the different instances. |
public System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count) Reads a block of bytes from the current stream at the current position, and writes the data to the specified byte array. Parameter buffer: A System.Byte array. When this method returns, contains the specified byte array with the values between offset and (offset + count - 1) replaced by the characters read from the current stream. Parameter offset: A System.Int32 that specifies the byte offset in buffer at which to begin writing. Parameter count: A System.Int32 that specifies the maximum number of bytes to read. Returns: A System.Int32 that specifies the total number of bytes read into the buffer, or zero if the end of the stream is reached before any bytes are read. Throws: : buffer is null. Throws: : offset or count is negative. Throws: : (offset + count ) is larger than the length of buffer. Throws: : The current stream is closed. If the read operation is successful, the current position within the stream advances by the number of bytes read. If an exception occurs, the current position within the stream remains unchanged. If the byte array specified in the buffer parameter is the underlying buffer returned by the System.IO.MemoryStream.GetBuffer method, the array contents are overwritten, and no exception is thrown. This method overrides System.IO.Stream.Read(System.Byte[],System.Int32,System.Int32). Example: The following example demonstrates the result of reading from a System.IO.MemoryStream into its underlying byte array. using System;
using System.IO;
public class MemoryStreamTest {
public static void Main() {
byte[] values = new byte [] {0,1,2,3,4,5,6,7,8,9};
foreach (byte b in values) {
Console.Write(b);
}
Console.WriteLine();
MemoryStream ms = new MemoryStream (values);
ms.Read(values, 1, 5);
foreach (byte b in values) {
Console.Write(b);
}
}
}
The output is 0123456789 0012346789 |
public System.Int32 ReadByte() Reads a byte from the current stream at the current position. Returns: The byte cast to a System.Int32, or -1 if the end of the stream has been reached. Throws: : The current stream is closed. If the read operation is successful, the current position within the stream is advanced by one byte. If an exception occurs, the current position within the stream is unchanged. This method overrides System.IO.Stream.ReadByte. |
public System.Int64 Seek(System.Int64 offset, System.IO.SeekOrigin loc) Sets the current position within the current stream to the specified value. Parameter offset: A System.Int64 that specifies the new position within the stream. This is relative to the loc parameter, and may be positive or negative. Parameter loc: A System.IO.SeekOrigin value that specifies the seek reference point. Returns: A System.Int64 containing the new position within the stream, calculated by combining the seek reference point and the offset. Throws: : Seeking is attempted before the beginning or more than one byte beyond the end of the stream. Throws: : offset is greater than the maximum length of the System.IO.MemoryStream. Throws: : loc is not a valid System.IO.SeekOrigin value. Throws: : The current stream is closed. The position cannot be set to more than one byte beyond the end of the stream. This method overrides System.IO.Stream.Seek(System.Int64,System.IO.SeekOrigin). |
public System.Void SetLength(System.Int64 value) Sets the length of the current stream to the specified value. Parameter value: A System.Int64 that specifies the value at which to set the length. Throws: : The current stream is not resizable and value is greater than the current System.IO.MemoryStream.Capacity. -or- The current stream does not support writing. Throws: : value is negative or is greater than the maximum length of the System.IO.MemoryStream, where the maximum length is (System.Int32.MaxValue - origin), and origin is the index into the underlying buffer at which the stream starts. If the specified value is less than the current length of the stream, the stream is truncated. If after the truncation the current position within the stream is past the end of the stream, the System.IO.MemoryStream.ReadByte method returns -1, the System.IO.MemoryStream.Read(System.Byte[],System.Int32,System.Int32) method reads zero bytes into the provided byte array, and System.IO.MemoryStream.Write(System.Byte[],System.Int32,System.Int32) and System.IO.MemoryStream.WriteByte(System.Byte) methods append specified bytes at the end of the stream, increasing its length. If the specified value is larger than the current capacity and the stream is resizable, the capacity is increased, and the current position within the stream is unchanged. If the length is increased, the contents of the stream between the old and the new length are initialized to zeros. A System.IO.MemoryStream instance must support writing for this method to work. Use the System.IO.MemoryStream.CanWrite property to determine whether the current instance supports writing. For additional information, see System.IO.Stream.CanWrite . This method overrides System.IO.Stream.SetLength(System.Int64). |
public virtual System.Byte[] ToArray() Writes the entire stream contents to a System.Byte array, regardless of the current position within the stream. Returns: A new System.Byte array. This method returns a copy of the contents of the System.IO.MemoryStream as a byte array. If the current instance was constructed on a provided byte array, a copy of the section of the array to which the current instance has access is returned. For additional information, see the System.IO.MemoryStream (System.Byte[], System.Int32, System.Int32 ) constructor. This method works when the System.IO.MemoryStream is closed. As described above. |
public System.Void Write(System.Byte[] buffer, System.Int32 offset, System.Int32 count) Writes a block of bytes to the current stream at the current position using data read from buffer. Parameter buffer: The System.Byte array to write data from. Parameter offset: A System.Int32 that specifies the zero based byte offset into buffer at which to begin writing from. Parameter count: A System.Int32 that specifies the maximum number of bytes to write from buffer. Throws: : buffer is null. Throws: : The current stream does not support writing. -or- The current position is closer than count bytes to the end of the stream, and the capacity cannot be modified. Throws: : (offset + count ) is greater than the length of buffer. Throws: : offset or count are negative. Throws: : An I/O error occurred. Throws: : The current stream is closed. If the write operation is successful, the current position within the stream is advanced by the number of bytes written. If an exception occurs, the current position within the stream is unchanged. Write operations at the end of a resizable System.IO.MemoryStream expand the System.IO.MemoryStream. Use the System.IO.MemoryStream.CanWrite method to determine whether the current stream supports writing. This method overrides System.IO.Stream.Write(System.Byte[],System.Int32,System.Int32). |
public System.Void WriteByte(System.Byte value) Writes a System.Byte to the current stream at the current position. Parameter value: The System.Byte to write. Throws: : The current stream is closed. Throws: : The current stream does not support writing. -or- The current position is at the end of the stream, and the stream's capacity cannot be modified. Write operations at the end of a resizable System.IO.MemoryStream expand the System.IO.MemoryStream. If the write operation is successful, the current position within the stream is advanced by one byte. If an exception occurs, the position is unchanged. Use the System.IO.MemoryStream.CanWrite method to determine whether the current stream supports writing. This method overrides System.IO.Stream.WriteByte(System.Byte). |
public virtual System.Void WriteTo(System.IO.Stream stream) Writes the entire contents of the current System.IO.MemoryStream instance to a specified stream. Parameter stream: The System.IO.Stream to write the current memory stream to. Throws: : stream is null. Throws: : The current or target stream is closed. When the current stream is open, this method is equivalent to calling System.IO.Stream.Write(System.Byte[],System.Int32,System.Int32) and passing in the underlying buffer of the current instance. As described above. |
| Functions inherited from System.IO.Stream: |
|---|
public virtual System.IAsyncResult BeginRead(System.Byte[] buffer, System.Int32 offset, System.Int32 count, System.AsyncCallback callback, System.Object state) Begins an asynchronous read operation. Parameter buffer: The System.Byte array to read the data into. Parameter offset: A System.Int32 that specifies the byte offset in buffer at which to begin writing data read from the stream. Parameter count: A System.Int32 that specifies the maximum number of bytes to read from the stream. Parameter callback: A System.AsyncCallback delegate to be called when the read is complete, or null. Parameter state: An application-defined object, or null. Returns: A System.IAsyncResult that contains information about the asynchronous read operation, which could still be pending. Throws: : An I/O error occurred. Throws: : The current System.IO.Stream does not support reading. This method starts an asynchronous read operation. To determine how many bytes were read and release resources allocated by this method, call the System.IO.Stream.EndRead(System.IAsyncResult) method and specify the System.IAsyncResult object returned by this method. The System.IO.Stream.EndRead(System.IAsyncResult) method should be called exactly once for each call to System.IO.Stream.BeginRead(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object). If the callback parameter is not null, the method referenced by callback is invoked when the asynchronous operation completes. The System.IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The current position in the stream is updated when the asynchronous read or write is issued, not when the I/O operation completes. Multiple simultaneous asynchronous requests render the request completion order uncertain. The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method. Use the System.IO.Stream.CanRead property to determine whether the current instance supports reading. As described above. |
public virtual System.IAsyncResult BeginWrite(System.Byte[] buffer, System.Int32 offset, System.Int32 count, System.AsyncCallback callback, System.Object state) Begins an asynchronous write operation. Parameter buffer: The System.Byte array to be written to the current stream. Parameter offset: A System.Int32 that specifies the byte offset in buffer at which to begin copying bytes to the current stream. Parameter count: A System.Int32 that specifies the maximum number of bytes to be written to the current stream. Parameter callback: A System.AsyncCallback delegate to be called when the write is complete, or null. Parameter state: An application-defined object, or null. Returns: A System.IAsyncResult that represents the asynchronous write, which could still be pending. Throws: : The current System.IO.Stream does not support writing. Throws: : An I/O error occurred. Pass the System.IAsyncResult returned by this method to System.IO.Stream.EndWrite(System.IAsyncResult) to ensure that the write completes and frees resources appropriately. If an error occurs during an asynchronous write, an exception will not be thrown until System.IO.Stream.EndWrite(System.IAsyncResult) is called with the System.IAsyncResult returned by this method. If a failure is detected from the underlying OS (such as if a floppy is ejected in the middle of the operation), the results of the write operation are undefined. If the callback parameter is not null, the method referenced by callback is invoked when the asynchronous operation completes. The System.IAsyncResult object returned by this method is passed as the argument to the method referenced by callback. The state parameter can be any object that the caller wishes to have available for the duration of the asynchronous operation. This object is available via the System.IAsyncResult.AsyncState property of the object returned by this method. If a stream is writable, writing at the end of it expands the stream. The current position in the stream is updated when you issue the asynchronous read or write, not when the I/O operation completes. Multiple simultaneous asynchronous requests render the request completion order uncertain. buffer should generally be greater than 64 KB. Use the System.IO.Stream.CanWrite property to determine whether the current instance supports writing. As described above. |
public virtual System.Void Close() Closes the current stream and releases any resources associated with the current stream. Following a call to this method, other operations on the stream might throw exceptions. If the stream is already closed, a call to System.IO.Stream.Close throws no exceptions. If this method is called while an asynchronous read or write is pending for a stream, the behavior of the stream is undefined. As described above. |
protected virtual System.Threading.WaitHandle CreateWaitHandle() Allocates a System.Threading.WaitHandle object. Returns: A reference to the allocated System.Threading.WaitHandle. When called for the first time this method creates a System.Threading.WaitHandle object and returns it. On subsequent calls, the System.IO.Stream.CreateWaitHandle method returns a reference to the same wait handle. System.IO.Stream.CreateWaitHandle is useful if you implement the asynchronous methods and require a way of blocking in System.IO.Stream.EndRead(System.IAsyncResult) or System.IO.Stream.EndWrite(System.IAsyncResult) until the asynchronous operation is complete. |
public virtual System.Int32 EndRead(System.IAsyncResult asyncResult) Ends a pending asynchronous read request. Parameter asyncResult: The System.IAsyncResult object that references the pending asynchronous read request. Returns: A System.Int32 that indicates the number of bytes read from the stream, between 0 and the number of bytes specified via the System.IO.Stream.BeginRead(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object) count parameter. Streams only return 0 at the end of the stream, otherwise, they block until at least 1 byte is available. Throws: : asyncResult is null. Throws: : asyncResult did not originate from a System.IO.Stream.BeginRead(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object) method on the current stream. System.IO.Stream.EndRead(System.IAsyncResult) blocks until the I/O operation has completed. As described above. |
public virtual System.Void EndWrite(System.IAsyncResult asyncResult) Ends an asynchronous write operation. Parameter asyncResult: A System.IAsyncResult that references the outstanding asynchronous I/O request. Throws: : The asyncResult parameter is null. Throws: : asyncResult did not originate from a System.IO.Stream.BeginWrite(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object) method on the current stream. System.IO.Stream.EndWrite(System.IAsyncResult) is required to be called exactly once for every System.IO.Stream.BeginWrite(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object). System.IO.Stream.EndWrite(System.IAsyncResult) blocks until the write I/O operation has completed. As described above. |
public System.Void Flush() Flushes the internal buffer. Throws: : An I/O error occurs, such as the file being already closed. Implementers should use this method to move any information from an underlying buffer to its destination. The System.IO.Stream.Flush method should clear the buffer, but the stream should not be closed. Depending upon the state of the object, the current position within the stream might need to be modified (for example, if the underlying stream supports seeking). For additional information see System.IO.Stream.CanSeek . As described above. Override System.IO.Stream.Flush on streams that implement a buffer. |
public System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count) Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. Parameter buffer: A System.Byte array. When this method returns, the elements between offset and (offset + count - 1) are replaced by the bytes read from the current source. Parameter offset: A System.Int32 that specifies the zero based byte offset in buffer at which to begin storing the data read from the current stream. Parameter count: A System.Int32 that specifies the maximum number of bytes to be read from the current stream. Returns: A System.Int32 that specifies the total number of bytes read into the buffer, or zero if the end of the stream has been reached before any data can be read. Throws: : (offset + count - 1) is greater than the length of buffer. Throws: : buffer is null. Throws: : offset or count is less than zero. Throws: : An I/O error occurred. Throws: : The current stream does not support reading. Use the System.IO.Stream.CanRead property to determine whether the current instance supports reading. As described above. |
public virtual System.Int32 ReadByte() Reads a byte from the stream and advances the position within the stream by one byte. Returns: The unsigned byte cast to a System.Int32 , or -1 if at the end of the stream. Throws: : The stream does not support reading. Throws: : The stream is closed. Throws: : An I/O error has occurred. As described above. Use the System.IO.Stream.CanRead property to determine whether the current instance supports reading. |
public System.Int64 Seek(System.Int64 offset, System.IO.SeekOrigin origin) Sets the position within the current stream. Parameter offset: A System.Int64 that specifies the byte offset relative to origin. Parameter origin: A System.IO.SeekOrigin value indicating the reference point used to obtain the new position. Returns: A System.Int64 that specifies the new position within the current stream. Throws: : The stream does not support seeking, such as if the stream is constructed from a pipe or console output. Throws: : The current System.IO.Stream is closed. Throws: : An I/O error has occurred. Use the System.IO.Stream.CanSeek property to determine whether the current instance supports seeking. If offset is negative, the new position is required to precede the position specified by origin by the number of bytes specified by offset. If offset is zero, the new position is required to be the position specified by origin. If offset is positive, the new position is required to follow the position specified by origin by the number of bytes specified by offset. If you intend to use a file as a backing store for a stream implementation, you are required to override System.IO.Stream.Seek(System.Int64,System.IO.SeekOrigin) to set the System.IO.Stream.Position property one byte beyond the end of the stream. The position cannot be set to more than one byte beyond the end of the stream. Classes derived from System.IO.Stream that support seeking are required to override this method. |
public System.Void SetLength(System.Int64 value) Sets the length of the current stream. Parameter value: A System.Int64 that specifies the desired length of the current stream in bytes. Throws: : The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. Throws: : The current System.IO.Stream is closed. Throws: : An I/O error occurred. Use the System.IO.Stream.CanWrite property to determine whether the current instance supports writing, and the System.IO.Stream.CanSeek property to determine whether seeking is supported. If the specified value is less than the current length of the stream, the stream is truncated. If the specified value is larger than the current length of the stream, the stream is expanded. If the stream is expanded, the contents of the stream between the old and the new length are initialized to zeros. There is no default implementation. Classes derived from System.IO.Stream are required to support both writing and seeking for System.IO.Stream.SetLength(System.Int64) to work. |
public System.Void System.IDisposable.Dispose() Implemented to support the System.IDisposable interface. [Note: For more information, see System.IDisposable.Dispose.] |
public System.Void Write(System.Byte[] buffer, System.Int32 offset, System.Int32 count) Writes a sequence of bytes to the current stream and advances the current position within the current stream by the number of bytes written. Parameter buffer: A System.Byte array containing the data to write. Parameter offset: A System.Int32 that specifies the zero based byte offset in buffer at which to begin copying bytes to the current stream. Parameter count: A System.Int32 that specifies the number of bytes to be written to the current stream. Throws: : (offset + count ) is greater than the length of buffer. Throws: : buffer is null. Throws: : offset or count is negative. Throws: : An I/O error occurred. Throws: : The stream does not support writing. Use the System.IO.Stream.CanWrite property to determine whether the current instance supports writing. If the write operation is successful, the position within the stream advances by the number of bytes written. If an exception occurs, the position within the stream remains unchanged. |
public virtual System.Void WriteByte(System.Byte value) Writes a System.Byte to the current position in the stream and advances the position within the stream by one byte. Parameter value: The System.Byte to write to the stream. Throws: : The stream does not support writing. Throws: : The stream is closed. Throws: : An I/O error has occurred. Use the System.IO.Stream.CanWrite property to determine whether the current instance supports writing. As described above. |
| Functions inherited from System.MarshalByRefObject: |
|---|
| 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
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 |
| Functions inherited from System.IDisposable: |
|---|
public System.Void Dispose() Performs application-defined tasks associated with freeing or resetting resources. This method is, by convention, used for all tasks associated with freeing resources held by an object, or preparing an object for reuse. When implementing the System.IDisposable.Dispose method, objects should seek to ensure that all held resources are freed by propagating the call through the containment hierarchy. For example, if an object A allocates an object B, and B allocates an object C, then A's System.IDisposable.Dispose implementation should call System.IDisposable.Dispose on B, which should in turn call System.IDisposable.Dispose on C. Objects should also call the System.IDisposable.Dispose method of their base class if the base class implements System.IDisposable. If an object's System.IDisposable.Dispose method is called more than once, the object should ignore all calls after the first one. The object should not throw an exception if its System.IDisposable.Dispose method is called multiple times. System.IDisposable.Dispose may throw an exception if an error occurs because a resource has already been freed and System.IDisposable.Dispose had not been called previously. A resource type may use a particular convention to denote an allocated state versus a freed state. An example of this is stream classes, which are traditionally thought of as open or closed. Classes that have such conventions may choose to implement a public method with a customized name, which calls the System.IDisposable.Dispose method. Because the System.IDisposable.Dispose method must be called explicitly, objects that implement System.IDisposable should also implement a finalizer to handle freeing resources when System.IDisposable.Dispose is not called. By default, the garbage collector will automatically call an object's finalizer prior to reclaiming its memory. However, once the System.IDisposable.Dispose method has been called, it is typically unnecessary and/or undesirable for the garbage collector to call the disposed object's finalizer. To prevent automatic finalization, System.IDisposable.Dispose implementations can call System.GC.SuppressFinalize(System.Object). For additional information on implementing finalizers, see System.GC and System.Object.Finalize. Example: Resource classes should follow the pattern illustrated by this example: class ResourceWrapper : BaseType, IDisposable {
// Pointer to a external resource.
private int handle;
private OtherResource otherRes; //Other resource you use.
private bool disposed = false;
public ResourceWrapper () {
handle = //Allocate on the unmanaged side.
otherRes = new OtherResource (...);
}
// Free your own state.
private void freeState () {
if (!disposed) {
CloseHandle (handle);
dispose = true;
}
}
// Free your own state, call dispose on all state you hold,
// and take yourself off the Finalization queue.
public void Dispose () {
freeState ();
OtherRes.Dispose();
// If base type implements dispose, call it.
base.Dispose();
GC.SuppressFinalize(this);
}
// Free your own state (not other state you hold)
// and give your base class a chance to finalize.
~ResourceWrapper (){
freeState();
}
}
|
| Functions inherited from System.IDisposable: |
|---|
public System.Void Dispose() Performs application-defined tasks associated with freeing or resetting resources. This method is, by convention, used for all tasks associated with freeing resources held by an object, or preparing an object for reuse. When implementing the System.IDisposable.Dispose method, objects should seek to ensure that all held resources are freed by propagating the call through the containment hierarchy. For example, if an object A allocates an object B, and B allocates an object C, then A's System.IDisposable.Dispose implementation should call System.IDisposable.Dispose on B, which should in turn call System.IDisposable.Dispose on C. Objects should also call the System.IDisposable.Dispose method of their base class if the base class implements System.IDisposable. If an object's System.IDisposable.Dispose method is called more than once, the object should ignore all calls after the first one. The object should not throw an exception if its System.IDisposable.Dispose method is called multiple times. System.IDisposable.Dispose may throw an exception if an error occurs because a resource has already been freed and System.IDisposable.Dispose had not been called previously. A resource type may use a particular convention to denote an allocated state versus a freed state. An example of this is stream classes, which are traditionally thought of as open or closed. Classes that have such conventions may choose to implement a public method with a customized name, which calls the System.IDisposable.Dispose method. Because the System.IDisposable.Dispose method must be called explicitly, objects that implement System.IDisposable should also implement a finalizer to handle freeing resources when System.IDisposable.Dispose is not called. By default, the garbage collector will automatically call an object's finalizer prior to reclaiming its memory. However, once the System.IDisposable.Dispose method has been called, it is typically unnecessary and/or undesirable for the garbage collector to call the disposed object's finalizer. To prevent automatic finalization, System.IDisposable.Dispose implementations can call System.GC.SuppressFinalize(System.Object). For additional information on implementing finalizers, see System.GC and System.Object.Finalize. Example: Resource classes should follow the pattern illustrated by this example: class ResourceWrapper : BaseType, IDisposable {
// Pointer to a external resource.
private int handle;
private OtherResource otherRes; //Other resource you use.
private bool disposed = false;
public ResourceWrapper () {
handle = //Allocate on the unmanaged side.
otherRes = new OtherResource (...);
}
// Free your own state.
private void freeState () {
if (!disposed) {
CloseHandle (handle);
dispose = true;
}
}
// Free your own state, call dispose on all state you hold,
// and take yourself off the Finalization queue.
public void Dispose () {
freeState ();
OtherRes.Dispose();
// If base type implements dispose, call it.
base.Dispose();
GC.SuppressFinalize(this);
}
// Free your own state (not other state you hold)
// and give your base class a chance to finalize.
~ResourceWrapper (){
freeState();
}
}
|