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