CodeBlanks Logo Icon CodeBlanks

this

Learn to access the class itself with this.

The this keyword

this means 'this instance' inside a method. It is most used in constructors when a parameter shares a name with a field. Example: User(String name) { this.name = name; }.

Here name refers to the parameter, this.name to the field. Without this the two names clash; the assignment would not happen. So this is required as a disambiguator.

If the names differ, this is unnecessary: User(String n) { name = n; }. But Dart prefers the short form User(this.name), which already embeds this. this earns its place in the long form.

this and the short form

this can be written explicitly or used implicitly through Dart's short constructor form. User(this.name) is the same as User(String name) { this.name = name; }, just shorter.

The short form works when the parameter name matches the field. When they differ, use the long form. Example: User(String fullName) { name = fullName; } — here this is not required.

In practice Dart developers prefer the short form. It is less code and makes this automatic. The long form is essential when extra logic (validation, for example) is needed.

Practice Assign with this

Define a User class with a String name field. In the constructor User(String name) body, perform this.name = name. Inside main create a User('Ayşe') instance and print it with print(u.name).

Starter code

main.dart
void main() {
  // define the User class

  // create an instance and print
}

Sample solution

main.dart
class User {
  String name;
  User(String name) {
    this.name = name;
  }
}

void main() {
  var u = User('Ayşe');
  print(u.name);
}

Expected output

Ayşe

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does this.name = name do?

  • Assigns the name field to the name parameter
  • Deletes both
  • Throws an error
  • Assigns the name parameter to the name field Correct answer

Explanation: this.name is the field, name is the parameter; the field gets the value.

2 Using this

Question
class User {
  String name;
  User(String name) {
    ____ = name;
  }
}
Answer
class User {
  String name;
  User(String name) {
    this.name = name;
  }
}

Explanation: this.name is the field, name is the parameter.

3 Match the this concepts

Term Meaning
this This instance
this.name Field
name Parameter ( in constructor )
this.name = name Assignment

All lessons in Beginner