Errm so what does "if (object)" and "Assert(object)" do??

Jarrett Billingsley kb3ctd2 at yahoo.com
Fri Mar 9 19:45:09 PST 2007


"Chris Warwick" <sp at m.me.not> wrote in message 
news:est5n5$1krh$1 at digitalmars.com...
> Errm so what does "if (object)" and "Assert(object)" do??

"if(object)" is the same as "if(object !is null)".

But "assert(object)" is a little tricky.  It's a little-known feature.  If 
you use "assert(object)", it will call any invariants defined for the 
object, i.e.

class C
{
    invariant
    {
        writefln("foo");
    }
}

...
scope c = new C();
assert(c); // prints foo since it calls the invariant

This means that if you use "assert(objectReference)" on a null reference, 
you will (like with '==' !) get an access violation, since it tries to look 
up the invariant from a null reference.

Therefore, when doing an assert on an object reference, you should always 
use "assert(c is null)" or "assert(c !is null)". 




More information about the Digitalmars-d-learn mailing list