August 06, 2013 Re: With statement become like C#'s using? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Bosak | On 2013-08-05 17:45:23 +0000, Bosak said: > I think this dispose thing should be added to D, because it is a very common practice in C#(and not only). In the book I used to learn C# long ago I remember how they sayed like 100 of times: "If you use an object that implements IDisposable ALLWAYS use it in an using statement". It is not a strange or not-intuitive feature. In fact it can make the "scoped" variables idea more popular. And instead of explicitly adding an using statement you just declare your variable as scoped and the compiler takes care of calling it's dispose automatically when it gets out of scope. In http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2012/Three-Unlikely-Successful-Features-of-D I make the argument that C#'s "using" misses the point and D's "scope" statement is a better proposition. Andrei |
August 06, 2013 Re: With statement become like C#'s using? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Bosak | On 2013-08-05 14:40, Bosak wrote: > In C# there is this using construct: > > using(Bitmap image = this.OpenImage("filename.bmp")) { > image.Name = "foo"; > //use image like image.sth > } > > which is translated to: > > { > Bitmap image = this.OpenImage("filename.bmp"); > try { > image.Name = "foo"; > //use image like image.sth > } > finally { > IDisposable obj = image as IDisposable; > if(obj != null) > obj.Dispose(); > } > } > > I know that the with statement is different, but it can be improved so > that you can declare things in it like an using statement: > > with(Bitmap image = open("filename.bmp")) { > name = "foo"; > //no need to specify image.sth > } > > or even a more implicit one: > with(open("filename.bmp")) { > //ditto > } > > And both of the above to be translated to: > > { > Bitmap temp = expression; > //use bitmap > delete temp; // Call destructor/finallizer of the object > //I'm not sure if delete was the proper way to call a destructor in D > } > > And I hope you got the point. Tell me what you think. You can replicate the C# using statement with a library function: module test; import std.stdio; alias writeln println; template isDisposable (T) { enum isDisposable = __traits(compiles, { T t; t.dispose(); }); } void using (alias block, T)(T t) if (isDisposable!(T)) { block(t); scope (exit) t.dispose(); } void using (string block, T)(T t) if (isDisposable!(T)) { with (t) mixin(block); scope (exit) t.dispose(); } class Foo { void bar () { writeln("bar"); } void dispose () { writeln("dispose"); } } void main () { using!(foo => foo.bar())(new Foo); using!q{ bar(); }(new Foo); } If D could have a better syntax for delegates/blocks, it could look like this: using(new Foo ; foo) { foo.bar(); } -- /Jacob Carlborg |
Copyright © 1999-2021 by the D Language Foundation