Recent

Author Topic: [CLOSED] ClassType method  (Read 1112 times)

julkas

  • Guest
[CLOSED] ClassType method
« on: May 23, 2020, 05:39:31 pm »
From http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/System__TObject__ClassType.html
Quote
Note: In Delphi code, use the is or as operators instead of System::TObject::ClassType.
Why ?
« Last Edit: May 24, 2020, 07:56:13 am by julkas »

jamie

  • Hero Member
  • *****
  • Posts: 6128
Re: ClassType method
« Reply #1 on: May 23, 2020, 05:44:07 pm »
so what's the question ?

if Sender is TSomeClass then …

That does a compare..

 With Sender As TSomeClass do …

 is that what you are referring to ?

basically does type checking of classes..
The only true wisdom is knowing you know nothing

Warfley

  • Hero Member
  • *****
  • Posts: 1499
Re: ClassType method
« Reply #2 on: May 23, 2020, 05:50:55 pm »
Honestly I don't know, ClassType and is have some differences.
E.g. consider foo being of type TFoo, which inherits from TBar then:
Code: Pascal  [Select][+][-]
  1. foo is TFoo // True
  2. foo is TBar // True
  3. foo is TObject // True
while:
Code: Pascal  [Select][+][-]
  1. foo.ClassType = TFoo // True
  2. foo.ClassType = TBar // False
  3. foo.ClassType = TObject // False
So their use is pretty use-case dependent.

And as has nothing to do with that at all. Sure you could implement a check like this:
Code: Pascal  [Select][+][-]
  1. var tmp: TFoo;
  2. try
  3.   tmp := foo as TFoo;
  4. except on E: Exception do
  5.   tmp := nil;
  6. end;
  7.  
  8. if Assigned(tmp) then
But let's be honest, this code is at most usable as a punchline but should never see the light of day in any production environment

PascalDragon

  • Hero Member
  • *****
  • Posts: 5462
  • Compiler Developer
Re: ClassType method
« Reply #3 on: May 23, 2020, 09:25:11 pm »
I don't know why the Delphi documentation recommends the is operator (and also the as one) compared to using ClassType in C++, but is also checks whether the class instance is Nil, ClassType will crash in that case. Also is is essentially a call to InheritsFrom and not ClassType.

egsuh

  • Hero Member
  • *****
  • Posts: 1289
Re: ClassType method
« Reply #4 on: May 24, 2020, 01:28:00 am »
Does following discussion have something to do with current thread?

https://forum.lazarus.freepascal.org/index.php/topic,48966.msg353641.html#msg353641

julkas

  • Guest
Re: ClassType method
« Reply #5 on: May 24, 2020, 07:54:46 am »
is would be best choice.
Thanks.

 

TinyPortal © 2005-2018