0

I have a simple programme in dart to test out if variables assigned hold reference.

 class User{
  int? id;
  String? name;
  int? age;

  User(this.id, this.name, this.age);
}



  User user1 = User(1,'Harry', 21);
  User user2 = user1;
  user2.name =  'James';

  print(user1.name); //prints out James
  print(user2.name); //prints out James

I read that Dart is an Assigned by value language. So why does user1.name have a value of James and not Harry even if it was not explicitly changed?.

Thanoss
  • 439
  • 5
  • 11

1 Answers1

2

Dart is an object oriented language, and like almost every other object oriented language, objects have identity.

That means objects are not denotable values, though; you can't store an object in a variable because the object has an existence, an identity, independent of that variable. You can only store a reference to an object in the variable.

Dart is call-by-value, but all the values are object references.

It's the same in Java, JavaScript and Python. C# has non-object values too, but for its objects, aka. "reference types", it works exactly the same. Dart does not have any values which are not objects.

lrn
  • 64,680
  • 7
  • 105
  • 121