Menu

Custom operators

Will Pittenger Bharath Gaddam

Operators are the ONLY place where you can define something that the code you write can NOT have variable syntax. You MUST use the syntax pre-defined for the operator you’re overriding. The table in [Operators] lists which operators can be overridden. The key here is the operator keyword. It marks what you’re declaring as an operator. List the parameter in the order they appear delimited by commas. All custom operators must be declared as members of a struct, class, interface, or enum type—even in DASIL! The sample below shows how to declare typical operators. All operators are implicitly static.

public operator - var int left, var int right
  returns int

public operator -- (\prefix\ | \postfix\) var int assign

public operator -- var ref int assign, var int delta ' This is overloaded
  returns int

public operator = var ref int assign, var int newValue ' assignment operator
  returns int

public operator = var int left , var int right ' equality
  returns boolean

Some notes:

  • If the operator’s definition has a var whose type is a ref type (not just a reference), your override must have ref too. Ditto for the out operator.
  • Note the unary ++ and -- will always be passed one of two special keywords that specify how the operator was called: as a prefix operator or a postfix operator.
  • Most operators will return something.
  • ASIL doesn’t yet define any ternary operators, but if it ever does, they will be declared as a_b where a and b are the operators. So the ?: operator from C would be written as ?_:.
  • Operators can’t be generics. They can, however, be methods inside a generic type.
  • If you override and, or, and not; the rest compiler will generic nor, band, xor, and xnor for you.
  • As listed in the table below, some operators have two “names”. These can be override with either name.

    Name 1 Name 2
    <> ><
    >= =>
    <= =<

Default implementations of comparison operators

If your type implements IComparable, the compiler will generate the ==, <>, <, <=, >=, and > operators for you.


Related

Wiki: Enums
Wiki: Home
Wiki: Operators
Wiki: keywords-class
Wiki: keywords-enum
Wiki: keywords-interface
Wiki: keywords-operator
Wiki: keywords-out
Wiki: keywords-ref
Wiki: operators-addition
Wiki: operators-and
Wiki: operators-band
Wiki: operators-dec
Wiki: operators-div
Wiki: operators-exponential
Wiki: operators-float-division
Wiki: operators-gt-equal
Wiki: operators-gt
Wiki: operators-inc
Wiki: operators-inequality
Wiki: operators-lt-equal
Wiki: operators-lt
Wiki: operators-minus
Wiki: operators-mod
Wiki: operators-multiplication
Wiki: operators-nor
Wiki: operators-not
Wiki: operators-or
Wiki: operators-xnor
Wiki: operators-xor

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.