Using specific patterns to implement interfaces - c#

I have been very intriuged by design patterns lately, and specifically following correct design patterns in my classes that implement one or several interfaces.
Let's take an example. When a class implement IDisposable you should follow a specific pattern to make sure that your resources are properly cleaned up, by creating a private Dispose(bool disposing) method that differentiates between if it's called by the finalizer, or if it's called from the public Dispose method. Also, a finalizer should be implemented in this case, and you might also need a private bool variable called isDisposed that is set by the Dispose method, so that any method called after th object is Disposed will call a Exception making it clear that this object is already disposed, instead of the code inside the method crashing because some of the required resouces are disposed, and thereby no longer available.
There are also a lot of other interfaces I routinely implement, but it's not all of them I am sure if the way I implement them is the preferred way of doing it, and I might find out later on that it causes a subtle bug that is hard to find, that would probably have been non-existant if I had followed the proper pattern in the first place.
some examples of interfaces I would like to know the best way of implementing are ISerializable, IComparable, IComparable<>, ICloneable, IEnumerable<>, and so on. All interfaces from the Framework are interesting here, so it should not be limited to those I have listed above.
What I'm after is for different interfaces, the preferred way and hopefully also a link to resource on the internet that explains how and also why a specific pattern should be followed.
I hope to get a good collection of these patterns, as I know that they can greatly improve my code and make it more correct, and follow best-practices
It would be great if there are several patterns for the same interface so we can discuss which one is preferred. That might also cause some of you to maybe move over to a new pattern, or make modifications to your existing patterns to improve your code even further, and that would be great!
Edit
After reading Grzenios comment, I would also urge everyone to give the context the pattern should be applied for. For example the IDIsposable pattern should only be followed if you have some unmanaged resources inside your class that you need to dispose, and not if all the objects you need to dispose implements IDisposable themselves.
Edit 2
I should probably start this myself, since I put the question out here. So I'll describe one pattern I know well, and that is the IDisposable pattern.
This pattern should only be used if your class contain one or more unmanaged resources inside your class, and you hav eto make sure that they get Disposed. in this case in addition to the Dispose method we will need a finalizer in case the user of your class forget to dispose it.
So first thing first. Your class should implement the IDisposable interface, and you will have to define the public Dispose method as goverend by the interface. This method should look like this:
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
This will call the protected Dispose(bool) method that takes care of the actual cleanup.
Also, include a vaiable in your class to indicate if the class is disposed or not:
private bool alreadyDisposed = false;
GC.SuppressFinalize tells the garbage collector that this item does not need to be finalized even if it has a finalizer.
Then you need the protected Dispose method. Make it protected instead of private in case any derived class needs to override it:
protected virtual void Dispose(bool isDisposing)
{
if (alreadyDisposed)
{
return;
}
if (isDisposing)
{
// free all managed resources here
}
// free all unmanaged resources here.
alreadyDisposed = true;
}
The finalizer should also call Dispose(bool) if the user forgets to clean up:
~SomeClass(){
Dispose(false);
}
If some method require a disposed resource to function, make the function like this:
public void SomeMethod()
{
if (alreadyDisposed)
throw new ObjectDisposedException("SomeClass",
"Called SomeMethod on Disposed object");
// Method body goes here
}
That's it. This will make sure that the resources gets cleaned up. Preferable by the user of your class calling Dispose, but by adding a Finalizer as a fallback method.

