using keyword over methods
Today the "using" keyword can be used to create try/finally blocks in a easy and safe manner. The problem is that using keyword requires an IDisposable instance.
But in many situations we have a start/end approach, lock/unlock or similar that do not return any value and, surely have a better performance if no helper object is created.
So, I think that it will be great if void methods can be marked with "finalizer" methods, so when used in a using clause, the compiler can create the right begin/end block.
I have a sample at: http://www.paulozemek.com/Polarlight.TestPage.aspx
There, the Initialize method is marked with a finally Finalize (but in .Net using an attribute may be enough) so, the using keyword works fine over the Initialize method.
Thank you for your suggestion! While we aim to respond to every suggestion, we are closing older ones that don’t have enough votes so newer ones from you can move to the top. If this suggestion is still important to you, feel free to open it again.
I implemented a macro called `on_finally` for Enhanced C# that implements a similar feature. It's not as convenient as `using`, but it's nice in situations where `using` doesn't apply.
Paulo Zemek commented
In fact, there are many problems that I see when using structs.
1) If they are internal, then boxing is needed (for the IDisposable interface). I tend to use this.
2) If they are public, then people can see and use them directly. With creates 2 other problems:
2.1) I prefer to have a method that returns the IDisposable, instead of using the helper struct directly. But this is slower than using the struct directly.
2.2) If I decide to use the struct directly, then users must know about the existence of the struct and must never forget to pass the constructor parameter, as structs always have a default constructor.
So, look at the difference:
// Ok, Monitor.Enter has the lock keyword, but this can be used to anything, like:
Today, considering I use the fastest struct, I will use:
But, in this case, I need a ReadLock class or struct. If it is a struct, then nothing forbids me of doing:
} // forgetting to pass a parameter.
I actually have an extension method, so I do:
Which returns a struct, but boxed as IDisposable, so I don't see it. I really did that to avoid users of my library seeing the ReadLock class.
Paulo Zemek commented
Yes... when I said helper objects I was refering to structs.
Structs, even when boxed (if I get them as IDisposable) are faster than reference types (at least on my tests) but they are still a lot slower than the try/finally approach.
Surely for many things the speed difference is not important... but for the cases when it is, and for a cleaner approach, I think it will be good to have the alternative.
Have you measured the performance of using() with a struct type? http://stackoverflow.com/questions/2412981/if-my-struct-implements-idisposable-will-it-be-boxed-when-used-in-a-using-statem