I'm getting in nerve between dispose and finalize. Here is my example code:
public class Car:IDisposable
{
public string name;
public Car()
{
name = "My Car";
}
public void Dispose()
{
Console.WriteLine("This object has been disposed");
}
}
public static void Main()
{
Car anotherCar;
using (var car = new Car())
{
anotherCar = car;
Console.WriteLine("Before dispose. Name is: "+anotherCar.name);
}
Console.WriteLine("After dispose. Name is: "+anotherCar.name);
}
The result is:
Before dispose. Name is My Car
This object has been disposed
After dispose. Name is My Car
My question is : because C# will automatically dispose object after using{}
, so I think at line "After dispose". anotherCar.name
must be NULL. why it still be "My Car" ?
And my another question is : my book said that you shouldn't use GC.Collect()
for some reason and one of these is Performance. So, who dispose object ? If that is Garbage Collector,too so I think dipose()
has the same performance issues with finalizer()
Thanks :)