This is a mirror of official site: http://jasper-net.blogspot.com/

Everybody thinks about CLR objects the wrong way (well not everybody)

| Wednesday, August 11, 2010
Many people responded to Everybody thinks about garbage collection the wrong way by proposing variations on auto-disposal based on scope:

"Any local variable that is IDisposable should dispose itself when it goes out of scope."
"You should be able to attach an attribute to a class that says the destructor should be called immediately after leaving scope."
"It should have promised to call finalizers on scope exit."
What these people fail to recognize is that they are dealing with object references, not objects. (I'm restricting the discussion to reference types, naturally.) In C++, you can put an object in a local variable. In the CLR, you can only put an object reference in a local variable.

For those who think in terms of C++, imagine if it were impossible to declare instances of C++ classes as local variables on the stack. Instead, you had to declare a local variable that was a pointer to your C++ class, and put the object in the pointer.

C#C++
void Function(OtherClass o) { // No longer possible to declare objects // with automatic storage duration Color c(0,0,0); Brush b(c); o.SetBackground(b); }
void Function(OtherClass o) { Color c = new Color(0,0,0); Brush b = new Brush(c); o.SetBackground(b); }
void Function(OtherClass* o) { Color* c = new Color(0,0,0); Brush* b = new Brush(c); o->SetBackground(b); }

This world where you can only use pointers to refer to objects is the world of the CLR.


Read more: The old new thing

Posted via email from .NET Info

0 comments: