Recent

Author Topic: Class constants  (Read 7284 times)

PX

  • New Member
  • *
  • Posts: 14
Class constants
« on: September 21, 2007, 01:01:54 pm »
Hello, is it possible to have constants or read-only variables in a class?

like:

Quote

type
   TClass = class
        const hello = 'hi';
    end;


Ive been pulling my hair trying to do this... Is there a way?

Thanks!

antonio

  • Hero Member
  • *****
  • Posts: 605
RE: Class constants
« Reply #1 on: September 21, 2007, 03:23:52 pm »
Couldn't you use a field?

PX

  • New Member
  • *
  • Posts: 14
RE: Class constants
« Reply #2 on: September 21, 2007, 05:04:04 pm »
a field?

antonio

  • Hero Member
  • *****
  • Posts: 605
Re: Class constants
« Reply #3 on: September 21, 2007, 05:17:20 pm »
Code: [Select]

type
   TClass = class
    FField:string;
   public
    property MyString:string read FField;  // a readonly property
   end;
    (...)
constructor tclass.create;
begin
  // inherited Create here;
  FField := 'hi';
end;    
     (...)

PX

  • New Member
  • *
  • Posts: 14
RE: Class constants
« Reply #4 on: September 21, 2007, 05:50:39 pm »
ah I see thanks =)

pinaxe

  • Newbie
  • Posts: 1
Re: Class constants
« Reply #5 on: July 04, 2016, 07:22:58 pm »
Yep it is easy.
//-------------------------------------------
tMyClass = class(TObject)
    MyInt  :integer;
  private
    const MYCONSTANT1=3;
    procedure MyProc();
  public
    const MYCONSTANT2=4;
end;
//-------------------------------------------

User137

  • Hero Member
  • *****
  • Posts: 1791
    • Nxpascal home
Re: Class constants
« Reply #6 on: July 05, 2016, 03:12:18 am »
Or a function guarantees to be readonly
Code: Pascal  [Select][+][-]
  1. type
  2.   TClass = class
  3.   public
  4.     function MyString: string;
  5.   end;
  6. ...
  7. function TClass.MyString;
  8. begin
  9.   Result := 'hi';
  10. end;

If you add "inline" to it, it might remove all the overhead of a function call too.
« Last Edit: July 05, 2016, 03:14:22 am by User137 »

 

TinyPortal © 2005-2018