Assignability of an object to a structural type

If a variable is declared as a structural type, any object whose type satisfies the structural type can be assigned to that variable. The participating members of a structural type are:

  • Property getters
  • Property setters
  • Methods

Adding a var declaration to a structural type does not specify the ability to get or set a variable or property an instance of this type. Instead, a var declaration defines a static constant variable on the type. To get or set data from a variable and properties on an instance of the structural type, you must use the property getter and setter syntax in its declaration.

Property assignment compatibility

For properties, assignment compatibility extends to primitive types. For example, if a structure defines a property as type double, a compatible property can define it as a class that defines it as an int. Because an int can coerce to a double with no loss of precision, the property is call-compatible.

Method assignment compatibility

For methods, given type T and structure S, a T method is structurally assignable to an identically named method in S if all of the following are true:

  • The number of parameters in both methods is the same.
  • The parameter types of the method on T are assignable from the parameter types of the method on S.
  • The return type of the method on T is assignable to the return type of the method on S.

In other words, the parameter types are contravariant and the return type is covariant.

Method signature variance on structure methods supports primitive types as well as reference types.

Interface assignment compatibility

If you define a structure that extends an interface, the structure gets the properties and method signatures of the interface. The structural assignability rules stated earlier apply, rather than interface assignability rules.

See also