function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
AndrzejWAndrzejW 

APEX Automatic read only properties

Hi Guys,

 

APEX Code allows creating automatic read-only properties, for example:

 

public integer MyReadOnlyProp { get; }

 

Can anyone tell me how can this property ever return a sensible value, if its internal storage is not accessible? I must be missing something very basic here.

 

Many thanks,

 

Andrzej

WesNolte__cWesNolte__c

Hey

 

It's not obvious is it:) This notation means you can only read this variable from another class and/or page. You can set it within the class that owns it though. So, as an example, you could give it a value in the class constructor(or anywhere really) eg.

 

public myClass(){

   MyReadOnlyProp = 19;

}

 

Cheers,

Wes

AndrzejWAndrzejW

Hi Wes,

 

Thanks for your reply! What you said is exactly what I hoped for. However the following code:

 

public class TestReadOnlyProperty { public string ReadOnlyProperty {get;} public TestReadOnlyProperty() { ReadOnlyProperty = 'Hey'; } }

 

won't compile with the following error:

 

ERROR - Compile error: member variable not visible for assignment

Many thanks,

 

Andrzej

WesNolte__cWesNolte__c

Hey

 

Well that's no good. Jeez Louise. Well there's an alternative in that you could change your property into a simple var and then supply a getter for it ie.

 

private String ReadonlyProp;

 

 public TestReadOnlyProperty()
    {
        ReadOnlyProperty = 'Hey';
    }

public String getReadOnlyProp(){

return ReadOnlyProp;

}

 

Not as concise as I'd like it to be, but not too shabby either:)

 

Wes

WesNolte__cWesNolte__c

Thanks for posting this prob buddy, I never would've known about this otherwise:)

 

Wes

AndrzejWAndrzejW

Thanks for your help Wes. I found this sample code in Force.com Apex Code Developer's Guide:

 

public class AutomaticProperty { public integer MyReadOnlyProp { get; } public double MyReadWriteProp { get; set; } public string MyWriteOnlyProp { set; } }

It appears that the first and the third properties do not make any sense, because there is no alternative access to their internal storage.

I still hope that there is some magic syntax that allows access to the internal storage from within the class. Maybe it will be added in the next release :smileyhappy:

Cheers,

Andrzej

 

 

SFRichSFRich

In order for the first and third properties to work, you need to add the 'private' keyword.  'Private' will allow you to set (or get) the value only from within the class.

 

public class AutomaticProperty {

 

//*public get, private set
   public integer MyReadOnlyProp { get; private set;}


//Public set, private get

   public string MyWriteOnlyProp {private get; set; }
}