Call Dispose on anything
-
PIEBALDconsult wrote:
I dislike language features that rely on the framework
would that include "string literals" which get easily created, initialized and interned? :)
Luc Pattyn
I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages
Local announcement (Antwerp region): Lange Wapper? 59.24% waren verstandig genoeg om NEEN te stemmen; bye bye viaduct.
string
is a C# keyword, it is required by the language. In the implementation of C# for .net thestring
type is backed by theSystem.String
type. I (well maybe not me, but someone) could implement the C# language for some other platform (OpenVMS perhaps). Such an implementation may not require that string be backed bySystem.String
, the language doesn't demand it. In .net, theusing
statement relies on the existence of anSystem.IDisposable
interface. I feel that this is too tightly coupled. Were I to write my own implementation of C# I would not want to have to have anSystem.IDisposable
interface, the language shouldn't demand it, it's not a keyword. Were I to write my own implementation of C# I would allow theusing
statement to operate on any type. -
PIEBALDconsult wrote:
On the other hand, I don't think it's supposed to work this way.
Extension methods are, from what I understand, an ugly kludge which serves mainly to make Intellisense more useful, at the expense of introducing all sorts of potential weird bugs. If I had my druthers, compilers would support extension classes rather than extension methods; from a run-time perspective, objects of an extension class would in reality be objects of the underlying class; from a compiler perspective, they would be interchangeable, but the extension classes would support extension methods and properties in addition to the methods and properties of the underlying class. Failing that, the Intellisense usefulness of extension classes would be achieved by making it so that typing "object.extensionMethod(" would be automatically rearranged to "extensionMethod(object," so as to make clear what was actually happening.
supercat9 wrote:
Extension methods are, from what I understand, an ugly kludge
Hear hear! And poorly implemented too. X|
-
supercat9 wrote:
I don't see any reason "using" shouldn't work even when it's superfluous
Indeed. My feeling is that either
object
should implement IDisposable ( X| ) or theusing
statement shouldn't rely on the IDisposable interface. In fact I dislike language features that rely on the framework.PIEBALDconsult wrote:
My feeling is that either object should implement IDisposable ( Dead )
Why the face? Because you think that would have been a good solution, or because you think it unfortunate that Object includes no such feature? Personally, I think Dispose would have been a better "standard" feature for an object than Finalize. Implementation of the standard dispose pattern requires that an object have a finalizer--even if it doesn't actually do anything--if derived classes may require non-null finalizers. Requiring that classes which implement finalizers must explicitly register them could eliminate that problem.
-
PIEBALDconsult wrote:
My feeling is that either object should implement IDisposable ( Dead )
Why the face? Because you think that would have been a good solution, or because you think it unfortunate that Object includes no such feature? Personally, I think Dispose would have been a better "standard" feature for an object than Finalize. Implementation of the standard dispose pattern requires that an object have a finalizer--even if it doesn't actually do anything--if derived classes may require non-null finalizers. Requiring that classes which implement finalizers must explicitly register them could eliminate that problem.
Because I feel that not requiring the IDisposable interface is a cleaner solution.
-
string
is a C# keyword, it is required by the language. In the implementation of C# for .net thestring
type is backed by theSystem.String
type. I (well maybe not me, but someone) could implement the C# language for some other platform (OpenVMS perhaps). Such an implementation may not require that string be backed bySystem.String
, the language doesn't demand it. In .net, theusing
statement relies on the existence of anSystem.IDisposable
interface. I feel that this is too tightly coupled. Were I to write my own implementation of C# I would not want to have to have anSystem.IDisposable
interface, the language shouldn't demand it, it's not a keyword. Were I to write my own implementation of C# I would allow theusing
statement to operate on any type.PIEBALDconsult wrote:
may not require that string be backed by System.String
I do want an easy way to initialize and to assign a new literal value to a System.String object. string literals, the thing understood by compilers, does exactly that; so for me a string literal must be a System.String I would not want to write
string s=new string(new char[]{'H','e','l','l','o'};
!PIEBALDconsult wrote:
I would allow the using statement to operate on any type
I'm not sure I like the idea; I can see some advantage, but then I don't want code to start looking like this:
using (int i=new int())
using (int j=new int())
for (i=0; i<10; i++) {
for (j=0; j<10; j++) {
...
}
}PIEBALDconsult wrote:
the using statement relies on the existence of an System.IDisposable interface
and what would you do about
foreach
? it needs an array, or an IEnumerable or an IEnumerable<T>. I got used to it and wouldn't like to loose it. And just ignoring the code block for objects that are not enumerable (without a warning/error) seems inappropriate. :)Luc Pattyn
I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages
Local announcement (Antwerp region): Lange Wapper? 59.24% waren verstandig genoeg om NEEN te stemmen; bye bye viaduct.
modified on Monday, October 19, 2009 4:43 PM
-
PIEBALDconsult wrote:
My feeling is that either object should implement IDisposable ( Dead )
Why the face? Because you think that would have been a good solution, or because you think it unfortunate that Object includes no such feature? Personally, I think Dispose would have been a better "standard" feature for an object than Finalize. Implementation of the standard dispose pattern requires that an object have a finalizer--even if it doesn't actually do anything--if derived classes may require non-null finalizers. Requiring that classes which implement finalizers must explicitly register them could eliminate that problem.
supercat9 wrote:
Implementation of the standard dispose pattern requires that an object have a finalizer
Not true!! You only need (and only should have) a finalizer if you explicitly use unmanaged resources yourself. If you simply use a managed class that has unmanaged resources (eg: StreamWriter), you do NOT need a finalizer. The StreamWriter will have its own finalizer that will take care of its resources. Since Finalize is already a virtual method, there is no need to override it just to let derived classes override it.
-
PIEBALDconsult wrote:
may not require that string be backed by System.String
I do want an easy way to initialize and to assign a new literal value to a System.String object. string literals, the thing understood by compilers, does exactly that; so for me a string literal must be a System.String I would not want to write
string s=new string(new char[]{'H','e','l','l','o'};
!PIEBALDconsult wrote:
I would allow the using statement to operate on any type
I'm not sure I like the idea; I can see some advantage, but then I don't want code to start looking like this:
using (int i=new int())
using (int j=new int())
for (i=0; i<10; i++) {
for (j=0; j<10; j++) {
...
}
}PIEBALDconsult wrote:
the using statement relies on the existence of an System.IDisposable interface
and what would you do about
foreach
? it needs an array, or an IEnumerable or an IEnumerable<T>. I got used to it and wouldn't like to loose it. And just ignoring the code block for objects that are not enumerable (without a warning/error) seems inappropriate. :)Luc Pattyn
I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages
Local announcement (Antwerp region): Lange Wapper? 59.24% waren verstandig genoeg om NEEN te stemmen; bye bye viaduct.
modified on Monday, October 19, 2009 4:43 PM
Luc Pattyn wrote:
I would not want to write string s=new string(new char[]{'H','e','l','l','o'}; !
I don't see why you'd have to.
Luc Pattyn wrote:
foreach
Oh, yeah, that was the other one, but it should work too.
-
supercat9 wrote:
Implementation of the standard dispose pattern requires that an object have a finalizer
Not true!! You only need (and only should have) a finalizer if you explicitly use unmanaged resources yourself. If you simply use a managed class that has unmanaged resources (eg: StreamWriter), you do NOT need a finalizer. The StreamWriter will have its own finalizer that will take care of its resources. Since Finalize is already a virtual method, there is no need to override it just to let derived classes override it.
I thought that the accepted dispose pattern was to have a finalizer which does nothing but "Dispose(False)" and then have any derived classes override Dispose(Boolean). Is that not how stuff is supposed to happen? Or is the expectation that stuff will happen like that, but each derived class is supposed to override the finalizer with (potentially yet another) finalizer that simply calls Dispose(False)? In any case, I would tend to think that having objects register for finalization would be better than having it occur automatically. Many objects that use unmanaged resources won't necessarily acquire them until some time after they're created. An object with a finalizer could unregister itself for garbage collection in its initializer and then re-register if it's going to allocate some unmanaged resources, but that would seem a little clunky.
-
PIEBALDconsult wrote:
On the other hand, I don't think it's supposed to work this way.
Extension methods are, from what I understand, an ugly kludge which serves mainly to make Intellisense more useful, at the expense of introducing all sorts of potential weird bugs. If I had my druthers, compilers would support extension classes rather than extension methods; from a run-time perspective, objects of an extension class would in reality be objects of the underlying class; from a compiler perspective, they would be interchangeable, but the extension classes would support extension methods and properties in addition to the methods and properties of the underlying class. Failing that, the Intellisense usefulness of extension classes would be achieved by making it so that typing "object.extensionMethod(" would be automatically rearranged to "extensionMethod(object," so as to make clear what was actually happening.
supercat9 wrote:
Extension methods are, from what I understand, an ugly kludge which serves mainly to make Intellisense more useful, at the expense of introducing all sorts of potential weird bugs.
It's because, as you so well said, don't understand them! ;P
A train station is where the train stops. A bus station is where the bus stops. On my desk, I have a work station.... _________________________________________________________ My programs never have bugs, they just develop random features.
-
Hmmm... you're right, I didn't test it. I had originally written it with the test for IDisposable then removed it thinking it unnecessary. Ah well, it's not a serious piece of code anyway. On the other hand, I don't think it's supposed to work this way.
PIEBALDconsult wrote:
On the other hand, I don't think it's supposed to work this way.
The compiler of course has no run-time type information when generating the code. Hence, it depends on the declared type of a reference to know where to look for members. Since the point of this code was to add a dummy Dispose to types that do not have Dispose, the only possible match is the extension methods. Personally, I find extension methods to be largely fluff. There is absolutely nothing an extension method can achieve that cannot be achieved with traditional utility methods. Calling class methods using instance syntax is also somewhat confusing, and generally such features tend to be seen as "cool" and misused accordingly. Much of the same can be said of initializers, though they are at least useful for anonymous types (which is a useful addition to the language). However, the one saving grace of extension methods have to do with a less technical aspect. It can be difficult to keep one's code base so well organized that it's always easy to find (and thus use) one's available utility methods. With extension methods it's possible to have a collection of them in one or any number of classes and discover the relevant ones via intellisense by remembering nothing more than to include a using directive. Some would also say it results in "more readable code", though I think that's rather mixed.
string s = textBox1.Text.Reverse();
may be easier to read thanstring s = StrUtil.Reverse(s);
, but since the latter actually shows what happens and the first one does not, it's not necessarily "more readable"! -
supercat9 wrote:
Extension methods are, from what I understand, an ugly kludge which serves mainly to make Intellisense more useful, at the expense of introducing all sorts of potential weird bugs.
It's because, as you so well said, don't understand them! ;P
A train station is where the train stops. A bus station is where the bus stops. On my desk, I have a work station.... _________________________________________________________ My programs never have bugs, they just develop random features.
Super Lloyd wrote:
It's because, as you so well said, don't understand them!
Suppose I write "foo.bar()". What circumstances will determine whether this:
- Produces a build-time error
- Produces code which will throw "method not implemented" at run-time
- Execute a native method of foo's class
- Execute an extension method (if several exist, which one?)
In the absence of extension methods, if an object is used in two contexts where it is declared identically. foo.bar() will perform the same action in both contexts. It may perform different actions on different objects, and the actions may depend upon how foo is declared, but the objects actual and declared types together serve to completely define the object's public fields, methods, and behaviors. What precisely determines what code will run when foo.bar() is executed on a system which uses extension methods?
-
I thought that the accepted dispose pattern was to have a finalizer which does nothing but "Dispose(False)" and then have any derived classes override Dispose(Boolean). Is that not how stuff is supposed to happen? Or is the expectation that stuff will happen like that, but each derived class is supposed to override the finalizer with (potentially yet another) finalizer that simply calls Dispose(False)? In any case, I would tend to think that having objects register for finalization would be better than having it occur automatically. Many objects that use unmanaged resources won't necessarily acquire them until some time after they're created. An object with a finalizer could unregister itself for garbage collection in its initializer and then re-register if it's going to allocate some unmanaged resources, but that would seem a little clunky.
The pattern as I understand it is to have the finalizer call Dispose(False), BUT you only have a finalizer when you directly hold unmanaged resources (usually stored as an IntPtr). The VB IDE spits out some decent code to get you started with the pattern as I understand it. That code will then look something like this (this is typed by hand, YMMV):
Private alreadyDisposed As Boolean
Protected Overridable Sub Dispose(disposing As Boolean)
'Do not release things more than once. The Dispose method should
'be able to be called multiple times
If Not alreadyDisposed Then
If disposing
'clean up managed disposables
If mySerialPort IsNot Nothing Then mySerialPort.Dispose()
End If'clean up unmanaged resources, such as IntPtrs alreadyDisposed = True End If
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
'If you don't have a finalizer, this will do nothing
GC.SuppressFinalize(Me)
End Sub'if you need it (the IDE does not generate this
'method because it is normally not needed):
Protected Overrides Sub Finalize()
'this method is only needed if you have unmanaged resources
Try
Dispose(False)
Finally
'don't forget to call the base
MyBase.Finalize()
End Try
End SubOne thing I don't know is what will happen if you derive from a class with a finalizer and do not implement a finalizer on the derived class. My assumption is that the object will still be finalized, but it is just a guess. The safest thing to do would be to reimplement the Finalize method which will turn the base finalizers into do-nothing routines because dispose was already called. As far as the registering for finalization, I would recommend the approach to make the finalizable object as small as possible so that it is only created when the resource is acquired. This may mean creating another class to contain the resource and giving the bigger class that does not use the resource right away a field of the new type. The bigger class will no longer need to be finalizable and there will be no unnecessary finalizations or unregistration/registration required.
-
The pattern as I understand it is to have the finalizer call Dispose(False), BUT you only have a finalizer when you directly hold unmanaged resources (usually stored as an IntPtr). The VB IDE spits out some decent code to get you started with the pattern as I understand it. That code will then look something like this (this is typed by hand, YMMV):
Private alreadyDisposed As Boolean
Protected Overridable Sub Dispose(disposing As Boolean)
'Do not release things more than once. The Dispose method should
'be able to be called multiple times
If Not alreadyDisposed Then
If disposing
'clean up managed disposables
If mySerialPort IsNot Nothing Then mySerialPort.Dispose()
End If'clean up unmanaged resources, such as IntPtrs alreadyDisposed = True End If
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
'If you don't have a finalizer, this will do nothing
GC.SuppressFinalize(Me)
End Sub'if you need it (the IDE does not generate this
'method because it is normally not needed):
Protected Overrides Sub Finalize()
'this method is only needed if you have unmanaged resources
Try
Dispose(False)
Finally
'don't forget to call the base
MyBase.Finalize()
End Try
End SubOne thing I don't know is what will happen if you derive from a class with a finalizer and do not implement a finalizer on the derived class. My assumption is that the object will still be finalized, but it is just a guess. The safest thing to do would be to reimplement the Finalize method which will turn the base finalizers into do-nothing routines because dispose was already called. As far as the registering for finalization, I would recommend the approach to make the finalizable object as small as possible so that it is only created when the resource is acquired. This may mean creating another class to contain the resource and giving the bigger class that does not use the resource right away a field of the new type. The bigger class will no longer need to be finalizable and there will be no unnecessary finalizations or unregistration/registration required.
I just looked at the auto-generated code, and it seems that there is a #Region created with a parameterless Dispose() which calls Dispose(True) and SuppressFinalize, but does not actually contain a finalizer (though if a finalizer is created, it's supposed to call Dispose(False)). That seems like a good approach to doing things. Your comment about minimizing the actual Finalizable "footprint" is a good one. Among other things, if an object controls multiple unmanaged objects, splitting things up would allow separate finalizers for each. BTW, are there any sorts of well-designed objects which use finalizers but do not implement iDisposable? I still find it strange that all objects inherit Finalize, but not Dispose.
-
Super Lloyd wrote:
It's because, as you so well said, don't understand them!
Suppose I write "foo.bar()". What circumstances will determine whether this:
- Produces a build-time error
- Produces code which will throw "method not implemented" at run-time
- Execute a native method of foo's class
- Execute an extension method (if several exist, which one?)
In the absence of extension methods, if an object is used in two contexts where it is declared identically. foo.bar() will perform the same action in both contexts. It may perform different actions on different objects, and the actions may depend upon how foo is declared, but the objects actual and declared types together serve to completely define the object's public fields, methods, and behaviors. What precisely determines what code will run when foo.bar() is executed on a system which uses extension methods?
I think it's relatively simple. The declared method of the declared type will be called if it exist. Otherwise it will throw a compile time error unless there is an extension method with such a name for such a declared type in the static classes of the declared using in the referenced DLLs. (I don't know what the "not implemented exception" does there, it will be thrown when whatever method throwing it is called) Further, if you use VS and thanks to intellisense, you'll know right away if: 1. the method exits 2. the method is on the declared type 3. the method is an extension method none of this should requires much though as: 1. when you use an object and call the method, and assuming you are not producing random code ;), you know very well what are the methods on the type that you are interested in! in other word mot only you don't have to think if you use VS, but also, extension method are not ambiguous at all! heck, me who use extension method a lot, the only problem I found them is that I have to write the "using namespace" explicitly myself, as VS won't do it!
A train station is where the train stops. A bus station is where the bus stops. On my desk, I have a work station.... _________________________________________________________ My programs never have bugs, they just develop random features.
-
I think it's relatively simple. The declared method of the declared type will be called if it exist. Otherwise it will throw a compile time error unless there is an extension method with such a name for such a declared type in the static classes of the declared using in the referenced DLLs. (I don't know what the "not implemented exception" does there, it will be thrown when whatever method throwing it is called) Further, if you use VS and thanks to intellisense, you'll know right away if: 1. the method exits 2. the method is on the declared type 3. the method is an extension method none of this should requires much though as: 1. when you use an object and call the method, and assuming you are not producing random code ;), you know very well what are the methods on the type that you are interested in! in other word mot only you don't have to think if you use VS, but also, extension method are not ambiguous at all! heck, me who use extension method a lot, the only problem I found them is that I have to write the "using namespace" explicitly myself, as VS won't do it!
A train station is where the train stops. A bus station is where the bus stops. On my desk, I have a work station.... _________________________________________________________ My programs never have bugs, they just develop random features.
Super Lloyd wrote:
The declared method of the declared type will be called if it exist.
That's what I thought until I started this thread.
-
Super Lloyd wrote:
The declared method of the declared type will be called if it exist.
That's what I thought until I started this thread.
I think you were thinking the method of the.... runtime type will be called. But there is no ambiguity and no runtime checking, it all happen at compile time! so if you wrote object o; o.foo() That would fail, because there is no foo() method on object. If it compiles that means that the foo() extension has been detected (at compile) and will be called. And nothing will change, i.e. if o is not only an object but a subclass which has a foo() method, this method won't be called by surprise contrary to the original extension, the extension will still be called as has been decided at compile time. With extension method there is no runtime snafu to fear, it all happen at compile time and compile time only!
A train station is where the train stops. A bus station is where the bus stops. On my desk, I have a work station.... _________________________________________________________ My programs never have bugs, they just develop random features.
-
I think you were thinking the method of the.... runtime type will be called. But there is no ambiguity and no runtime checking, it all happen at compile time! so if you wrote object o; o.foo() That would fail, because there is no foo() method on object. If it compiles that means that the foo() extension has been detected (at compile) and will be called. And nothing will change, i.e. if o is not only an object but a subclass which has a foo() method, this method won't be called by surprise contrary to the original extension, the extension will still be called as has been decided at compile time. With extension method there is no runtime snafu to fear, it all happen at compile time and compile time only!
A train station is where the train stops. A bus station is where the bus stops. On my desk, I have a work station.... _________________________________________________________ My programs never have bugs, they just develop random features.
So are you saying that the extension method will get called if and only if the compiler was unaware of a normally-declared method when the code was built? What happens if between rebuilds a class in a library gets updated and a new property, method, or field gets added which shadows an extension method? My understanding is that the component-oriented architecture was designed to allow methods, properties, and fields to be added to classes without breaking applications that use them (such applications will never attempt to reference the new methods, properties, and fields, and will be unaware of their existence). In the absence of extension methods, if new methods are added to a library but all pre-existing methods, properties, etc. are unchanged, updating the library in an existing project will not affect the project application's behavior. If applications that use a class might have extension methods, how can one safely add classes, methods, or fields to it without potentially breaking applications of which one might be unaware?
-
So are you saying that the extension method will get called if and only if the compiler was unaware of a normally-declared method when the code was built? What happens if between rebuilds a class in a library gets updated and a new property, method, or field gets added which shadows an extension method? My understanding is that the component-oriented architecture was designed to allow methods, properties, and fields to be added to classes without breaking applications that use them (such applications will never attempt to reference the new methods, properties, and fields, and will be unaware of their existence). In the absence of extension methods, if new methods are added to a library but all pre-existing methods, properties, etc. are unchanged, updating the library in an existing project will not affect the project application's behavior. If applications that use a class might have extension methods, how can one safely add classes, methods, or fields to it without potentially breaking applications of which one might be unaware?
It's an interesting scenario that you just outlined, that can indeed happen. I won't elaborate too much on it (it's left as an exrcise to the reader ;P ), just say that in practice that hasn't happen to me yet. As I created extension method, so far, only for enums, interfaces and the following BCL classes: string, Stream (which haven't changed their signature much), so, in my case, I would say it's pretty safe. On a late note I would say the "problem" you outlined was on purpose, I think it's used in some of the LINQ libraries.
A train station is where the train stops. A bus station is where the bus stops. On my desk, I have a work station.... _________________________________________________________ My programs never have bugs, they just develop random features.
-
It's an interesting scenario that you just outlined, that can indeed happen. I won't elaborate too much on it (it's left as an exrcise to the reader ;P ), just say that in practice that hasn't happen to me yet. As I created extension method, so far, only for enums, interfaces and the following BCL classes: string, Stream (which haven't changed their signature much), so, in my case, I would say it's pretty safe. On a late note I would say the "problem" you outlined was on purpose, I think it's used in some of the LINQ libraries.
A train station is where the train stops. A bus station is where the bus stops. On my desk, I have a work station.... _________________________________________________________ My programs never have bugs, they just develop random features.
I use extension methods a lot, and don't face the problems that "could" eventually happen. But, that's because using them a lot and using them in strange manners is different. For example, let's see the Stream class: Write(buffer, index, count); But, in general, I call: Write(buffer, 0, buffer.Length); So, I created an extension method that does this. If, in the future, there is a Write method with only one parameter, I really think it will still do the same I did, so I don't see a problem. One pair of things I really think should be done with extension methods is "Equals and GetHashCode". I really think these should only exist on objects that implement IEquatable (or IEquatable generic) interface. And, by default, an extension method could check if the object implement thems and, if not, return the ReferenceEquals or the "reference id" of the object. I think that actually it is horrible to know when an object implements equals and when it does not implements. But that's not the case here.
-
PIEBALDconsult wrote:
My feeling is that either object should implement IDisposable ( Dead )
Why the face? Because you think that would have been a good solution, or because you think it unfortunate that Object includes no such feature? Personally, I think Dispose would have been a better "standard" feature for an object than Finalize. Implementation of the standard dispose pattern requires that an object have a finalizer--even if it doesn't actually do anything--if derived classes may require non-null finalizers. Requiring that classes which implement finalizers must explicitly register them could eliminate that problem.
You don't need to implement the finalizer. The problem arises with the use of Dispose() calling Dispose(true) and the finalizer calling Dispose(false). You can always create your class with only Dispose() virtual. And, an inheritor that needs the destructor/finalize, makes the Dispose() as Dispose(true) and sealed, and creates the Dispose(bool disposing) and the finalizer. Very simple.