Fields#

Classes, structs, compact classes and interfaces can have fields. They are a simple way of storing data in an object.

Add a field to an object#

Lets take a class as an example:

public class MyClass : Object {

    // ...

    private int a_field;
}

A field just consists of a access modifier, a data type, and a name.

Using a field#

They can be accessed later very easily as a member of the object:

public class MyClass : Object {

    // ...

    private int a_field;

    public void print_a () {
        stdout.printf (this.a_field.to_string ());
    }
}

Access modifier in different object types#

Different object types have different abilities to have fields:

Classes

private

Structs

public

Compact classes

private

Enums and Flags

-

Interfaces

private

Aliases

-

Warning

Some of these are only highly recommended, and not something impossible. But there are reasons why only these options are shown here.

Default values#

Classes, interfaces and compact classes allow it to specify a default value for a field:

public class MyClass : Object {

    // ...

    private int a_field = 0;
}

This is sometimes useful. For structs you can achieve the same by assigning a initial value in the constructor.

static fields#

Static fields are the same for all instances of an object. They exist only once and have one value. Especially for static data, or that is used across all instances, this is useful.

Tip

Static fields (and also class fields) should be always private. Also in structs. Use static properties or methods instead, when they should be public.

class fields#

In classes derived from GLib.Object you also can use the class keyword:

This lets the field go into the class structure of the object. In practice this means that these fields are like static fields the same for all instances of the class, but not subclasses.

You mostly should use static fields, and not class fields, except when you really need that feature, for example when subclasses want to override the value of the field with a custom one.