While you're learning about design patterns, you should also look at some common anti-patterns, you get an idea where the pattern comes from. IDisposable is somewhat of an anti-pattern, a minor version of sequential coupling, in that it requires a user to call dispose, and if he forgets, you're in the shit. One of the main reasons of the "disposable pattern" is to fix this issue.
A preferred technique (of mine anyway), wherever possible, is not to expose an IDisposable object to a user, but expose a single method (call it Using(...) for example), which takes a delegate which would execute the code normally contained in your using(...) { } block. This method can perform your construction, execute the delegate, then dispose the resources it consumed, and omits at least 3 problems with IDisposable: That of the user forgetting to call it, the user calling it more than once, and the user calling it too early - you don't need to bother with that boilerplate "disposable pattern" when there's no IDisposable exposed.
An example, lets say I have a File IO requirement where I need to open the same files regularly (and thus, I can't be waiting on the garbage collector to call Finalize in the event that a user forgets to call Dispose).
class MyFileStream {
FileStream fs;
private MyFileStream(string filename, FileMode mode) {
fs = new FileStream(filename, FileMode.Open);
}
private void Dispose() {
fs.Dispose();
}
public static void Using(string filename, FileMode mode, Action<MyFileStream> use) {
MyFileStream mfs = new MyFileStream(filename, mode);
use(mfs);
mfs.Dispose();
}
public void Read(...) { ... }
}
A caller can then say
var x = default(...);
MyFileStream.Using("filename.txt", FileMode.Open, (stream) => {
x = stream.Read(...);
});
Console.WriteLine(x);
Note that this is rather similar to the using() { } language syntax anyway, only this time you are forced to use it, and it imposes further restrictions. One cannot forget to clear up the resources this way.
Still, this pattern isn't always suitable because you sometimes need the resources to last longer than just a method call or so, but if you find the opportunity to use it, do so.
I've completely gone off topic anyway, so back to what you were asking.
Do not use ICloneable - it says nothing about how an object is being cloned (deep or shallow), if you require such thing, create your own IDeepCloneable or IShallowCloneable interfaces instead.
For IEnumerable<>, it's a rare event that you need to create your own, because there's a rather large collection of existing classes in the framework already, and you can usually get additional features much more simply by implementing extension methods (Such as those in LINQ, or your own, making use of the powerful yield keyword, which will create an IEnumerable<> for you in the background).
I wouldn't say there's any specific pattern for the rest, they're pretty self explanatory.

For example the IDIsposable pattern should only be followed if you have some unmanaged resources inside your class that you need to dispose, and not if all the objects you need to dispose implements IDisposable themselves.
I disagee with the above. I never recommend allowing the GC to do clean up and be implicit about object and resource disposal. It's kind of like waiting for the maid to come around and pick up your wet towels at a hotel; it will happen eventually, but the right thing to do is pick them up and hang them up yourself.
Deterministic disposal of objects and keeping scope of those resources as minimal as possible will make for the leanest and most efficient applications, not to mention that for developers reading the code, it is much more explicit to dispose of resources and reads better. Like a beginning and an end to a story that one can see all in one place. I instantiate the object as late as possible and dispose of it as soon as possible after use minimizing scope. Either explicitly calling .Dispose on the object or utilizing a Using block that calls the .Dispose method automatically are (2) good ways of cleaning up.
There are also a lot of other interfaces I routinely implement, but it's not all of them I am sure if the way I implement them is the preferred way of doing it, and I might find out later on that it causes a subtle bug that is hard to find, that would probably have been non-existant if I had followed the proper pattern in the first place.
The entire purpose of an Interface is to create a guidline for the methods, properties, events, etc. that a class is to implement, but not provide the details on how to do it. That is up to you. There is no "pattern" per se of how to implement specefic Interfaces. Don't get thrown off by the IDisposable Interface. Upon creating the Interface in VS.NET, the plumming code is created for you which is not typical for an Interface, and in reality could be completely changed to what you need.
I think where you might be getting confused is about Implementing Interfaces that are in the .NET Framework, but you need to look at the concept of an Interface and not just the ones available in the Framework. If you really want to see examples of how the Interfaces in the .NET Framework are implemented, look at either the MSDN or decompile other Framework objects that implement those Interfaces to see how Microsoft implements them.
As you grow in OOD, you will begin to see the power behind interfaces and begin to create them for your classes. For example lets say you have an interface named IMachine with a method called .StartEngine(). We just want the implementer of the Interface to define all of the details themself; there is no 'pattern' to follow and we the Interface designer don't need to know or care how it is implemented. For a car maybe the methods implementation involves "Get the keys, place them in the ignition, put in park, press brake pedal, turn ignition..." However for a lawnmower the same methods implementation is "Put gass in the mower, prime the carborateor, pull the clutch, pull the cord..."
So you see you can't just look at Interfaces by the ones in the .NET Framework and how to apply a certain pattern to thier implementation. The implementation details, patterns, etc. are up to the implementing class, and as long as the details of the Interface are sufficed, then thats what matters.
Hope this helps a bit...

Related

Minimal IDisposable implimenation for managed resources only

There is a LOT of info around about the "standard full" IDisposable implementation for disposing of unmanaged resources - but in reality this case is (very) rare (most resources are already wrapped by managed classes). This question focuses on a mimimal implementation of IDisposable for the much more common "managed resources only" case.
1: Is the mimimal implementation of IDisposable in the code below correct, are there issues?
2: Is there any reason to add a full standard IDisposable implementation (Dispose(), Dispose(bool), Finalizer etc) over the minimal implimentation presented?
3: Is it OK/wise in this minimal case to make the Dispose virtual (since we are not providing Dispose(bool))?
4: If this minimal implementation is replaced with a full standard implementation that includes a (useless, in this case) finalizer - does this change how the GC handles the object? Are there any downsides?
5: The example includes Timer and event handlers as these cases are particularly important not to miss as failing to dispose them will keep objects alive and kicking (this in the case of Timer, eventSource in case of the event handler) until the GC gets round to disposing them in its time. Are there any other examples like these?
class A : IDisposable {
private Timer timer;
public A(MyEventSource eventSource) {
eventSource += Handler
}
private void Handler(object source, EventArgs args) { ... }
public virtual void Dispose() {
timer.Dispose();
if (eventSource != null)
eventSource -= Handler;
}
}
class B : A, IDisposable {
private TcpClient tpcClient;
public override void Dispose() {
(tcpClient as IDispose).Dispose();
base.Dispose();
}
}
refs:
MSDN
SO: When do I need to manage managed resources
SO: How to dispose managed resource in Dispose() method in C#
SO: Dispose() for cleaning up managed resources
The implementation is correct, there are no issues, provided no derived class directly owns an unmanaged resource.
One good reason to implement the full pattern is the "principle of least surprise". Since there is no authoritative document in MSDN describing this simpler pattern, maintenance developers down the line might have their doubts - even you felt the need to ask StackOverflow :)
Yes it's OK for Dispose to be virtual in this case.
The overhead of the unnecessary finalizer is negligible if Dispose has been called, and is correctly implemented (i.e. calls GC.SuppressFinalize)
The overwhelming majority of IDisposable classes outside the .NET Framework itself are IDisposable because they own managed IDisposable resources. It's rare for them to directly hold an unmanaged resource - this only happens when using P/Invoke to access unmanaged resources that aren't exposed by the .NET Framework.
Therefore there is probably a good argument for promoting this simpler pattern:
In the rare cases that unmanaged resources are used, they should be wrapped in a sealed IDisposable wrapper class that implements a finalizer (like SafeHandle). Because it's sealed, this class doesn't need the full IDisposable pattern.
In all other cases, the overwhelming majority, your simpler pattern could be used.
But unless and until Microsoft or some other authoritative source actively promotes it, I'll continue to use the full IDisposable pattern.
Another option is to refactor your code to avoid inheritance and make your IDisposable classes sealed. Then the simpler pattern is easy to justify, as the awkward gyrations to support possible inheritance are no longer necessary. Personally I take this approach most of the time; in the rare case where I want to make a non-sealed class disposable, I just follow the 'standard' pattern. One nice thing about cultivating this approach is that it tends to push you toward composition rather than inheritance, which generally makes code easier to maintain and test.
My recommended Dispose pattern is for a non-virtual Dispose implementation to chain to a virtual void Dispose(bool), preferably after something like:
int _disposed;
public bool Disposed { return _disposed != 0; }
void Dispose()
{
if (System.Threading.Interlocked.Exchange(ref _disposed, 1) != 0)
Dispose(true);
GC.SuppressFinalize(this); // In case our object holds references to *managed* resources
}
Using this approach will ensure that Dispose(bool) only gets called once, even if multiple threads try to invoke it simultaneously. Although such simultaneous disposal attempts are rare(*), it's cheap to guard against them; if the base class doesn't do something like the above, every derived class must have its own redundant double-dispose guard logic and likely a redundant flag as well.
(*) Some communications classes which are mostly single-threaded and use blocking I/O allow Dispose to be called from any threading context to cancel an I/O operation which is blocking its own thread [obviously Dispose can't be called on that thread, since that thread can't do anything while it's blocked]. It's entirely possible--and not unreasonable--for such objects, or objects which encapsulate them, to have an outside thread try to Dispose them as a means of aborting their current operation at just the moment they were going to be disposed by their main thread. Simultaneous Dispose calls are likely to be rare, but their possibility doesn't indicate any "design problem" provided that the Dispose code can act upon one call and ignore the other.

What is this IDisposable doing for me?

I am working on a "learning program" and using the Code Rush refactoring tool with my learning. With the latest update of Code Rush it has been recommending implementing IDisposable to my programs. I know what MSDN says about IDisposable and I have a real basic understanding of what it does but because I don't know all the implications of implementing it I have been ignoring the recommendation. Today I decided to learn more about it and went along with the recommendation.
This is what it added to my program.
class Program : IDisposable
{
static Service _proxy;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
if (_proxy != null)
{
_proxy.Dispose();
_proxy = null;
}
}
~Program()
{
Dispose(false);
}
So my questions is this. Does that do everything I need to do to get the advantage of IDisposable or do I need to do something in code to make it work? I put a break points on that and never reached it through the debugger so either it was not needed or I am not using it the way it was intended. Can someone please shed some light on what this is doing for me or how I should use it so it does do something for me?
In this case, CodeRush is suggesting you implement IDisposable because your class encapsulates an IDisposable resource (it's seeing _proxy, though that's not entirely a good thing since it's static). Code Rush thinks that there is a type that you're using which should be explicitly cleaned up, but you're not providing a way to do it via your class.
That being said, IDisposable is tricky - and this is one case where the generated code is not really a good implementation (even if _proxy were an instance variable). I would recommend not using the destructor in this case. It will cause performance issues in the GC, and in this case, doesn't help with the safety, as the encapsulated resource should handle that the case where you forget to call Dispose() for you. For details, see my series on IDisposable, and, in particular, encapsulating an IDisposable class.
In addition, this class shouldn't implement IDisposable (unless there is some other reason to do so) given the code above, as the _proxy resource is static. Disposing a static resource from an instance is likely to cause problems, at least in a general case. (In this case, it's obviously not problematic, but it's not a good practice...) Typically, a static variable has a very different lifetime than an instance member, so automatically disposing of it would be inappropriate.
In a properly-written program, at any given time, for every object that could possibly have a meaningful implementation of IDisposable, there will be some entity that is responsible for ensuring that IDisposable.Dispose will get called on that object sometime between the last "real use" of that instance and its ultimate abandonment. In general, if an object Foo is going to hold references to objects which implement IDisposable, at least one of the following scenarios should apply:
Some other object will also hold the reference for at least as long as Foo needs it, and will take care of calling Dispose on it, so Foo should let the other object take care of the Dispose.
The object holding the reference will be the last thing to use the IDisposable object in question; if Foo doesn't call Dispose, nothing else will. In that scenario, Foo must ensure that that other object's Dispose method gets called once it (Foo) is no longer needed, and before it is abandoned. The most idiomatic way to handle this is for Foo to implement IDisposable.Dispose, and for its Dispose method to call Dispose on the IDisposable objects to which it holds the last useful references.
There are some scenarios where a class designer might not know whether its class is going to hold the last useful reference to an IDisposable object. In some cases, this issue may be resolved by having a class constructor specify whether a IDisposable passed to the constructor is being "lent" or "given". Other cases may require the use of reference-counting wrappers or other complex techniques.

Should we implement IDisposable if one member is IDisposable?

I think so. But take a look at a built-in class in ASP.NET:
public sealed class HttpPostedFile
{
public Stream InputStream { get; } // Stream implements IDisposable
// other properties and methods
}
Suppose I have an instance of HttpPostedFile called file. Since there is no Dispose method to explicitly invoke, file.InputStream.Dispose() won't be invoked until it's destructed, which I think goes against the original intention of IDisposable. I think the correct implementation should contain a standard IDisposable implementation. So, if one of the members implements IDisposable, the class needs to implement it too.
What are your opinions? It seems to be a bit complicated.
In general, you should implement IDisposable if you own the resource represented by the property - see this question for a discussion on this subject.
I'd say that because HttpPostedFile is instantiated during processing of an HTTP request, it doesn't own the stream, and hence doesn't dispose it. The stream will be disposed when the HTTP request processing finishes.
If your class creates one or more IDisposable objects and holds the only references to them, then your class should almost certainly implement IDisposable and dispose the IDisposable objects it created. If one or more IDisposable objects will be passed into the constructor of your class, then you need to consider a few scenarios:
Your creator may want to keep using the IDisposable after you're done with it, and will certainly know when it's no longer needed (the semantics of your class would let him know you're done with it).
Your creator won't want to use the IDisposable after you're done with it, and may not know when you're going to be done with it.
Your class may be used in some circumstances corresponding to (1) above, and in some circumstances (2), but your creator will know in advance which circumstance applies.
Your creator can't predict whether he's going to want to keep using the object after you're done with it.
For scenario #1, there's no need for you to implement IDisposable, though it might not be a bad idea to implement a do-nothing IDisposable handler and have your consumers use it, in case another scenario applies in future.
For scenario #2, your object should take ownership of the IDisposable, and should Dispose it when done. I don't really like having objects take unconditional ownership of IDisposables; I prefer to implement things as in #3.
There are two ways of handling #3. The one I prefer is for your object to take a parameter (either a Boolean or an enum) along with the IDisposable, indicating whether it is supposed to take ownership of the IDisposable. Your class unconditionally implements IDisposable; the implementation disposes of any objects it has taken ownership of, but not those it hasn't. An alternative is to have two subclasses with a common base class - one subclass implements IDisposable and the other does not. I prefer the former pattern, because it allows for the addition of a method to replace an IDisposable with a new one (of which it may or may not take ownership). For example, if I were implementing a control with an Image property, I would have a SetImage method which with a parameter to specify whether the control should own the passed-in image; that method would Dispose the old image if it owned it, and could then either take ownership of the new image or not.
bool OwnMyImage;
Image MyImage;
void SetImage(Image NewImage, bool TakeOwnership)
{
IDisposable oldDisposable; // Could reuse one variable for multiple IDisposables
if (OwnMyImage)
{
oldDisposable = Threading.Interlocked.Exchange(MyImage, null);
if (oldDisposable != null)
{
oldDisposable.Dispose();
}
}
OwmMyImage = TakeOwnership;
MyImage = NewImage;
}
Scenario #4 is complicated; the best way to handle it is probably for your object to implement IDisposable by raising a Disposed event. Your creator can use that event to do either Dispose the object if you were the last one using it, or adjust a flag or counter so that other code will know the object shouldn't be left undisposed on your behalf.
It depends.
Stream is also implemented by TextStream (possibly on top of StringBuilder), so no unmanaged resources are required.
HttpPostedFile may not use any unmanaged resources at all, so it's safe to postpone deconstruction until the garbage collector sees fit.

Why would a class implement IDisposable explicitly instead of implicitly?

I was using the FtpWebResponse class and didn't see a Dispose method. It turns out that the class implements IDisposable, but does so explicitly so that you must first cast your instance to IDisposable before calling Dispose:
// response is an instance of FtpWebResposne
((IDisposable) response).Dispose();
Why would the designer of a class such as this one choose to implement IDisposable explicitly? As Anthony Pegram says, doing things this way masks the fact that the object should be disposed for the average developer who is not consulting the documentation every time he/she uses a class.
This is normally done if the class has a Close method that is the exact same as Dispose. The original Dispose is hidden in an explicit implementation so that the exact same method doesn't have two names.
It's officially recommended here:
Do implement a Close method for cleanup purposes if such terminology is standard, for example as with a file or socket. When doing so, it is recommended that you make the Close implementation identical to Dispose...
Consider implementing interface members explicitly to hide a member and add an equivalent member with a better name.
Occasionally a domain-specific name is more appropriate than Dispose. For example, a file encapsulation might want to use the method name Close. In this case, implement Dispose privately and create a public Close method that calls Dispose.
(P.S. I disagree with this convention.)
Occasionally a class will have a Dispose method that is part of the interface but doesn't actually need to be called because the only resource to dispose of is memory: MemoryStream, for example.
As mentioned by others, if the class has a Close method that does the same thing as Dispose, arguably Dispose only needs to exist to support the "using" pattern so it may as well be explicit.
It's a little weird looking to me too. For what it's worth: the base class (WebResponse) implements a Close() method. Reflector shows that WebResponse's Dispose() method just calls Close() and an Internal OnDispose virtual that does nothing.
I have to confess that it smells a little to me, but I bet that they explicitly implemented IDisposable so that there would not be confusion in Intellisense between calling Close() or Dispose().
In addition to what's been said, I might suggest that implementing IDisposable explicitly encourages use of the using block, as it can be used on any type which implements IDisposable and it is more natural (to most people, anyway) to write this:
using (var response = GetResponse())
{
// do something
}
Than this:
var response = GetResponse();
// do something
((IDisposable)response).Dispose();
I'm not sure that would be a developer's intention in explicitly implementing IDisposable, but it's possible.

Consider a "disposable" keyword in C#

What are your opinions on how disposable objects are implemented in .Net? And how do you solve the repetitiveness of implementing IDisposable classes?
I feel that IDisposable types are not the first-class citizens that they should've been. Too much is left to the mercy of the developer.
Specifically, I wonder if there should'nt have been better support in the languages and tools to make sure that disposable things are both implemented correctly and properly disposed of.
In C# for instance, what if my class that needs to implement the disposable semantics could be declared like this:
public class disposable MyDisposableThing
{
~MyDisposableThing()
{
// Dispose managed resources
}
}
The compiler could in this case easily generate an implementation of the IDisposable interface. The destructor ~MyDisposableThing could be transformed into the actual Dispose method that should release managed resources.
The intermediate C# code would look like this:
public class MyDisposableThing : IDisposable
{
private void MyDisposableThingDestructor()
{
// Dispose my managed resources
}
~MyDisposableThing()
{
DisposeMe(false);
}
public void Dispose()
{
DisposeMe(true);
GC.SuppressFinalize(this);
}
private bool _disposed;
private void DisposeMe(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Call the userdefined "destructor"
MyDisposableThingDestructor();
}
}
_disposed = true;
}
}
This would make for much cleaner code, less boilerplate disposing code, and a consistent way of disposing managed resources. Implementing IDisposable by hand would still be supported for edge cases and unmanaged resources.
Ensuring that instances are properly disposed is another challenge. Consider the following code:
private string ReadFile(string filename)
{
var reader = new StreamReader();
return reader.ReadToEnd(filename);
}
The reader variable never outlives the scope of the method but would have to wait for the GC to dispose it. In this case, the compiler could raise an error that the StreamReader object was not explicitly disposed. This error would prompt the developer to wrap it in a using statement:
private string ReadFile(string filename)
{
using (var reader = new StreamReader())
{
return reader.ReadToEnd(filename);
}
}
An oft-stated principle is that "design patterns are needed to address language deficiencies". This is an example of that principle. We need the disposable pattern because the language doesn't give it to you.
I agree that disposability could have been elevated out of the "pattern" world and into the C# language proper, as we did with, say, property getters and setters (which are standardizations of the pattern of having getter and setter methods), or events (which standardize the idea of storing a delegate and calling it when something interesting happens.)
But language design is expensive and there is a finite amount of effort that can be applied to it. Thus we try to find the most useful, compelling patterns to put into the language proper. And we try to find a way that does so in a way that is not merely convenient, but actually adds more expressive power to the language. LINQ, for example, moves the concepts of filtering, projecting, joining, grouping and ordering data into the language proper, which adds a lot of expressive power to the language.
Though this is certainly a good idea, I don't think it meets the bar. It would be a nice convenience, I agree, but it doesn't enable any really rich new scenarios.
In addition to the other answers, there is the problem of how much should this implement and what should people expect from it? Say I declared my class like this:
public disposable class MyClass
{
readonly AnotherDisposableObject resource = new AnotherDisposableObject();
~MyClass()
{
this.resource.Dispose();
}
public void DoStuff()
{
this.resource.SomeMethod();
}
}
Then what would you expect to happen if a caller called DoStuff after the instance had been disposed? Should the compiler automatically insert something like
if (this.disposed) throw new ObjectDisposedException();
at the start of every method because you have declared the class as disposable?
If so then what about cases where methods are explicitly allowed to be called after an object is disposed (e.g. MemoryStream.GetBuffer)? Would you have to introduce a new keyword that indicated this to the compiler, e.g. public useafterdispose void ...?
If not then how do you explain to people that the new keyword implements some of the boiler-plate code for you, but that they still need to write code to check whether the object is disposed in each method? Moreover, how can they even check this, because all the state information about whether the object has been disposed is auto-generated! Now they need to track their own flag in the ~MyClass method which undoes half the work the compiler should be doing for you.
I think as a specific language pattern there are too many holes in the concept, and it only attempts to solve one specific problem. Now what could solve this entire class of problem in a general-purpose fashion is mixins (i.e. a Disposable mixin) and this language feature would be generally reusable for different concepts (e.g. Equatable mixin, Comparable mixin, etc.). That's where my money would go.
Personally, I consider the support for IDisposable to be quite decent in the current version of .NET. The presence of the using keyword pretty much makes it into a first-class construct for me.
I do admit there is a certain amount of boilerplate code involved, but not enough to warrant a new language features. (Auto-implemented properties was a good example of a feature that was begging to be introduced.) You've missed out an important point in your post that this "boilerplate" code is not always what you need. Mainly, you need to dispose unmanaged resources outside of the if (disposing) block.
Of course, the destructor (~MyDisposableThing) and parameterless Dispose() method are genuinely boilerplate and could be eliminated by the user of a language keyword, as you suggest - but again I'm not sure the introduction of an actual new keyword is all that necessary for a few lines of code.
I certainly see the point you are making here, and do sympathise with it to some degree. (I'm sure no coder would complain if your suggestion becamse part of the language specification.) However, it's not likely to convince the .NET development team when there are a rather limited number of lines of code anyway, some of which are arguably fairly context-specific (and thus not boilerplate).
I completely agree that IDisposable needs better language suppprt. Here's my variant of it from a while ago. The details are probably wrong, but C++/CLI serves as a pretty good model for this. Unfortunately it confuses the hell out of C# programmers when I show them examples in C++/CLI. But it already does "the right thing" in terms of implementation; we would just need a new syntax in C#.
Even the simplest Windows Forms application has a Dispose method in it, which is generated by a wizard and is fragile in the face of inexpert changes. The idea of composing components together such that one component can "own" several others is so fundamental that IDisposable is practically unavoidable, and unfortunately it seems to take several pages of most books to explain how to implement it correctly.
The existing using statement takes care of the client side. Where we need more language support is on the implementation side.
Some of the fields of a class are references to things that the class "owns", and some not owned. So we have to be able to mark a field as owned.
Also, it would be a very bad idea to automatically generate a finalizer. Most often, a class will own other objects that implement IDisposable. Not all classes are thread safe, nor should they need to be. If they are called from a finalizer, that happens on another thread, forcing them to be thread safe. This is probably the one area around IDisposable that causes the most confusion - a lot of people read the books and come away with the mistaken impression that you have to write a finalizer on an object that supports IDisposable.
I realize this is an old thread but there is something that has been overlooked.
Dispose pattern in both C# and Java break the fundamental reason for not having a deterministic destructor.
MyObject A = new MyObject()
MyObject B = A;
A.Dispose();
What is the state of B now? What if the owner of B didn't really want it disposed. You now have the same issue in C++ where you have to keep track of all the references of objects you are holding on to.
IDisposable is only truly valid within the context of using() and ensuring resource cleanup if an exception occurs.
There are design patterns to do this but it isn't IDisposable
#Peter Yes I am arguing that the Dipsosable pattern has a fault. When implemented the Disposable pattern isn't normally meant to just dispose OS resources with the idea of being able to continue using the object that was disposed. By using the Disposable pattern outside of a try{} finally{} in Java or using() in .NET you break one of the reasons of having a GC. I am not saying memory will leak. I am saying you can now have other parts of the code that have a reference to an Object that has been disposed. Now the onus is back on the developer to check if an object has been disposed before each call, or at the very least catch a ObjectDisposedException.
Lets look at a silly example:
FileStream stream = new FileStream (#"c:\mylog.txt");
logger.setStream (stream);
Who is supposed to invoke .Dispose()? It may not be obvious that the logger is now aquiring ownership of the file stream. Let's say the stream was created somewhere else outside of the developer knowing it will be set as the logging stream.
if we were to add one line, we would break the logger
using (FileStream stream = new FileStream (#"c:\mylog.txt"))
{ logger.setStream (stream); }
or
FileStream stream = new FileStream (#"c:\mylog.txt");
logger.setStream (stream);
stream.Dispose();
The Disposable pattern does not reference count for resources. The developer now has to be conscious of who owns the object and who is responsible for cleaning it up. The real problem is that when Dispose() is invoked the normal behavior is to invalidate the whole object preventing it from being used.
IMHO, the .net languages have a major shortcoming in their handling of iDisposable, which is that there is no nice way of handling initializers that throw exceptions. Unless one 'leaks' a copy of the object under construction or the disposable objects therein, there's no way to clean up any iDisposable objects which were created (either in an initializer, or a base-level constructor) before an initializer throws.
Two features I would like to see toward that end:
A class declaration that would cause a particular method to be invoked if an exception throws out of its constructor.
A field declaration which would indicate that the field should have .Dispose called upon it if some special private method or keyword is used on the object.
BTW, I would also like to see a declaration available for structure methods which would indicate that the method alters the underlying structure. Use of such methods would be forbidden on structure rvalues, and use of such methods on structure properties would generate a read-modify-write sequence.
Okay you need to understand the difference between managed and unmanaged memory.
Put simply, c++ style destructors wouldn't work in the managed world of c# because there's no guarantee when the object gets garbage collected, hence you would never know when the destructor would get called, which would make things very unpredictable.
As opposed to c++, when destructors get called as soon as the class goes out of scope, so you can guarantee when it gets called.
This is the reason why c# can't have destructors.

Categories

Resources