Should I always implement the dispose pattern if my class defines a field in which the field type implements the delete pattern? WITH#

I recently read this in Jeffrey Richter's "CLR via C #";

Important If a class defines a field in which field types are specified that implements the dispose pattern, the class itself must also implement the layout pattern. The Dispose method must recycle the object referenced by the field. This allows someone to use the class to call Recycle on it, which in turn frees up resources used by the object itself.

Will this be true in the following example?

public class SomeClass
{
    private readonly StreamReader _reader; //a disposable class

    public SomeClass(StreamReader reader)
    {
        _reader = reader;
    }
}

StreamReader , intance , , , - , IDisposable SomeClass, _reader , . , , ?

+4
2

StreamReader , , , , - IDisposable SomeClass

. , IDisposable, . , - , , , , :

public class SomeClass : IDisposable
{
    private readonly StreamReader _reader; //a disposable class
    private bool shouldDispose;

    public SomeClass(StreamReader reader) : this(reader, true)
    {
    }

    public SomeClass(StreamReader reader, bool shouldDispose)
    {
        _reader = reader;
        this.shouldDispose = shouldDispose;
    }

    public void Dispose()
    {
        if (shouldDispose)
        {
            Dispose(true);
        }
    }

    protected void Dispose(bool isDisposing)
    {
        if (isDisposing)
        {
            _reader.Dispose();
        }
    }
}
+2

, "" . , , .

public class DbSomething : IDisposable
{
    private SqlConnection _connection;

    public DbSomething (SqlConnection connection){
       _connection = connection;
    }

~DbSomething() {
     Dispose(true);
}
bool disposed = false;

public void Dispose()
{ 
   Dispose(true);
   GC.SuppressFinalize(this);           
}


protected virtual void Dispose(bool disposing)
{
  if (disposed)
     return; 

  if (disposing) 
  {
     _connection.Dispose();
  }
  disposed = true;
 }
}

, IDisposable , , - ? , .

,

public class DbSomething : IDisposable
{
    private SqlConnection _connection;

    public DbSomething (){
       _connection = new SqlConnection();
    }

    //same dispose
}

SqlConnection. , . , , SqlConnection ?

public class DbSomething
{
    public SqlConnection Connection;

    public DbSomething (){
       Connection = new SqlConnection();
    }

   //same dispose  
}

, , , . factory , , . , , , , , .

, , :

public class DbSomething
{
   public SqlConnection CreateSqlConnection () => return new SqlConnection();
}
+1

Source: https://habr.com/ru/post/1653331/


All Articles