PDA

View Full Version : Parameter explicit typecast to implicit



cronodragon
01-08-2007, 03:25 PM
I have something like this:

type
myClass = class(TObject)
...

procedure DoSomething(var Obj:TObject);
begin
...
end;

var
myObj: myClass;

Now I want to call the procedure like this:

DoSomething(myObj);

But I get a type error. I don't see why since myClass is a decendant of TObject. So I have to explicitly typecast the parameter inelegantly:

DoSomething(TObject(myObj));

I think the compiler is trying to save me from using a parameter which is not of the right type, but by doing that it is forcing me to use a solution which is unsafe, since I could typecast a variable which is not a class by mistake. Of course I could use the "as" operator, but I think it's too slow. Is there a way to tell the compiler not to be so strict with classes?

Regards! :D

VilleK
01-08-2007, 04:39 PM
This is because of the "var" in the parameter declaration.

If you remove the "var" like this:

procedure DoSomething(Obj:TObject);

...then your code will compile.

Is there a reason that you need to use "var" in this particular procedure?

cronodragon
01-08-2007, 04:46 PM
Yes, to free any kind of object and assign the variable to nil. Some of my objects doesn't allow calling to Free, so I can't use FreeAndNil. :P

cairnswm
01-08-2007, 06:59 PM
Arn't all objects passes by reference (like vaR) anyway? So you dont need the var bit.

cronodragon
01-08-2007, 07:22 PM
Well, the idea is to assign the reference variable inside the procedure, like:

procedure ReleaseObj(var Obj:TObject);
begin
Obj.Free; // but i can't use Free() all the time
Obj := nil;
end;

I suppose there should be a compiler switch or directive to avoid the explicit typecast... is there any? :?

cairnswm
01-08-2007, 07:32 PM
Try This

procedure FreeAndNil(var Obj);
var
Temp: TObject;
begin
Temp := TObject(Obj);
Pointer(Obj) := nil;
Temp.Free;
end;


Its the wat FreeAndNil is defined.

cronodragon
01-08-2007, 07:55 PM
That's what I was looking for, thanks!

Just one question, isn't the open parameter a bit unsafe? Since you could assign whatever variable, and there isn't a type checking. Anyway I'll do it that way, since it improves code readability, and the other way around has the same drawback.

cairnswm
02-08-2007, 05:47 PM
I didn't write that. Thats how FreeAndNull is defined in sysutils.pas - its a straight copy-paste.