Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

d
function
communitycreator

What are the property functions in D?

Chinweuba Elijah Azubuike

What is a function?

Functions are generally code blocks that carry out certain instruction in an application. These blocks of code can be called multiple times during the runtime of the application whose functions are reusable.

What are property functions?

Member functions, such as member variables, can be used with properties. The @property keyword is used to access these properties. The characteristics are associated with functions that return values based on the requirements. Let's look at an example of a property.

Example

import std.stdio;

struct Square { 
   double objectWidth; 
   double objectHeight;  

   double objectArea() const @property {  
      return objectWidth*objectHeight;  
   } 

   void objectArea(double newArea) @property {  
      auto multiplier = newArea / objectArea; 
      objectWidth *= multiplier; 
      writeln("Value set!");  
   } 
}

void main() { 
   auto square = Square(50,50); 
   writeln("The area is ", square.objectArea);  
   
   
}
D property function

Explanation

  • Line 3: We instantiate our square struct.
  • Line 4–5: We instantiate our variables for the example.
  • Line 7–9: We declare our property function and define its return value. notice the @property keyword.
  • Line 11-15: We define the logic of the square function.
  • Line 19: We call the property function and equate it to a variable
  • Line 20: We print the output to the console.

RELATED TAGS

d
function
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring