I am following MSDN guideline of implementing a Dispose Method. I’ve written my simple code to better understand and run the code step by step.
EDITED: changed title to better fit the problem
This is the code:
class Program {
static void Main(string[] args) {
Base0 base0 = new Base0();
base0.Dispose();
Console.WriteLine();
Sub1 sub1 = new Sub1();
sub1.Dispose();
Console.ReadLine();
}
}
class Base0 : IDisposable {
private bool disposed;
public Base0() {
Console.WriteLine("Creating Base0!");
this.disposed = false;
// allocating some resources
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) {
Console.WriteLine("Disposing " + this.GetType().ToString() + "!");
if (!this.disposed) {
if (disposing) {
// disposing all managed resources
}
// disposing all unmanaged resources
}
}
public void DoSomething() {
if (this.disposed) {
throw new ObjectDisposedException(this.GetType().ToString());
}
}
~Base0() {
Dispose(false);
}
}
class Sub1 : Base0 {
private bool disposed;
public Sub1() {
Console.WriteLine("Creating Sub1!");
this.disposed = false;
// allocating some resources
}
protected override void Dispose(bool disposing) {
Console.WriteLine("Disposing " + this.GetType().ToString() + "!");
if (!this.disposed) {
try {
if (disposing) {
// disposing all managed resources
}
// disposing all unmanaged resources
}
finally {
base.Dispose(disposing);
}
}
}
}
This is the output:
Creating Base0!
Disposing DisposeFinalizeMethods.Base0!
Creating Base0!
Creating Sub1!
Disposing DisposeFinalizeMethods.Sub1!
Disposing DisposeFinalizeMethods.Sub1!
I am confused because I expected that the last line would be saying “Diposing … Base0!”, the base type.
The code executes as it should, I’ve checked it ‘step by step’ many times, I understand it but there is something that I’ve missed. What am I missing?
OK, this is not about Dispose or IDisposable but about GetType.
this.GetType()is a call to a virtual method. When called in a base-class it will give the Type of the actual (derived) type.To reproduce:
Will print
BB.