property

Summary

The property modifier is used to declare a method as a getter or setter.

Syntax

property member

Parameters

member
The member to turn into a getter or setter.

Description

The property modifier turns a class method into a getter or setter.

If the property keyword is applied to a method with no parameters, it becomes a getter.

If the property keyword is applied to a method with one parameter, it becomes a setter. Setters must have the void return type.

The property modifier cannot be applied to a method with more than one parameter.

Examples

Defining and using a getter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import System;
 
class Person
{
    private string mName;
 
    public Person(string name) {
        this.mName = name;
    }
 
    public property string name() { // Define the getter
        return this.mName;
    }
}
 
Person person = new Person("Bob");
Console.log(person.name); // Use the getter
Defining and using a setter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Person
{
    private string mName;
 
    public Person(string name) {
        this.mName = name;
    }
 
    public property void name(string newName) { // Define the setter
        this.mName = newName;
    }
}
 
Person person = new Person("");
person.name = "Bob"; // Use the setter
Defining and using a getter/setter together
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import System;
 
class Person
{
    private string mName;
 
    public Person(string name) {
        this.mName = name;
    }
 
    public property string name() { // Define the getter
        return this.mName;
    }
    public property void name(string newName) { // Define the setter
        this.mName = newName;
    }
}
 
Person person = new Person("");
person.name = "Bob"; // Use the setter
Console.log(person.name); // Use the getter

See Also

Share

HTML | BBCode | Direct Link