public class AnswerModel: IDisposable
{
private bool disposedValue;
public string Answer { get; set; }
public string CodeSnippet { get; set; }
public string AnswerBy { get; set; }
public DateTime DatePosted { get; set; }
public string TimeStatus { get; set; }
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects)
}
// TODO: free unmanaged resources (unmanaged objects) and override finalizer
// TODO: set large fields to null
disposedValue = true;
}
}
// // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
~AnswerModel()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: false);
}
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
using (AnswerModel a = new AnswerModel())
{
a.Answer = answer.Answered;
a.AnswerBy = answer.AnswerBy;
a.DatePosted = answer.DatePosted;
a.CodeSnippet = answer.CodeSnippet;
answerModel.Add(a);
}
How to dispose the variables in the AnswerModel instance?
Does it happen by itself?
CodePudding user response:
C# is a memory managed language. Objects created on the heap will get garbage collected automatically when there is no reference to the object and a GC cycle occurs (GC = garbage collector).
However there are some object that use resources outside the managed memory, For example File Streams, Web Connections or Database connection. They implement an interface called IDisposable
with a function called Dispose()
, that you can call when you finish using the resource.
In addition ~Object()
Finalizers
are not good practice, because you don't know exactly when the GC frees the object, and it can create a load that you cannot control.
In conclusion you should implement IDisposable
when your object uses outside resources that need to be Disposed
, so you can free the resource when you don't need them anymore.